- editor_api: importa dub e speakers juntos. - voice_chunks (falantes) vira a migração v15, depois da v14 do vídeo final (antes era criada fora das migrações). - dub.voice_for: qualquer voz que não é o streamer (other1, other2…) usa a segunda voz da dublagem. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1247 lines
76 KiB
TypeScript
1247 lines
76 KiB
TypeScript
"use client";
|
||
// "Configuração do corte": modal em abas que edita o formato (vertical 9:16 ou horizontal 16:9) e a
|
||
// duração, o layout (onde fica a câmera, a área do jogo), a legenda e o crédito. Abre de uma SESSÃO
|
||
// ("Configurar corte") ou de um CANAL ("Padrão do canal"). Camadas: padrão ← canal ← sessão; salvar
|
||
// manda só o que a camada fixa (layerFrom). O quadro e a prévia vêm do serviço (/api/files, com &v=
|
||
// para furar cache). A prévia fica sempre ao lado e muda de proporção com o formato.
|
||
//
|
||
// Serviço antigo: não manda o grupo `format` (tratamos como vertical, via withFormat) e ignora o grupo
|
||
// ao salvar; a prévia dele sai sempre 1080×1920.
|
||
import { useCallback, useEffect, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
|
||
import {
|
||
MODE_LABEL, aspectOf, captureLabel, clipperCall, formatClock, gbPerHourLabel, layerFrom, mergeSettings, withFormat,
|
||
type Aspect, type CamDetect, type ClipperChannel, type ClipperSession, type CutLayer, type CutSettings, type FrameResult, type LayoutMode,
|
||
type PreviewResult, type Rect, type SettingsPayload,
|
||
} from "./clipper-client";
|
||
import {
|
||
AlertIcon, CheckIcon, ClockIcon, EyeIcon, InstagramIcon, RefreshIcon, SettingsIcon, SparkIcon, TikTokIcon, TrashIcon, UndoIcon, XIcon, YouTubeIcon,
|
||
} from "./icons";
|
||
import { RECT_MIN_SIZE, clampRect, moveRect, nudgeRect, resizeRect } from "./rect-geometry";
|
||
import { Tabs, type TabItem } from "./tabs";
|
||
import { Badge, Button, ChoiceGroup, Feedback, Field, RangeField, Select, Spinner, Switch, cx, fileUrl } from "./ui";
|
||
import type { VoiceInfo } from "./voice-client";
|
||
// Gancho e fontes (editor de cortes): seletor com amostra e fontes empacotadas carregadas no navegador.
|
||
import { HOOK_ANIM_LABEL, HOOK_STYLE_LABEL, SYSTEM_FONTS, hookOf, type HookAnim, type HookSettings, type HookStyle } from "./clipper-client";
|
||
import { FontPicker, fontStack, usePackagedFonts } from "./clip-editor-fonts";
|
||
import { askConfirm } from "./confirm-dialog";
|
||
|
||
export type CutScope =
|
||
| { kind: "session"; session: ClipperSession; name: string }
|
||
| { kind: "channel"; channel: ClipperChannel; /** Sessão mais recente do canal, para quadro e prévia. */ session: ClipperSession | null };
|
||
|
||
type Message = { ok: boolean; text: string } | null;
|
||
type Target = "cam" | "game";
|
||
type TabId = "format" | "camera" | "caption" | "hook" | "credit";
|
||
|
||
/** Sessão ainda gravando (a qualidade nova só vale na próxima gravação ou retomada). */
|
||
const ACTIVE_CAPTURE: ClipperSession["status"][] = ["starting", "recording"];
|
||
|
||
/** Limites do serviço (os padrões vêm de `defaults`, não daqui). */
|
||
const DURATION_LIMITS = {
|
||
minS: { min: 5, max: 120, step: 1 },
|
||
maxS: { min: 15, max: 180, step: 1 },
|
||
backtrackS: { min: 0, max: 120, step: 5 },
|
||
} as const;
|
||
|
||
const ASPECTS: Record<Aspect, { label: string; ratio: string; size: string; use: string; detail: string; networks: ReactNode }> = {
|
||
vertical: {
|
||
label: "Vertical", ratio: "9:16", size: "1080×1920", use: "Shorts, Reels e TikTok",
|
||
detail: "Câmera em cima e o jogo embaixo, ou o vídeo inteiro com fundo desfocado.",
|
||
networks: <><YouTubeIcon size={15} /><InstagramIcon size={15} /><TikTokIcon size={15} /></>,
|
||
},
|
||
horizontal: {
|
||
label: "Horizontal", ratio: "16:9", size: "1920×1080", use: "YouTube (vídeo normal)",
|
||
detail: "O jogo em tela cheia, como na live. Bom para jogadas longas e tela grande.",
|
||
networks: <YouTubeIcon size={15} />,
|
||
},
|
||
};
|
||
|
||
/* ---------- Modal ---------- */
|
||
|
||
/** Modal nativo (<dialog> com showModal): foco preso, Esc fecha, fundo inerte. Monta o editor só aberto. */
|
||
export function CutSettingsDialog({ scope, onClose, onSaved }: { scope: CutScope | null; onClose: () => void; onSaved: () => void }) {
|
||
const ref = useRef<HTMLDialogElement>(null);
|
||
const dirtyRef = useRef(false);
|
||
|
||
useEffect(() => {
|
||
const dialog = ref.current;
|
||
if (!dialog) return;
|
||
if (scope && !dialog.open) dialog.showModal();
|
||
if (!scope && dialog.open) dialog.close();
|
||
}, [scope]);
|
||
|
||
const requestClose = useCallback(async () => {
|
||
if (dirtyRef.current && !(await askConfirm({ title: "Fechar sem salvar?", message: "Os ajustes feitos aqui se perdem.",
|
||
confirmLabel: "Fechar sem salvar", cancelLabel: "Continuar editando", tone: "danger" }))) return;
|
||
dirtyRef.current = false;
|
||
onClose();
|
||
}, [onClose]);
|
||
|
||
// Altura fixa: trocar de aba não faz o modal pular de tamanho.
|
||
return (
|
||
<dialog ref={ref} aria-labelledby="cut-settings-title"
|
||
onCancel={(e) => { e.preventDefault(); requestClose(); }}
|
||
className="m-auto h-[min(94vh,68rem)] max-h-[94vh] w-[min(96vw,112rem)] overflow-hidden rounded-panel border border-line-strong bg-canvas p-0 text-fg shadow-pop backdrop:bg-black/75 backdrop:backdrop-blur-[2px]">
|
||
{scope && (
|
||
<CutSettingsEditor key={scope.kind === "session" ? `s${scope.session.id}` : `c${scope.channel.id}`} scope={scope}
|
||
onDirty={(d) => { dirtyRef.current = d; }} onClose={requestClose} onSaved={onSaved} />
|
||
)}
|
||
</dialog>
|
||
);
|
||
}
|
||
|
||
/* ---------- Editor ---------- */
|
||
|
||
/** O serviço antigo não manda `format`: completa como vertical, para o rascunho e a comparação "não salvo". */
|
||
function normalizePayload(p: SettingsPayload): SettingsPayload {
|
||
return { ...p, effective: withFormat(p.effective), defaults: withFormat(p.defaults) };
|
||
}
|
||
|
||
function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
|
||
scope: CutScope; onDirty: (dirty: boolean) => void; onClose: () => void; onSaved: () => void;
|
||
}) {
|
||
const session = scope.session;
|
||
const base = scope.kind === "session" ? `sessions/${scope.session.id}` : `channels/${encodeURIComponent(scope.channel.id)}`;
|
||
const channelId = scope.kind === "session" ? scope.session.channelId : scope.channel.id;
|
||
|
||
const [payload, setPayload] = useState<SettingsPayload | null>(null);
|
||
const [draft, setDraft] = useState<CutSettings | null>(null);
|
||
const [loadError, setLoadError] = useState<string | null>(null);
|
||
const [pending, setPending] = useState<string | null>(null);
|
||
const [message, setMessage] = useState<Message>(null);
|
||
const [target, setTarget] = useState<Target>("cam");
|
||
const [frame, setFrame] = useState<FrameResult | null>(null);
|
||
const [frameT, setFrameT] = useState<number | null>(null);
|
||
const [frameError, setFrameError] = useState<string | null>(null);
|
||
const [frameLoading, setFrameLoading] = useState(false);
|
||
const [preview, setPreview] = useState<PreviewResult | null>(null);
|
||
/** Formato pedido na última prévia (o serviço antigo não devolve `aspect`). */
|
||
const [previewAsked, setPreviewAsked] = useState<Aspect>("vertical");
|
||
const [previewError, setPreviewError] = useState<string | null>(null);
|
||
|
||
const load = useCallback(async (resetDraft: boolean) => {
|
||
const r = await clipperCall<SettingsPayload>(`${base}/settings`);
|
||
if (!r.ok) { setLoadError(r.error); return null; }
|
||
setLoadError(null);
|
||
const data = normalizePayload(r.data);
|
||
setPayload(data);
|
||
if (resetDraft) setDraft(structuredClone(data.effective));
|
||
return data;
|
||
}, [base]);
|
||
|
||
useEffect(() => { void load(true); }, [load]);
|
||
|
||
const loadFrame = useCallback(async (t: number | null) => {
|
||
if (!session) return;
|
||
setFrameLoading(true);
|
||
const r = await clipperCall<FrameResult>(`sessions/${session.id}/frame${t === null ? "" : `?t=${t.toFixed(1)}`}`);
|
||
setFrameLoading(false);
|
||
if (!r.ok) { setFrameError(r.error); return; }
|
||
setFrameError(null);
|
||
setFrame(r.data);
|
||
setFrameT(r.data.t);
|
||
}, [session]);
|
||
|
||
useEffect(() => { void loadFrame(null); }, [loadFrame]);
|
||
|
||
const dirty = Boolean(payload && draft && JSON.stringify(draft) !== JSON.stringify(payload.effective));
|
||
useEffect(() => { onDirty(dirty); }, [dirty, onDirty]);
|
||
// Fontes empacotadas (assets/fonts): carregadas para as amostras aparecerem na própria fonte.
|
||
usePackagedFonts(payload ? payload.fontFiles ?? {} : undefined);
|
||
|
||
if (loadError && !payload) {
|
||
return (
|
||
<EditorShell scope={scope} onClose={onClose}>
|
||
<div className="grid justify-items-start gap-4 p-6">
|
||
<Feedback ok={false}>Não foi possível ler a configuração: {loadError}</Feedback>
|
||
<Button variant="secondary" onClick={() => void load(true)}><RefreshIcon size={16} />Tentar de novo</Button>
|
||
</div>
|
||
</EditorShell>
|
||
);
|
||
}
|
||
if (!payload || !draft) {
|
||
return (
|
||
<EditorShell scope={scope} onClose={onClose}>
|
||
<p role="status" className="flex items-center gap-3 p-6 text-sm text-fg-muted"><Spinner />Carregando a configuração…</p>
|
||
</EditorShell>
|
||
);
|
||
}
|
||
|
||
// Base de baixo de cada camada: a sessão herda do canal; o canal herda do padrão.
|
||
const sessionBase = mergeSettings(payload.defaults, payload.channel ?? null);
|
||
const ownCount = countFields(payload.own);
|
||
const aspect = aspectOf(draft.format);
|
||
const horizontal = aspect === "horizontal";
|
||
const invalid = draft.duration.minS >= draft.duration.maxS;
|
||
|
||
function update<G extends keyof CutSettings>(group: G, values: Partial<CutSettings[G]>) {
|
||
setDraft((d) => (d ? { ...d, [group]: { ...d[group], ...values } } : d));
|
||
}
|
||
|
||
/** De onde vem o valor salvo de um campo: fixado nesta camada, herdado do canal ou padrão do Clipador. */
|
||
function originOf(group: keyof CutSettings, key: string): string {
|
||
const has = (layer: CutLayer | null | undefined) => (layer?.[group] as Record<string, unknown> | undefined)?.[key] !== undefined;
|
||
if (has(payload!.own)) return scope.kind === "session" ? "fixado nesta sessão" : "fixado nesta fonte";
|
||
if (scope.kind === "session" && has(payload!.channel)) return "herdado da fonte";
|
||
return "padrão do Clipador";
|
||
}
|
||
|
||
async function save(kind: "session" | "channel" | "clear-session" | "clear-channel") {
|
||
if (!draft || !payload) return;
|
||
setPending(kind);
|
||
setMessage(null);
|
||
let r: Awaited<ReturnType<typeof clipperCall<SettingsPayload>>>;
|
||
if (kind === "session") {
|
||
r = await clipperCall<SettingsPayload>(`${base}/settings`, "PUT", layerFrom(draft, sessionBase, payload.own));
|
||
} else if (kind === "channel") {
|
||
const channelOwn = scope.kind === "session" ? payload.channel : payload.own;
|
||
r = await clipperCall<SettingsPayload>(`channels/${encodeURIComponent(channelId!)}/settings`, "PUT", layerFrom(draft, payload.defaults, channelOwn));
|
||
} else {
|
||
r = await clipperCall<SettingsPayload>(`${base}/settings`, "PUT", {});
|
||
}
|
||
setPending(null);
|
||
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
|
||
// Salvar no canal a partir da sessão: relê a sessão (o efetivo dela muda).
|
||
let fresh: SettingsPayload | null = normalizePayload(r.data);
|
||
if (scope.kind === "session" && kind === "channel") fresh = await load(true);
|
||
else { setPayload(fresh); setDraft(structuredClone(fresh.effective)); }
|
||
const sessionStillOverrides = scope.kind === "session" && kind === "channel" && fresh && countFields(fresh.own) > 0;
|
||
// Serviço antigo: aceita o PUT mas descarta o grupo `format`. Avisa em vez de fingir que salvou.
|
||
const formatDropped = (kind === "session" || kind === "channel") && draft.format.aspect === "horizontal"
|
||
&& fresh !== null && r.data.effective.format === undefined;
|
||
const captureChanged = (kind === "session" || kind === "channel") && draft.capture?.quality !== payload.effective.capture?.quality;
|
||
setMessage({
|
||
ok: true,
|
||
text: (kind === "session" ? "Salvo nesta sessão. Vale para os próximos renders."
|
||
: kind === "channel" ? `Salvo como padrão da fonte.${sessionStillOverrides ? " Esta sessão tem ajustes próprios que continuam valendo; use “Limpar da sessão” para herdar tudo da fonte." : ""}`
|
||
: kind === "clear-session" ? "Ajustes da sessão apagados: ela volta a herdar da fonte e do padrão."
|
||
: "Padrão da fonte apagado: volta ao padrão do Clipador.")
|
||
+ (captureChanged ? " A qualidade de gravação nova vale na próxima gravação ou retomada." : "")
|
||
+ (formatDropped ? " Atenção: o Clipador em execução ainda não conhece o formato horizontal; o formato ficou vertical. Reinicie o serviço atualizado e salve de novo." : ""),
|
||
});
|
||
onSaved();
|
||
}
|
||
|
||
async function detectCam() {
|
||
if (!session) return;
|
||
setPending("detect");
|
||
setMessage(null);
|
||
const r = await clipperCall<CamDetect>(`sessions/${session.id}/detect-cam`, "POST");
|
||
setPending(null);
|
||
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
|
||
// O serviço pode ter salvo (no canal, se ele não tinha câmera; senão na sessão): relê as camadas,
|
||
// mas mantém o rascunho e só aplica a câmera achada.
|
||
await load(false);
|
||
if (r.data.hasWebcam && r.data.cam) {
|
||
update("layout", { cam: r.data.cam });
|
||
setTarget("cam");
|
||
setMessage({ ok: true, text: `Câmera encontrada.${r.data.gameOnScreen === false ? " A IA não viu jogo na tela neste momento." : ""} Confira o retângulo e salve.` });
|
||
} else {
|
||
setMessage({ ok: true, text: "A IA não achou webcam na tela. Sem câmera, o corte usa o vídeo inteiro com fundo desfocado." });
|
||
}
|
||
onSaved();
|
||
}
|
||
|
||
async function runPreview() {
|
||
if (!session || !draft) return;
|
||
setPending("preview");
|
||
setPreviewError(null);
|
||
const asked = aspectOf(draft.format);
|
||
const r = await clipperCall<PreviewResult>(`sessions/${session.id}/preview`, "POST", { ...(frameT !== null ? { t: frameT } : {}), settings: draft });
|
||
setPending(null);
|
||
if (!r.ok) { setPreviewError(r.error); return; }
|
||
setPreview(r.data);
|
||
setPreviewAsked(asked);
|
||
}
|
||
|
||
const busy = pending !== null;
|
||
const rect = draft.layout[target];
|
||
const groupCount = (...groups: (keyof CutSettings)[]) => {
|
||
const n = groups.reduce((sum, g) => sum + Object.keys(payload.own[g] ?? {}).length, 0);
|
||
return n > 0 ? n : undefined;
|
||
};
|
||
const layerName = scope.kind === "session" ? "esta sessão" : "esta fonte";
|
||
// Fontes que o serviço aceita: as do Windows e as empacotadas (com arquivo em assets/fonts).
|
||
const packagedFonts = Object.keys(payload.fontFiles ?? {});
|
||
const captureOptions = payload.captureQualities ?? [];
|
||
const fontList = [...new Set([...(payload.fonts?.length ? payload.fonts : SYSTEM_FONTS), ...packagedFonts])];
|
||
|
||
const tabs: TabItem<TabId>[] = [
|
||
{ id: "format", label: "Formato e duração", icon: <AspectIcon />, count: groupCount("format", "duration", "capture") },
|
||
{ id: "camera", label: "Câmera e layout", icon: <CameraIcon />, count: groupCount("layout") },
|
||
{ id: "caption", label: "Legenda", icon: <CaptionIcon />, count: groupCount("caption") },
|
||
{ id: "hook", label: "Gancho", icon: <HookIcon />, count: groupCount("hook") },
|
||
{ id: "credit", label: "Crédito", icon: <AtIcon />, count: groupCount("credit") },
|
||
];
|
||
|
||
/* ----- Aba: formato e duração ----- */
|
||
const formatPanel = (
|
||
<>
|
||
<Section title="Formato do vídeo" aside={<Origin text={originOf("format", "aspect")} />}
|
||
description="Escolha para qual tela o corte é feito. Câmera, legenda e crédito se ajustam ao formato.">
|
||
<fieldset className="grid gap-3 sm:grid-cols-2">
|
||
<legend className="sr-only">Formato do vídeo</legend>
|
||
{(["vertical", "horizontal"] as const).map((a) => {
|
||
const info = ASPECTS[a];
|
||
return (
|
||
<label key={a}
|
||
className={cx("group relative grid cursor-pointer grid-cols-[5.5rem_minmax(0,1fr)] items-center gap-4 rounded-card border bg-sunken/40 p-4 transition-colors",
|
||
"border-line-strong hover:border-fg-subtle/60 has-checked:border-accent has-checked:bg-accent-soft/50",
|
||
"has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-accent")}>
|
||
<input type="radio" name="cut-aspect" value={a} className="sr-only" checked={aspect === a}
|
||
onChange={() => update("format", { aspect: a })} />
|
||
<span className="grid size-22 place-items-center">
|
||
<FrameMock aspect={a} layout={draft.layout} caption={draft.caption} credit={draft.credit}
|
||
className={a === "vertical" ? "h-full" : "w-full"} />
|
||
</span>
|
||
<span className="grid min-w-0 gap-1">
|
||
<span className="flex flex-wrap items-center gap-2 text-sm font-semibold text-fg">
|
||
{info.label} {info.ratio}
|
||
{payload.defaults.format.aspect === a && <span className="rounded-full bg-overlay px-2 py-0.5 text-[0.6875rem] font-medium text-fg-subtle">padrão</span>}
|
||
</span>
|
||
<span className="flex items-center gap-2 text-[0.8125rem] text-fg-muted">
|
||
<span className="flex gap-1 text-fg-subtle">{info.networks}</span>{info.use}
|
||
</span>
|
||
<span className="font-mono text-[0.6875rem] text-fg-subtle">{info.size}</span>
|
||
<span className="text-xs leading-relaxed text-fg-subtle">{info.detail}</span>
|
||
</span>
|
||
<span aria-hidden="true"
|
||
className="absolute top-3 right-3 grid size-5 place-items-center rounded-full border border-line-strong text-transparent group-has-checked:border-accent group-has-checked:bg-accent group-has-checked:text-accent-fg">
|
||
<CheckIcon size={13} />
|
||
</span>
|
||
</label>
|
||
);
|
||
})}
|
||
</fieldset>
|
||
{horizontal && (
|
||
<Note tone="info">
|
||
No horizontal o corte usa o quadro inteiro do jogo (ou a área do jogo marcada). A câmera em cima e o fundo desfocado
|
||
ficam só para o vertical; “Câmera inteira” continua valendo. Detalhes na aba “Câmera e layout”.
|
||
</Note>
|
||
)}
|
||
</Section>
|
||
|
||
<Section title="Duração do corte"
|
||
description="A IA escolhe o trecho dentro destes limites. Os valores mostram minutos:segundos e o total em segundos.">
|
||
<div className="grid gap-x-8 gap-y-5 xl:grid-cols-2">
|
||
<RangeField label="Duração mínima" {...DURATION_LIMITS.minS} value={draft.duration.minS}
|
||
onChange={(minS) => update("duration", { minS })} format={durationLabel}
|
||
hint={`Padrão: ${formatClock(payload.defaults.duration.minS)} · ${originOf("duration", "minS")}`} />
|
||
<RangeField label="Duração máxima" {...DURATION_LIMITS.maxS} value={draft.duration.maxS}
|
||
onChange={(maxS) => update("duration", { maxS })} format={durationLabel}
|
||
hint={`Padrão: ${formatClock(payload.defaults.duration.maxS)} · ${originOf("duration", "maxS")}. ${horizontal ? "No YouTube horizontal não há limite curto; aqui vai até 3:00." : "Shorts aceita até 3:00."}`} />
|
||
<RangeField className="xl:col-span-2" label="Quanto a IA pode voltar no tempo" {...DURATION_LIMITS.backtrackS} value={draft.duration.backtrackS}
|
||
onChange={(backtrackS) => update("duration", { backtrackS })} format={(v) => (v === 0 ? "não volta" : durationLabel(v))}
|
||
hint={`Para dar contexto: pegar a ação que aconteceu antes do comentário ou da reação do chat. Padrão: ${formatClock(payload.defaults.duration.backtrackS)} · ${originOf("duration", "backtrackS")}`} />
|
||
</div>
|
||
{invalid
|
||
? <p role="alert" className="flex items-center gap-2 text-xs text-danger"><AlertIcon size={14} />A duração mínima precisa ser menor que a máxima.</p>
|
||
: <DurationSummary duration={draft.duration} />}
|
||
</Section>
|
||
|
||
{/* Qualidade de GRAVAÇÃO da live (serviço antigo não manda as opções: a seção some). */}
|
||
{captureOptions.length > 0 && draft.capture && (
|
||
<Section title="Qualidade da gravação" aside={<Origin text={originOf("capture", "quality")} />}
|
||
description="Em que resolução a live é gravada. Mais resolução deixa a câmera recortada mais nítida no corte e ocupa mais disco. Vale na próxima gravação ou retomada; uma gravação em andamento continua como está.">
|
||
<fieldset className="grid gap-2">
|
||
<legend className="sr-only">Qualidade da gravação</legend>
|
||
{captureOptions.map((o) => (
|
||
<label key={o.id}
|
||
className={cx("group grid cursor-pointer grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-3 rounded-control border bg-sunken/40 px-3.5 py-2.5 transition-colors",
|
||
"border-line-strong hover:border-fg-subtle/60 has-checked:border-accent has-checked:bg-accent-soft/50",
|
||
"has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-accent")}>
|
||
<input type="radio" name="cut-capture" value={o.id} className="sr-only" checked={draft.capture?.quality === o.id}
|
||
onChange={() => update("capture", { quality: o.id })} />
|
||
<span aria-hidden="true" className="grid size-4 place-items-center rounded-full border border-line-strong group-has-checked:border-accent">
|
||
<span className="size-2 rounded-full bg-accent opacity-0 group-has-checked:opacity-100" />
|
||
</span>
|
||
<span className="grid min-w-0 gap-0.5">
|
||
<span className="flex flex-wrap items-center gap-2 text-sm font-semibold text-fg">
|
||
{o.label}
|
||
{payload.defaults.capture?.quality === o.id && <span className="rounded-full bg-overlay px-2 py-0.5 text-[0.6875rem] font-medium text-fg-subtle">padrão</span>}
|
||
</span>
|
||
<span className="text-xs leading-relaxed text-fg-subtle">{o.hint}</span>
|
||
</span>
|
||
<span className="text-right font-mono text-xs whitespace-nowrap text-fg-muted tabular-nums" title="Disco por hora de live (medido em lives reais da Twitch)">
|
||
≈ {gbPerHourLabel(o.gbPerHour, o.gbPerHourMax)}
|
||
</span>
|
||
</label>
|
||
))}
|
||
</fieldset>
|
||
{session?.capture && (
|
||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-control border border-line bg-sunken/40 px-3 py-2 text-xs text-fg-muted">
|
||
<span className="font-semibold text-fg">{scope.kind === "session" ? "Esta sessão" : `Última sessão (#${session.id})`}:</span>
|
||
{ACTIVE_CAPTURE.includes(session.status) ? "gravando" : "gravada"} em
|
||
<span className="font-mono text-fg">{captureLabel(session.capture)}</span>
|
||
<span className="text-fg-subtle">
|
||
{[session.capture.codec.toUpperCase(), session.capture.gbPerHour ? `≈ ${gbPerHourLabel(session.capture.gbPerHour)}` : ""].filter(Boolean).join(" · ")}
|
||
</span>
|
||
{session.capture.mixed && <Badge tone="warning" dot={false}>trechos em outra resolução</Badge>}
|
||
</p>
|
||
)}
|
||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||
Os blocos gravados ficam no disco até o Clipador apagá-los (CLIPPER_KEEP_HOURS, padrão 6 h, só sem corte pendente):
|
||
6 h de live em 1080p60 ocupam ~20 GB; em 720p, ~9 GB. 2K só é gravado quando a fonte transmite em 2K (na Twitch, pela transmissão aprimorada).
|
||
</p>
|
||
</Section>
|
||
)}
|
||
</>
|
||
);
|
||
|
||
/* ----- Aba: câmera e layout ----- */
|
||
const effectiveHorizontal = draft.layout.mode === "cam_only" && draft.layout.cam
|
||
? "a câmera inteira (só o streamer)"
|
||
: draft.layout.game ? "a área do jogo marcada, em tela cheia" : "o quadro inteiro do jogo";
|
||
const cameraPanel = (
|
||
<>
|
||
{horizontal && (
|
||
<Note tone="info">
|
||
<strong className="font-semibold">Formato horizontal:</strong> o corte sai com {effectiveHorizontal}. “Câmera em cima”,
|
||
“Desfoque” e a altura da câmera só valem no vertical; ficam guardados para quando você voltar a ele. Marque a área do jogo
|
||
para cortar bordas, sobreposições ou o chat da live.
|
||
</Note>
|
||
)}
|
||
|
||
<section aria-labelledby="cut-frame" className="grid gap-3">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<h3 id="cut-frame" className="text-sm font-semibold text-fg">Onde ficam a câmera e o jogo</h3>
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<div role="group" aria-label="Retângulo em edição" className="flex gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
|
||
{(["cam", "game"] as const).map((t) => (
|
||
<button key={t} type="button" aria-pressed={target === t} onClick={() => setTarget(t)}
|
||
className={cx("flex items-center gap-2 rounded-[0.45rem] px-3 py-1 text-[0.8125rem] font-medium transition-colors focus-visible:outline-2 focus-visible:outline-accent",
|
||
target === t ? "bg-overlay text-fg" : "text-fg-muted hover:text-fg")}>
|
||
<span aria-hidden="true" className={cx("size-2.5 rounded-sm", t === "cam" ? "bg-accent" : "bg-option-b")} />
|
||
{t === "cam" ? "Câmera" : "Área do jogo (opcional)"}
|
||
</button>
|
||
))}
|
||
</div>
|
||
{session && (
|
||
<Button variant="flame" size="sm" disabled={busy} onClick={() => void detectCam()}>
|
||
{pending === "detect" ? <><Spinner className="size-3.5" />Procurando…</> : <><SparkIcon size={15} />Achar câmera com IA</>}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
|
||
<RectCanvas imageUrl={frame ? `${fileUrl(frame.file)}&v=${encodeURIComponent(frame.version)}` : null}
|
||
loading={frameLoading} cam={draft.layout.cam} game={draft.layout.game} target={target}
|
||
onTarget={setTarget} onChange={(which, r) => update("layout", { [which]: r } as Partial<CutSettings["layout"]>)} />
|
||
|
||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||
Arraste no quadro para desenhar o retângulo selecionado; arraste o retângulo para mover e os cantos para redimensionar.
|
||
Pelo teclado: foque o retângulo e use as setas (Shift + setas muda o tamanho).
|
||
</p>
|
||
</section>
|
||
|
||
<div className="grid gap-5 2xl:grid-cols-2">
|
||
<Section title="Retângulo e quadro de referência">
|
||
<div className="flex flex-wrap items-end gap-x-5 gap-y-3">
|
||
<RectFields label={target === "cam" ? "Câmera" : "Área do jogo"} rect={rect}
|
||
onChange={(r) => update("layout", { [target]: r } as Partial<CutSettings["layout"]>)} />
|
||
{rect && (
|
||
<Button variant="ghost" size="sm" onClick={() => update("layout", { [target]: null } as Partial<CutSettings["layout"]>)}>
|
||
<TrashIcon size={15} />Remover {target === "cam" ? "câmera" : "área do jogo"}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
{session ? (
|
||
<div className="grid gap-2 border-t border-line pt-4">
|
||
<RangeField label="Instante do quadro" min={0} max={Math.max(1, Math.floor(session.durationS))} step={1}
|
||
value={frameT ?? 0} onChange={setFrameT} format={(v) => formatClock(v)} disabled={frameLoading} />
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<Button variant="secondary" size="sm" disabled={frameLoading || frameT === null} onClick={() => void loadFrame(frameT)}>
|
||
{frameLoading ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Ver este instante
|
||
</Button>
|
||
<Button variant="ghost" size="sm" disabled={frameLoading} onClick={() => void loadFrame(null)}>Agora</Button>
|
||
{scope.kind === "channel" && <span className="text-xs text-fg-subtle">Quadro da sessão #{session.id} desta fonte.</span>}
|
||
</div>
|
||
{frameError && <Feedback ok={false}>{frameError}</Feedback>}
|
||
</div>
|
||
) : (
|
||
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-xs text-fg-subtle">
|
||
Esta fonte ainda não tem sessão gravada: dá para ajustar tudo, mas o quadro de referência e a prévia aparecem depois da primeira gravação.
|
||
</p>
|
||
)}
|
||
</Section>
|
||
|
||
<Section title="Modo de layout"
|
||
description={horizontal ? "No horizontal só “Câmera inteira” muda o resultado; os outros modos saem com o jogo em tela cheia." : undefined}>
|
||
<ChoiceGroup<LayoutMode> name="cut-mode" legend="Modo" value={draft.layout.mode} onChange={(mode) => update("layout", { mode })}
|
||
options={(["auto", "cam_top", "cam_only", "blur", "game_only"] as const).map((m) => ({ value: m, label: MODE_LABEL[m].label, hint: MODE_LABEL[m].hint }))} />
|
||
{!horizontal && (draft.layout.mode === "cam_top" || draft.layout.mode === "auto") && !draft.layout.cam && (
|
||
<p className="text-xs text-warning">Sem câmera marcada, o corte sai com fundo desfocado.</p>
|
||
)}
|
||
{draft.layout.mode === "cam_only" && !draft.layout.cam && (
|
||
<p className="text-xs text-warning">“Câmera inteira” precisa da câmera marcada; sem ela, o corte {horizontal ? "sai com o jogo em tela cheia" : "sai com fundo desfocado"}.</p>
|
||
)}
|
||
<RangeField label="Altura da câmera" min={0.2} max={0.6} step={0.01} value={draft.layout.camHeight}
|
||
onChange={(camHeight) => update("layout", { camHeight })} format={pct}
|
||
disabled={horizontal || !draft.layout.cam || draft.layout.mode === "blur" || draft.layout.mode === "game_only"}
|
||
hint={horizontal ? "Só no vertical, com a câmera em cima." : "Quanto da tela vertical a webcam ocupa no layout com câmera em cima."} />
|
||
</Section>
|
||
</div>
|
||
</>
|
||
);
|
||
|
||
/* ----- Aba: legenda ----- */
|
||
const captionPanel = (
|
||
<Section title="Legenda (transcrição)" aside={<Switch label="Mostrar legenda" checked={draft.caption.enabled} onChange={(enabled) => update("caption", { enabled })} />}
|
||
description="As palavras faladas aparecem no vídeo, com a palavra do momento destacada.">
|
||
<fieldset disabled={!draft.caption.enabled} className="grid gap-x-8 gap-y-6 disabled:opacity-50 xl:grid-cols-2">
|
||
<legend className="sr-only">Estilo da legenda</legend>
|
||
<div className="grid content-start gap-4">
|
||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Aparência</h4>
|
||
<CaptionSample caption={draft.caption} />
|
||
<div className="grid gap-2">
|
||
<span className="text-[0.8125rem] font-medium text-fg-muted">Fonte</span>
|
||
<FontPicker variant="panel" label="Fonte da legenda" fonts={fontList} packaged={packagedFonts} value={draft.caption.font}
|
||
onChange={(font) => update("caption", { font })} columns={2} />
|
||
</div>
|
||
<RangeField label="Tamanho" min={40} max={140} step={2} value={draft.caption.size} onChange={(size) => update("caption", { size })} format={(v) => `${v} px`} />
|
||
<div className="grid grid-cols-3 gap-2">
|
||
<ColorField label="Texto" value={draft.caption.color} onChange={(color) => update("caption", { color })} />
|
||
<ColorField label="Palavra falada" value={draft.caption.highlight} onChange={(highlight) => update("caption", { highlight })} />
|
||
<ColorField label="Contorno" value={draft.caption.outline} onChange={(outline) => update("caption", { outline })} />
|
||
</div>
|
||
<RangeField label="Espessura do contorno" min={0} max={14} step={1} value={draft.caption.outlineWidth}
|
||
onChange={(outlineWidth) => update("caption", { outlineWidth })} format={(v) => `${v} px`} />
|
||
<h4 className="pt-2 text-eyebrow font-semibold text-fg-subtle uppercase">Fala de outra pessoa</h4>
|
||
<p className="-mt-2 text-xs text-fg-subtle">
|
||
Colega no Discord ou outro jogador no chat de voz: a legenda dele sai logo abaixo da do streamer, nesta cor.
|
||
</p>
|
||
<div className="grid grid-cols-3 gap-2">
|
||
<ColorField label="Cor da outra pessoa" value={draft.caption.otherColor ?? "#5CE1FF"}
|
||
onChange={(otherColor) => update("caption", { otherColor })} />
|
||
</div>
|
||
<Switch label="Tamanho automático" checked={!draft.caption.otherSize}
|
||
onChange={(auto) => update("caption", { otherSize: auto ? null : Math.round(draft.caption.size * 0.85) })}
|
||
hint="85% do tamanho da legenda do streamer." />
|
||
{Boolean(draft.caption.otherSize) && (
|
||
<RangeField label="Tamanho da outra pessoa" min={30} max={140} step={2} value={draft.caption.otherSize ?? 70}
|
||
onChange={(otherSize) => update("caption", { otherSize })} format={(v) => `${v} px`} />
|
||
)}
|
||
</div>
|
||
<div className="grid content-start gap-4">
|
||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Ritmo e posição</h4>
|
||
<RangeField label="Palavras por vez" min={1} max={6} step={1} value={draft.caption.maxWords} onChange={(maxWords) => update("caption", { maxWords })} />
|
||
<Switch label="Caixa alta" checked={draft.caption.uppercase} onChange={(uppercase) => update("caption", { uppercase })} />
|
||
<Switch label="Tradução em português embaixo (teste)" checked={draft.dev?.translation ?? draft.caption.translation ?? false}
|
||
onChange={(translation) => update("dev", { translation })}
|
||
hint="Só no vídeo de revisão (fonte em inglês): a fala traduzida aparece embaixo da legenda. O vídeo final, ao aprovar, sai sem ela." />
|
||
<Switch label="Posição automática" checked={draft.caption.y === null}
|
||
onChange={(auto) => update("caption", { y: auto ? null : 0.74 })}
|
||
hint={horizontal ? "O serviço escolhe a altura no quadro horizontal." : "Na emenda entre câmera e jogo, ou a cerca de 74% da altura."} />
|
||
{draft.caption.y !== null && (
|
||
<RangeField label="Altura da legenda" min={0.08} max={0.9} step={0.01} value={draft.caption.y}
|
||
onChange={(y) => update("caption", { y })} format={(v) => `${pct(v)} do topo`} />
|
||
)}
|
||
<MockFigure aspect={aspect} layout={draft.layout} caption={draft.caption} credit={null} />
|
||
</div>
|
||
</fieldset>
|
||
<DubSettings dev={draft.dev} onChange={(values) => update("dev", values)} />
|
||
</Section>
|
||
);
|
||
|
||
/* ----- Aba: gancho ----- */
|
||
const hook = hookOf(draft);
|
||
const setHook = (values: Partial<HookSettings>) => update("hook", { ...hook, ...values });
|
||
const hookPanel = (
|
||
<Section title="Gancho (abertura do corte)" aside={<Origin text={originOf("hook", "style")} />}
|
||
description="O texto curto que a IA põe nos primeiros segundos de cada corte. Dá para trocar em cada corte, no editor.">
|
||
{!payload.hookStyles && (
|
||
<Note tone="warning">O Clipador em execução ainda não conhece o gancho em tarja: estes ajustes só são salvos depois de reiniciar o serviço atualizado.</Note>
|
||
)}
|
||
<div className="grid gap-x-8 gap-y-6 xl:grid-cols-2">
|
||
<div className="grid content-start gap-4">
|
||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Posição e estilo</h4>
|
||
<HookSample hook={hook} aspect={aspect} layout={draft.layout} caption={draft.caption} onMove={(y) => setHook({ y })} />
|
||
{(() => {
|
||
const place = hookPlacement(hook, aspect, draft.layout, draft.caption);
|
||
return (
|
||
<div className="grid gap-3">
|
||
<ChoiceGroup<"auto" | "chosen"> name="cut-hook-place" legend="Onde o gancho aparece" value={hook.y === null ? "auto" : "chosen"}
|
||
onChange={(v) => setHook({ y: v === "auto" ? null : place.y })}
|
||
options={[
|
||
{ value: "auto", label: "Automático", hint: place.camTop ? "logo abaixo da câmera" : "longe da legenda" },
|
||
{ value: "chosen", label: "Escolhido por mim", hint: "arraste no quadro" },
|
||
]} />
|
||
{hook.y !== null && (
|
||
<RangeField label="Altura do gancho na tela" min={0.04} max={0.96} step={0.002} value={hook.y}
|
||
onChange={(y) => setHook({ y })} format={hookPct}
|
||
hint={`Automático daria ${hookPct(place.auto)}. 0 % é o topo do vídeo.`} />
|
||
)}
|
||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||
{hook.y === null
|
||
? <>Agora em {hookPct(place.y)} da altura{place.camTop ? ", logo abaixo da câmera" : ""}. Arraste o gancho no quadro para escolher outro lugar.</>
|
||
: <>Centro do gancho em {hookPct(hook.y)} da altura (o mesmo número do editor do corte).</>}
|
||
{" "}Enquanto o gancho aparece, a legenda que ficaria embaixo dele desce para logo abaixo da tarja.
|
||
</p>
|
||
</div>
|
||
);
|
||
})()}
|
||
<ChoiceGroup<HookStyle> name="cut-hook-style" legend="Estilo" value={hook.style} onChange={(style) => setHook({ style })}
|
||
options={(["banner", "plain"] as const).map((v) => ({ value: v, label: HOOK_STYLE_LABEL[v].label, hint: HOOK_STYLE_LABEL[v].hint }))} />
|
||
<div className="grid grid-cols-2 gap-2">
|
||
{hook.style === "banner" && <ColorField label="Cor da tarja" value={hook.bg} onChange={(bg) => setHook({ bg })} />}
|
||
<ColorField label="Cor do texto" value={hook.color} onChange={(color) => setHook({ color })} />
|
||
</div>
|
||
<ChoiceGroup<HookAnim> name="cut-hook-anim" legend="Animação de entrada" value={hook.anim} onChange={(anim) => setHook({ anim })}
|
||
options={(["slide", "pop", "fade", "none"] as const).map((v) => ({ value: v, label: HOOK_ANIM_LABEL[v] }))} />
|
||
<RangeField label="Tempo na tela" min={1} max={8} step={0.5} value={hook.seconds} onChange={(seconds) => setHook({ seconds })}
|
||
format={(v) => `${v.toLocaleString("pt-BR")} s`}
|
||
hint={`Padrão: ${hookOf(payload.defaults).seconds.toLocaleString("pt-BR")} s · ${originOf("hook", "seconds")}`} />
|
||
</div>
|
||
<div className="grid content-start gap-2">
|
||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Fonte do gancho</h4>
|
||
<FontPicker variant="panel" label="Fonte do gancho" fonts={fontList} packaged={packagedFonts} value={hook.font}
|
||
onChange={(font) => setHook({ font })} columns={2} />
|
||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||
Na tarja o texto sai em maiúsculas, em até 2 linhas; se não couber, a fonte diminui (nunca corta palavra).
|
||
</p>
|
||
</div>
|
||
</div>
|
||
</Section>
|
||
);
|
||
|
||
/* ----- Aba: crédito ----- */
|
||
const creditPanel = (
|
||
<Section title="Crédito da fonte" aside={<Switch label="Mostrar crédito" checked={draft.credit.enabled} onChange={(enabled) => update("credit", { enabled })} />}
|
||
description="O endereço do streamer, por cima do vídeo. Para cortes de terceiros, deixe ligado.">
|
||
<div className="grid gap-x-8 gap-y-6 xl:grid-cols-[minmax(0,1fr)_auto]">
|
||
<fieldset disabled={!draft.credit.enabled} className="grid content-start gap-4 disabled:opacity-50">
|
||
<legend className="sr-only">Estilo do crédito</legend>
|
||
<ChoiceGroup<"top" | "bottom"> name="cut-credit" legend="Posição" value={draft.credit.position}
|
||
onChange={(position) => update("credit", { position })}
|
||
options={[{ value: "top", label: "Em cima" }, { value: "bottom", label: "Embaixo" }]} />
|
||
<RangeField label="Tamanho" min={24} max={80} step={2} value={draft.credit.size} onChange={(size) => update("credit", { size })} format={(v) => `${v} px`}
|
||
hint={!horizontal && draft.layout.mode === "cam_top" ? "Com a câmera em cima, o crédito de cima desce para o pé da câmera." : undefined} />
|
||
</fieldset>
|
||
<MockFigure aspect={aspect} layout={draft.layout} caption={null} credit={draft.credit} />
|
||
</div>
|
||
</Section>
|
||
);
|
||
|
||
return (
|
||
<EditorShell scope={scope} onClose={onClose}
|
||
meta={<>
|
||
<Badge tone="info" dot={false}>{ASPECTS[aspect].label} {ASPECTS[aspect].ratio}</Badge>
|
||
<Badge dot={false}><ClockIcon size={12} />{formatClock(draft.duration.minS)}–{formatClock(draft.duration.maxS)}</Badge>
|
||
{ownCount > 0
|
||
? <Badge tone="accent">{layerName} fixa {ownCount} ajuste{ownCount === 1 ? "" : "s"} (contados nas abas)</Badge>
|
||
: <Badge>{scope.kind === "session" ? "herdando da fonte e do padrão" : "usando o padrão do Clipador"}</Badge>}
|
||
{dirty && <Badge tone="warning">alterações não salvas</Badge>}
|
||
</>}
|
||
footer={
|
||
<footer className="grid gap-3 border-t border-line bg-surface px-6 py-4">
|
||
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
{scope.kind === "session" ? (
|
||
<>
|
||
<Button disabled={busy || !dirty || invalid} onClick={() => void save("session")}>
|
||
{pending === "session" ? <Spinner /> : <CheckIcon size={16} />}Salvar na sessão
|
||
</Button>
|
||
{channelId && (
|
||
<Button variant="secondary" disabled={busy || invalid} onClick={async () => {
|
||
if (await askConfirm({ title: "Salvar estes ajustes como padrão da fonte?",
|
||
message: "Valem para as próximas sessões dela.", confirmLabel: "Salvar na fonte" })) void save("channel");
|
||
}}>
|
||
{pending === "channel" ? <Spinner /> : <CheckIcon size={16} />}Salvar como padrão da fonte
|
||
</Button>
|
||
)}
|
||
{ownCount > 0 && (
|
||
<Button variant="ghost" disabled={busy} onClick={async () => {
|
||
if (await askConfirm({ title: "Limpar os ajustes desta sessão?",
|
||
message: "Ela volta a herdar da fonte e do padrão.", confirmLabel: "Limpar", tone: "danger" })) void save("clear-session");
|
||
}}>
|
||
{pending === "clear-session" ? <Spinner /> : <TrashIcon size={16} />}Limpar da sessão
|
||
</Button>
|
||
)}
|
||
</>
|
||
) : (
|
||
<>
|
||
<Button disabled={busy || !dirty || invalid} onClick={() => void save("channel")}>
|
||
{pending === "channel" ? <Spinner /> : <CheckIcon size={16} />}Salvar padrão da fonte
|
||
</Button>
|
||
{ownCount > 0 && (
|
||
<Button variant="ghost" disabled={busy} onClick={async () => {
|
||
if (await askConfirm({ title: "Apagar o padrão desta fonte?",
|
||
message: "Ele volta ao padrão do Clipador.", confirmLabel: "Apagar padrão", tone: "danger" })) void save("clear-channel");
|
||
}}>
|
||
{pending === "clear-channel" ? <Spinner /> : <TrashIcon size={16} />}Voltar ao padrão do Clipador
|
||
</Button>
|
||
)}
|
||
</>
|
||
)}
|
||
{dirty && (
|
||
<Button variant="ghost" disabled={busy} onClick={() => setDraft(structuredClone(payload.effective))}><UndoIcon size={16} />Desfazer</Button>
|
||
)}
|
||
<span className="ml-auto max-w-md text-xs text-fg-subtle">
|
||
{invalid
|
||
? <span className="text-danger">Para salvar, corrija a duração na aba “Formato e duração”: a mínima precisa ser menor que a máxima.</span>
|
||
: <>Vale para os próximos renders. Para refazer um corte já pronto, use “Re-renderizar” no cartão dele.</>}
|
||
</span>
|
||
</div>
|
||
</footer>
|
||
}>
|
||
<div className={cx("grid gap-6 p-6",
|
||
horizontal ? "lg:grid-cols-[minmax(0,1fr)_minmax(18rem,25rem)] 2xl:grid-cols-[minmax(0,1fr)_minmax(20rem,32rem)]" : "lg:grid-cols-[minmax(0,1fr)_minmax(15rem,20rem)]")}>
|
||
<Tabs<TabId> param={null} label="Seções da configuração do corte" items={tabs} className="min-w-0 content-start"
|
||
panels={{ format: formatPanel, camera: cameraPanel, caption: captionPanel, hook: hookPanel, credit: creditPanel }} />
|
||
|
||
{/* Prévia: sempre ao lado, na proporção do formato escolhido. */}
|
||
<aside aria-labelledby="cut-preview" className="grid content-start gap-3 lg:sticky lg:top-0 lg:self-start">
|
||
<div className="flex h-12 items-center justify-between gap-3 border-b border-line">
|
||
<h3 id="cut-preview" className="text-sm font-semibold text-fg">Prévia <span className="font-mono text-xs font-normal text-fg-subtle">{ASPECTS[aspect].size}</span></h3>
|
||
{preview && <Badge dot={false}>{MODE_LABEL[preview.mode]?.label ?? preview.mode}</Badge>}
|
||
</div>
|
||
<div className={cx("relative mx-auto grid max-w-full place-items-center overflow-hidden rounded-card border border-line bg-sunken",
|
||
horizontal ? "aspect-video w-full" : "aspect-9/16 h-[min(36rem,calc(94vh-20rem))]")}>
|
||
{preview ? (
|
||
// eslint-disable-next-line @next/next/no-img-element -- imagem local servida por /api/files
|
||
<img src={`${fileUrl(preview.file)}&v=${encodeURIComponent(preview.version)}`} alt="Prévia de como o corte vai ficar"
|
||
className={cx("size-full object-contain transition-opacity", pending === "preview" && "opacity-40")} />
|
||
) : (
|
||
<p className="max-w-52 px-4 text-center text-xs leading-relaxed text-fg-subtle">
|
||
{session ? "Clique em “Ver prévia” para ver câmera, jogo, legenda e crédito montados com os ajustes atuais." : "A prévia precisa de uma sessão gravada."}
|
||
</p>
|
||
)}
|
||
{pending === "preview" && <span className="absolute inset-0 grid place-items-center"><Spinner className="size-6 text-accent" /></span>}
|
||
</div>
|
||
<Button variant="secondary" disabled={!session || busy} onClick={() => void runPreview()}>
|
||
{pending === "preview" ? <Spinner /> : <EyeIcon size={16} />}Ver prévia
|
||
</Button>
|
||
{preview && <p className="text-xs text-fg-subtle">Quadro de {formatClock(preview.t)}. A prévia usa o que está na tela, mesmo sem salvar.</p>}
|
||
{preview && previewAsked === "horizontal" && preview.aspect === undefined && (
|
||
<Note tone="warning">O Clipador em execução ainda não gera prévia horizontal: a imagem acima é a vertical.</Note>
|
||
)}
|
||
{preview && previewAsked !== aspect && (
|
||
<Note tone="info">Esta prévia é do formato {ASPECTS[previewAsked].label.toLowerCase()}. Clique em “Ver prévia” para atualizar.</Note>
|
||
)}
|
||
{previewError && <Feedback ok={false}>{previewError}</Feedback>}
|
||
</aside>
|
||
</div>
|
||
</EditorShell>
|
||
);
|
||
}
|
||
|
||
/* ----- Dublagem em português (camada de teste; doc/clipador/DUBLAGEM.md) ----- */
|
||
|
||
// Padrões do Clipador (layout.DEFAULTS["dev"]); valem com o serviço antigo, que ainda não manda as chaves.
|
||
const DUB_VOICE = "pt-br-antonio";
|
||
const DUB_VOICE_OTHER = "kokoro-pm-alex";
|
||
const DUB_DUCK = 0.25;
|
||
|
||
function voiceLabel(v: VoiceInfo): string {
|
||
const gender = v.gender === "male" ? "masculina" : v.gender === "female" ? "feminina" : null;
|
||
return [v.name, gender, v.offline ? "offline" : "online"].filter(Boolean).join(" · ");
|
||
}
|
||
|
||
/** Fica fora da caixa da legenda: a dublagem não depende de a legenda estar ligada. */
|
||
function DubSettings({ dev, onChange }: {
|
||
dev: CutSettings["dev"]; onChange: (values: Partial<NonNullable<CutSettings["dev"]>>) => void;
|
||
}) {
|
||
const on = dev?.dub ?? false;
|
||
const [voices, setVoices] = useState<VoiceInfo[] | null>(null);
|
||
useEffect(() => {
|
||
if (!on || voices) return;
|
||
let alive = true;
|
||
// Só vozes TTS prontas em português: voz clonada fica de fora (nunca imitar o streamer, que não consentiu).
|
||
fetch("/api/voice/status", { cache: "no-store" }).then((r) => r.json()).then((s: { voices?: VoiceInfo[] }) => {
|
||
if (alive) setVoices((s.voices ?? []).filter((v) => v.provider !== "clone" && (v.languages ?? []).some((l) => l.toLowerCase().startsWith("pt"))));
|
||
}).catch(() => { if (alive) setVoices([]); });
|
||
return () => { alive = false; };
|
||
}, [on, voices]);
|
||
const voice = dev?.dubVoice ?? DUB_VOICE;
|
||
const other = dev?.dubVoiceOther ?? DUB_VOICE_OTHER;
|
||
const duck = dev?.dubDuck ?? DUB_DUCK;
|
||
const options = (current: string) => {
|
||
const list = voices ?? [];
|
||
// A voz salva aparece mesmo se o serviço estiver fora (ou se ela sair do catálogo).
|
||
return list.some((v) => v.id === current) ? list : [{ id: current, name: current } as VoiceInfo, ...list];
|
||
};
|
||
return (
|
||
<div className="mt-6 grid gap-x-8 gap-y-4 border-t border-line pt-5 xl:grid-cols-2">
|
||
<Switch label="Dublagem em português (teste)" checked={on} onChange={(dub) => onChange({ dub })}
|
||
hint={"Só no vídeo de revisão (fonte em inglês): cada frase traduzida é dublada por uma voz TTS pronta e o áudio original fica baixo por baixo — dá para ouvir o jogo. O 1º render demora mais (~1,6 s por frase; depois fica guardado). O vídeo final, ao aprovar, sai com o áudio original."} />
|
||
{on && (
|
||
<div className="grid content-start gap-4">
|
||
{voices === null && <p role="status" className="flex items-center gap-2 text-xs text-fg-subtle"><Spinner className="size-3" />Carregando as vozes…</p>}
|
||
{voices !== null && voices.length === 0 && <Note tone="warning">Serviço de voz fora do ar: a dublagem não sai até ele voltar.</Note>}
|
||
<Field label="Voz do streamer">
|
||
<Select value={voice} onChange={(e) => onChange({ dubVoice: e.target.value })}>
|
||
{options(voice).map((v) => <option key={v.id} value={v.id}>{v.languages ? voiceLabel(v) : v.id}</option>)}
|
||
</Select>
|
||
</Field>
|
||
<Field label="Voz de outra pessoa" hint="Para as falas de quem não é o streamer, quando a transcrição separar quem fala.">
|
||
<Select value={other} onChange={(e) => onChange({ dubVoiceOther: e.target.value })}>
|
||
{options(other).map((v) => <option key={v.id} value={v.id}>{v.languages ? voiceLabel(v) : v.id}</option>)}
|
||
</Select>
|
||
</Field>
|
||
<RangeField label="Volume do áudio original durante a dublagem" min={0} max={1} step={0.05} value={duck}
|
||
onChange={(dubDuck) => onChange({ dubDuck })} format={pct}
|
||
hint="Fora das falas dubladas o áudio fica normal." />
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function countFields(layer: CutLayer | null | undefined): number {
|
||
return Object.values(layer ?? {}).reduce((n, g) => n + Object.keys(g ?? {}).length, 0);
|
||
}
|
||
|
||
function pct(v: number): string {
|
||
return `${Math.round(v * 100)}%`;
|
||
}
|
||
|
||
/** "1:30 · 90 s" (abaixo de um minuto, só "45 s"). */
|
||
function durationLabel(seconds: number): string {
|
||
return seconds >= 60 ? `${formatClock(seconds)} · ${seconds} s` : `${seconds} s`;
|
||
}
|
||
|
||
function EditorShell({ scope, onClose, meta, footer, children }: {
|
||
scope: CutScope; onClose: () => void; meta?: ReactNode; footer?: ReactNode; children: ReactNode;
|
||
}) {
|
||
return (
|
||
<div className="flex h-full max-h-[94vh] flex-col">
|
||
<header className="flex flex-wrap items-start justify-between gap-4 border-b border-line bg-surface px-6 py-4">
|
||
<div className="grid min-w-0 gap-1.5">
|
||
<p className="flex items-center gap-2 text-eyebrow font-semibold text-accent uppercase"><SettingsIcon size={13} />Configuração do corte</p>
|
||
<h2 id="cut-settings-title" className="text-title text-fg">
|
||
{scope.kind === "session" ? <>Sessão #{scope.session.id} · {scope.name}</> : <>Padrão da fonte · {scope.channel.displayName || scope.channel.channel}</>}
|
||
</h2>
|
||
{meta && <div className="flex flex-wrap items-center gap-2">{meta}</div>}
|
||
</div>
|
||
<button type="button" onClick={onClose} aria-label="Fechar"
|
||
className="grid size-9 place-items-center rounded-control text-fg-subtle hover:bg-raised hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
|
||
<XIcon size={18} />
|
||
</button>
|
||
</header>
|
||
<div className="min-h-0 flex-1 overflow-y-auto">{children}</div>
|
||
{footer}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Bloco de uma aba: título, descrição curta e um canto à direita (chave liga/desliga ou origem do valor). */
|
||
function Section({ title, description, aside, children }: { title: string; description?: ReactNode; aside?: ReactNode; children: ReactNode }) {
|
||
return (
|
||
<section className="grid content-start gap-5 rounded-card border border-line bg-surface p-5">
|
||
<div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
|
||
<div className="grid min-w-0 gap-1">
|
||
<h3 className="text-[0.9375rem] font-semibold text-fg">{title}</h3>
|
||
{description && <p className="max-w-[70ch] text-[0.8125rem] leading-relaxed text-fg-subtle">{description}</p>}
|
||
</div>
|
||
{aside}
|
||
</div>
|
||
{children}
|
||
</section>
|
||
);
|
||
}
|
||
|
||
function Origin({ text }: { text: string }) {
|
||
return <span className="rounded-full border border-line-strong px-2.5 py-0.5 text-[0.6875rem] text-fg-subtle">{text}</span>;
|
||
}
|
||
|
||
function Note({ tone, children }: { tone: "info" | "warning"; children: ReactNode }) {
|
||
return (
|
||
<p className={cx("flex items-start gap-2 rounded-control border px-3 py-2.5 text-xs leading-relaxed",
|
||
tone === "info" ? "border-info/25 bg-info-soft text-info" : "border-warning/25 bg-warning-soft text-warning")}>
|
||
<AlertIcon size={14} className="mt-px" />
|
||
<span>{children}</span>
|
||
</p>
|
||
);
|
||
}
|
||
|
||
/** Resumo em frase + régua de 0 a 3:00: faixa do corte (mínimo cheio, até o máximo mais claro) e quanto a IA pode voltar. */
|
||
function DurationSummary({ duration }: { duration: CutSettings["duration"] }) {
|
||
const scale = 180;
|
||
const at = (s: number) => `${Math.min(100, (s / scale) * 100)}%`;
|
||
return (
|
||
<div className="grid gap-3 rounded-control border border-line bg-sunken/40 px-4 py-3">
|
||
<p className="text-[0.8125rem] leading-relaxed text-fg-muted">
|
||
Cada corte terá entre <strong className="font-semibold text-fg">{formatClock(duration.minS)}</strong> e{" "}
|
||
<strong className="font-semibold text-fg">{formatClock(duration.maxS)}</strong>.{" "}
|
||
{duration.backtrackS > 0
|
||
? <>Para dar contexto, a IA pode começar até <strong className="font-semibold text-fg">{formatClock(duration.backtrackS)}</strong> antes do momento que chamou atenção.</>
|
||
: <>A IA não volta no tempo: o corte começa perto do momento que chamou atenção.</>}
|
||
</p>
|
||
<div aria-hidden="true" className="grid gap-1.5">
|
||
<div className="grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-3 text-[0.6875rem] text-fg-subtle">
|
||
<span>Duração</span>
|
||
<span className="relative h-2.5 rounded-full bg-overlay">
|
||
<span className="absolute inset-y-0 left-0 rounded-full bg-accent" style={{ width: at(duration.minS) }} />
|
||
<span className="absolute inset-y-0 rounded-r-full bg-accent/35" style={{ left: at(duration.minS), width: `calc(${at(duration.maxS)} - ${at(duration.minS)})` }} />
|
||
</span>
|
||
<span>Voltar no tempo</span>
|
||
<span className="relative h-2.5 rounded-full bg-overlay">
|
||
<span className="absolute inset-y-0 left-0 rounded-full bg-violet/70" style={{ width: at(duration.backtrackS) }} />
|
||
</span>
|
||
</div>
|
||
<div className="ml-[6.75rem] flex justify-between font-mono text-[0.625rem] text-fg-subtle">
|
||
<span>0:00</span><span>1:00</span><span>2:00</span><span>3:00</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Esquema do quadro final (não é a prévia): câmera em laranja, jogo em ciano, legenda em branco e
|
||
* crédito em cinza, na proporção do formato. Serve de miniatura no seletor e de guia nas abas.
|
||
*/
|
||
function FrameMock({ aspect, layout, caption, credit, className }: {
|
||
aspect: Aspect; layout: CutSettings["layout"]; caption: CutSettings["caption"] | null; credit: CutSettings["credit"] | null; className?: string;
|
||
}) {
|
||
const vertical = aspect === "vertical";
|
||
const hasCam = Boolean(layout.cam);
|
||
const camOnly = layout.mode === "cam_only" && hasCam;
|
||
const camTop = vertical && hasCam && (layout.mode === "cam_top" || layout.mode === "auto");
|
||
const blur = vertical && !camOnly && (layout.mode === "blur" || ((layout.mode === "cam_top" || layout.mode === "auto" || layout.mode === "cam_only") && !hasCam));
|
||
const camH = camTop ? layout.camHeight : 0;
|
||
const captionY = caption?.enabled ? (caption.y ?? (camTop ? camH : vertical ? 0.74 : 0.85)) : null;
|
||
return (
|
||
<span aria-hidden="true" className={cx("relative block overflow-hidden rounded-[0.35rem] border border-line-strong bg-sunken",
|
||
vertical ? "aspect-9/16" : "aspect-video", className)}>
|
||
{camOnly ? (
|
||
<span className="absolute inset-0 bg-accent/35" />
|
||
) : blur ? (
|
||
<>
|
||
<span className="absolute inset-0 bg-option-b/12" />
|
||
<span className="absolute inset-x-0 top-1/2 aspect-video -translate-y-1/2 border-y border-option-b/60 bg-option-b/35" />
|
||
</>
|
||
) : (
|
||
<>
|
||
{camTop && <span className="absolute inset-x-0 top-0 border-b border-accent/70 bg-accent/35" style={{ height: `${camH * 100}%` }} />}
|
||
<span className="absolute inset-x-0 bottom-0 bg-option-b/30" style={{ top: `${camH * 100}%` }} />
|
||
</>
|
||
)}
|
||
{captionY !== null && (
|
||
<span className={cx("absolute left-1/2 h-[6%] -translate-x-1/2 -translate-y-1/2 rounded-[2px] bg-fg/90", vertical ? "w-3/4" : "w-2/5")}
|
||
style={{ top: `${captionY * 100}%` }} />
|
||
)}
|
||
{/* Com a câmera em cima, o crédito "em cima" desce para o pé da câmera (igual ao serviço). */}
|
||
{credit?.enabled && (
|
||
<span className={cx("absolute left-1/2 h-[4%] -translate-x-1/2 rounded-full bg-fg/50", vertical ? "w-1/2" : "w-1/5",
|
||
credit.position === "top" ? (camTop ? "" : "top-[4%]") : "bottom-[4%]")}
|
||
style={credit.position === "top" && camTop ? { top: `calc(${camH * 100}% - 8%)` } : undefined} />
|
||
)}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
/** Esquema com legenda, ao lado dos controles da legenda e do crédito. */
|
||
function MockFigure(props: { aspect: Aspect; layout: CutSettings["layout"]; caption: CutSettings["caption"] | null; credit: CutSettings["credit"] | null }) {
|
||
const vertical = props.aspect === "vertical";
|
||
return (
|
||
<figure className="grid justify-items-start gap-2">
|
||
<FrameMock {...props} className={vertical ? "h-56" : "w-72"} />
|
||
<figcaption className="max-w-72 text-[0.6875rem] leading-relaxed text-fg-subtle">
|
||
Esquema aproximado no formato {ASPECTS[props.aspect].label.toLowerCase()} ({ASPECTS[props.aspect].ratio}). Para ver de verdade, use “Ver prévia”.
|
||
</figcaption>
|
||
</figure>
|
||
);
|
||
}
|
||
|
||
/* ---------- Ícones das abas (traço igual ao de icons.tsx) ---------- */
|
||
|
||
function TabSvg({ children }: { children: ReactNode }) {
|
||
return (
|
||
<svg viewBox="0 0 24 24" width={16} height={16} fill="none" stroke="currentColor" strokeWidth="1.75"
|
||
strokeLinecap="round" strokeLinejoin="round" className="shrink-0" aria-hidden="true" focusable="false">
|
||
{children}
|
||
</svg>
|
||
);
|
||
}
|
||
const AspectIcon = () => <TabSvg><rect x="3" y="7" width="12" height="9" rx="1.5" /><rect x="16.5" y="3.5" width="5" height="17" rx="1.5" /></TabSvg>;
|
||
const CameraIcon = () => <TabSvg><rect x="3" y="6.5" width="13" height="11" rx="2" /><path d="m16 10.5 5-3v9l-5-3" /></TabSvg>;
|
||
const CaptionIcon = () => <TabSvg><rect x="3" y="5" width="18" height="14" rx="2.5" /><path d="M7 12.5h4M13 12.5h4M7 15.5h7" /></TabSvg>;
|
||
const HookIcon = () => <TabSvg><rect x="2.5" y="7" width="19" height="7" rx="1" /><path d="M7 10.5h10M9 18h6" /></TabSvg>;
|
||
const AtIcon = () => <TabSvg><circle cx="12" cy="12" r="3.5" /><path d="M15.5 12v1.25a2.25 2.25 0 0 0 4.5 0V12a8 8 0 1 0-3.2 6.4" /></TabSvg>;
|
||
|
||
/* ---------- Campos da legenda ---------- */
|
||
|
||
function ColorField({ label, value, onChange }: { label: string; value: string; onChange: (hex: string) => void }) {
|
||
const [text, setText] = useState(value);
|
||
const [synced, setSynced] = useState(value);
|
||
if (synced !== value) { setSynced(value); setText(value); }
|
||
return (
|
||
<div className="grid min-w-0 grid-cols-1 gap-2">
|
||
<span className="text-[0.8125rem] font-medium text-fg-muted">{label}</span>
|
||
<span className="flex h-10 min-w-0 items-center gap-2 rounded-control border border-line-strong bg-sunken/60 px-2 focus-within:border-accent">
|
||
<input type="color" value={value} onChange={(e) => onChange(e.target.value.toUpperCase())} aria-label={`${label}: escolher cor`}
|
||
className="size-7 shrink-0 cursor-pointer rounded border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-accent" />
|
||
<input value={text} maxLength={7} size={7} aria-label={`${label}: código da cor`} spellCheck={false}
|
||
onChange={(e) => {
|
||
setText(e.target.value);
|
||
if (/^#[0-9A-Fa-f]{6}$/.test(e.target.value)) onChange(e.target.value.toUpperCase());
|
||
}}
|
||
className="w-full min-w-0 flex-1 bg-transparent font-mono text-xs text-fg uppercase focus-visible:outline-none" />
|
||
</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Amostra instantânea (aproximada) da legenda: cores, contorno, fonte e caixa alta. A prévia real vem do serviço. */
|
||
function CaptionSample({ caption }: { caption: CutSettings["caption"] }) {
|
||
const words = ["ASSIM", "VAI", "FICAR"].map((w) => (caption.uppercase ? w : w.toLowerCase()));
|
||
const stroke = Math.min(4, caption.outlineWidth / 3);
|
||
return (
|
||
<div aria-hidden="true" className="grid place-items-center overflow-hidden rounded-control border border-line bg-[repeating-linear-gradient(45deg,#26262d_0_12px,#1d1d23_12px_24px)] px-3 py-4">
|
||
<span className="text-center text-2xl leading-tight" style={{
|
||
fontFamily: fontStack(caption.font), fontWeight: 900, color: caption.color,
|
||
WebkitTextStroke: stroke ? `${stroke}px ${caption.outline}` : undefined, paintOrder: "stroke fill",
|
||
}}>
|
||
{words.map((w, i) => <span key={w} style={i === 1 ? { color: caption.highlight } : undefined}>{w}{i < words.length - 1 ? " " : ""}</span>)}
|
||
</span>
|
||
{/* A fala de outra pessoa (colega no Discord), logo abaixo e na cor dela. */}
|
||
<span className="text-center text-lg leading-tight" style={{
|
||
fontFamily: fontStack(caption.font), fontWeight: 900, color: caption.otherColor ?? "#5CE1FF",
|
||
WebkitTextStroke: stroke ? `${stroke}px ${caption.outline}` : undefined, paintOrder: "stroke fill",
|
||
}}>{caption.uppercase ? "E O COLEGA" : "e o colega"}</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---------- Campos numéricos do retângulo (alternativa ao mouse) ---------- */
|
||
|
||
function RectFields({ label, rect, onChange }: { label: string; rect: Rect | null; onChange: (r: Rect) => void }) {
|
||
const fields: { key: keyof Rect; label: string }[] = [
|
||
{ key: "x", label: "X" }, { key: "y", label: "Y" }, { key: "w", label: "Largura" }, { key: "h", label: "Altura" },
|
||
];
|
||
return (
|
||
<fieldset className="flex flex-wrap items-end gap-2">
|
||
<legend className="mb-1.5 text-[0.8125rem] font-medium text-fg-muted">{label} (% do quadro)</legend>
|
||
{fields.map((f) => (
|
||
<label key={f.key} className="grid gap-1 text-[0.6875rem] text-fg-subtle">
|
||
{f.label}
|
||
<input type="number" min={0} max={100} step={0.5} disabled={!rect}
|
||
value={rect ? Math.round(rect[f.key] * 1000) / 10 : ""}
|
||
onChange={(e) => {
|
||
if (!rect || e.target.value === "") return;
|
||
onChange(clampRect({ ...rect, [f.key]: Number(e.target.value) / 100 }));
|
||
}}
|
||
className="h-8 w-20 rounded-md border border-line-strong bg-sunken/60 px-2 font-mono text-xs text-fg focus:border-accent focus-visible:outline-none disabled:opacity-50" />
|
||
</label>
|
||
))}
|
||
{!rect && <span className="pb-2 text-xs text-fg-subtle">nenhum: desenhe no quadro</span>}
|
||
</fieldset>
|
||
);
|
||
}
|
||
|
||
/* ---------- Quadro com retângulos arrastáveis ---------- */
|
||
|
||
// Limites, mover, redimensionar e teclado vêm de rect-geometry.ts (o monitor "Fonte" do editor usa os mesmos).
|
||
type Corner = "nw" | "ne" | "sw" | "se";
|
||
type Drag =
|
||
| { kind: "draw"; which: Target; origin: { x: number; y: number }; before: Rect | null }
|
||
| { kind: "move"; which: Target; origin: { x: number; y: number }; start: Rect }
|
||
| { kind: "resize"; which: Target; corner: Corner; start: Rect };
|
||
|
||
function RectCanvas({ imageUrl, loading, cam, game, target, onTarget, onChange }: {
|
||
imageUrl: string | null; loading: boolean; cam: Rect | null; game: Rect | null; target: Target;
|
||
onTarget: (t: Target) => void; onChange: (which: Target, rect: Rect | null) => void;
|
||
}) {
|
||
const box = useRef<HTMLDivElement>(null);
|
||
const drag = useRef<Drag | null>(null);
|
||
|
||
const point = (e: PointerEvent) => {
|
||
const b = box.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 onPointerDown(e: PointerEvent<HTMLDivElement>) {
|
||
if (e.button !== 0) return;
|
||
const el = e.target as HTMLElement;
|
||
const which = (el.closest("[data-rect]") as HTMLElement | null)?.dataset.rect as Target | undefined;
|
||
const corner = el.dataset.corner as Corner | undefined;
|
||
const p = point(e);
|
||
const current = { cam, game };
|
||
if (which && corner) drag.current = { kind: "resize", which, corner, start: current[which]! };
|
||
else if (which) drag.current = { kind: "move", which, origin: p, start: current[which]! };
|
||
else drag.current = { kind: "draw", which: target, origin: p, before: current[target] };
|
||
if (which) onTarget(which);
|
||
box.current!.setPointerCapture(e.pointerId);
|
||
e.preventDefault();
|
||
}
|
||
|
||
function onPointerMove(e: PointerEvent<HTMLDivElement>) {
|
||
const d = drag.current;
|
||
if (!d) return;
|
||
const p = point(e);
|
||
if (d.kind === "draw") {
|
||
const x = Math.min(p.x, d.origin.x), y = Math.min(p.y, d.origin.y);
|
||
onChange(d.which, { x, y, w: Math.abs(p.x - d.origin.x), h: Math.abs(p.y - d.origin.y) });
|
||
} else if (d.kind === "move") {
|
||
onChange(d.which, moveRect(d.start, d.origin, p));
|
||
} else {
|
||
onChange(d.which, resizeRect(d.start, d.corner, p));
|
||
}
|
||
}
|
||
|
||
function onPointerUp(e: PointerEvent<HTMLDivElement>) {
|
||
const d = drag.current;
|
||
drag.current = null;
|
||
if (box.current?.hasPointerCapture(e.pointerId)) box.current.releasePointerCapture(e.pointerId);
|
||
if (d?.kind !== "draw") return;
|
||
// Um clique sem arrastar não apaga o retângulo que já existia.
|
||
const p = point(e);
|
||
const w = Math.abs(p.x - d.origin.x), h = Math.abs(p.y - d.origin.y);
|
||
if (w < RECT_MIN_SIZE || h < RECT_MIN_SIZE) onChange(d.which, d.before);
|
||
else onChange(d.which, clampRect({ x: Math.min(p.x, d.origin.x), y: Math.min(p.y, d.origin.y), w, h }));
|
||
}
|
||
|
||
function onRectKey(which: Target, r: Rect, e: KeyboardEvent<HTMLDivElement>) {
|
||
const next = nudgeRect(r, e.key, e.shiftKey);
|
||
if (!next) return;
|
||
e.preventDefault();
|
||
onTarget(which);
|
||
onChange(which, next);
|
||
}
|
||
|
||
const rects: { which: Target; rect: Rect | null }[] = [{ which: "game", rect: game }, { which: "cam", rect: cam }];
|
||
|
||
return (
|
||
<div ref={box} onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp}
|
||
className="relative aspect-video w-full cursor-crosshair touch-none overflow-hidden rounded-card border border-line-strong bg-sunken select-none">
|
||
{imageUrl ? (
|
||
// eslint-disable-next-line @next/next/no-img-element -- quadro local servido por /api/files
|
||
<img src={imageUrl} alt="Quadro do vídeo original" draggable={false} className={cx("pointer-events-none absolute inset-0 size-full object-cover", loading && "opacity-50")} />
|
||
) : (
|
||
<div className="pointer-events-none absolute inset-0 grid place-items-center bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[10%_10%] text-xs text-fg-subtle">
|
||
{loading ? <Spinner className="size-5 text-accent" /> : "Quadro 16:9 (sem imagem de referência)"}
|
||
</div>
|
||
)}
|
||
{rects.map(({ which, rect }) => rect && (
|
||
<div key={which} data-rect={which} tabIndex={0} role="group"
|
||
aria-label={`${which === "cam" ? "Câmera" : "Área do jogo"}: x ${pct(rect.x)}, y ${pct(rect.y)}, largura ${pct(rect.w)}, altura ${pct(rect.h)}. Setas movem; Shift + setas mudam o tamanho.`}
|
||
onKeyDown={(e) => onRectKey(which, rect, e)}
|
||
className={cx("absolute cursor-move border-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-fg",
|
||
which === "cam" ? "border-accent bg-accent/15" : "border-option-b border-dashed bg-option-b/10",
|
||
which === target ? "z-10" : "opacity-70")}
|
||
style={{ left: `${rect.x * 100}%`, top: `${rect.y * 100}%`, width: `${rect.w * 100}%`, height: `${rect.h * 100}%` }}>
|
||
<span className={cx("pointer-events-none absolute -top-px left-0 -translate-y-full rounded-t-md px-1.5 py-0.5 text-[0.6875rem] font-semibold whitespace-nowrap",
|
||
which === "cam" ? "bg-accent text-accent-fg" : "bg-option-b text-sunken")}>
|
||
{which === "cam" ? "Câmera" : "Jogo"}
|
||
</span>
|
||
{which === target && (["nw", "ne", "sw", "se"] as const).map((c) => (
|
||
<span key={c} data-corner={c} aria-hidden="true"
|
||
className={cx("absolute size-3 rounded-sm border-2 border-canvas",
|
||
which === "cam" ? "bg-accent" : "bg-option-b",
|
||
c.includes("n") ? "-top-1.5" : "-bottom-1.5", c.includes("w") ? "-left-1.5" : "-right-1.5",
|
||
c === "nw" || c === "se" ? "cursor-nwse-resize" : "cursor-nesw-resize")} />
|
||
))}
|
||
</div>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---------- Amostra e posição do gancho ---------- */
|
||
|
||
// Espelho de `layout.hook_y` do Clipador (app/layout.py): com a câmera em cima, logo abaixo dela; senão 20 % da altura,
|
||
// trocando de lado se cair na legenda automática. Escolhido (`hook.y`) vale como está.
|
||
const HOOK_BELOW_CAM = 0.044;
|
||
const clampHookY = (y: number) => Math.min(0.96, Math.max(0.04, y));
|
||
const hookPct = (y: number) => `${(Math.round(y * 1000) / 10).toLocaleString("pt-BR")} %`;
|
||
|
||
function hookPlacement(hook: HookSettings, aspect: Aspect, layout: CutSettings["layout"], caption: CutSettings["caption"]) {
|
||
const vertical = aspect === "vertical";
|
||
const hasCam = Boolean(layout.cam);
|
||
const camTop = vertical && hasCam && (layout.mode === "cam_top" || layout.mode === "auto");
|
||
const camH = camTop ? layout.camHeight : 0;
|
||
// Legenda automática: na emenda câmera/jogo (câmera em cima), 74 % no vertical, 85 % no horizontal.
|
||
const capAuto = caption.y ?? (camTop ? camH + 0.02 : vertical ? 0.74 : 0.85);
|
||
let auto = 0.2;
|
||
if (camTop) auto = Math.min(0.96, Math.round((camH + HOOK_BELOW_CAM) * 1000) / 1000);
|
||
else if (Math.abs(capAuto - 0.2) < 0.2) auto = capAuto > 0.3 ? capAuto - 0.22 : Math.min(0.85, capAuto + 0.22);
|
||
return { y: hook.y ?? auto, auto, camTop, camH, captionY: caption.enabled ? capAuto : null };
|
||
}
|
||
|
||
/**
|
||
* Amostra do gancho num quadro no formato do corte: tarja (faixa na largura toda) ou texto simples com caixa, na fonte
|
||
* e nas cores escolhidas. "Ver a entrada" toca a animação (Web Animations; nada com movimento reduzido).
|
||
*/
|
||
function HookSample({ hook, aspect, layout, caption, onMove }: {
|
||
hook: HookSettings; aspect: Aspect; layout: CutSettings["layout"]; caption: CutSettings["caption"];
|
||
/** Nova posição (fração da altura) ao arrastar ou usar o teclado. */
|
||
onMove: (y: number) => void;
|
||
}) {
|
||
const band = useRef<HTMLSpanElement>(null);
|
||
const text = useRef<HTMLSpanElement>(null);
|
||
const frame = useRef<HTMLDivElement>(null);
|
||
const [run, setRun] = useState(0);
|
||
const [dragging, setDragging] = useState(false);
|
||
const banner = hook.style === "banner";
|
||
const place = hookPlacement(hook, aspect, layout, caption);
|
||
const fromPointer = (clientY: number) => {
|
||
const r = frame.current?.getBoundingClientRect();
|
||
if (!r) return;
|
||
onMove(clampHookY(Math.round(((clientY - r.top) / r.height) * 1000) / 1000));
|
||
};
|
||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||
const step = e.key === "PageUp" || e.key === "PageDown" ? 0.05 : 0.01;
|
||
if (e.key === "ArrowUp" || e.key === "PageUp") onMove(clampHookY(place.y - step));
|
||
else if (e.key === "ArrowDown" || e.key === "PageDown") onMove(clampHookY(place.y + step));
|
||
else return;
|
||
e.preventDefault();
|
||
};
|
||
useEffect(() => {
|
||
if (!run || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||
const t = text.current, b = band.current;
|
||
if (hook.anim === "slide") {
|
||
b?.animate([{ transform: "translateX(-100%)" }, { transform: "none" }], { duration: 240 });
|
||
t?.animate([{ transform: "translateX(55%)", offset: 0 }, { transform: "translateX(55%)", offset: 90 / 430 }, { transform: "none" }], { duration: 430 });
|
||
} else if (hook.anim === "pop") {
|
||
for (const el of [b, t]) el?.animate([{ transform: "scale(.7)", opacity: 0 }, { transform: "scale(1.08)", opacity: 1, offset: 0.64 }, { transform: "none" }], { duration: 220 });
|
||
} else if (hook.anim === "fade") {
|
||
for (const el of [b, t]) el?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 250 });
|
||
}
|
||
}, [run, hook.anim]);
|
||
const words = "Assim fica o gancho";
|
||
const size = aspect === "vertical" ? "text-base" : "text-lg";
|
||
const textStyle = { fontFamily: fontStack(hook.font), fontWeight: 700, color: hook.color } as const;
|
||
const at = { top: `${place.y * 100}%`, transform: "translateY(-50%)" } as const;
|
||
return (
|
||
<div className="grid gap-2">
|
||
{/* Quadro do corte: câmera (laranja) e jogo (ciano) como na aba Câmera, a legenda tracejada e o gancho, que se
|
||
arrasta para cima e para baixo (ou setas do teclado com o quadro em foco). */}
|
||
<div ref={frame} role="slider" tabIndex={0} aria-label="Posição do gancho na tela" aria-orientation="vertical"
|
||
aria-valuemin={4} aria-valuemax={96} aria-valuenow={Math.round(place.y * 100)}
|
||
aria-valuetext={`${hookPct(place.y)} da altura${hook.y === null ? " (automática)" : ""}`}
|
||
onKeyDown={onKey}
|
||
onPointerDown={(e: PointerEvent<HTMLDivElement>) => { e.currentTarget.setPointerCapture(e.pointerId); setDragging(true); fromPointer(e.clientY); }}
|
||
onPointerMove={(e: PointerEvent<HTMLDivElement>) => { if (dragging) fromPointer(e.clientY); }}
|
||
onPointerUp={() => setDragging(false)} onPointerCancel={() => setDragging(false)}
|
||
className={cx("relative touch-none overflow-hidden rounded-control border border-line bg-sunken select-none focus-visible:outline-2 focus-visible:outline-accent",
|
||
dragging ? "cursor-grabbing" : "cursor-grab",
|
||
aspect === "vertical" ? "mx-auto aspect-9/16 h-80" : "aspect-video w-full max-w-md")}>
|
||
{place.camTop && (
|
||
<span aria-hidden="true" className="absolute inset-x-0 top-0 grid place-items-center border-b border-accent/70 bg-accent/25 text-[0.6875rem] font-semibold tracking-wide text-accent uppercase"
|
||
style={{ height: `${place.camH * 100}%` }}>Câmera</span>
|
||
)}
|
||
<span aria-hidden="true" className="absolute inset-x-0 bottom-0 grid place-items-end justify-center bg-option-b/15 pb-2 text-[0.6875rem] font-semibold tracking-wide text-option-b uppercase"
|
||
style={{ top: `${place.camH * 100}%` }}>Jogo</span>
|
||
{place.captionY !== null && (
|
||
<span aria-hidden="true" className="absolute left-1/2 grid h-[5%] w-3/4 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-[3px] border border-dashed border-fg/60 text-[0.625rem] text-fg-muted"
|
||
style={{ top: `${place.captionY * 100}%` }}>legenda</span>
|
||
)}
|
||
{banner ? (
|
||
<span ref={band} aria-hidden="true" className="absolute inset-x-0 grid place-items-center px-2 py-1.5 shadow-[0_0_0_2px_rgba(0,0,0,.35)]" style={{ ...at, background: hook.bg }}>
|
||
<span ref={text} className={cx("block text-center leading-tight uppercase", size)}
|
||
style={{ ...textStyle, WebkitTextStroke: "3px #000", paintOrder: "stroke fill", textShadow: "2px 2px 0 #000" }}>{words}</span>
|
||
</span>
|
||
) : (
|
||
<span aria-hidden="true" className="absolute inset-x-0 grid place-items-center px-2" style={at}>
|
||
<span ref={text} className={cx("block bg-[#E11D48] px-2 py-1 text-center leading-tight", size)} style={textStyle}>{words}</span>
|
||
</span>
|
||
)}
|
||
</div>
|
||
<Button variant="ghost" size="sm" className="justify-self-start" disabled={hook.anim === "none"} onClick={() => setRun((n) => n + 1)}>
|
||
<EyeIcon size={15} />Ver a entrada
|
||
</Button>
|
||
</div>
|
||
);
|
||
}
|