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
+90
View File
@@ -0,0 +1,90 @@
import Link from "next/link";
import { connection } from "next/server";
import { AccountCreateForm, AccountDetail, NetworkHandles } from "@/components/account-manager";
import { ArrowRightIcon, PlusIcon, PublishIcon, SettingsIcon, UsersIcon } from "@/components/icons";
import { EmptyState, LinkButton, Meta, PageHeader, cx } from "@/components/ui";
import { listAccounts } from "@/lib/accounts";
import { listStories } from "@/lib/stories";
export const metadata = { title: "Canais de publicação" };
/**
* Canais de publicação (no código: accounts): lista densa à esquerda e o detalhe (ou a criação) ao lado.
* `?account=<id>` abre o detalhe; `?new=1` abre o formulário de novo canal.
*/
export default async function AccountsPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
await connection();
const sp = await searchParams;
const accounts = listAccounts();
const selected = sp.account ? accounts.find((a) => a.id === sp.account) : undefined;
const creating = sp.new === "1" || (accounts.length === 0 && !sp.account);
const stories = listStories().map((s) => ({ id: s.id, title: s.title, kind: s.kind }));
return (
<>
<PageHeader eyebrow="Distribuição" title="Canais de publicação"
description="Cada canal reúne os seus perfis no YouTube, no TikTok e no Instagram. Ligue histórias e fontes de corte a ele: o que você aprovar sai nas redes do canal."
meta={<>
<Meta icon={<PublishIcon size={15} />}>Fila e horários em <Link href="/publishing" className="text-fg-muted underline underline-offset-2 hover:text-fg">Publicações</Link></Meta>
<Meta icon={<SettingsIcon size={15} />}>Apps das redes e horários bons em <Link href="/settings" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
</>}
actions={<LinkButton variant="primary" href="/accounts?new=1"><PlusIcon size={16} />Novo canal</LinkButton>} />
<div className="grid grid-cols-1 items-start gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(26rem,34rem)]">
<section aria-labelledby="lista-contas" className="grid min-w-0 gap-3">
<h2 id="lista-contas" className="sr-only">Lista de canais de publicação</h2>
{accounts.length === 0 ? (
<EmptyState icon={<UsersIcon />} title="Nenhum canal de publicação ainda">
Crie o primeiro canal ao lado, conecte as redes dele e escolha quais histórias e fontes de corte ele publica.
</EmptyState>
) : (
<ul className="grid divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
<li aria-hidden="true"
className="hidden grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)_6.5rem_1rem] gap-x-5 bg-raised/60 px-5 py-2.5 text-[0.6875rem] font-semibold tracking-[0.12em] text-fg-subtle uppercase md:grid">
<span>Canal</span><span>Redes</span><span className="text-right">Histórias</span><span />
</li>
{accounts.map((a) => {
const active = a.stories.filter((s) => s.status === "active").length;
const current = a.id === selected?.id;
return (
<li key={a.id}>
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`} aria-current={current ? "true" : undefined}
className={cx("group relative grid items-center gap-x-5 gap-y-1.5 px-5 py-3 transition-colors md:grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)_6.5rem_1rem]",
current ? "bg-raised" : "hover:bg-raised/50")}>
<span aria-hidden="true" className={cx("absolute inset-y-2.5 left-0 w-[3px] rounded-r-full bg-accent", current ? "opacity-100" : "opacity-0")} />
<span className="grid min-w-0 gap-0.5">
<span className="truncate text-sm font-semibold text-fg">{a.name}</span>
<span className="truncate text-xs text-fg-subtle">{a.niche || "sem nicho"}</span>
</span>
<NetworkHandles networks={a.networks} />
<span className="text-xs text-fg-muted md:text-right">
<span className="font-display text-base font-semibold text-fg tabular-nums">{active}</span> ativa{active === 1 ? "" : "s"}
</span>
<ArrowRightIcon size={16} className="text-fg-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-fg max-md:hidden" />
</Link>
</li>
);
})}
</ul>
)}
</section>
{/* Em tela estreita, o painel aberto vem antes da lista. */}
<div className={cx("grid min-w-0 gap-6 xl:sticky xl:top-8", (creating || selected) && "max-xl:order-first")}>
{creating ? <AccountCreateForm />
: selected ? <AccountDetail key={selected.id} account={selected} stories={stories} />
: sp.account ? (
<EmptyState compact icon={<UsersIcon />} title="Canal não encontrado"
action={<LinkButton href="/accounts">Ver todos</LinkButton>}>
Ele pode ter sido apagado.
</EmptyState>
) : (
<EmptyState compact icon={<UsersIcon />} title="Escolha um canal">
Abra um canal da lista para conectar as redes, ajustar como publicar e ligar histórias e fontes.
</EmptyState>
)}
</div>
</div>
</>
);
}
+142
View File
@@ -0,0 +1,142 @@
"use server";
// Ações de formulário (server actions). Devolvem { error } ou { message } para o formulário.
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prepareBranches } from "@/lib/branches";
import { addManualComments, closeDecision, decisionVotes } from "@/lib/decisions";
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
import { slugify } from "@/lib/paths";
import { UserError, createEpisode, createStory, deleteStory, getEpisodeById, getStory, provisionalTitle } from "@/lib/stories";
import { CHOICES, type Choice, type Provider, type StoryKind } from "@/lib/types";
export type FormState = { error?: string; message?: string } | null;
function failure(error: unknown): FormState {
if (error instanceof UserError) return { error: error.message };
console.error(error);
return { error: "Erro interno. Veja o terminal do painel." };
}
export async function createStoryAction(_prev: FormState, form: FormData): Promise<FormState> {
let id: string;
try {
id = createStory({
title: String(form.get("title") ?? ""),
id: String(form.get("id") ?? ""),
logline: String(form.get("logline") ?? ""),
kind: String(form.get("kind") ?? "interactive") as StoryKind,
branchCount: Number(form.get("branchCount") ?? 2),
}).id;
} catch (error) {
return failure(error);
}
revalidatePath("/");
redirect(`/stories/${id}`);
}
/**
* "Criar história com IA": o criador manda um texto (ideia, sinopse ou rascunho) e a IA monta
* bíblia, ep01 e título. Por padrão usa o Codex (GPT) para enredo; cai para o Claude se o Codex
* não estiver disponível. Campos: text (obrigatório), title (opcional), kind, provider ("" = automático).
*/
export async function createStoryFromTextAction(_prev: FormState, form: FormData): Promise<FormState> {
let target: string;
try {
const text = String(form.get("text") ?? "").trim();
if (text.length < 20) throw new UserError("Escreva pelo menos uma ou duas frases sobre a história (mínimo 20 caracteres).");
if (text.length > 20_000) throw new UserError("Texto longo demais (máx. 20 mil caracteres).");
const kind = String(form.get("kind") ?? "interactive") as StoryKind;
const title = String(form.get("title") ?? "").trim() || provisionalTitle(text);
// Identificador único: título provisório + sufixo se já existir.
const base = slugify(title) || "historia";
let id = base;
for (let n = 2; getStory(id); n++) id = `${base}-${n}`;
const story = createStory({ title, id, logline: "", kind, branchCount: Number(form.get("branchCount") ?? 2) });
// Documental é um vídeo só: sem título de episódio ("Abertura" só faz sentido numa série).
const ep = createEpisode(story.id, { title: kind === "documentary" ? "" : "Abertura" });
const chosen = String(form.get("provider") ?? "");
const provider: Provider = chosen === "claude" || chosen === "codex" ? chosen : defaultProviderFor("story");
// Modelo escolhido no formulário; vazio = padrão da tarefa (no Codex, o do config.toml). startRun valida.
const model = String(form.get("model") ?? "") || defaultModelFor("story", provider);
const run = startRun({
provider, model, kind: "story", request: text,
storyId: story.id, episodeId: ep.id,
});
target = `/agent?run=${run.id}`;
} catch (error) {
return failure(error);
}
revalidatePath("/");
redirect(target);
}
/** Exclui uma história (arquivos vão para data/trash/). Campo: storyId. Volta para a página inicial. */
export async function deleteStoryAction(_prev: FormState, form: FormData): Promise<FormState> {
try {
deleteStory(String(form.get("storyId") ?? ""));
} catch (error) {
return failure(error);
}
revalidatePath("/");
redirect("/");
}
export async function createEpisodeAction(_prev: FormState, form: FormData): Promise<FormState> {
let target: string;
try {
const storyId = String(form.get("storyId") ?? "");
const parent = Number(form.get("parentEpisodeId") ?? 0) || undefined;
const ep = createEpisode(storyId, { title: String(form.get("title") ?? ""), parentEpisodeId: parent });
target = `/stories/${storyId}/episodes/${ep.number}`;
} catch (error) {
return failure(error);
}
redirect(target);
}
export async function addCommentsAction(_prev: FormState, form: FormData): Promise<FormState> {
try {
const episodeId = Number(form.get("episodeId"));
const r = addManualComments(episodeId, String(form.get("comments") ?? ""));
revalidateEpisode(episodeId);
return {
message: `${r.added} comentário(s) adicionado(s)` + (r.duplicates ? `, ${r.duplicates} repetido(s) ignorado(s)` : "") +
(r.rejected.length ? `. Linhas sem "autor: texto" ignoradas: ${r.rejected.length}` : "."),
};
} catch (error) {
return failure(error);
}
}
export async function closeDecisionAction(_prev: FormState, form: FormData): Promise<FormState> {
try {
const episodeId = Number(form.get("episodeId"));
const manualWinner = String(form.get("manualWinner") ?? "");
const d = closeDecision(episodeId, (CHOICES as string[]).includes(manualWinner)
? { winner: manualWinner as Choice, reason: String(form.get("reason") ?? "") } : undefined);
revalidateEpisode(episodeId);
const votes = Object.entries(decisionVotes(d)).map(([letter, n]) => `${letter}: ${n}`).join(" × ");
return { message: `Votação fechada: venceu ${d.winner} (${votes}, ${d.method === "manual" ? "decisão manual" : "por votos"}). A vertente vencedora entrou no caminho principal.` };
} catch (error) {
return failure(error);
}
}
/** "Preparar vertentes": a IA escreve opções, roteiro e cena de cada vertente do próximo nível. */
export async function prepareBranchesAction(_prev: FormState, form: FormData): Promise<FormState> {
try {
const episodeId = Number(form.get("episodeId"));
const ep = prepareBranches(episodeId, { regenerate: form.get("regenerate") === "1" });
revalidateEpisode(episodeId);
return { message: ep.branches_status === "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)." };
} catch (error) {
return failure(error);
}
}
function revalidateEpisode(episodeId: number): void {
const ep = getEpisodeById(episodeId);
if (ep) revalidatePath(`/stories/${ep.story_id}/episodes/${ep.number}`);
}
+56
View File
@@ -0,0 +1,56 @@
import { connection } from "next/server";
import { AgentConsole, RunHistory, type AgentDefaults } from "@/components/agent-console";
import { ClockIcon } from "@/components/icons";
import { Card, PageHeader } from "@/components/ui";
import { PREFERRED_PROVIDER, models, defaultModelFor, defaultProviderFor, getRun, listRuns, providers } from "@/lib/agents";
import { listEpisodes, listStories } from "@/lib/stories";
import { AGENT_KINDS, type AgentKind } from "@/lib/types";
export const metadata = { title: "Agente" };
export default async function AgentPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
await connection();
const sp = await searchParams;
const runId = sp.run ? Number(sp.run) : undefined;
const viewing = runId ? getRun(runId) ?? null : null;
const stories = listStories().map((s) => ({
id: s.id, title: s.title, kind: s.kind,
episodes: listEpisodes(s.id).map((e) => ({ id: e.id, number: e.number, title: e.title })),
}));
const kind = ((AGENT_KINDS as string[]).includes(sp.kind ?? "") ? sp.kind : viewing?.kind) as AgentKind | undefined;
// Agente e modelo padrão de cada tarefa (enredo e roteiro com o GPT via Codex; cai para o outro se faltar).
const map = <T,>(fn: (k: AgentKind) => T) => Object.fromEntries(AGENT_KINDS.map((k) => [k, fn(k)])) as Record<AgentKind, T>;
const defaults: AgentDefaults = {
provider: map(defaultProviderFor),
preferred: PREFERRED_PROVIDER,
model: map((k) => ({ claude: defaultModelFor(k, "claude"), codex: defaultModelFor(k, "codex") })),
};
return (
<>
<PageHeader eyebrow="Agentes de código" title="Console do agente"
description="Peça uma história, um roteiro, uma cena ou um ajuste. Enredo e roteiro saem com o GPT (Codex); a cena, com o Claude. Um agente roda por vez, sempre dentro do projeto." />
<div className="grid items-start gap-8 xl:grid-cols-[minmax(0,1fr)_20rem] 2xl:grid-cols-[minmax(0,1fr)_26rem]">
<AgentConsole
key={runId ?? "novo"}
providers={providers().map((p) => ({ id: p.id, available: p.available, version: p.version, note: p.note }))}
models={models()}
defaults={defaults}
stories={stories}
initial={{
storyId: sp.story ?? viewing?.story_id ?? undefined,
episodeId: sp.episode ? Number(sp.episode) : viewing?.episode_id ?? undefined,
kind, runId,
// Pedido pronto vindo de outra página (ex.: "Peça uma cena nova ao agente" na montagem).
request: sp.prompt?.slice(0, 2000),
}}
viewing={viewing}
/>
<Card title={<span className="flex items-center gap-2"><ClockIcon size={16} />Histórico</span>} description="Últimas 30 execuções" className="xl:sticky xl:top-8">
<RunHistory runs={listRuns()} activeId={runId} />
</Card>
</div>
</>
);
}
@@ -0,0 +1,12 @@
import { endChannel } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
/** Encerra o canal nesta conta (fica no histórico). */
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string; channelId: string }> }) {
try {
const { id, channelId } = await ctx.params;
return Response.json(endChannel(id, channelId));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,12 @@
import { linkChannel } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
/** Liga um canal de live do Clipador à conta: {channelId} (ex.: "twitch-alanzoka"). */
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = (await request.json()) as { channelId?: string };
return Response.json(linkChannel((await ctx.params).id, String(body.channelId ?? "")));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,14 @@
import { checkNetwork } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
type Ctx = { params: Promise<{ id: string; platform: string }> };
/** Confere a conexão ("Já entrei" no modo sessão; relê o perfil na API oficial) → AccountNetwork. */
export async function POST(_request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
return Response.json(await checkNetwork(id, platform));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,15 @@
import { connectNetwork } from "@/lib/accounts";
import { errorResponse, readJson } from "@/lib/http";
type Ctx = { params: Promise<{ id: string; platform: string }> };
/** Começa a conexão: {mode: "official"|"session"} → {network: AccountNetwork, next: ConnectNext}. */
export async function POST(request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
const body = await readJson<{ mode: string }>(request);
return Response.json(await connectNetwork(id, platform, body.mode));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,16 @@
import { networkCreatorInfo } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string; platform: string }> };
/** TikTok oficial: {nickname, privacyOptions, maxDurationS, commentDisabled, duetDisabled, stitchDisabled}. */
export async function GET(_request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
return Response.json(await networkCreatorInfo(id, platform));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,14 @@
import { reopenNetwork } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
type Ctx = { params: Promise<{ id: string; platform: string }> };
/** Modo sessão: reabre o navegador para entrar de novo → {network, next}. */
export async function POST(_request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
return Response.json(await reopenNetwork(id, platform));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,24 @@
import { disconnectNetwork, updateNetworkSettings } from "@/lib/accounts";
import { errorResponse, readJson } from "@/lib/http";
type Ctx = { params: Promise<{ id: string; platform: string }> };
/** Ajustes da rede no canal: {enabled?, dailyLimit?, privacy?, tiktokMode?} → AccountNetwork. */
export async function PUT(request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
return Response.json(updateNetworkSettings(id, platform, await readJson(request)));
} catch (error) {
return errorResponse(error);
}
}
/** Desconecta (o Publicador apaga tokens e o perfil de navegador) → AccountView. Os ajustes da rede ficam. */
export async function DELETE(_request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
return Response.json(await disconnectNetwork(id, platform));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,15 @@
import { pasteNetworkToken } from "@/lib/accounts";
import { errorResponse, readJson } from "@/lib/http";
type Ctx = { params: Promise<{ id: string; platform: string }> };
/** Instagram oficial: {accessToken} vai para o cofre do Publicador → AccountNetwork (o token nunca volta). */
export async function POST(request: Request, ctx: Ctx) {
try {
const { id, platform } = await ctx.params;
const body = await readJson<{ accessToken: string }>(request);
return Response.json(await pasteNetworkToken(id, platform, body.accessToken));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,12 @@
import { linkNetwork } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
/** Vincula um perfil: {platform: "tiktok"|"instagram"|"youtube", handle: "@usuario"} (simulado). */
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = (await request.json()) as { platform?: string; handle?: string };
return Response.json(linkNetwork((await ctx.params).id, String(body.platform ?? ""), String(body.handle ?? "")));
} catch (error) {
return errorResponse(error);
}
}
+27
View File
@@ -0,0 +1,27 @@
import { deleteAccount, getAccount, updateAccount } from "@/lib/accounts";
import { errorResponse, readJson } from "@/lib/http";
export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
const account = getAccount((await ctx.params).id);
return account ? Response.json(account) : Response.json({ error: "Canal de publicação não encontrado." }, { status: 404 });
}
/** Edita nome, nicho, notas e regras: {name?, niche?, notes?, approvalMode?: "manual"|"auto", timing?: "now"|"best_slot", aiLabel?: "auto"|"always"|"never"}. */
export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = await readJson<{ name: string; niche: string; notes: string; approvalMode: string; timing: string; aiLabel: string }>(request);
return Response.json(updateAccount((await ctx.params).id, body));
} catch (error) {
return errorResponse(error);
}
}
/** Apaga o canal (perfis, vínculos, fila e publicações dele saem junto; as histórias ficam). */
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
deleteAccount((await ctx.params).id);
return Response.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,12 @@
import { endStory } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
/** Encerra a história nesta conta (fica no histórico e nas métricas). */
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string; storyId: string }> }) {
try {
const { id, storyId } = await ctx.params;
return Response.json(endStory(id, storyId));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,12 @@
import { linkStory } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
/** Liga uma história à conta: {storyId}. Várias ativas ao mesmo tempo. */
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = (await request.json()) as { storyId?: string };
return Response.json(linkStory((await ctx.params).id, String(body.storyId ?? "")));
} catch (error) {
return errorResponse(error);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { createAccount, listAccounts } from "@/lib/accounts";
import { errorResponse } from "@/lib/http";
export const dynamic = "force-dynamic";
export async function GET() {
return Response.json(listAccounts(), { headers: { "Cache-Control": "no-store" } });
}
/** Cria uma conta: {name, niche?, notes?}. */
export async function POST(request: Request) {
try {
const body = (await request.json()) as { name?: string; niche?: string; notes?: string };
return Response.json(createAccount({ name: String(body.name ?? ""), niche: body.niche, notes: body.notes }));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,11 @@
import { cancelRun } from "@/lib/agents";
import { errorResponse, parseId } from "@/lib/http";
export async function POST(_request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
cancelRun(parseId((await ctx.params).id));
return Response.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,46 @@
// Server-Sent Events: primeiro o histórico gravado, depois os eventos ao vivo.
// Leitura do histórico e inscrição acontecem na mesma passagem síncrona; eventos novos só
// chegam em callbacks posteriores, então nada se perde entre as duas etapas.
import { followUpRunOf, getRun, isActive, readEvents, subscribe } from "@/lib/agents";
import { errorResponse, parseId } from "@/lib/http";
export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const id = parseId((await ctx.params).id);
if (!getRun(id)) return Response.json({ error: "Execução não encontrada." }, { status: 404 });
const encoder = new TextEncoder();
let unsubscribe = () => {};
const stream = new ReadableStream({
start(controller) {
let closed = false;
const send = (event: string, data: unknown) => {
if (!closed) controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
};
const finish = (live: boolean) => {
// followUpRunId: a continuação criada por uma mensagem enviada durante a execução. Só ao
// vivo: abrir uma execução antiga do histórico não deve pular para a continuação dela.
const run = getRun(id);
send("end", run ? { ...run, followUpRunId: live ? followUpRunOf(id) : null } : null);
unsubscribe();
closed = true;
controller.close();
};
readEvents(id).forEach((e) => send("event", e));
if (!isActive(id)) return finish(false);
unsubscribe = subscribe(id, (e) => (e === null ? finish(true) : send("event", e)));
request.signal.addEventListener("abort", () => {
closed = true;
unsubscribe();
});
},
cancel() {
unsubscribe();
},
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" },
});
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,16 @@
// Mensagem do usuário durante a execução: { text, mode: "now" | "queue" }.
// "now" interrompe e retoma a sessão com a correção; "queue" envia quando o agente terminar.
import { sendFollowUp } from "@/lib/agents";
import { errorResponse, parseId } from "@/lib/http";
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const id = parseId((await ctx.params).id);
const body = (await request.json()) as { text?: unknown; mode?: unknown };
const mode = body.mode === "queue" ? "queue" : "now";
sendFollowUp(id, typeof body.text === "string" ? body.text : "", mode);
return Response.json({ ok: true, mode });
} catch (error) {
return errorResponse(error);
}
}
+16
View File
@@ -0,0 +1,16 @@
import { startRun } from "@/lib/agents";
import { errorResponse } from "@/lib/http";
import type { AgentKind, Provider } from "@/lib/types";
export async function POST(request: Request) {
try {
const body = (await request.json()) as {
provider: Provider; model?: string; kind: AgentKind; request: string;
storyId?: string | null; episodeId?: number | null; resumeRunId?: number | null;
};
const run = startRun({ ...body, model: body.model ?? "" });
return Response.json({ id: run.id });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,10 @@
import { promoteAsset } from "@/lib/assets";
import { errorResponse } from "@/lib/http";
export async function POST(_request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
return Response.json(promoteAsset((await ctx.params).id));
} catch (error) {
return errorResponse(error);
}
}
+25
View File
@@ -0,0 +1,25 @@
import { createAsset } from "@/lib/assets";
import { errorResponse } from "@/lib/http";
import type { AssetKind } from "@/lib/types";
export async function POST(request: Request) {
try {
const form = await request.formData();
const file = form.get("file");
if (!(file instanceof File)) return Response.json({ error: "Envie um arquivo." }, { status: 400 });
const text = (key: string) => String(form.get(key) ?? "");
const asset = await createAsset({
file,
name: text("name"),
kind: text("kind") as AssetKind,
scope: text("scope") === "story" ? "story" : "library",
storyId: text("storyId") || undefined,
license: text("license"),
source: text("source"),
notes: text("notes"),
});
return Response.json(asset);
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,17 @@
import { proxy } from "@/lib/clipper";
import { errorResponse } from "@/lib/http";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ path: string[] }> };
/** Repassa a página /clipper ao serviço do Clipador (lista de caminhos permitidos em lib/clipper.ts). */
async function handle(request: Request, ctx: Ctx): Promise<Response> {
try {
return await proxy(request, (await ctx.params).path);
} catch (error) {
return errorResponse(error);
}
}
export { handle as GET, handle as POST, handle as PATCH, handle as PUT, handle as DELETE };
@@ -0,0 +1,23 @@
import { errorResponse, readJson } from "@/lib/http";
import { collectMetrics, isCollecting, listMetricSyncs } from "@/lib/metrics-sync";
/** Última leitura dos números de cada rede de cada canal (e se há uma leitura em andamento). */
export async function GET(request: Request) {
try {
const accountId = new URL(request.url).searchParams.get("accountId") || undefined;
return Response.json({ running: isCollecting(), syncs: listMetricSyncs(accountId) });
} catch (error) {
return errorResponse(error);
}
}
/** "Atualizar números": lê agora todos os posts publicados (do canal, se vier `accountId`). Pode levar minutos. */
export async function POST(request: Request) {
try {
const body = (await readJson(request).catch(() => ({}))) as { accountId?: unknown };
const accountId = typeof body.accountId === "string" && body.accountId ? body.accountId : undefined;
return Response.json(await collectMetrics({ accountId, force: true }));
} catch (error) {
return errorResponse(error);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { dashboard } from "@/lib/metrics";
export const dynamic = "force-dynamic";
/** Totais e desempenho (por rede, conta, história e episódio). `?account=<id>` filtra por conta. */
export async function GET(request: Request) {
const account = new URL(request.url).searchParams.get("account") || undefined;
return Response.json(dashboard({ accountId: account }), { headers: { "Cache-Control": "no-store" } });
}
@@ -0,0 +1,20 @@
import { errorResponse } from "@/lib/http";
import { clearSimulated, simulateMetrics } from "@/lib/metrics";
/** Gera publicações e métricas SIMULADAS para as contas e histórias vinculadas (selo "simulado"). */
export async function POST() {
try {
return Response.json(simulateMetrics());
} catch (error) {
return errorResponse(error);
}
}
/** Apaga todos os dados simulados (os reais ficam). */
export async function DELETE() {
try {
return Response.json({ removed: clearSimulated() });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,33 @@
import { errorResponse, parseId, readJson } from "@/lib/http";
import { approveEpisode, episodeApproval, unapproveEpisode } from "@/lib/publishing";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
/** Estado da aprovação: renders finais possíveis, título/legenda, canais que recebem e jobs. */
export async function GET(_request: Request, ctx: Ctx) {
try {
return Response.json(episodeApproval(parseId((await ctx.params).id)), { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
/** "Aprovar para publicar": {renderId, title, caption} → EpisodeApproval (cria/atualiza os jobs). */
export async function POST(request: Request, ctx: Ctx) {
try {
return Response.json(approveEpisode(parseId((await ctx.params).id), await readJson(request)));
} catch (error) {
return errorResponse(error);
}
}
/** Desfaz a aprovação (cancela o que ainda não saiu). */
export async function DELETE(_request: Request, ctx: Ctx) {
try {
return Response.json(await unapproveEpisode(parseId((await ctx.params).id)));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,13 @@
import { prepareBranches } from "@/lib/branches";
import { errorResponse, parseId } from "@/lib/http";
/** Prepara (ou refaz, com {"regenerate": true}) as vertentes do próximo nível de um episódio. */
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = (await request.json().catch(() => ({}))) as { regenerate?: boolean };
const ep = prepareBranches(parseId((await ctx.params).id), { regenerate: body.regenerate === true });
return Response.json({ episodeId: ep.id, branchesStatus: ep.branches_status, runId: ep.branches_run_id });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,14 @@
// "Gerar de novo" de um trecho ({ index }): outra variação da cena do Godot ou outra imagem da internet.
import { errorResponse, parseId } from "@/lib/http";
import { regenerateShot } from "@/lib/montage";
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const id = parseId((await ctx.params).id);
const body = (await request.json()) as { index?: unknown; target?: unknown };
const target = body.target === "inset" || body.target === "remove-inset" ? body.target : "visual";
return Response.json({ montage: await regenerateShot(id, Number(body.index), target) });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,22 @@
// POST começa a montagem do MP4 ({ auto: true } = um clique: plano, narração, cenas 2D e montagem);
// DELETE ?render=<id> cancela a que está em andamento.
import { errorResponse, parseId } from "@/lib/http";
import { cancelMontageRender, startMontageRender } from "@/lib/montage";
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = (await request.json().catch(() => ({}))) as { auto?: unknown; replan?: unknown };
return Response.json(startMontageRender(parseId((await ctx.params).id), { auto: body.auto === true, replan: body.replan === true }));
} catch (error) {
return errorResponse(error);
}
}
export async function DELETE(request: Request) {
try {
cancelMontageRender(parseId(new URL(request.url).searchParams.get("render") ?? ""));
return Response.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,29 @@
// Montagem documental: GET devolve o estado (trechos, áudios, visuais, opções e montagens);
// PATCH ajusta voz, velocidade, legenda e, por trecho, o texto falado e o visual.
import { errorResponse, parseId } from "@/lib/http";
import { VISUAL_KINDS, listMontageRenders, loadMontage, montageJob, updateMontage, visualOptions } from "@/lib/montage";
import { DOC2D_TEMPLATES } from "@/lib/montage-godot";
import { listLibrary } from "@/lib/scene-library";
import { getEpisodeById } from "@/lib/stories";
function state(id: number) {
return { storyId: getEpisodeById(id)?.story_id ?? "", montage: loadMontage(id), kinds: VISUAL_KINDS, templates: DOC2D_TEMPLATES, library: listLibrary(), options: visualOptions(id), renders: listMontageRenders(id), job: montageJob(id) };
}
export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
return Response.json(state(parseId((await ctx.params).id)));
} catch (error) {
return errorResponse(error);
}
}
export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const id = parseId((await ctx.params).id);
updateMontage(id, await request.json());
return Response.json(state(id));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,13 @@
// Renderiza no Godot a cena 2D de UM trecho ({ index }), para ver antes de montar o vídeo.
import { errorResponse, parseId } from "@/lib/http";
import { renderShotScene } from "@/lib/montage";
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const id = parseId((await ctx.params).id);
const body = (await request.json()) as { index?: unknown };
return Response.json({ montage: await renderShotScene(id, Number(body.index)) });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,19 @@
// Envia a imagem ou o clipe de um trecho (multipart: file, index, credit, license, sourceUrl).
import { errorResponse, parseId } from "@/lib/http";
import { uploadShotVisual } from "@/lib/montage";
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const id = parseId((await ctx.params).id);
const form = await request.formData();
const file = form.get("file");
if (!(file instanceof File)) return Response.json({ error: "Envie um arquivo." }, { status: 400 });
const text = (key: string) => String(form.get(key) ?? "");
const montage = await uploadShotVisual(id, Number(text("index")), {
file, credit: text("credit"), license: text("license"), sourceUrl: text("sourceUrl"),
});
return Response.json({ montage });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,13 @@
import { errorResponse, parseId } from "@/lib/http";
import { startRender } from "@/lib/renders";
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const { profile } = (await request.json()) as { profile?: string };
if (profile !== "preview" && profile !== "final") return Response.json({ error: "Perfil inválido." }, { status: 400 });
const job = startRender(parseId((await ctx.params).id), profile);
return Response.json(job);
} catch (error) {
return errorResponse(error);
}
}
+39
View File
@@ -0,0 +1,39 @@
// Entrega arquivos do repositório ao navegador (vídeos, imagens, roteiros, assets),
// só de output/, stories/ e assets/. Suporta Range para o player de vídeo.
import fs from "node:fs";
import path from "node:path";
import { Readable } from "node:stream";
import { SERVABLE_ROOTS, resolveInside } from "@/lib/paths";
const TYPES: Record<string, string> = {
".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mkv": "video/x-matroska", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
".md": "text/markdown; charset=utf-8", ".json": "application/json; charset=utf-8", ".txt": "text/plain; charset=utf-8",
".wav": "audio/wav", ".mp3": "audio/mpeg", ".ogg": "audio/ogg", ".glb": "model/gltf-binary", ".gltf": "model/gltf+json",
};
export async function GET(request: Request) {
const rel = new URL(request.url).searchParams.get("path") ?? "";
const full = rel ? resolveInside(rel, SERVABLE_ROOTS) : null;
if (!full || !fs.existsSync(full) || !fs.statSync(full).isFile()) {
return Response.json({ error: "Arquivo não encontrado ou fora das pastas permitidas." }, { status: 404 });
}
const size = fs.statSync(full).size;
const type = TYPES[path.extname(full).toLowerCase()] ?? "application/octet-stream";
const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get("range") ?? "");
if (range) {
const start = range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2]));
const end = range[1] && range[2] ? Math.min(Number(range[2]), size - 1) : size - 1;
if (start >= size || start > end) {
return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${size}` } });
}
const stream = Readable.toWeb(fs.createReadStream(full, { start, end })) as ReadableStream;
return new Response(stream, {
status: 206,
headers: { "Content-Type": type, "Content-Length": String(end - start + 1), "Content-Range": `bytes ${start}-${end}/${size}`, "Accept-Ranges": "bytes", "Cache-Control": "no-store" },
});
}
const stream = Readable.toWeb(fs.createReadStream(full)) as ReadableStream;
return new Response(stream, {
headers: { "Content-Type": type, "Content-Length": String(size), "Accept-Ranges": "bytes", "Cache-Control": "no-store" },
});
}
@@ -0,0 +1,11 @@
import { publisherStatus } from "@/lib/publisher";
export const dynamic = "force-dynamic";
/**
* Saúde do Publicador sem falhar: {online: true, browser: {found, kind, path}, worker, queue}
* ou {online: false, reason}.
*/
export async function GET() {
return Response.json(await publisherStatus(), { headers: { "Cache-Control": "no-store" } });
}
@@ -0,0 +1,19 @@
import { errorResponse, parseId, readJson } from "@/lib/http";
import { publishClip } from "@/lib/publishing";
type Ctx = { params: Promise<{ id: string }> };
/**
* POST /api/publishing/clips/[id] — "Publicar" no cartão de um corte aprovado do Clipador.
* Corpo (JSON): {accountId, platforms: ["youtube"|"tiktok"|"instagram"], timing?: "now"|"best_slot"}.
* → {jobs, skipped: [{platform, reason}], placed}. Não precisa da fonte ligada ao canal (jobs com origem manual).
*/
export async function POST(request: Request, ctx: Ctx) {
try {
const { id } = await ctx.params;
const body = await readJson<{ accountId: string; platforms: string[]; timing: string }>(request);
return Response.json(await publishClip(parseId(id), body));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,33 @@
import { errorResponse, isJsonRequest, parseId, readJson } from "@/lib/http";
import { approveJob, cancelPublishJob, markPublished, markRemoved, publishNow, retryJob } from "@/lib/publishing";
import type { PublishJob } from "@/lib/types";
type Ctx = { params: Promise<{ id: string; action: string }> };
type Body = { confirm?: unknown; url?: unknown };
const ACTIONS: Record<string, (id: number, body: Body) => PublishJob | Promise<PublishJob>> = {
approve: (id) => approveJob(id),
"publish-now": (id) => publishNow(id),
retry: (id, body) => retryJob(id, body),
cancel: (id) => cancelPublishJob(id),
"mark-published": (id, body) => markPublished(id, body),
removed: (id) => markRemoved(id),
};
/**
* POST /api/publishing/jobs/[id]/(approve|publish-now|retry|cancel|mark-published) → PublishJob. Corpo opcional (JSON):
* `retry` aceita {confirm: true} — exigido quando o job tem `mayBeLive` (senão 409 com a mensagem para confirmar);
* `mark-published` exige {url} — o link do vídeo na rede ("Já saiu: informar o link");
* `removed` — você apagou o vídeo na rede: libera a rede para publicar de novo ("Apaguei na rede").
*/
export async function POST(request: Request, ctx: Ctx) {
try {
const { id, action } = await ctx.params;
const handler = ACTIONS[action];
if (!handler) return Response.json({ error: "Ação desconhecida." }, { status: 404 });
const body = isJsonRequest(request) ? await readJson<{ confirm: boolean; url: string }>(request) : {};
return Response.json(await handler(parseId(id), body));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,24 @@
import { errorResponse, parseId, readJson } from "@/lib/http";
import { getJobView, updateJob } from "@/lib/publishing";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function GET(_request: Request, ctx: Ctx) {
try {
const job = getJobView(parseId((await ctx.params).id));
return job ? Response.json(job) : Response.json({ error: "Publicação não encontrada." }, { status: 404 });
} catch (error) {
return errorResponse(error);
}
}
/** Muda horário, título ou legenda: {scheduledAt?: ISO, title?, caption?} → PublishJob. */
export async function PATCH(request: Request, ctx: Ctx) {
try {
return Response.json(updateJob(parseId((await ctx.params).id), await readJson(request)));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,18 @@
import { errorResponse } from "@/lib/http";
import { listJobs } from "@/lib/publishing";
export const dynamic = "force-dynamic";
/** Fila de publicação: ?status=a,b&accountId=&sourceKind=clip|episode&sourceId=&limit= → PublishJob[]. */
export async function GET(request: Request) {
try {
const q = new URL(request.url).searchParams;
const status = (q.get("status") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
return Response.json(listJobs({
status, accountId: q.get("accountId") || undefined, sourceKind: q.get("sourceKind") || undefined,
sourceId: q.get("sourceId") || undefined, limit: q.get("limit") ? Number(q.get("limit")) : undefined,
}), { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,13 @@
import { errorResponse } from "@/lib/http";
import { publishingSummary } from "@/lib/publishing";
export const dynamic = "force-dynamic";
/** Contagens da fila por estado (menu e dashboard) e saúde do despachante. */
export async function GET() {
try {
return Response.json(publishingSummary(), { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
+22
View File
@@ -0,0 +1,22 @@
import { errorResponse, parseId } from "@/lib/http";
import { cancelRender, getRender } from "@/lib/renders";
/** Estado do render (o painel consulta a cada poucos segundos enquanto roda). */
export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const job = getRender(parseId((await ctx.params).id));
return job ? Response.json(job) : Response.json({ error: "Render não encontrado." }, { status: 404 });
} catch (error) {
return errorResponse(error);
}
}
/** Cancela o render em andamento. */
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
cancelRender(parseId((await ctx.params).id));
return Response.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,43 @@
import { errorResponse, readJson } from "@/lib/http";
import { deleteApp, getApps, putApp } from "@/lib/publisher";
import { mustPlatform } from "@/lib/publishing";
import { UserError } from "@/lib/stories";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ platform: string }> };
/** Estado do app de uma rede: {configured, clientId, redirectUri, notes} (o segredo nunca volta). */
export async function GET(_request: Request, ctx: Ctx) {
try {
const platform = mustPlatform((await ctx.params).platform);
return Response.json((await getApps())[platform], { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
/** Grava o app da rede no cofre do Publicador: {clientId, clientSecret} (no Instagram o secret é opcional). Resposta sem o segredo. */
export async function PUT(request: Request, ctx: Ctx) {
try {
const platform = mustPlatform((await ctx.params).platform);
const body = await readJson<{ clientId: string; clientSecret: string }>(request);
const clientId = typeof body.clientId === "string" ? body.clientId.trim() : "";
const clientSecret = typeof body.clientSecret === "string" ? body.clientSecret.trim() : "";
if (!clientId || clientId.length > 512) throw new UserError("Preencha o Client ID.");
if (clientSecret.length > 1024) throw new UserError("Client Secret longo demais.");
if (!clientSecret && platform !== "instagram") throw new UserError("Preencha o Client Secret.");
return Response.json(await putApp(platform, { clientId, clientSecret: clientSecret || undefined }));
} catch (error) {
return errorResponse(error);
}
}
/** Apaga o app da rede do cofre do Publicador. */
export async function DELETE(_request: Request, ctx: Ctx) {
try {
return Response.json(await deleteApp(mustPlatform((await ctx.params).platform)));
} catch (error) {
return errorResponse(error);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { errorResponse } from "@/lib/http";
import { getApps } from "@/lib/publisher";
export const dynamic = "force-dynamic";
/** Apps das três redes no Publicador: {youtube, tiktok, instagram} com {configured, clientId, redirectUri, notes}. Sem segredo. */
export async function GET() {
try {
return Response.json(await getApps(), { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
+22
View File
@@ -0,0 +1,22 @@
import { errorResponse, readJson } from "@/lib/http";
import { getSettings, updateSettings } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Configurações gerais: {publishingPaused, slots: {youtube: ["12:00", ...], ...}, timezone}. */
export async function GET() {
try {
return Response.json(getSettings(), { headers: { "Cache-Control": "no-store" } });
} catch (error) {
return errorResponse(error);
}
}
/** Atualiza só o que vier: {publishingPaused?, slots?: {<rede>?: ["HH:MM", ...]}, timezone?}. */
export async function PUT(request: Request) {
try {
return Response.json(updateSettings(await readJson(request)));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,10 @@
import { storyFlow } from "@/lib/flow";
export const dynamic = "force-dynamic";
/** Árvore da história (nós e arestas) para o editor de fluxo. */
export async function GET(_request: Request, ctx: { params: Promise<{ storyId: string }> }) {
const flow = storyFlow((await ctx.params).storyId);
if (!flow) return Response.json({ error: "História não encontrada." }, { status: 404 });
return Response.json(flow, { headers: { "Cache-Control": "no-store" } });
}
+30
View File
@@ -0,0 +1,30 @@
// Criar história com IA pela API (o mesmo que o formulário "Nova história com IA"): cria a história
// e o primeiro episódio e põe o agente para escrever. { text, title?, kind?, provider?, model? }
// → { storyId, episodeId, runId }. Útil para automação (o coordenador dispara o agente do painel).
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
import { errorResponse } from "@/lib/http";
import { slugify } from "@/lib/paths";
import { UserError, createEpisode, createStory, getStory, provisionalTitle } from "@/lib/stories";
import { STORY_KINDS, type Provider, type StoryKind } from "@/lib/types";
export async function POST(request: Request) {
try {
const body = (await request.json()) as { text?: unknown; title?: unknown; kind?: unknown; provider?: unknown; model?: unknown };
const text = String(body.text ?? "").trim();
if (text.length < 20) throw new UserError("Escreva pelo menos uma ou duas frases (mínimo 20 caracteres).");
if (text.length > 20_000) throw new UserError("Texto longo demais (máx. 20 mil caracteres).");
const kind = (STORY_KINDS as string[]).includes(String(body.kind)) ? (body.kind as StoryKind) : "documentary";
const title = String(body.title ?? "").trim() || provisionalTitle(text);
const base = slugify(title) || "historia";
let id = base;
for (let n = 2; getStory(id); n++) id = `${base}-${n}`;
const story = createStory({ title, id, logline: "", kind, branchCount: 2 });
const ep = createEpisode(story.id, { title: kind === "documentary" ? "" : "Abertura" });
const provider: Provider = body.provider === "claude" || body.provider === "codex" ? body.provider : defaultProviderFor("story");
const model = String(body.model ?? "") || defaultModelFor("story", provider);
const run = startRun({ provider, model, kind: "story", request: text, storyId: story.id, episodeId: ep.id });
return Response.json({ storyId: story.id, episodeId: ep.id, runId: run.id });
} catch (error) {
return errorResponse(error);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { errorResponse } from "@/lib/http";
import { updateAzure } from "@/lib/voice";
/** Grava região e chave do Azure Speech no voice/.env (o pnpm dev reinicia o serviço sozinho). A chave não volta. */
export async function PUT(request: Request) {
try {
updateAzure(await request.json());
return Response.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { errorResponse } from "@/lib/http";
import { addCloneVoice } from "@/lib/voice";
/** Clona uma voz a partir de uma gravação (10–30 s), com consentimento registrado. */
export async function POST(request: Request) {
try {
return Response.json(await addCloneVoice(await request.formData()));
} catch (error) {
return errorResponse(error);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { errorResponse } from "@/lib/http";
import { updateSettings } from "@/lib/voice";
/** Grava dispositivo, modelo do Whisper e RVC no voice/.env (o pnpm dev reinicia o serviço sozinho). */
export async function PUT(request: Request) {
try {
const result = updateSettings(await request.json());
return Response.json({ ok: true, ...result });
} catch (error) {
return errorResponse(error);
}
}
+8
View File
@@ -0,0 +1,8 @@
import { getStatus } from "@/lib/voice";
export const dynamic = "force-dynamic";
/** Estado do serviço de voz + vozes + configurações (nunca falha: offline vira `online: false`). */
export async function GET() {
return Response.json(await getStatus(), { headers: { "Cache-Control": "no-store" } });
}
@@ -0,0 +1,11 @@
import { errorResponse } from "@/lib/http";
import { synthesize } from "@/lib/voice";
/** Gera a fala (OGG/Opus) para ouvir no painel. */
export async function POST(request: Request) {
try {
return await synthesize(await request.json());
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,14 @@
import { errorResponse } from "@/lib/http";
import { transcribe } from "@/lib/voice";
/** Transcreve um áudio enviado (texto, frases ou palavras com tempo) e devolve o .srt quando há tempos. */
export async function POST(request: Request) {
try {
const form = await request.formData();
const file = form.get("file");
if (!(file instanceof File)) return Response.json({ error: "Envie um arquivo de áudio." }, { status: 400 });
return Response.json(await transcribe(file, String(form.get("language") ?? "pt-BR"), String(form.get("detail") ?? "segments")));
} catch (error) {
return errorResponse(error);
}
}
@@ -0,0 +1,12 @@
import { errorResponse } from "@/lib/http";
import { removeUserVoice } from "@/lib/voice";
/** Remove uma voz de personagem adicionada pelo painel (as vozes base não saem). */
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
try {
await removeUserVoice((await params).id);
return Response.json({ ok: true });
} catch (error) {
return errorResponse(error);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { errorResponse } from "@/lib/http";
import { addUserVoice } from "@/lib/voice";
/** Adiciona uma voz de personagem: voz base + modelo RVC (.pth e .index opcional). */
export async function POST(request: Request) {
try {
return Response.json(await addUserVoice(await request.formData()));
} catch (error) {
return errorResponse(error);
}
}
+41
View File
@@ -0,0 +1,41 @@
import { connection } from "next/server";
import { AssetTable } from "@/components/asset-table";
import { AssetUpload } from "@/components/asset-upload";
import { FilmIcon, LibraryIcon, UploadIcon } from "@/components/icons";
import { Card, Meta, PageHeader, SectionHeader } from "@/components/ui";
import { ASSET_KINDS, listAssets } from "@/lib/assets";
import { listStories } from "@/lib/stories";
export const metadata = { title: "Assets" };
export default async function AssetsPage() {
await connection();
const stories = listStories();
const library = listAssets({ scope: "library" });
const perStory = listAssets({ scope: "story" });
return (
<>
<PageHeader eyebrow="Recursos" title="Assets"
description="Modelos, texturas, fundos e áudios. A biblioteca serve a qualquer história; os exclusivos ficam na pasta da história e podem ser promovidos."
meta={<>
<Meta icon={<LibraryIcon size={15} />}>{library.length} na biblioteca · <code>assets/library/</code></Meta>
<Meta icon={<FilmIcon size={15} />}>{perStory.length} em histórias · <code>stories/&lt;história&gt;/assets/</code></Meta>
</>} />
<section aria-labelledby="biblioteca" className="grid gap-5">
<SectionHeader id="biblioteca" eyebrow="Compartilhada" title="Biblioteca" />
<AssetTable assets={library} />
</section>
<section aria-labelledby="por-historia" className="grid gap-5">
<SectionHeader id="por-historia" eyebrow="Exclusivos" title="Assets das histórias"
description="Cada asset tem um asset.json com licença, origem e metadados; escala, orientação e capacidades ficam “a definir” até o asset ser testado num render." />
<AssetTable assets={perStory} showStory />
</section>
<Card eyebrow={<><UploadIcon size={13} />Envio</>} title="Enviar asset" description="O arquivo vai para a biblioteca ou para a pasta da história escolhida.">
<AssetUpload stories={stories.map((s) => ({ id: s.id, title: s.title }))} kinds={ASSET_KINDS} />
</Card>
</>
);
}
@@ -0,0 +1,15 @@
import { notFound } from "next/navigation";
import { ClipEditor } from "@/components/clip-editor";
export const metadata = { title: "Editor de corte" };
/**
* Editor de cortes do Clipador: prévia 9:16, transcrição clicável, timeline com forma de onda e chat, legenda
* animada, gancho, zoom, narração e exportação. Tudo é buscado no navegador (/api/clipper/clips/<id>/edit…).
*/
export default async function ClipEditPage({ params }: { params: Promise<{ clipId: string }> }) {
const { clipId } = await params;
const id = Number(clipId);
if (!Number.isInteger(id) || id <= 0) notFound();
return <ClipEditor clipId={id} />;
}
+39
View File
@@ -0,0 +1,39 @@
import { connection } from "next/server";
import type { ChannelAccounts } from "@/components/clipper-channels";
import { ClipperStudio } from "@/components/clipper-studio";
import Link from "next/link";
import { BroadcastIcon, PublishIcon, ScissorsIcon, SparkIcon } from "@/components/icons";
import { Meta, PageHeader } from "@/components/ui";
import { listAccounts } from "@/lib/accounts";
export const metadata = { title: "Clipador" };
/**
* Clipador: cortes automáticos de lives (Twitch, YouTube, Kick). O estado muda a cada segundo
* (gravação, IA, render), então a página busca /api/clipper/* no navegador e consulta de novo
* enquanto houver trabalho. Do servidor vem só em quais canais de publicação cada fonte está ligada.
*/
export default async function ClipperPage() {
await connection();
const channelAccounts: ChannelAccounts = {};
for (const account of listAccounts()) {
for (const link of account.channels) {
if (link.status !== "active") continue;
(channelAccounts[link.channel_id] ??= []).push({ id: account.id, name: account.name });
}
}
return (
<>
<PageHeader eyebrow="Cortes de live" title="Clipador"
description="Grava lives de terceiros, acha os picos de reação do chat, pede o veredito da IA e entrega cortes verticais com legenda, prontos para você aprovar."
meta={<>
<Meta icon={<BroadcastIcon size={15} />}>Twitch, YouTube e Kick</Meta>
<Meta icon={<SparkIcon size={15} />}>Juiz: Codex ou Claude pela CLI</Meta>
<Meta icon={<ScissorsIcon size={15} />}>MP4 1080×1920 com legenda</Meta>
<Meta icon={<PublishIcon size={15} />}>Cortes aprovados saem nas redes dos <Link href="/accounts" className="text-fg-muted underline underline-offset-2 hover:text-fg">canais de publicação</Link></Meta>
</>} />
<ClipperStudio channelAccounts={channelAccounts} />
</>
);
}
+181
View File
@@ -0,0 +1,181 @@
import { connection } from "next/server";
import { DashboardFilter, MetricsSyncControls, SimulatedControls } from "@/components/dashboard-controls";
import {
AlertIcon, ChartIcon, CheckIcon, EyeIcon, FilmIcon, HeartIcon, LinkIcon, PlayIcon, SendIcon, TrendDownIcon, TrophyIcon, UsersIcon,
} from "@/components/icons";
import { DailyViewsChart, Kpi, MetricTable, VideoTable, type MetricRow } from "@/components/metrics-view";
import { PLATFORM_META } from "@/components/platforms";
import { Card, LinkButton, PageHeader, cx, formatCompact, formatInteger, formatPercent } from "@/components/ui";
import { listAccounts } from "@/lib/accounts";
import { dashboard, type Dashboard } from "@/lib/metrics";
import { getSettings } from "@/lib/settings";
export const metadata = { title: "Dashboard" };
/** Número do episódio a partir da chave de arquivo (ep02, ep02-b → 2), para o link da página do episódio. */
function episodeNumber(fileKey: string): number | null {
const m = /^ep(\d+)/i.exec(fileKey);
return m ? Number(m[1]) : null;
}
export default async function DashboardPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
await connection();
const sp = await searchParams;
const accounts = listAccounts();
const accountId = sp.account && accounts.some((a) => a.id === sp.account) ? sp.account : "";
const data = dashboard({ accountId: accountId || undefined });
const empty = data.totals.publications === 0;
const accountName = accounts.find((a) => a.id === accountId)?.name;
return (
<>
<PageHeader eyebrow="Desempenho" title="Dashboard"
description={accountName
? <>O que funciona e o que não no canal <strong className="font-semibold text-fg">{accountName}</strong>.</>
: "O que funciona e o que não: views de cada vídeo, engajamento por rede, canal de publicação, história e episódio."}
meta={data.simulated ? <SimulatedSeal /> : undefined}
actions={accounts.length > 0 && <DashboardFilter accounts={accounts.map((a) => ({ id: a.id, name: a.name }))} value={accountId} />} />
{data.simulated && (
<div role="note" className="flex flex-wrap items-center justify-between gap-4 rounded-card border border-warning/35 bg-warning-soft px-5 py-4">
<p className="flex max-w-[75ch] items-start gap-3 text-sm text-fg">
<AlertIcon size={18} className="mt-0.5 text-warning" />
<span><strong className="font-semibold text-warning">Dados simulados.</strong> Parte dos números abaixo é de exemplo, gerada no painel (não veio das redes). Apague os simulados antes de tomar decisões com eles.</span>
</p>
<SimulatedControls simulated />
</div>
)}
{!empty && (
<MetricsSyncControls syncs={data.syncs} accountId={accountId || undefined} everyHours={getSettings().metricsEveryHours}
showAccount={!accountId && accounts.length > 1} />
)}
{empty ? <EmptyDashboard data={data} filtered={!!accountId} /> : <DashboardBody data={data} />}
</>
);
}
function SimulatedSeal() {
return (
<span className="inline-flex h-7 items-center gap-2 rounded-full border border-warning/50 bg-warning-soft px-3 text-xs font-bold tracking-[0.08em] text-warning uppercase">
<AlertIcon size={14} />Dados simulados
</span>
);
}
function DashboardBody({ data }: { data: Dashboard }) {
const t = data.totals;
const best = data.byEpisode.slice(0, Math.min(5, Math.ceil(data.byEpisode.length / 2)));
const worst = data.byEpisode.slice(best.length).slice(-5).reverse();
const episodeRow = (e: Dashboard["byEpisode"][number]): MetricRow => {
const n = episodeNumber(e.fileKey);
return {
key: String(e.episodeId), totals: e,
label: <><span className="font-mono text-xs text-fg-subtle">{e.fileKey.toUpperCase()}</span> {e.title || "Sem título"}</>,
sub: e.storyTitle,
href: n ? `/stories/${e.storyId}/episodes/${n}` : `/stories/${e.storyId}`,
};
};
return (
<>
<section aria-labelledby="kpis">
<h2 id="kpis" className="sr-only">Totais</h2>
<dl className="grid grid-cols-2 gap-3 md:grid-cols-3 2xl:grid-cols-6">
<Kpi emphasis icon={<EyeIcon size={14} />} label="Views" value={formatCompact(t.views)} hint={`${formatInteger(t.views)} no total`} />
<Kpi icon={<HeartIcon size={14} />} label="Engajamento" value={formatPercent(t.engagementRate)}
hint={`${formatCompact(t.likes + t.comments + t.shares + t.saves)} interações`} />
<Kpi icon={<PlayIcon size={14} />} label="Conclusão" value={formatPercent(t.completionRate)} hint="assistiram até o fim" />
<Kpi icon={<SendIcon size={14} />} label="Publicações" value={formatInteger(t.publications)} hint={`${data.byVideo.length} vídeo${data.byVideo.length === 1 ? "" : "s"}`} />
<Kpi icon={<UsersIcon size={14} />} label="Canais" value={formatInteger(data.counts.accounts)} hint={`${data.counts.networks} redes vinculadas`} />
<Kpi icon={<FilmIcon size={14} />} label="Histórias ativas" value={formatInteger(data.counts.activeStories)} hint={`de ${data.counts.stories}`} />
</dl>
</section>
<Card eyebrow={<><EyeIcon size={13} />Views</>} title="Views de cada vídeo"
description="Somadas as redes em que o vídeo saiu. Clique no número de uma rede para abrir o post.">
<VideoTable videos={data.byVideo} />
</Card>
<div className="grid grid-cols-1 items-start gap-6 2xl:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
<Card eyebrow={<><ChartIcon size={13} />Alcance</>} title="Views por dia" description="Pelo dia da publicação (últimos 30 dias com dado).">
<DailyViewsChart daily={data.daily} />
</Card>
<Card title="Por rede" description="Onde as histórias rendem mais.">
<MetricTable caption="Desempenho por rede" firstColumn="Rede"
rows={data.byPlatform.slice().sort((a, b) => b.views - a.views).map((p) => {
const meta = PLATFORM_META[p.platform];
const Icon = meta.icon;
return { key: p.platform, totals: p, label: <span className="inline-flex items-center gap-2"><Icon size={15} className="text-fg-subtle" />{meta.label}</span> };
})} />
</Card>
</div>
{data.byEpisode.length > 0 && <div className="grid grid-cols-1 items-start gap-6 2xl:grid-cols-2">
<Card title="Melhores episódios" eyebrow={<><TrophyIcon size={13} />Maior engajamento</>}
description="O que repetir: tom, gancho e escolhas desses episódios.">
<MetricTable caption="Melhores episódios por engajamento" firstColumn="Episódio" rows={best.map(episodeRow)} />
</Card>
<Card title="Piores episódios" eyebrow={<span className="inline-flex items-center gap-2 text-danger"><TrendDownIcon size={13} />Menor engajamento</span>}
description="O que rever antes do próximo." >
<MetricTable caption="Piores episódios por engajamento" firstColumn="Episódio" rows={worst.map(episodeRow)}
empty="Poucos episódios publicados para comparar." />
</Card>
</div>}
<div className="grid grid-cols-1 items-start gap-6 2xl:grid-cols-2">
<Card title="Por canal de publicação">
<MetricTable caption="Desempenho por canal de publicação" firstColumn="Canal"
rows={data.byAccount.map((a) => ({ key: a.accountId, totals: a, label: a.name, href: `/accounts?account=${encodeURIComponent(a.accountId)}` }))} />
</Card>
{data.byStory.length > 0 && <Card title="Por história">
<MetricTable caption="Desempenho por história" firstColumn="História"
rows={data.byStory.map((s) => ({ key: s.storyId, totals: s, label: s.title, href: `/stories/${s.storyId}` }))} />
</Card>}
</div>
</>
);
}
/** Sem publicações: diz o que falta, passo a passo, e oferece gerar dados simulados. */
function EmptyDashboard({ data, filtered }: { data: Dashboard; filtered: boolean }) {
const steps = [
{ done: data.counts.accounts > 0, label: "Crie um canal de publicação", hint: "Em Canais de publicação, “Novo canal”." },
{ done: data.counts.networks > 0, label: "Vincule uma rede", hint: "Conecte TikTok, Instagram ou YouTube." },
{ done: data.counts.activeStories > 0, label: "Vincule uma história", hint: "Com pelo menos um episódio." },
];
const ready = steps.every((s) => s.done);
return (
<section aria-labelledby="sem-dados" className="grid gap-6 rounded-card border border-dashed border-line-strong bg-sunken/30 px-6 py-10 md:px-10">
<div className="grid max-w-[65ch] gap-2">
<span className="grid size-12 place-items-center rounded-2xl border border-line-strong bg-raised text-accent"><ChartIcon /></span>
<h2 id="sem-dados" className="mt-2 font-display text-title text-fg">{filtered ? "Este canal ainda não tem publicações" : "Ainda não há publicações para medir"}</h2>
<p className="text-sm leading-relaxed text-fg-muted">
Quando um vídeo sai numa rede, o painel lê sozinho as views, curtidas e comentários dele e mostra aqui. Enquanto nada foi
publicado, dá para gerar dados simulados e ver como o dashboard aponta o que funciona e o que não. Os simulados ficam marcados e saem com um clique.
</p>
</div>
<ol className="grid gap-3 md:grid-cols-3">
{steps.map((s, i) => (
<li key={s.label} className={cx("flex items-start gap-3 rounded-control border px-4 py-3",
s.done ? "border-success/25 bg-success-soft/50" : "border-line bg-surface")}>
<span className={cx("grid size-6 shrink-0 place-items-center rounded-full text-xs font-bold",
s.done ? "bg-success text-sunken" : "bg-raised text-fg-muted")}>
{s.done ? <CheckIcon size={14} /> : i + 1}
</span>
<span className="grid gap-0.5">
<span className="text-sm font-medium text-fg">{s.label}<span className="sr-only">{s.done ? " (feito)" : " (pendente)"}</span></span>
<span className="text-xs text-fg-subtle">{s.hint}</span>
</span>
</li>
))}
</ol>
<div className="flex flex-wrap items-start gap-3">
<LinkButton href="/accounts"><LinkIcon size={16} />Abrir Canais de publicação</LinkButton>
<SimulatedControls simulated={data.simulated} />
</div>
{!ready && <p className="text-xs text-fg-subtle">Sem os três passos, “Gerar dados simulados” não tem o que publicar.</p>}
</section>
);
}
+383
View File
@@ -0,0 +1,383 @@
/* A camada do @xyflow/react (editor de fluxo) fica ABAIXO das do Tailwind: utilitários e tokens vencem. */
@layer xyflow, theme, base, components, utilities;
@import "tailwindcss";
/*
* Design system do painel CenaForge — "estúdio à noite".
* Tema escuro por padrão (uso prolongado, vídeo em destaque). As páginas usam estes tokens
* (bg-surface, text-fg-muted, border-line, bg-accent...) e nunca cores soltas.
* Contrastes contra bg-surface (#111114): fg 17:1, fg-muted 8:1, fg-subtle 5,2:1, accent 7:1 (WCAG AA).
*/
@theme {
/* Superfícies, da mais funda para a mais alta */
--color-sunken: #060608;
--color-canvas: #0a0a0c;
--color-surface: #111114;
--color-raised: #18181d;
--color-overlay: #222229;
/* Bordas */
--color-line: #1f1f26;
--color-line-strong: #2f2f39;
/* Texto */
--color-fg: #f4f4f6;
--color-fg-muted: #a9a9b4;
--color-fg-subtle: #858591;
/* Destaque da marca: brasa da forja (laranja) com a chama (rosa) para o que é IA */
--color-accent: #ff7a1a;
--color-accent-hover: #ff9142;
--color-accent-fg: #1c0a00;
--color-accent-soft: #2a1407;
--color-flame: #ff4d7d;
--color-glow: #ffb547;
/* Opção B da votação (A usa o destaque) */
--color-option-b: #2dd4e8;
--color-option-b-soft: #062a31;
/* Opções C e D (histórias com 3 ou 4 vertentes por decisão) */
--color-option-c: #b19bff;
--color-option-c-soft: #1f1a3d;
--color-option-d: #a3e05a;
--color-option-d-soft: #18280b;
/* Estados */
--color-success: #3ddc84;
--color-success-soft: #0b2a1a;
--color-warning: #fbbf24;
--color-warning-soft: #2e2208;
--color-danger: #ff6b6b;
--color-danger-hover: #ff9a9a;
--color-danger-soft: #34121a;
--color-info: #5cbcff;
--color-info-soft: #0b2236;
--color-violet: #b19bff;
--color-violet-soft: #1f1a3d;
/* Editor de cortes (/clipper/edit): tema de editor de vídeo, neutro e denso. Valores do tema "darkest" do
FilmCraft (MIT/Apache-2.0), que por sua vez mede o padrão dos editores profissionais: fundo preto entre os
painéis, painel cinza-chumbo, texto cinza claro, azul só para foco, tempo e valores editáveis. */
--color-nle-app: #000000;
--color-nle-panel: #1d1d1d;
--color-nle-well: #0e0e0e;
--color-nle-row: #232323;
--color-nle-hover: #2c2c2c;
--color-nle-pressed: #3a3a3a;
--color-nle-line: #303030;
--color-nle-text: #d1d1d1;
--color-nle-dim: #b0b0b0;
--color-nle-faint: #6e6e6e;
--color-nle-accent: #2f6bdf;
--color-nle-hot: #4096f3;
--color-nle-focus: #5794ec;
--color-nle-danger: #dc513d;
/* Raios */
--radius-control: 0.625rem;
--radius-card: 1rem;
--radius-panel: 1.375rem;
/* Sombras */
--shadow-card: 0 1px 0 0 rgb(255 255 255 / 0.04) inset, 0 1px 2px rgb(0 0 0 / 0.4), 0 12px 32px -16px rgb(0 0 0 / 0.7);
--shadow-pop: 0 24px 64px -12px rgb(0 0 0 / 0.85), 0 0 0 1px rgb(255 255 255 / 0.05);
--shadow-glow: 0 0 0 1px rgb(255 122 26 / 0.35), 0 10px 30px -10px rgb(255 122 26 / 0.55);
/* Escala tipográfica: display (título da página), title (seção), lead (texto de abertura) */
--text-display: 2.75rem;
--text-display--line-height: 1.05;
--text-display--letter-spacing: -0.035em;
--text-display--font-weight: 650;
--text-title: 1.25rem;
--text-title--line-height: 1.3;
--text-title--letter-spacing: -0.015em;
--text-title--font-weight: 600;
--text-lead: 1.0625rem;
--text-lead--line-height: 1.6;
--text-eyebrow: 0.6875rem;
--text-eyebrow--line-height: 1;
--text-eyebrow--letter-spacing: 0.16em;
/* Fontes locais (o painel funciona offline). Segoe UI Variable tem cortes Display e Text no Windows 11. */
--font-sans: "Segoe UI Variable Text", "Segoe UI Variable", ui-sans-serif, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--font-display: "Segoe UI Variable Display", "Segoe UI Variable", ui-sans-serif, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--font-mono: ui-monospace, "Cascadia Code", "Cascadia Mono", "SF Mono", Consolas, "Liberation Mono", monospace;
/* Largura da barra lateral */
--spacing-rail: 4.5rem;
--spacing-rail-open: 15.5rem;
}
@layer base {
:root {
color-scheme: dark;
}
html {
scrollbar-color: var(--color-line-strong) transparent;
scrollbar-gutter: stable;
}
body {
background-color: var(--color-canvas);
/* Luz quente vinda do alto, como um set iluminado: dá profundidade sem competir com o conteúdo. */
background-image:
radial-gradient(60rem 28rem at 70% -12rem, rgb(255 122 26 / 0.07), transparent 70%),
radial-gradient(40rem 24rem at 15% -10rem, rgb(255 77 125 / 0.04), transparent 70%);
background-repeat: no-repeat;
color: var(--color-fg);
font-family: var(--font-sans);
font-feature-settings: "ss01", "cv11";
}
h1, h2, h3 {
font-family: var(--font-display);
text-wrap: balance;
}
p {
text-wrap: pretty;
}
::selection {
background: var(--color-accent);
color: var(--color-accent-fg);
}
/* Foco visível em todo elemento interativo */
:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
code {
font-family: var(--font-mono);
font-size: 0.85em;
background: var(--color-raised);
border: 1px solid var(--color-line);
border-radius: 0.375rem;
padding: 0.05em 0.35em;
color: var(--color-fg);
}
pre code {
background: none;
border: 0;
padding: 0;
}
/* Select com seta própria (a nativa some no tema escuro do Windows) */
select:not([multiple]) {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a9a9b4' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 0.7rem center;
background-size: 1rem;
padding-right: 2.25rem;
}
select option {
background: var(--color-raised);
color: var(--color-fg);
}
}
/*
* Barra lateral: recolhida (só ícones) e expandida POR CIMA do conteúdo ao passar o mouse ou ao
* focar pelo teclado (:focus-visible — um clique do mouse não a deixa presa aberta).
*/
@layer components {
.rail {
width: var(--spacing-rail);
background-color: rgb(10 10 12 / 0.92);
backdrop-filter: blur(20px);
transition: width 220ms cubic-bezier(0.2, 0.8, 0.2, 1), box-shadow 220ms ease, background-color 220ms ease;
}
.rail:hover,
.rail:has(:focus-visible) {
width: var(--spacing-rail-open);
background-color: var(--color-surface);
box-shadow: 24px 0 64px -16px rgb(0 0 0 / 0.85), 1px 0 0 0 var(--color-line-strong);
}
/* Pequena intenção antes de abrir: passar o mouse de raspão não abre a barra. */
.rail:hover {
transition-delay: 90ms;
}
.rail-label {
opacity: 0;
transform: translateX(-6px);
transition: opacity 160ms ease, transform 200ms ease;
}
.rail:hover .rail-label,
.rail:has(:focus-visible) .rail-label {
opacity: 1;
transform: none;
transition-delay: 110ms;
}
/* Texto com o degradê da chama, para o que é feito pela IA */
.text-flame {
background: linear-gradient(95deg, var(--color-glow), var(--color-accent) 45%, var(--color-flame));
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
/* Borda em degradê para o painel de destaque */
.flame-frame {
position: relative;
isolation: isolate;
}
.flame-frame::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
padding: 1px;
border-radius: inherit;
background: linear-gradient(135deg, rgb(255 181 71 / 0.7), rgb(255 122 26 / 0.35) 35%, rgb(255 77 125 / 0.25) 70%, rgb(255 255 255 / 0.04));
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
}
/*
* Editor de fluxo (@xyflow/react): as variáveis da biblioteca apontam para os tokens do tema,
* para o canvas, os controles e o minimapa conversarem com o resto do painel.
*/
.react-flow.cf-flow {
--xy-background-color: transparent;
--xy-background-pattern-dots-color: var(--color-line-strong);
--xy-edge-stroke: var(--color-line-strong);
--xy-minimap-background-color: var(--color-sunken);
--xy-minimap-mask-background-color: rgb(10 10 12 / 0.7);
--xy-minimap-mask-stroke-color: var(--color-line-strong);
--xy-minimap-node-background-color: var(--color-overlay);
--xy-controls-button-background-color: var(--color-raised);
--xy-controls-button-background-color-hover: var(--color-overlay);
--xy-controls-button-color: var(--color-fg-muted);
--xy-controls-button-color-hover: var(--color-fg);
--xy-controls-button-border-color: var(--color-line-strong);
--xy-controls-box-shadow: 0 1px 2px rgb(0 0 0 / 0.5);
--xy-attribution-background-color: transparent;
--xy-node-border-radius: var(--radius-card);
font-family: var(--font-sans);
}
.cf-flow .react-flow__controls {
overflow: hidden;
border: 1px solid var(--color-line-strong);
border-radius: var(--radius-control);
}
.cf-flow .react-flow__controls-button {
width: 30px;
height: 30px;
}
.cf-flow .react-flow__controls-button:focus-visible,
.cf-flow .react-flow__minimap:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: -2px;
}
.cf-flow .react-flow__minimap {
overflow: hidden;
border: 1px solid var(--color-line-strong);
border-radius: var(--radius-control);
}
/* Nós customizados: sem moldura da biblioteca (o cartão é nosso) e alças invisíveis (não há ligação manual). */
.cf-flow .react-flow__node {
border: 0;
background: transparent;
padding: 0;
box-shadow: none;
}
.cf-flow .react-flow__handle {
opacity: 0;
pointer-events: none;
}
.cf-flow .react-flow__attribution {
color: var(--color-fg-subtle);
}
.cf-flow .react-flow__attribution a {
color: inherit;
}
/* ---------- Editor de cortes ---------- */
.nle {
font-size: 12px;
line-height: 1.35;
color: var(--color-nle-text);
scrollbar-color: #4b4b4b transparent;
scrollbar-width: thin;
}
.nle ::selection {
background: rgb(47 107 223 / 0.55);
}
/* Controle deslizante fino, no padrão dos painéis de efeito. */
.nle input[type="range"] {
appearance: none;
height: 14px;
background: transparent;
cursor: pointer;
}
.nle input[type="range"]::-webkit-slider-runnable-track {
height: 2px;
border-radius: 1px;
background: #4a4a4a;
}
.nle input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 11px;
height: 11px;
margin-top: -4.5px;
border-radius: 50%;
border: 1.5px solid #d1d1d1;
background: var(--color-nle-panel);
}
.nle input[type="range"]:hover::-webkit-slider-thumb {
background: #d1d1d1;
}
.nle input[type="range"]::-moz-range-track {
height: 2px;
background: #4a4a4a;
}
.nle input[type="range"]::-moz-range-thumb {
width: 9px;
height: 9px;
border-radius: 50%;
border: 1.5px solid #d1d1d1;
background: var(--color-nle-panel);
}
.nle input[type="range"]:focus-visible {
outline: 1px solid var(--color-nle-focus);
outline-offset: 2px;
}
.nle dialog::backdrop {
background: rgb(0 0 0 / 0.72);
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
transition-delay: 0ms !important;
scroll-behavior: auto !important;
}
}
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
<defs>
<linearGradient id="g" x1="4" y1="2" x2="28" y2="30" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#ffb547"/>
<stop offset="0.5" stop-color="#ff7a1a"/>
<stop offset="1" stop-color="#ff4d7d"/>
</linearGradient>
</defs>
<rect width="32" height="32" rx="9" fill="url(#g)"/>
<rect x="8" y="4" width="16" height="24" rx="4" fill="#1c0a00"/>
<path d="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" fill="url(#g)"/>
</svg>

After

Width:  |  Height:  |  Size: 612 B

+35
View File
@@ -0,0 +1,35 @@
import type { Metadata, Viewport } from "next";
import { ConfirmHost } from "@/components/confirm-dialog";
import { Sidebar } from "@/components/sidebar-nav";
import "./globals.css";
export const metadata: Metadata = {
title: { default: "CenaForge", template: "%s · CenaForge" },
description: "Painel local de histórias, episódios, assets e agentes.",
};
export const viewport: Viewport = {
themeColor: "#0a0a0c",
colorScheme: "dark",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="pt-BR" className="h-full antialiased">
<body className="min-h-full">
<a href="#conteudo"
className="sr-only z-[60] rounded-control bg-accent px-4 py-2 font-semibold text-accent-fg focus:not-sr-only focus:fixed focus:top-3 focus:left-24">
Pular para o conteúdo
</a>
<Sidebar />
{/* O conteúdo reserva só a largura da barra recolhida (a expandida passa por cima) e usa todo o
resto da tela, com gutters de 16/24/32 px. Medida de leitura (~75ch) só em textos longos. */}
<main id="conteudo" className="min-h-screen pl-rail">
<div className="grid w-full min-w-0 grid-cols-1 gap-12 px-4 pt-6 pb-20 md:px-6 md:pt-8 xl:px-8 xl:pt-10 max-md:gap-9">{children}</div>
</main>
{/* Modal de confirmação/aviso único do painel (askConfirm/showAlert). */}
<ConfirmHost />
</body>
</html>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { ArrowLeftIcon } from "@/components/icons";
import { Eyebrow, LinkButton } from "@/components/ui";
export default function NotFound() {
return (
<section className="grid min-h-[70vh] place-items-center">
<div className="grid max-w-lg justify-items-center gap-5 text-center">
<span aria-hidden="true" className="font-display text-[8rem] leading-none font-bold tracking-[-0.06em] text-flame opacity-90">404</span>
<Eyebrow tone="muted">Corta!</Eyebrow>
<h1 className="text-display text-fg">Essa cena não existe</h1>
<p className="text-lead text-fg-muted">A história ou o episódio pode ter outro identificador. Volte à lista e abra pelo painel.</p>
<LinkButton variant="primary" size="lg" href="/" className="mt-2"><ArrowLeftIcon size={18} />Voltar às histórias</LinkButton>
</div>
</section>
);
}
+109
View File
@@ -0,0 +1,109 @@
import Link from "next/link";
import { connection } from "next/server";
import { DeleteStoryButton } from "@/components/delete-story-button";
import { CreateStoryForm } from "@/components/forms";
import { ArrowRightIcon, ChevronDownIcon, FilmIcon, PenIcon } from "@/components/icons";
import { StoryComposer } from "@/components/story-composer";
import { storyFormatLabel, unitTerms } from "@/components/story-formats";
import {
Badge, EmptyState, PageHeader, SectionHeader, StagePipeline, Stat, episodeCode, formatRelative, hueOf,
} from "@/components/ui";
import { defaultProviderFor, models, providers } from "@/lib/agents";
import { listEpisodes, listStories } from "@/lib/stories";
import type { EpisodeView, Story } from "@/lib/types";
export default async function HomePage() {
await connection();
const stories = listStories().map((s) => ({ story: s, episodes: listEpisodes(s.id) }));
const totalEpisodes = stories.reduce((sum, s) => sum + s.episodes.length, 0);
const rendered = stories.reduce((sum, s) => sum + s.episodes.filter((e) => e.stage === "renderizado" || e.stage === "decidido").length, 0);
const openVotes = stories.reduce((sum, s) => sum + (s.story.kind === "interactive" ? s.episodes.filter((e) => e.stage === "renderizado").length : 0), 0);
const available = Object.fromEntries(providers().map((p) => [p.id, p.available])) as Record<"claude" | "codex", boolean>;
return (
<>
<PageHeader eyebrow="Estúdio CenaForge" title={<>Suas histórias, <span className="text-fg-subtle">episódio a episódio.</span></>}
description="Escreva com IA, monte a cena, renderize o vertical e deixe o público decidir o próximo capítulo."
actions={stories.length > 0 && (
<dl className="flex gap-10 rounded-card border border-line bg-surface/60 px-7 py-5">
<Stat label="Histórias" value={stories.length} />
<Stat label="Episódios" value={totalEpisodes} />
<Stat label="Renderizados" value={rendered} />
{openVotes > 0 && <Stat label="Em votação" value={openVotes} />}
</dl>
)} />
<StoryComposer autoProvider={defaultProviderFor("story")} available={available} models={models()} />
<section aria-labelledby="lista-historias" className="grid gap-6">
<SectionHeader id="lista-historias" eyebrow="Biblioteca" title="Em produção"
description={stories.length > 0 ? "Abra uma história para continuar de onde parou." : undefined} />
{stories.length === 0 ? (
<EmptyState icon={<FilmIcon />} title="Nenhuma história ainda">
Cole uma ideia no painel acima e a IA monta a primeira história com você.
</EmptyState>
) : (
<ul className="grid gap-5 lg:grid-cols-2 2xl:grid-cols-3">
{stories.map(({ story, episodes }) => <StoryCard key={story.id} story={story} episodes={episodes} />)}
</ul>
)}
</section>
<details className="group rounded-card border border-line bg-surface/50 open:bg-surface">
<summary className="flex cursor-pointer list-none items-center gap-4 rounded-card px-6 py-5 transition-colors hover:bg-raised/40 [&::-webkit-details-marker]:hidden">
<span className="grid size-10 shrink-0 place-items-center rounded-xl border border-line-strong bg-raised text-fg-muted"><PenIcon size={18} /></span>
<span className="grid min-w-0 flex-1 gap-0.5">
<span className="font-display text-[0.9375rem] font-semibold text-fg">Prefere começar sem IA?</span>
<span className="text-[0.8125rem] text-fg-subtle">Crie uma história vazia com título e premissa, e escreva você mesmo.</span>
</span>
<ChevronDownIcon size={18} className="shrink-0 text-fg-subtle transition-transform group-open:rotate-180" />
</summary>
<div className="border-t border-line px-6 pt-5 pb-6">
<CreateStoryForm />
</div>
</details>
</>
);
}
/** Cartão de história: um "pôster" vertical com a cor própria da história e o estado do último episódio. */
function StoryCard({ story, episodes }: { story: Story; episodes: EpisodeView[] }) {
const last = episodes.at(-1);
const hue = hueOf(story.id);
const interactive = story.kind === "interactive";
const terms = unitTerms(story.kind);
return (
<li className="relative">
{/* Fora do link: um botão dentro de <a> não é válido. Fica no canto inferior direito do cartão. */}
<DeleteStoryButton storyId={story.id} title={story.title} compact className="absolute right-4 bottom-4 z-10" />
<Link href={`/stories/${story.id}`}
className="group flex h-full gap-5 rounded-card border border-line bg-surface p-4 shadow-card transition-[border-color,background-color,transform] duration-200 hover:-translate-y-0.5 hover:border-line-strong hover:bg-raised/60">
<div aria-hidden="true"
className="relative flex aspect-[9/16] w-24 shrink-0 flex-col justify-between overflow-hidden rounded-xl border border-white/10 p-2.5"
style={{ background: `linear-gradient(160deg, oklch(0.55 0.16 ${hue}) 0%, oklch(0.32 0.12 ${(hue + 40) % 360}) 55%, oklch(0.16 0.04 ${(hue + 60) % 360}) 100%)` }}>
<span className="font-mono text-[0.625rem] font-semibold text-white/80">{last ? terms.code(last.number) : terms.code(0)}</span>
<span className="font-display text-[1.75rem] leading-none font-bold text-white/90">{story.title.charAt(0).toUpperCase()}</span>
<span className="absolute inset-x-0 bottom-0 h-1/2 bg-linear-to-t from-black/50 to-transparent" />
</div>
<div className="flex min-w-0 flex-1 flex-col py-1">
<div className="flex items-start justify-between gap-3">
<h3 className="font-display text-[1.1875rem] leading-snug font-semibold tracking-[-0.015em] text-fg transition-colors group-hover:text-accent">{story.title}</h3>
<ArrowRightIcon size={18} className="mt-1 shrink-0 text-fg-subtle opacity-0 transition-[opacity,transform] group-hover:translate-x-0.5 group-hover:opacity-100" />
</div>
<p className="mt-1.5 line-clamp-2 text-sm leading-relaxed text-fg-muted">{story.logline || "Sem premissa ainda."}</p>
<div className="mt-auto grid gap-3 pt-4">
{last ? <StagePipeline stage={last.stage} /> : <span className="text-xs text-fg-subtle">Sem {terms.many}</span>}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 pr-10 text-xs text-fg-subtle">
<Badge tone={interactive ? "accent" : "neutral"}>{storyFormatLabel(story.kind)}</Badge>
<span>{episodes.length} {episodes.length === 1 ? terms.one : terms.many}</span>
<span aria-hidden="true">·</span>
<span>atualizada {formatRelative(story.updated_at)}</span>
</div>
</div>
</div>
</Link>
</li>
);
}
+25
View File
@@ -0,0 +1,25 @@
import Link from "next/link";
import { ClockIcon, PublishIcon, SettingsIcon } from "@/components/icons";
import { PublishingBoard } from "@/components/publishing-board";
import { Meta, PageHeader } from "@/components/ui";
export const metadata = { title: "Publicações" };
/**
* Publicações: a fila de envio para YouTube, TikTok e Instagram. Os dados mudam a cada segundo
* (progresso do envio), então a página busca /api/publishing/* no navegador.
*/
export default function PublishingPage() {
return (
<>
<PageHeader eyebrow="Distribuição" title="Publicações"
description="Tudo o que vai para as redes: o que espera a sua aprovação, o que está agendado, o que está saindo agora e o que já foi publicado."
meta={<>
<Meta icon={<PublishIcon size={15} />}>Redes e regras em <Link href="/accounts" className="text-fg-muted underline underline-offset-2 hover:text-fg">Canais de publicação</Link></Meta>
<Meta icon={<ClockIcon size={15} />}>Horários bons em <Link href="/settings" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
<Meta icon={<SettingsIcon size={15} />}>O painel precisa estar aberto para publicar</Meta>
</>} />
<PublishingBoard />
</>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { SettingsPanel } from "@/components/settings-panel";
import { PageHeader } from "@/components/ui";
export const metadata = { title: "Configurações" };
/** Configurações do painel: publicação, apps das redes, navegador da sessão logada e a explicação dos modos. */
export default function SettingsPage() {
return (
<>
<PageHeader eyebrow="Painel" title="Configurações"
description="Horários de publicação, os apps de cada rede e o navegador usado na sessão logada. Tudo fica só neste computador." />
<SettingsPanel />
</>
);
}
@@ -0,0 +1,292 @@
import { notFound } from "next/navigation";
import { connection } from "next/server";
import path from "node:path";
import { EpisodeApprove } from "@/components/episode-approve";
import { CloseDecisionForm, CommentsForm, CreateEpisodeForm, PrepareBranchesForm } from "@/components/forms";
import { BookIcon, ChatIcon, ClapperIcon, FolderIcon, PenIcon, PlayIcon, SparkIcon } from "@/components/icons";
import { RenderControls } from "@/components/render-controls";
import { MontageEditor } from "@/components/montage-editor";
import { ScriptReader } from "@/components/script-reader";
import { unitTerms } from "@/components/story-formats";
import {
Breadcrumb, CHOICE_STYLE, Card, ChoiceChip, EmptyState, LinkButton, Meta, PageHeader, StagePipeline, StatusBadge, cx, episodeCode, fileUrl, formatDate,
} from "@/components/ui";
import { DECISION_RULE, decisionVotes, leader, listComments, tally } from "@/lib/decisions";
import { REPO_ROOT, readTextIfExists } from "@/lib/paths";
import { episodeApproval, type EpisodeApproval } from "@/lib/publishing";
import { listRenders } from "@/lib/renders";
import { parseScript } from "@/lib/script-doc";
import { getEpisode, getStory, listEpisodes } from "@/lib/stories";
import type { Choice, EpisodeView } from "@/lib/types";
export async function generateMetadata({ params }: { params: Promise<{ storyId: string; number: string }> }) {
const { storyId, number } = await params;
const story = getStory(storyId);
return { title: story ? `${unitTerms(story.kind).code(Number(number))} · ${story.title}` : "Episódio" };
}
export default async function EpisodePage({ params }: { params: Promise<{ storyId: string; number: string }> }) {
await connection();
const { storyId, number } = await params;
const story = getStory(storyId);
const ep = story ? getEpisode(storyId, Number(number)) : undefined;
if (!story || !ep) notFound();
const script = readTextIfExists(path.join(REPO_ROOT, ep.scriptPath));
const renders = listRenders(ep.id);
const running = renders.find((r) => r.status === "running") ?? null;
const latestOk = renders.find((r) => r.status === "success" && r.mp4);
const interactive = story.kind === "interactive";
const documentary = story.kind === "documentary";
const readingHref = `/stories/${story.id}/episodes/${ep.number}/roteiro`;
const t = tally(ep.id);
const comments = listComments(ep.id);
const isLast = listEpisodes(storyId).at(-1)?.id === ep.id;
const terms = unitTerms(story.kind);
const label = terms.code(ep.number); // como a interface chama: ep01 ou vídeo
const agentLink = (kind: string) => `/agent?story=${story.id}&episode=${ep.id}&kind=${kind}`;
// Opções em jogo (2 a 4). Sem vertentes preparadas, valem A e B da cena.
const options = choiceOptions(ep);
const letters = options.map((o) => o.letter);
const totalVotes = letters.reduce((sum, l) => sum + (t.votes[l] ?? 0), 0);
// Aprovação para publicar (vídeo final, título, legenda, canais que recebem). Falha aqui não derruba a página.
let approval: EpisodeApproval | null = null;
try { approval = episodeApproval(ep.id); } catch { approval = null; }
return (
<>
<PageHeader
breadcrumb={<Breadcrumb items={[{ href: "/", label: "Histórias" }, { href: `/stories/${story.id}`, label: story.title }, { label }]} />}
eyebrow={documentary ? "Vídeo documental" : <>Episódio {ep.number} · {story.title}</>}
// Documental: o título é o do roteiro (o vídeo é um só; "Abertura" era nome de episódio de série).
title={(documentary && script ? parseScript(script).title : null) || ep.overlay?.title || ep.title || story.title}
description={ep.parent_choice ? `Continua a escolha ${ep.parent_choice} do episódio anterior.` : undefined}
meta={<>
<StagePipeline stage={ep.stage} />
{!documentary && <Meta icon={<FolderIcon size={15} />}><code>{ep.configPath}</code></Meta>}
</>}
actions={<>
<LinkButton variant="ghost" href={agentLink("free")}>Outro pedido</LinkButton>
{script && <LinkButton variant="secondary" href={readingHref}><BookIcon size={16} />Ler roteiro</LinkButton>}
{/* A cena 3D (rua do entregador) não serve ao documental, que é montado com imagens e narração. */}
{!documentary && <LinkButton href={agentLink("scene")}><ClapperIcon size={16} />Montar cena</LinkButton>}
<LinkButton variant="flame" href={agentLink("script")}><SparkIcon size={16} />Roteiro com IA</LinkButton>
</>} />
<div className={cx("grid items-start gap-8", interactive && "xl:grid-cols-[minmax(0,1fr)_24rem] 2xl:grid-cols-[minmax(0,1fr)_28rem]")}>
<div className="grid min-w-0 content-start gap-8">
<Card eyebrow={<><PlayIcon size={12} />Vídeo</>} title="Prévia e render">
<div className="grid gap-8 md:grid-cols-[minmax(0,17rem)_minmax(0,1fr)]">
<div className="grid min-w-0 content-start gap-4">
<div className="relative aspect-[9/16] w-full overflow-hidden rounded-2xl border border-line-strong bg-sunken shadow-pop">
{latestOk?.mp4 ? (
<video key={latestOk.mp4} controls className="size-full object-contain" src={fileUrl(latestOk.mp4)} />
) : (
<div className="grid size-full place-items-center bg-[radial-gradient(circle_at_50%_35%,rgb(255_122_26/0.08),transparent_65%)] p-5 text-center">
<div className="grid justify-items-center gap-3">
<span className="grid size-14 place-items-center rounded-full border border-line-strong bg-raised text-fg-muted"><PlayIcon size={22} /></span>
<p className="font-display text-[0.9375rem] font-semibold">Sem vídeo ainda</p>
<p className="text-xs leading-relaxed text-fg-subtle">
{documentary
? "Monte o vídeo na seção Montagem: áudio por trecho, imagens e o botão “Montar vídeo”."
: ep.hasConfig ? "Renderize a prévia para ver o primeiro corte." : "Escreva o roteiro e monte a cena; depois renderize."}
</p>
</div>
</div>
)}
</div>
{approval && <EpisodeApprove episodeId={ep.id} approval={approval} label={label} />}
</div>
{documentary ? (
<div className="grid min-w-0 content-start gap-4">
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Como este vídeo é feito</h3>
<ol className="grid gap-3 text-sm leading-relaxed text-fg-muted">
<li><span className="font-semibold text-fg">1. Roteiro</span>: leia trecho a trecho abaixo ou no modo leitura.</li>
<li><span className="font-semibold text-fg">2. Narração</span>: um áudio por trecho, com números por extenso (seção Montagem).</li>
<li><span className="font-semibold text-fg">3. Imagens</span>: uma imagem ou clipe por trecho, de banco livre ou enviado por você.</li>
<li><span className="font-semibold text-fg">4. Montagem</span>: imagens, texto na tela, narração e legenda num MP4 vertical, pelo botão “Montar vídeo”.</li>
</ol>
</div>
) : (
<div className="grid min-w-0 content-start gap-7">
<div className="grid gap-3">
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Cena</h3>
{ep.hasConfig ? (
<div className="grid gap-3">
<p className="font-display text-[1.375rem] leading-snug font-semibold tracking-[-0.015em]">{ep.overlay?.title ?? "—"}</p>
<div className="grid gap-2 sm:grid-cols-2">
{options.map((o) => <ChoiceTile key={o.letter} letter={o.letter} text={o.label} />)}
</div>
</div>
) : <p className="text-sm text-fg-muted">Cena ainda não montada. Depois do roteiro, use “Montar cena”.</p>}
</div>
<RenderControls episodeId={ep.id} hasConfig={ep.hasConfig} running={running} />
<div className="grid gap-3">
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Histórico de renders</h3>
{renders.length === 0 ? <p className="text-sm text-fg-subtle">Nenhum render ainda.</p> : (
<ul className="grid divide-y divide-line rounded-control border border-line text-sm">
{renders.map((r) => (
<li key={r.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3.5 py-2.5">
<StatusBadge status={r.status} />
<span className="font-medium text-fg-muted">{r.profile === "final" ? "final" : r.profile === "documentary" ? "montagem" : "prévia"}</span>
<span className="text-xs text-fg-subtle">{formatDate(r.started_at)}</span>
<span className="ml-auto flex gap-3">
{r.mp4 && <a className="font-medium text-accent hover:underline" href={fileUrl(r.mp4)}>MP4</a>}
{r.run_dir && r.profile !== "documentary" && <a className="text-fg-muted hover:text-fg hover:underline" href={fileUrl(`${r.run_dir}/inspect/contact-sheet.png`)}>quadros</a>}
</span>
{r.error && <span className="w-full truncate text-xs text-danger" title={r.error}>{r.error.split("\n")[0]}</span>}
</li>
))}
</ul>
)}
</div>
</div>
)}
</div>
</Card>
{/* No documental o roteiro vem primeiro: é o que guia a narração e as imagens. */}
<Card className={cx(documentary && "order-first")} eyebrow={<><PenIcon size={12} />Roteiro</>}
title={documentary ? "Roteiro do vídeo" : `Roteiro do ${label}`} description={<code className="text-xs">{ep.scriptPath}</code>}
actions={script ? <LinkButton size="sm" variant="ghost" href={agentLink("script")}><SparkIcon size={14} />Revisar com IA</LinkButton> : undefined}>
{script ? (
<ScriptReader markdown={script} readingHref={readingHref} />
) : (
<EmptyState compact icon={<SparkIcon />} title="Roteiro ainda não escrito"
action={<LinkButton variant="primary" href={agentLink("script")}><SparkIcon size={16} />Escrever roteiro com IA</LinkButton>}>
O roteiro sai com o GPT (Codex) por padrão.
</EmptyState>
)}
</Card>
{documentary && script && (
<Card className="order-first" eyebrow={<><ClapperIcon size={12} />Montagem</>} title="Montagem do vídeo"
description="Um áudio por trecho (a voz fica natural) e um visual por trecho: foto, animação 2D, cena 3D do Godot, clipe ou cartela. Dá para misturar.">
<MontageEditor episodeId={ep.id} />
</Card>
)}
</div>
{interactive && (
<div className="grid min-w-0 content-start gap-8 xl:sticky xl:top-8">
<Card eyebrow="Decisão do público" title="Votação nos comentários">
<div className="mb-5 grid gap-4">
{options.map((o) => (
<VoteBar key={o.letter} letter={o.letter} label={o.label} votes={t.votes[o.letter] ?? 0} total={totalVotes}
winner={ep.decision?.winner === o.letter} />
))}
</div>
<p className="mb-5 text-xs leading-relaxed text-fg-subtle">
{t.totalComments} comentário(s), {t.ambiguousOrNoVote} sem voto válido. Regra: {DECISION_RULE}
</p>
{ep.decision ? (
<div className="rounded-card border border-accent/30 bg-accent-soft p-4 text-sm">
<div className="font-display text-base font-semibold text-accent">Venceu {ep.decision.winner}</div>
<div className="mt-0.5 text-xs text-fg-muted">
{Object.entries(decisionVotes(ep.decision)).map(([l, n]) => `${l}: ${n}`).join(" × ")}, {ep.decision.method === "manual" ? "decisão manual" : "por votos"} · {formatDate(ep.decision.closed_at)} · fotografia imutável
</div>
{isLast && <div className="mt-4"><CreateEpisodeForm storyId={story.id} parentEpisodeId={ep.id} label={`Criar ${episodeCode(ep.number + 1)} a partir de ${ep.decision.winner}`} /></div>}
</div>
) : (
<div className="grid gap-6 border-t border-line pt-5">
<CommentsForm episodeId={ep.id} />
<CloseDecisionForm episodeId={ep.id} tied={leader(t.votes) === null} letters={letters} />
</div>
)}
<p className="mt-5 text-xs text-fg-subtle">Integração com o Instagram ainda não existe: os comentários entram colados aqui.</p>
</Card>
{ep.status === "main" && (
<Card eyebrow={<><SparkIcon size={12} />Próximo nível</>} title="Vertentes"
description={`A IA escreve as ${story.branch_count} opções, com roteiro e cena de cada uma, antes da votação. O vídeo não é gerado aqui.`}>
{options.some((o) => o.fileKey) && (
<ul className="mb-5 grid gap-1.5 text-sm">
{options.filter((o) => o.fileKey).map((o) => (
<li key={o.letter} className="flex items-center gap-2.5">
<ChoiceChip letter={o.letter} size="sm" />
<code>{o.fileKey}</code>
<span className="text-xs text-fg-subtle">
{o.status === "main" ? "caminho principal" : o.status === "discarded" ? "descartada" : "candidata"}
</span>
</li>
))}
</ul>
)}
{ep.decision ? (
<p className="text-sm text-fg-muted">Votação fechada: a vertente {ep.decision.winner} seguiu para o caminho principal.</p>
) : (
<PrepareBranchesForm episodeId={ep.id} status={ep.branches_status} runId={ep.branches_run_id} hasScript={ep.hasScript} />
)}
</Card>
)}
<Card title={<span className="flex items-center gap-2"><ChatIcon size={16} />Comentários</span>} description={comments.length ? `${comments.length} no total` : undefined}>
{comments.length === 0 ? (
<EmptyState compact icon={<ChatIcon />} title="Nenhum comentário">
Cole os comentários do público no formulário da votação para apurar as opções.
</EmptyState>
) : (
<ul className="-mx-2 grid max-h-[40vh] gap-0.5 overflow-y-auto text-sm">
{comments.map((c) => (
<li key={c.id} className="flex items-start gap-3 rounded-lg px-2 py-2 hover:bg-raised/50">
<span className={cx("grid size-6 shrink-0 place-items-center rounded-md text-xs font-bold",
c.choice ? cx(CHOICE_STYLE[c.choice].soft, CHOICE_STYLE[c.choice].text) : "bg-raised text-fg-subtle")}>
{c.choice ?? "·"}
</span>
<span className="min-w-0 leading-relaxed">
<span className="font-medium text-fg-muted">{c.author_name}</span>{" "}
<span className="text-fg">{c.text}</span>
</span>
</li>
))}
</ul>
)}
</Card>
</div>
)}
</div>
</>
);
}
/** Opções da decisão deste episódio: as de `ep.choices` (2 a 4) ou, sem vertentes, A e B da cena. */
function choiceOptions(ep: EpisodeView): { letter: Choice; label?: string; fileKey: string | null; status: EpisodeView["status"] | null }[] {
const fromScene: Partial<Record<Choice, string | undefined>> = { A: ep.overlay?.choiceA, B: ep.overlay?.choiceB };
if (ep.choices.length === 0) {
return (["A", "B"] as Choice[]).map((letter) => ({ letter, label: fromScene[letter], fileKey: null, status: null }));
}
return ep.choices.map((c) => ({ letter: c.letter, label: c.label || fromScene[c.letter], fileKey: c.fileKey, status: c.status }));
}
function ChoiceTile({ letter, text }: { letter: Choice; text?: string }) {
const c = CHOICE_STYLE[letter];
return (
<div className={cx("flex gap-3 rounded-control border p-3", c.border, c.soft)}>
<ChoiceChip letter={letter} solid />
<span className="text-sm leading-snug text-fg">{text || "—"}</span>
</div>
);
}
/** Barra de proporção de uma opção da votação. */
function VoteBar({ letter, label, votes, total, winner }: { letter: Choice; label?: string; votes: number; total: number; winner?: boolean }) {
const pct = total > 0 ? Math.round((votes / total) * 100) : 0;
const c = CHOICE_STYLE[letter];
return (
<div>
<div className="mb-2 flex items-center gap-2.5">
<span className={cx("grid size-6 shrink-0 place-items-center rounded-md text-xs font-bold", winner ? cx(c.fill, c.fillFg) : cx(c.soft, c.text))}>{letter}</span>
<span className="min-w-0 flex-1 truncate text-sm text-fg-muted" title={label}>{label || `Opção ${letter}`}</span>
<span className="font-display text-2xl leading-none font-semibold tabular-nums">{votes}</span>
<span className="w-9 text-right text-xs tabular-nums text-fg-subtle">{pct}%</span>
</div>
<div className={cx("h-2 overflow-hidden rounded-full", c.soft)} role="img"
aria-label={`Opção ${letter}: ${votes} voto(s), ${pct}%${winner ? ", vencedora" : ""}`}>
<div className={cx("h-full rounded-full transition-[width]", c.fill)} style={{ width: `${pct}%` }} />
</div>
</div>
);
}
@@ -0,0 +1,52 @@
// Modo leitura: só o roteiro, diagramado, em largura confortável.
import path from "node:path";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { ArrowLeftIcon, SparkIcon } from "@/components/icons";
import { ScriptReader } from "@/components/script-reader";
import { unitTerms } from "@/components/story-formats";
import { Breadcrumb, EmptyState, LinkButton, PageHeader } from "@/components/ui";
import { REPO_ROOT, readTextIfExists } from "@/lib/paths";
import { parseScript } from "@/lib/script-doc";
import { getEpisode, getStory } from "@/lib/stories";
export async function generateMetadata({ params }: { params: Promise<{ storyId: string; number: string }> }) {
const { storyId } = await params;
return { title: `Roteiro · ${getStory(storyId)?.title ?? "História"}` };
}
export default async function ScriptPage({ params }: { params: Promise<{ storyId: string; number: string }> }) {
await connection();
const { storyId, number } = await params;
const story = getStory(storyId);
const ep = story ? getEpisode(storyId, Number(number)) : undefined;
if (!story || !ep) notFound();
const terms = unitTerms(story.kind);
const label = terms.code(ep.number);
const episodeHref = `/stories/${story.id}/episodes/${ep.number}`;
const script = readTextIfExists(path.join(REPO_ROOT, ep.scriptPath));
const title = script ? parseScript(script).title : null;
return (
<div className="mx-auto grid w-full max-w-5xl gap-8">
<PageHeader
breadcrumb={<Breadcrumb items={[
{ href: "/", label: "Histórias" }, { href: `/stories/${story.id}`, label: story.title },
{ href: episodeHref, label }, { label: "Roteiro" },
]} />}
eyebrow={<>Roteiro · {story.kind === "documentary" ? "vídeo documental" : `${terms.one} ${ep.number}`}</>}
title={title || ep.title || story.title}
description={<code className="text-xs">{ep.scriptPath}</code>}
actions={<>
<LinkButton variant="ghost" href={episodeHref}><ArrowLeftIcon size={16} />Voltar ao {terms.one}</LinkButton>
<LinkButton variant="flame" href={`/agent?story=${story.id}&episode=${ep.id}&kind=script`}><SparkIcon size={16} />Revisar com IA</LinkButton>
</>} />
{script ? <ScriptReader markdown={script} /> : (
<EmptyState icon={<SparkIcon />} title="Roteiro ainda não escrito"
action={<LinkButton variant="primary" href={`/agent?story=${story.id}&episode=${ep.id}&kind=script`}><SparkIcon size={16} />Escrever roteiro com IA</LinkButton>}>
Quando o roteiro existir, ele aparece aqui, trecho a trecho.
</EmptyState>
)}
</div>
);
}
+175
View File
@@ -0,0 +1,175 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { AssetTable } from "@/components/asset-table";
import { AssetUpload } from "@/components/asset-upload";
import { DeleteStoryButton } from "@/components/delete-story-button";
import { CreateEpisodeForm } from "@/components/forms";
import { ArrowRightIcon, BookIcon, ClockIcon, FilmIcon, FlowIcon, FolderIcon, PenIcon, SparkIcon, UploadIcon, UsersIcon } from "@/components/icons";
import { PLATFORM_META } from "@/components/platforms";
import { StoryFlowView } from "@/components/story-flow";
import { storyFormatLabel, unitTerms } from "@/components/story-formats";
import { Tabs } from "@/components/tabs";
import {
Badge, Breadcrumb, CHOICE_STYLE, Card, EmptyState, LinkButton, Meta, PageHeader, SectionHeader, StagePipeline, episodeCode, formatDate, formatRelative,
} from "@/components/ui";
import { listAccounts, type AccountView } from "@/lib/accounts";
import { ASSET_KINDS, listAssets } from "@/lib/assets";
import { storyFlow } from "@/lib/flow";
import { getStory, listEpisodes, listStories } from "@/lib/stories";
export async function generateMetadata({ params }: { params: Promise<{ storyId: string }> }) {
const { storyId } = await params;
return { title: getStory(storyId)?.title ?? "História" };
}
export default async function StoryPage({ params }: { params: Promise<{ storyId: string }> }) {
await connection();
const { storyId } = await params;
const story = getStory(storyId);
if (!story) notFound();
const episodes = listEpisodes(storyId);
const assets = listAssets({ storyId });
const last = episodes.at(-1);
const interactive = story.kind === "interactive";
const terms = unitTerms(story.kind);
// Roteiro para o botão "Ler roteiro": o do último episódio que já tem roteiro (no documental, o vídeo).
const withScript = [...episodes].reverse().find((e) => e.hasScript);
const nextBlocked = interactive && last && !last.decision;
const flow = storyFlow(storyId)!;
const accounts = listAccounts().filter((a) => a.stories.some((l) => l.story_id === storyId));
const activeAccounts = accounts.filter((a) => a.stories.some((l) => l.story_id === storyId && l.status === "active")).length;
return (
<>
<PageHeader
breadcrumb={<Breadcrumb items={[{ href: "/", label: "Histórias" }, { label: story.title }]} />}
eyebrow={<>{story.kind === "documentary" ? "Vídeo documental" : `História ${storyFormatLabel(story.kind)}`}</>}
title={story.title}
description={story.logline || <span className="text-fg-subtle">Sem premissa definida ainda.</span>}
meta={<>
<Meta icon={<FilmIcon size={15} />}>{episodes.length} {episodes.length === 1 ? terms.one : terms.many}</Meta>
<Meta icon={<FolderIcon size={15} />}><code>stories/{story.id}/</code></Meta>
<Meta icon={<ClockIcon size={15} />}>atualizada {formatRelative(story.updated_at)}</Meta>
</>}
actions={<>
{withScript && <LinkButton variant="secondary" href={`/stories/${story.id}/episodes/${withScript.number}/roteiro`}><BookIcon size={16} />Ler roteiro</LinkButton>}
<LinkButton variant="flame" href={`/agent?story=${story.id}&kind=script`}><SparkIcon size={16} />Escrever com IA</LinkButton>
<DeleteStoryButton storyId={story.id} title={story.title} />
</>} />
<Tabs label="Seções da história" defaultTab="episodes"
items={[
{ id: "episodes", label: terms.Many, icon: <FilmIcon size={16} />, count: episodes.length },
{ id: "flow", label: "Fluxo", icon: <FlowIcon size={16} /> },
{ id: "accounts", label: "Canais de publicação", icon: <UsersIcon size={16} />, count: activeAccounts },
]}
panels={{
episodes: <>
<section aria-labelledby="episodios" className="grid gap-5">
<SectionHeader id="episodios" eyebrow={story.kind === "documentary" ? "Produção" : "Temporada"} title={terms.Many}
description={interactive ? `Cada episódio termina numa escolha com ${story.branch_count} opções decidida pelos comentários; o próximo continua a opção vencedora.` : undefined} />
{episodes.length === 0 ? (
<EmptyState icon={<FilmIcon />} title={`Nenhum ${terms.one} ainda`}>
Crie o {terms.code(1)} logo abaixo. Em seguida, abra o {terms.one} e peça o roteiro ao agente.
</EmptyState>
) : (
<ol className="grid gap-3">
{episodes.map((ep) => (
<li key={ep.id}>
<Link href={`/stories/${story.id}/episodes/${ep.number}`}
className="group grid items-center gap-x-6 gap-y-3 rounded-card border border-line bg-surface px-5 py-4 shadow-card transition-[border-color,background-color] hover:border-line-strong hover:bg-raised/50 md:grid-cols-[4.5rem_minmax(0,1fr)_auto_auto_1.25rem]">
<span className="font-mono text-[1.375rem] leading-none font-semibold tracking-tight text-fg-subtle transition-colors group-hover:text-accent">
{terms.code(ep.number)}
</span>
<span className="grid min-w-0 gap-1">
<span className="truncate font-display text-[1.0625rem] font-semibold text-fg">{story.kind === "documentary" ? story.title : ep.overlay?.title || ep.title || "Sem título"}</span>
<span className="text-xs text-fg-subtle">
{ep.parent_choice ? `Continua a escolha ${ep.parent_choice}` : story.kind === "documentary" ? "Roteiro do vídeo" : "Abertura"} · criado {formatDate(ep.created_at)}
</span>
</span>
<StagePipeline stage={ep.stage} />
<span className="min-w-28 md:text-right">
{ep.decision
? <Badge tone={CHOICE_STYLE[ep.decision.winner].tone}>venceu {ep.decision.winner}</Badge>
: <span className="text-xs text-fg-subtle">{interactive ? "votação aberta" : "—"}</span>}
</span>
<ArrowRightIcon size={18} className="text-fg-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-fg max-md:hidden" />
</Link>
</li>
))}
</ol>
)}
<div className="flex flex-wrap items-center gap-4 rounded-card border border-dashed border-line-strong px-5 py-4">
<span className="grid size-9 place-items-center rounded-lg bg-raised text-fg-muted"><PenIcon size={16} /></span>
{nextBlocked ? (
<p className="text-sm text-fg-muted">Feche a votação do {episodeCode(last!.number)} para criar o próximo episódio a partir da escolha vencedora.</p>
) : (
<CreateEpisodeForm storyId={story.id} parentEpisodeId={interactive && last ? last.id : undefined}
label={last ? `Criar ${terms.code(last.number + 1)}${interactive ? ` (escolha ${last.decision?.winner})` : ""}` : `Criar ${terms.code(1)}`} />
)}
</div>
</section>
<section aria-labelledby="assets-historia" className="grid gap-5">
<SectionHeader id="assets-historia" eyebrow="Recursos" title="Assets disponíveis"
description="Os da biblioteca compartilhada e os exclusivos desta história." />
<AssetTable assets={assets} showStory />
<Card eyebrow={<><UploadIcon size={13} />Envio</>} title="Enviar asset para esta história">
<AssetUpload stories={listStories().map((s) => ({ id: s.id, title: s.title }))} kinds={ASSET_KINDS} defaultStoryId={story.id} />
</Card>
</section>
</>,
flow: <StoryFlowView initial={flow} />,
accounts: <StoryAccounts storyId={story.id} accounts={accounts} />,
}} />
</>
);
}
/** Aba Contas: quais contas publicam (ou já publicaram) esta história. */
function StoryAccounts({ storyId, accounts }: { storyId: string; accounts: AccountView[] }) {
if (accounts.length === 0) {
return (
<EmptyState icon={<UsersIcon />} title="Nenhuma conta publica esta história"
action={<LinkButton variant="primary" href="/accounts">Vincular em Contas</LinkButton>}>
Em Contas, abra uma conta e use “Vincular história”. Uma história pode sair em várias contas ao mesmo tempo.
</EmptyState>
);
}
return (
<section aria-labelledby="contas-historia" className="grid gap-5">
<SectionHeader id="contas-historia" eyebrow="Distribuição" title="Contas que publicam esta história"
actions={<LinkButton size="sm" href="/accounts"><UsersIcon size={15} />Gerenciar contas</LinkButton>} />
<ul className="grid divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
{accounts.map((a) => {
const link = a.stories.find((l) => l.story_id === storyId)!;
return (
<li key={a.id}>
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`}
className="grid items-center gap-x-6 gap-y-2 px-5 py-3.5 transition-colors hover:bg-raised/50 md:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto]">
<span className="grid min-w-0 gap-0.5">
<span className="truncate font-medium text-fg">{a.name}</span>
<span className="truncate text-xs text-fg-subtle">{a.niche || "sem nicho"}</span>
</span>
<span className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-1 text-xs text-fg-muted">
{a.networks.length === 0 ? <span className="text-fg-subtle">nenhuma rede vinculada</span> : a.networks.map((n) => {
const Icon = PLATFORM_META[n.platform].icon;
return <span key={n.platform} className="inline-flex items-center gap-1.5" title={PLATFORM_META[n.platform].label}><Icon size={14} />{n.handle}</span>;
})}
</span>
<span className="flex items-center gap-3 text-xs text-fg-subtle">
{link.status === "active"
? <><Badge tone="success">ativa</Badge>desde {formatDate(link.linked_at)}</>
: <><Badge tone="neutral">encerrada</Badge>em {formatDate(link.ended_at)}</>}
</span>
</Link>
</li>
);
})}
</ul>
</section>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { MicIcon, WaveIcon } from "@/components/icons";
import { Meta, PageHeader } from "@/components/ui";
import { VoiceStudio } from "@/components/voice-studio";
export const metadata = { title: "Vozes" };
// O estado do serviço de voz muda a cada segundo (reinício, download de modelo): a página busca
// /api/voice/status no navegador e consulta de novo quando precisa, em vez de renderizar no servidor.
export default async function VoicesPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
// ?text=: a narração vinda do leitor de roteiro ("Gerar áudio em Vozes"). O campo aceita até 2.000 caracteres.
const initialText = (await searchParams).text?.slice(0, 2000);
return (
<>
<PageHeader eyebrow="Áudio" title="Vozes"
description="Narração dos episódios, vozes de personagem e legendas com tempo. Tudo roda no seu computador, pelo serviço de voz local."
meta={<>
<Meta icon={<MicIcon size={15} />}>Narração: Kokoro e Piper (offline) · Edge, Google e Azure (online)</Meta>
<Meta icon={<WaveIcon size={15} />}>Legenda: Whisper · arquivo <code>.srt</code></Meta>
</>} />
<VoiceStudio initialText={initialText} />
</>
);
}
+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>
);
}

Some files were not shown because too many files have changed in this diff Show More