Files
CenaForge/panel/src/components/clipper-clip-table.tsx
T
MateuusandClaude Opus 5.5 26c9afa13a Painel: Equipe de IA no lugar do provedor único, juiz de contexto no modal e medição
- Ajustes → Juiz: "Usar IA" + um cartão por papel (varredura, analista, editor, juiz) com
  provedor, modelo do provedor escolhido, raciocínio (Codex), imagens (mosaico/quadros/nenhuma),
  liga/desliga (o editor não desliga), instruções padrão só leitura (fonte PT/EN) e instruções
  do administrador; regras do juiz (checagens críticas, ajustar trecho, frase de contexto,
  desconto por checagem). Opção "Linha do tempo em JSON" para comparar com o formato antigo.
- Cartão de medição (GET judge/report, liberado no proxy): chamadas e tokens por hora por
  papel, aprovação, descartes do juiz e concordância juiz x dono.
- Modal do corte: veredito do juiz de contexto em português (decisão, o que um espectador
  frio entende, frase de contexto, checagens) e "Sua avaliação" (bom/ruim/sem contexto);
  botão "Sem contexto" ao rejeitar; lista marca "descartado pelo juiz".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:38:34 -03:00

243 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
// Lista de cortes: uma linha por corte com o que decide (miniatura, título, fonte/sessão/trecho, situação, nota da IA,
// duração, estado ou publicação, ações rápidas da etapa). Clique na linha (fora de botões) ou Enter abre o modal do
// corte; a linha aberta fica destacada. A caixa de seleção só aparece no hover/foco ou no modo de seleção.
import { type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import {
CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, formatScore, languageShort, useClipperAction,
type Clip, type ClipperSession,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
import { VideoTag, canDelete, judgeScore, situationLabel, type DeleteClip } from "./clipper-clip-parts";
import type { QueueFilter } from "./clipper-queue";
import { ArrowRightIcon, CheckIcon, RefreshIcon, ScissorsIcon, SparkIcon, UndoIcon, XIcon } from "./icons";
import type { PublishJob } from "./publishing-client";
import { PublishChips } from "./publishing-ui";
import { Badge, Button, Feedback, Spinner, Table, THead, Td, Th, cx, fileUrl, formatRelative } from "./ui";
export type ClipTableProps = {
clips: Clip[];
sessions: ClipperSession[];
stage: QueueFilter;
nameOf: (clip: Clip) => string;
/** Idioma padrão do serviço: só mostra o chip de idioma quando a sessão do corte difere dele. */
defaultLanguage: string;
/** Etapa Aprovados: jobs de publicação por id do corte (null = ainda não lidos / etapa não é Aprovados). */
publishing: Map<string, PublishJob[]> | null;
onPublished: () => void;
onChanged: () => void;
onOpen: (clip: Clip) => void;
/** Corte aberto no modal (linha destacada). */
openId: number | null;
/** Modo de seleção ligado: a caixa aparece em todas as linhas. */
revealed: boolean;
selected: ReadonlySet<number>;
onSelect: (id: number, on: boolean) => void;
deleting: ReadonlySet<number>;
onDelete: DeleteClip;
};
export function ClipTable(props: ClipTableProps) {
const { clips, stage } = props;
const approved = stage === "approved";
return (
<Table className="bg-surface shadow-card">
<THead>
<Th className="w-8"><span className="sr-only">Selecionar</span></Th>
<Th className="w-14"><span className="sr-only">Miniatura</span></Th>
<Th>Corte</Th>
<Th className="max-lg:hidden">Situação</Th>
<Th className="w-20 text-right">Nota IA</Th>
<Th className="w-20 text-right max-md:hidden">Duração</Th>
<Th className={approved ? "min-w-48" : "w-40"}>{approved ? "Publicação" : "Estado"}</Th>
<Th className="text-right"><span className="sr-only">Ações</span></Th>
</THead>
<tbody>
{clips.map((clip) => <ClipRow key={clip.id} clip={clip} {...props} />)}
</tbody>
</Table>
);
}
/** Clique num botão, link, input ou texto selecionado não conta como "abrir a linha". */
function isInteractive(target: EventTarget | null): boolean {
return target instanceof Element && Boolean(target.closest("button, a, input, select, textarea, label, [role=dialog], video"));
}
function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, onPublished, onChanged, onOpen, openId, revealed, selected, onSelect, deleting, onDelete }:
ClipTableProps & { clip: Clip }) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const status = CLIP_STATUS[clip.status];
const isDeleting = deleting.has(clip.id);
const isSelected = selected.has(clip.id);
const open = openId === clip.id;
const name = nameOf(clip);
const title = clip.title || `Corte ${clip.id}`;
const session = sessions.find((s) => s.id === clip.sessionId);
const language = session?.language;
const score = judgeScore(clip);
const kept = clip.judge && "keep" in clip.judge ? clip.judge.keep : null;
// Descartado pelo juiz de contexto (EQUIPE-IA.md): o editor manteve, o juiz achou que não faz sentido sozinho.
const byContextJudge = clip.status === "discarded" && !!clip.judge && "keep" in clip.judge && clip.judge.discardedBy === "context";
const situation = situationLabel(clip);
const jobs = publishing?.get(String(clip.id)) ?? null;
const horizontal = clip.aspect === "horizontal";
const poster = clip.thumb ? fileUrl(clip.thumb) : null;
const onRowClick = (e: MouseEvent<HTMLTableRowElement>) => {
if (isInteractive(e.target) || window.getSelection()?.toString()) return;
onOpen(clip);
};
const onRowKey = (e: KeyboardEvent<HTMLTableRowElement>) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpen(clip); }
};
return (
<>
<tr tabIndex={0} aria-label={`Abrir o corte: ${title}`} onClick={onRowClick} onKeyDown={onRowKey} aria-current={open ? "true" : undefined}
className={cx("group/row cursor-pointer border-t border-line transition-colors first:border-t-0 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent",
open ? "bg-accent-soft/40" : isSelected ? "bg-raised/70" : "hover:bg-raised/40",
isDeleting && "opacity-50")}>
<Td className="pr-0 pl-3">
<input type="checkbox" checked={isSelected} disabled={!canDelete(clip) || isDeleting}
onChange={(e) => onSelect(clip.id, e.target.checked)}
aria-label={`Selecionar o corte ${clip.id}: ${title}`}
title={canDelete(clip) ? "Selecionar para apagar" : "A IA ou o render está trabalhando neste corte"}
className={cx("size-4 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/row:opacity-40 group-focus-within/row:opacity-40")
: revealed || isSelected ? "opacity-100" : "opacity-0 group-hover/row:opacity-100 group-focus-within/row:opacity-100")} />
</Td>
<Td className="px-2">
<span className={cx("relative grid shrink-0 place-items-center overflow-hidden rounded-md border border-line bg-sunken text-fg-subtle",
horizontal ? "h-9 w-16" : "h-16 w-9")}>
{/* 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" /> : <ScissorsIcon size={14} />}
</span>
</Td>
<Td>
<div className="grid min-w-0 max-w-[36rem] gap-0.5">
<p className="truncate font-medium text-fg" title={clip.title || undefined}>{title}</p>
{/* Fonte em inglês: o título do post é o inglês acima; a tradução é só para a equipe entender. */}
{clip.judge && "pt" in clip.judge && clip.judge.pt?.title && (
<p className="truncate text-xs text-fg-muted" title="Tradução do título (o post sai em inglês)">🇧🇷 {clip.judge.pt.title}</p>
)}
<p className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span className="text-fg-muted">{name}</span>
<span aria-hidden="true">·</span>
<span>sessão #{clip.sessionId}</span>
<span aria-hidden="true">·</span>
<span className="tabular-nums">{formatClock(clip.startS)}–{formatClock(clip.endS)}</span>
<span aria-hidden="true">·</span>
<span title={new Date(clip.createdAt).toLocaleString("pt-BR")}>{formatRelative(clip.createdAt)}</span>
{language && language !== defaultLanguage && (
<span className="rounded-sm border border-line-strong px-1 font-mono text-[0.625rem] text-fg-muted" title={`Idioma da live: ${language}`}>{languageShort(language)}</span>
)}
{horizontal && <span className="rounded-sm border border-line-strong px-1 text-[0.625rem] text-fg-muted">16:9</span>}
<VideoTag clip={clip} />
</p>
</div>
</Td>
<Td className="max-lg:hidden">
<span className="flex flex-wrap items-center gap-1.5">
{situation
? <Badge tone="accent" dot={false}>{situation}</Badge>
: <Badge tone={clip.source === "manual" ? "info" : clip.source === "ai" ? "violet" : "neutral"} dot={false}>{SOURCE_LABEL[clip.source]}</Badge>}
</span>
</Td>
<Td className="text-right">
{score === null
? <span className="text-fg-subtle" title={clip.source === "manual" ? "Corte manual: não passa pela IA" : "Sem nota da IA"}>—</span>
: <span className={cx("font-display text-lg font-semibold tabular-nums", kept === false ? "text-warning" : score >= 7 ? "text-success" : "text-fg")}
title={kept === false ? "A IA descartou" : "Nota da IA (0–10)"}>{formatScore(score)}</span>}
</Td>
<Td className="text-right text-fg-muted tabular-nums max-md:hidden">{formatDuration(clip.durationS)}</Td>
<Td>
{stage === "approved" && jobs
? <PublishChips jobs={jobs} emptyText={<span className="inline-flex items-center gap-1.5"><Badge tone={status.tone}>{status.label}</Badge><span>ainda não foi para nenhuma rede</span></span>} />
: byContextJudge
? <Badge tone="danger" dot={false}>descartado pelo juiz</Badge>
: <Badge tone={status.tone} pulse={status.pulse}>{status.label}</Badge>}
</Td>
<Td className="text-right">
<div className="flex items-center justify-end gap-1.5">
<QuickActions clip={clip} pending={pending} run={run} jobs={jobs}
onPublished={(m) => { setMessage(m); onPublished(); }} />
<Button variant="ghost" size="sm" onClick={() => onOpen(clip)} aria-label={`Abrir o corte: ${title}`} title="Abrir" className="text-fg-muted">
<ArrowRightIcon size={15} /><span className="max-xl:sr-only">Abrir</span>
</Button>
</div>
</Td>
</tr>
{(message || (clip.status === "error" && clip.error)) && (
<tr className="border-t-0">
<td colSpan={8} className="px-4 pt-0 pb-3">
<div aria-live="polite" className="grid gap-2">
{clip.status === "error" && clip.error && !message && (
<p className="truncate font-mono text-xs text-danger" title={clip.error}>{clip.error}</p>
)}
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
</div>
</td>
</tr>
)}
</>
);
}
type Run = ReturnType<typeof useClipperAction>["run"];
/** Ações rápidas da etapa, na própria linha (o resto fica no modal). */
function QuickActions({ clip, pending, run, jobs, onPublished }: {
clip: Clip; pending: string | null; run: Run; jobs: PublishJob[] | null; onPublished: (m: { ok: boolean; text: string }) => void;
}) {
const base = `clips/${clip.id}`;
const disabled = pending !== null;
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 label = clip.title || `corte ${clip.id}`;
switch (clip.status) {
case "ready":
return <>
<Button size="sm" disabled={disabled} onClick={() => void setStatus("approve", "approved", "Corte aprovado.")} aria-label={`Aprovar: ${label}`}>
{icon("approve", <CheckIcon size={15} />)}Aprovar
</Button>
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("reject", "rejected", "Corte rejeitado.")} aria-label={`Rejeitar: ${label}`}>
{icon("reject", <XIcon size={15} />)}Rejeitar
</Button>
</>;
case "approved":
return <>
{jobs && <ClipPublishButton clip={clip} jobs={jobs} onDone={onPublished} />}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Aprovação desfeita.")} aria-label={`Desfazer aprovação: ${label}`}>
{icon("undo", <UndoIcon size={15} />)}<span className="max-xl:sr-only">Desfazer</span>
</Button>
</>;
case "published":
return jobs ? <ClipPublishButton clip={clip} jobs={jobs} onDone={onPublished} variant="secondary" /> : null;
case "rejected":
return clip.file ? (
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Corte de volta para aprovar.")} aria-label={`Voltar para aprovar: ${label}`}>
{icon("undo", <UndoIcon size={15} />)}Voltar para aprovar
</Button>
) : null;
case "discarded":
return (
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Render forçado: o corte entrou na fila.")} aria-label={`Forçar render: ${label}`}>
{icon("render", <ScissorsIcon size={15} />)}Forçar render
</Button>
);
case "error":
return (
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Tentando de novo: o corte entrou na fila.")} aria-label={`Tentar render de novo: ${label}`}>
{icon("render", <RefreshIcon size={15} />)}Tentar de novo
</Button>
);
default:
return clip.status === "candidate" ? <span className="inline-flex items-center gap-1.5 text-xs text-violet"><SparkIcon size={13} />IA avaliando</span> : null;
}
}