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>
1103 lines
71 KiB
TypeScript
1103 lines
71 KiB
TypeScript
"use client";
|
||
// Propriedades do editor de cortes: o painel da direita mostra as propriedades DO QUE ESTÁ SELECIONADO (um
|
||
// trecho, um texto, um zoom, uma narração, palavras, ou uma camada inteira: vídeo, legenda, áudio…), no formato
|
||
// "rótulo · controle · valor em azul" dos editores de vídeo. Fluxos maiores abrem em modal: Exportar (prévia real,
|
||
// capa, render), IA sugere, Nova narração e Atalhos. Tudo que muda o projeto entra no desfazer e no autosave.
|
||
import { useEffect, useState, type ReactNode } from "react";
|
||
import {
|
||
HOOK_ANIM_LABEL, MODE_LABEL, clipperCall, hookOf, type Aspect, type CamDetect, type Clip, type CutSettings, type FrameSize, type HookAnim, type LayoutMode,
|
||
type Rect, type SettingsPayload,
|
||
} from "./clipper-client";
|
||
import { FontPicker } from "./clip-editor-fonts";
|
||
import {
|
||
RESOLVED_MODE_LABEL, chatDefault, clamp, clockTenths, cutAt, editLayout, keepRange, newHook, newId, outputDuration, produce, removeRange, resolvedMode,
|
||
round3, sessionClock, splitAt, toOutput, toSession, toggleChat, zoomFocusDefault, type CaptionPreset, type EditBundle, type EditProject, type EditWord,
|
||
type Frame, type LayerKey, type Narration, type Selection, type Suggestion, type TextOverlay, type ZoomOverlay,
|
||
} from "./clip-editor-model";
|
||
import { Btn, Check, ColorDot, Hint, Hot, Keycap, Modal, Pick, PropRow, PropSection, RectFields, RowButton, Scrub, fieldClass } from "./clip-editor-ui";
|
||
import { InsetProps, InsetsLayer, ReframeKeyProps, ReframeLayer, type KeyframeControl } from "./clip-editor-keyframes";
|
||
import { SourceTargetToggle } from "./clip-editor-source";
|
||
import { CheckIcon, DownloadIcon, MicIcon, PlayIcon, PlusIcon, ScissorsIcon, SparkIcon, TrashIcon, WandIcon } from "./icons";
|
||
import { clampRect } from "./rect-geometry";
|
||
import { Spinner, cx, fileUrl } from "./ui";
|
||
import { askConfirm } from "./confirm-dialog";
|
||
|
||
type Update = (fn: (p: EditProject) => EditProject, key?: string) => void;
|
||
type Notice = (ok: boolean, text: string) => void;
|
||
export type ModalKind = "export" | "ai" | "narration" | "keys" | null;
|
||
|
||
export type InspectorProps = {
|
||
bundle: EditBundle;
|
||
project: EditProject;
|
||
cfg: CutSettings;
|
||
playhead: number;
|
||
selection: Selection;
|
||
onProject: Update;
|
||
onSelect: (s: Selection) => void;
|
||
onSeek: (t: number) => void;
|
||
onNotice: Notice;
|
||
/** Troca a janela da gravação (gera outro proxy). */
|
||
onWindow: (lo: number, hi: number) => Promise<boolean>;
|
||
onModal: (m: ModalKind) => void;
|
||
clip: Clip;
|
||
/** Câmera e área do jogo no monitor "Fonte" (o mesmo estado nos dois lugares). */
|
||
source: SourceControl;
|
||
/** Formato efetivo do corte (quadro do vídeo e dos textos). */
|
||
frame: Frame;
|
||
/** Fontes que o serviço aceita (as empacotadas em `fontFiles`) e quadros de cada formato. */
|
||
catalog: EditorCatalog;
|
||
/** Keyframe do enquadramento no playhead e inserção nova (desenhada na Fonte). */
|
||
keyframes: KeyframeControl;
|
||
};
|
||
|
||
/** Retângulo da camada Câmera em edição na Fonte. */
|
||
type CamTarget = "cam" | "game";
|
||
|
||
/** O que o editor lê da rota de settings da sessão (o pacote do editor não traz). */
|
||
export type EditorCatalog = {
|
||
loaded: boolean; fonts: string[]; fontFiles: Record<string, string>; frames: Record<Aspect, FrameSize> | null;
|
||
/** Tamanho da gravação original (sessão › capture), para a prévia recortar como o FFmpeg. null = desconhecido. */
|
||
source: { w: number; h: number } | null;
|
||
};
|
||
|
||
const ASPECT_LABEL: Record<Aspect, string> = { vertical: "Vertical 9:16", horizontal: "Horizontal 16:9" };
|
||
|
||
/** Ligação entre Propriedades e o monitor "Fonte". */
|
||
export type SourceControl = {
|
||
/** Retângulo em edição (Câmera ou Área do jogo). */
|
||
target: CamTarget;
|
||
onTarget: (t: CamTarget) => void;
|
||
/** "Editar na fonte" ligado: a Fonte aparece mesmo em tela estreita ou escondida, com o retângulo focado. */
|
||
editing: boolean;
|
||
onEdit: (on: boolean, which?: CamTarget) => void;
|
||
/** Depois de gravar câmera/jogo na sessão: atualiza a configuração da sessão que o editor tem em memória. */
|
||
onSessionLayout: (layout: CutSettings["layout"]) => void;
|
||
};
|
||
|
||
const sec = (v: number) => `${v.toFixed(1).replace(".", ",")} s`;
|
||
const pct = (v: number) => `${Math.round(v * 100)}%`;
|
||
const LAYER_TITLE: Record<LayerKey, string> = {
|
||
video: "Vídeo", camera: "Câmera e layout", captions: "Legenda", texts: "Textos", zooms: "Zoom", audio: "Áudio da live",
|
||
narration: "Narração", music: "Música e efeitos", progress: "Barra de progresso", cover: "Capa", chat: "Chat na tela",
|
||
reframe: "Enquadramento do jogo", insets: "Inserções",
|
||
};
|
||
|
||
/** Título do painel (o que está selecionado) + o corpo certo. */
|
||
export function Properties(props: InspectorProps) {
|
||
const { selection: sel, project } = props;
|
||
let title = "Vídeo";
|
||
let body: ReactNode = <VideoProps {...props} />;
|
||
if (sel?.kind === "cut" && project.cuts[sel.index]) { title = `Trecho ${sel.index + 1}`; body = <CutProps {...props} index={sel.index} />; }
|
||
else if (sel?.kind === "range") { title = "Trecho selecionado"; body = <RangeProps {...props} a={sel.a} b={sel.b} />; }
|
||
else if (sel?.kind === "words") { title = sel.from === sel.to ? "Palavra" : `${sel.to - sel.from + 1} palavras`; body = <WordProps {...props} from={sel.from} to={sel.to} />; }
|
||
else if (sel?.kind === "overlay") {
|
||
const o = project.overlays.find((x) => x.id === sel.id);
|
||
if (o?.kind === "zoom") { title = "Zoom"; body = <ZoomProps {...props} zoom={o} />; }
|
||
else if (o?.kind === "inset") { title = sel.key !== undefined ? `Inserção · keyframe ${sel.key + 1}` : "Inserção"; body = <InsetProps {...props} inset={o} keyIndex={sel.key} />; }
|
||
else if (o) { title = o.kind === "hook" ? "Gancho" : "Texto"; body = <TextProps {...props} text={o} />; }
|
||
} else if (sel?.kind === "reframe" && project.reframe?.keys[sel.key]) {
|
||
title = "Enquadramento · keyframe";
|
||
body = <ReframeKeyProps {...props} index={sel.key} />;
|
||
} else if (sel?.kind === "narration") {
|
||
const n = project.audio.narration.find((x) => x.id === sel.id);
|
||
if (n) { title = "Narração"; body = <NarrationProps {...props} n={n} />; }
|
||
} else if (sel?.kind === "layer") {
|
||
title = LAYER_TITLE[sel.layer];
|
||
body = { video: <VideoProps {...props} />, camera: <CameraLayer {...props} />, chat: <ChatLayer {...props} />, captions: <CaptionProps {...props} />, texts: <TextsLayer {...props} />, zooms: <ZoomsLayer {...props} />,
|
||
audio: <AudioLayer {...props} />, narration: <NarrationLayer {...props} />, music: <MusicLayer {...props} />,
|
||
progress: <ProgressLayer {...props} />, cover: <CoverLayer {...props} />,
|
||
reframe: <ReframeLayer {...props} />, insets: <InsetsLayer {...props} /> }[sel.layer];
|
||
}
|
||
return (
|
||
<div>
|
||
<div className="flex h-7 items-center gap-2 border-b border-nle-line bg-nle-row px-3">
|
||
<span className="truncate text-[12px] font-semibold">{title}</span>
|
||
<span className="ml-auto shrink-0 text-[11px] text-nle-faint">corte #{props.clip.id}</span>
|
||
</div>
|
||
{body}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Vídeo (o corte inteiro) ---------------- */
|
||
|
||
function VideoProps({ bundle, project, cfg, playhead, onProject, onSelect, onSeek, onNotice, onWindow, frame, catalog, clip }: InspectorProps) {
|
||
const [busy, setBusy] = useState(false);
|
||
const horizontal = frame.aspect === "horizontal";
|
||
const sessionAspect: Aspect = bundle.settings.format?.aspect ?? clip.aspect ?? "vertical";
|
||
const sizeOf = (a: Aspect) => { const f = catalog.frames?.[a]; return f ? `${f.width}×${f.height}` : a === "vertical" ? "1080×1920" : "1920×1080"; };
|
||
const { lo, hi } = project.source;
|
||
const total = outputDuration(project.cuts);
|
||
const first = project.cuts[0];
|
||
const last = project.cuts[project.cuts.length - 1];
|
||
|
||
async function startEarlier(seconds: number) {
|
||
const target = Math.max(0, first.start - seconds);
|
||
if (target < lo) {
|
||
setBusy(true);
|
||
const ok = await onWindow(Math.max(0, target - 15), hi);
|
||
setBusy(false);
|
||
if (!ok) return;
|
||
}
|
||
onProject((p) => produce(p, (d) => {
|
||
d.cuts[0].start = round3(target);
|
||
d.source.lo = Math.min(d.source.lo, d.cuts[0].start);
|
||
}));
|
||
onSeek(target);
|
||
onNotice(true, `Início recuado ${seconds} s.`);
|
||
}
|
||
|
||
async function grow(side: "before" | "after") {
|
||
const nlo = side === "before" ? Math.max(0, lo - 30) : lo;
|
||
const nhi = side === "after" ? Math.min(bundle.sessionDurationS, hi + 30) : hi;
|
||
if (nhi - nlo > bundle.limits.maxWindowS) return onNotice(false, `A janela vai até ${bundle.limits.maxWindowS / 60} min.`);
|
||
setBusy(true);
|
||
await onWindow(nlo, nhi);
|
||
setBusy(false);
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<PropSection title="Corte">
|
||
<PropRow label="Formato" hint="Vale só para este corte; o padrão fica na configuração da sessão">
|
||
<Pick label="Formato do corte" value={project.settings.format?.aspect ?? ""}
|
||
onChange={(v) => onProject((p) => produce(p, (d) => {
|
||
if (v) d.settings = { ...d.settings, format: { aspect: v as Aspect } };
|
||
else { const { format: _drop, ...rest } = d.settings; d.settings = rest; }
|
||
}))}>
|
||
<option value="">Da sessão ({ASPECT_LABEL[sessionAspect]})</option>
|
||
{(["vertical", "horizontal"] as Aspect[]).map((a) => <option key={a} value={a}>{ASPECT_LABEL[a]} · {sizeOf(a)}</option>)}
|
||
</Pick>
|
||
</PropRow>
|
||
<PropRow label="Duração"><Hot className={total < cfg.duration.minS - 0.05 || total > cfg.duration.maxS + 0.05 ? "!text-[#e2b340]" : undefined}>{sec(total)}</Hot><span className="text-nle-faint">em {project.cuts.length} trecho(s)</span></PropRow>
|
||
{total < cfg.duration.minS - 0.05 && <Hint tone="warn">Abaixo do mínimo configurado ({cfg.duration.minS} s). A edição é livre; os cortes automáticos saem com pelo menos {cfg.duration.minS + 1} s.</Hint>}
|
||
{total > cfg.duration.maxS + 0.05 && <Hint tone="warn">Acima do máximo configurado ({cfg.duration.maxS} s).</Hint>}
|
||
<PropRow label="Layout">
|
||
<Pick label="Layout do corte" value={horizontal ? horizontalValue(project.settings.layout?.mode ?? null) : project.settings.layout?.mode ?? ""}
|
||
onChange={(v) => onProject((p) => produce(p, (d) => {
|
||
d.settings = { ...d.settings, layout: { ...(d.settings.layout ?? {}) } };
|
||
if (v) d.settings.layout!.mode = v as LayoutMode;
|
||
else delete d.settings.layout!.mode;
|
||
}))}>
|
||
<option value="">Da sessão ({RESOLVED_MODE_LABEL[resolvedMode({ ...bundle.settings, format: { aspect: frame.aspect } })].label})</option>
|
||
{(horizontal ? HORIZONTAL_MODES : ["auto", "cam_top", "blur", "game_only"] as LayoutMode[]).map((m) => <option key={m} value={m}>{modeName(m, frame.aspect)}</option>)}
|
||
</Pick>
|
||
</PropRow>
|
||
{horizontal
|
||
? <Hint>No horizontal o corte mostra o quadro inteiro (ou a área do jogo marcada, em tela cheia); “Câmera inteira” mostra só o streamer. Câmera em cima e desfoque ficam para o vertical.</Hint>
|
||
: <Hint>A posição da câmera deste corte se ajusta na camada “Câmera” ou direto no monitor “Fonte”; o padrão da sessão fica em “Configurar corte”.</Hint>}
|
||
</PropSection>
|
||
<PropSection title="Começo e fim">
|
||
<PropRow label="Recuar o início">
|
||
{[20, 10, 5, 2].map((s) => <Btn key={s} disabled={busy} className="px-1.5" onClick={() => void startEarlier(s)}>−{s} s</Btn>)}
|
||
</PropRow>
|
||
<PropRow label="No playhead">
|
||
<Btn className="px-1.5" title="Começar o corte no playhead (Q)" onClick={() => {
|
||
if (cutAt(project.cuts, playhead) < 0) return onNotice(false, "O playhead está num trecho fora do corte.");
|
||
onProject((p) => ({ ...p, cuts: removeRange(p.cuts, p.cuts[0].start, playhead) }));
|
||
}}>Começar aqui</Btn>
|
||
<Btn className="px-1.5" title="Terminar o corte no playhead (W)" onClick={() => {
|
||
if (cutAt(project.cuts, playhead) < 0) return onNotice(false, "O playhead está num trecho fora do corte.");
|
||
onProject((p) => ({ ...p, cuts: removeRange(p.cuts, playhead, p.cuts[p.cuts.length - 1].end) }));
|
||
}}>Terminar aqui</Btn>
|
||
</PropRow>
|
||
<PropRow label="Estender o fim">
|
||
<Btn className="px-1.5" disabled={playhead <= last.end}
|
||
onClick={() => onProject((p) => ({ ...p, cuts: keepRange(p.cuts, Math.min(playhead, last.end), Math.max(playhead, last.end)) }))}>Até o playhead</Btn>
|
||
</PropRow>
|
||
</PropSection>
|
||
<PropSection title="Janela da gravação">
|
||
<PropRow label="Carregada"><Hot>{sessionClock(lo)}–{sessionClock(hi)}</Hot><span className="text-nle-faint">{Math.round(hi - lo)} s</span></PropRow>
|
||
<PropRow label="Carregar mais">
|
||
<Btn className="px-1.5" disabled={busy || lo <= 0} onClick={() => void grow("before")}>{busy && <Spinner className="size-3" />}+30 s antes</Btn>
|
||
<Btn className="px-1.5" disabled={busy || hi >= bundle.sessionDurationS} onClick={() => void grow("after")}>+30 s depois</Btn>
|
||
</PropRow>
|
||
<Hint>A timeline mostra a janela inteira: o que está apagado ficou fora do corte e volta com “Manter”.</Hint>
|
||
</PropSection>
|
||
<PropSection title={`Trechos (${project.cuts.length})`}>
|
||
{project.cuts.map((c, i) => (
|
||
<button key={`${i}-${c.start}`} type="button" onClick={() => { onSelect({ kind: "cut", index: i }); onSeek(c.start); }}
|
||
className="flex h-6 cursor-pointer items-center gap-2 rounded-[3px] px-1.5 text-left hover:bg-nle-hover">
|
||
<span className="w-14 shrink-0 text-nle-text">Trecho {i + 1}</span>
|
||
<Hot>{clockTenths(toOutput(c.start, project.cuts).t)}</Hot>
|
||
<span className="ml-auto font-mono text-[11px] text-nle-dim">{sec(c.end - c.start)}</span>
|
||
</button>
|
||
))}
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
function CutProps(props: InspectorProps & { index: number }) {
|
||
const { project, playhead, onProject, onSelect, onSeek, index } = props;
|
||
const c = project.cuts[index];
|
||
const prev = project.cuts[index - 1], next = project.cuts[index + 1];
|
||
const nudge = (edge: "start" | "end", d: number) => onProject((p) => produce(p, (draft) => {
|
||
const cut = draft.cuts[index];
|
||
if (edge === "start") cut.start = round3(clamp(cut.start + d, prev ? prev.end : p.source.lo, cut.end - 0.2));
|
||
else cut.end = round3(clamp(cut.end + d, cut.start + 0.2, next ? next.start : p.source.hi));
|
||
}), `nudge-${edge}-${index}`);
|
||
const inside = playhead > c.start + 0.2 && playhead < c.end - 0.2;
|
||
return (
|
||
<>
|
||
<PropSection title="Tempo">
|
||
<PropRow label="No corte final"><Hot>{clockTenths(toOutput(c.start, project.cuts).t)}</Hot><span className="text-nle-faint">duração</span><Hot>{sec(c.end - c.start)}</Hot></PropRow>
|
||
<PropRow label="Entrada">
|
||
<Hot className="w-14">{sessionClock(c.start)}</Hot>
|
||
{[-1, -0.1, 0.1, 1].map((d) => <Btn key={d} variant="ghost" className="px-1" onClick={() => nudge("start", d)}>{d > 0 ? "+" : "−"}{Math.abs(d).toString().replace(".", ",")}</Btn>)}
|
||
</PropRow>
|
||
<PropRow label="Saída">
|
||
<Hot className="w-14">{sessionClock(c.end)}</Hot>
|
||
{[-1, -0.1, 0.1, 1].map((d) => <Btn key={d} variant="ghost" className="px-1" onClick={() => nudge("end", d)}>{d > 0 ? "+" : "−"}{Math.abs(d).toString().replace(".", ",")}</Btn>)}
|
||
</PropRow>
|
||
<Hint>Também dá para arrastar as bordas do clipe na timeline.</Hint>
|
||
</PropSection>
|
||
<PropSection title="Câmera e layout deste trecho">
|
||
<SubHead scope="só este trecho">Layout</SubHead>
|
||
<ModeButtons value={c.mode} allowDefault aspect={props.frame.aspect} onChange={(m) => onProject((p) => produce(p, (d) => { d.cuts[index].mode = m; }))} />
|
||
<Hint>{props.frame.aspect === "horizontal"
|
||
? "No horizontal: “Quadro inteiro” mostra o jogo em tela cheia e “Câmera inteira” só o streamer. Divida o trecho (S) para trocar no meio."
|
||
: "“Câmera inteira” mostra só o streamer na tela toda; “Só o jogo” tira a câmera. Divida o trecho (S) para trocar no meio."}</Hint>
|
||
<CameraControls {...props} />
|
||
</PropSection>
|
||
<PropSection title="Som deste trecho">
|
||
<Check label="Sem o som da live neste trecho (mudo)" checked={Boolean(c.muted)}
|
||
onChange={(v) => onProject((p) => produce(p, (d) => { if (v) d.cuts[index].muted = true; else delete d.cuts[index].muted; }))} />
|
||
<Hint>A narração e a música continuam tocando. Para mutar só um pedaço, divida o trecho antes.</Hint>
|
||
</PropSection>
|
||
<PropSection title="Cortar">
|
||
<div className="flex flex-wrap gap-1.5">
|
||
<Btn disabled={!inside} title="Divide este trecho no playhead (S)" onClick={() => onProject((p) => ({ ...p, cuts: splitAt(p.cuts, playhead) }))}>
|
||
<ScissorsIcon size={13} />Dividir no playhead
|
||
</Btn>
|
||
<Btn variant="danger" disabled={project.cuts.length < 2} title="Tira este trecho do corte (Delete)"
|
||
onClick={() => { onProject((p) => ({ ...p, cuts: p.cuts.filter((_, j) => j !== index) })); onSelect(null); }}>
|
||
<TrashIcon size={13} />Tirar do corte
|
||
</Btn>
|
||
<Btn variant="ghost" onClick={() => onSeek(c.start)}>Ir ao início</Btn>
|
||
</div>
|
||
<Hint>Com a lâmina (C), clique no clipe para dividir em qualquer ponto; selecione o pedaço e aperte Delete.</Hint>
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
function RangeProps({ project, onProject, onSelect, a, b }: InspectorProps & { a: number; b: number }) {
|
||
const outside = cutAt(project.cuts, (a + b) / 2) < 0;
|
||
return (
|
||
<PropSection title="Trecho">
|
||
<PropRow label="Gravação"><Hot>{sessionClock(a)}–{sessionClock(b)}</Hot><span className="text-nle-faint">{sec(b - a)}</span></PropRow>
|
||
<PropRow label="Situação"><span>{outside ? "fora do corte" : "dentro do corte"}</span></PropRow>
|
||
<div className="flex flex-wrap gap-1.5 pt-1">
|
||
<Btn variant="primary" onClick={() => { onProject((p) => ({ ...p, cuts: keepRange(p.cuts, a, b) })); onSelect(null); }}><CheckIcon size={13} />Manter no corte</Btn>
|
||
<Btn variant="danger" onClick={() => { onProject((p) => ({ ...p, cuts: removeRange(p.cuts, a, b) })); onSelect(null); }}><ScissorsIcon size={13} />Tirar do corte</Btn>
|
||
</div>
|
||
<Hint>Shift + arrastar na régua seleciona qualquer trecho da gravação.</Hint>
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
function WordProps({ project, onProject, onSelect, from, to }: InspectorProps & { from: number; to: number }) {
|
||
const words = project.captions.words;
|
||
const sel = words.slice(from, to + 1);
|
||
if (!sel.length) return null;
|
||
const a = sel[0].s, b = sel[sel.length - 1].e;
|
||
const setWords = (fn: (ws: EditWord[]) => EditWord[], key?: string) => onProject((p) => produce(p, (d) => { d.captions.words = fn(d.captions.words); }), key);
|
||
const inRange = (i: number) => i >= from && i <= to;
|
||
const single = sel.length === 1 ? sel[0] : null;
|
||
const nudge = (key: "s" | "e", d: number) => {
|
||
if (!single) return;
|
||
const next = { ...single, [key]: round3(single[key] + d) };
|
||
if (next.e - next.s >= 0.05) setWords((ws) => ws.map((x, i) => (i === from ? next : x)), `wt-${from}`);
|
||
};
|
||
return (
|
||
<>
|
||
<PropSection title="Texto da legenda">
|
||
{single ? (
|
||
<input aria-label="Texto da palavra" className={fieldClass} maxLength={40} value={single.w}
|
||
onChange={(e) => setWords((ws) => ws.map((x, i) => (i === from ? { ...x, w: e.target.value } : x)), `ww-${from}`)} />
|
||
) : <p className="text-nle-dim">“{sel.map((w) => w.w).join(" ").slice(0, 140)}”</p>}
|
||
<PropRow label="Gravação"><Hot>{sessionClock(a)}</Hot><span className="text-nle-faint">{sec(b - a)}</span></PropRow>
|
||
<Check label="Ênfase (cor de destaque)" checked={sel.every((w) => w.emph)}
|
||
onChange={(v) => setWords((ws) => ws.map((w, i) => (inRange(i) ? { ...w, emph: v || undefined } : w)))} />
|
||
<Check label="Ocultar da legenda" checked={sel.every((w) => w.hidden)}
|
||
onChange={(v) => setWords((ws) => ws.map((w, i) => (inRange(i) ? { ...w, hidden: v || undefined } : w)))} />
|
||
</PropSection>
|
||
{single && (
|
||
<PropSection title="Tempo da palavra">
|
||
<PropRow label="Início"><Hot className="w-14">{single.s.toFixed(2).replace(".", ",")}</Hot><Btn variant="ghost" className="px-1.5" onClick={() => nudge("s", -0.05)}>−50 ms</Btn><Btn variant="ghost" className="px-1.5" onClick={() => nudge("s", 0.05)}>+50 ms</Btn></PropRow>
|
||
<PropRow label="Fim"><Hot className="w-14">{single.e.toFixed(2).replace(".", ",")}</Hot><Btn variant="ghost" className="px-1.5" onClick={() => nudge("e", -0.05)}>−50 ms</Btn><Btn variant="ghost" className="px-1.5" onClick={() => nudge("e", 0.05)}>+50 ms</Btn></PropRow>
|
||
</PropSection>
|
||
)}
|
||
<PropSection title="Cortar pelo texto">
|
||
<div className="flex flex-wrap gap-1.5">
|
||
<Btn variant="danger" onClick={() => { onProject((p) => ({ ...p, cuts: removeRange(p.cuts, a, b) })); onSelect(null); }}><ScissorsIcon size={13} />Tirar do corte</Btn>
|
||
<Btn onClick={() => onProject((p) => ({ ...p, cuts: keepRange(p.cuts, a, b) }))}>Manter no corte</Btn>
|
||
{sel.length > 1 && <Btn variant="ghost" onClick={() => {
|
||
setWords((ws) => [...ws.slice(0, from), { s: a, e: b, w: sel.map((w) => w.w).join(" ") }, ...ws.slice(to + 1)]);
|
||
onSelect({ kind: "words", from, to: from });
|
||
}}>Juntar numa só</Btn>}
|
||
</div>
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Legenda ---------------- */
|
||
|
||
function CaptionProps({ bundle, project, cfg, onProject, catalog }: InspectorProps) {
|
||
const cap = project.captions;
|
||
const setStyle = (patch: Partial<CutSettings["caption"]>, key: string) =>
|
||
onProject((p) => produce(p, (d) => { Object.assign(d.captions.style, patch); }), key);
|
||
return (
|
||
<>
|
||
<PropSection title="Legenda queimada">
|
||
<Check label="Mostrar a legenda" checked={cap.enabled} onChange={(v) => onProject((p) => produce(p, (d) => { d.captions.enabled = v; }))} />
|
||
<PropRow label="Estilo animado">
|
||
<Pick label="Estilo da legenda" value={cap.preset}
|
||
onChange={(v) => onProject((p) => produce(p, (d) => { d.captions.preset = v as CaptionPreset; d.captions.style = {}; }))}>
|
||
{bundle.presets.map((pr) => <option key={pr.id} value={pr.id}>{pr.label}</option>)}
|
||
</Pick>
|
||
</PropRow>
|
||
<Hint>Trocar o estilo volta o tamanho e as palavras por bloco para o padrão dele.</Hint>
|
||
</PropSection>
|
||
<PropSection title="Texto" actions={Object.keys(cap.style).length ? <Btn variant="ghost" className="h-5 px-1.5 text-[11px]" onClick={() => onProject((p) => produce(p, (d) => { d.captions.style = {}; }))}>Restaurar</Btn> : null}>
|
||
<PropRow label="Fonte" top>
|
||
<FontPicker label="Fonte da legenda" fonts={catalog.fonts} packaged={Object.keys(catalog.fontFiles)} value={cfg.caption.font}
|
||
onChange={(v) => setStyle({ font: v }, "font")} collapsible />
|
||
</PropRow>
|
||
<PropRow label="Tamanho"><Scrub label="Tamanho" min={40} max={140} step={2} value={cfg.caption.size} onChange={(v) => setStyle({ size: v }, "size")} /></PropRow>
|
||
<PropRow label="Palavras por bloco"><Scrub label="Palavras por bloco" min={1} max={6} step={1} value={cfg.caption.maxWords} onChange={(v) => setStyle({ maxWords: v }, "maxWords")} /></PropRow>
|
||
<PropRow label="Contorno"><Scrub label="Contorno" min={0} max={14} step={1} value={cfg.caption.outlineWidth} onChange={(v) => setStyle({ outlineWidth: v }, "outline")} /></PropRow>
|
||
<PropRow label="Altura na tela">
|
||
<Scrub label="Altura na tela" min={0.08} max={0.9} step={0.01} value={cfg.caption.y ?? 0.74}
|
||
format={(v) => (cfg.caption.y === null ? "auto" : pct(v))} onChange={(v) => setStyle({ y: v }, "y")} />
|
||
</PropRow>
|
||
{cfg.caption.y !== null && <Btn variant="ghost" className="justify-self-start" onClick={() => setStyle({ y: null }, "y-auto")}>Altura automática</Btn>}
|
||
<Check label="MAIÚSCULAS" checked={cfg.caption.uppercase} onChange={(v) => setStyle({ uppercase: v }, "upper")} />
|
||
</PropSection>
|
||
<PropSection title="Cores">
|
||
<PropRow label="Texto"><ColorDot label="Cor do texto" value={cfg.caption.color} onChange={(v) => setStyle({ color: v }, "color")} /></PropRow>
|
||
<PropRow label="Palavra falada"><ColorDot label="Cor da palavra falada" value={cfg.caption.highlight} onChange={(v) => setStyle({ highlight: v }, "hl")} /></PropRow>
|
||
<PropRow label="Contorno"><ColorDot label="Cor do contorno" value={cfg.caption.outline} onChange={(v) => setStyle({ outline: v }, "ol")} /></PropRow>
|
||
<PropRow label="Ênfase"><ColorDot label="Cor da ênfase" value={cap.emphColor} onChange={(v) => onProject((p) => produce(p, (d) => { d.captions.emphColor = v; }), "emph")} /></PropRow>
|
||
<Hint>Corrija palavras e marque ênfase na Transcrição (duplo clique corrige). Para mudar a altura, arraste a legenda no vídeo.</Hint>
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Textos ---------------- */
|
||
|
||
const EMOJIS = ["😂", "💀", "🔥", "😱", "👀", "🤯", "GG", "KKKK"];
|
||
|
||
export function newText(project: EditProject, playhead: number, text = "TEXTO", big = false): TextOverlay {
|
||
const start = round3(clamp(playhead, project.source.lo, project.source.hi - 0.3));
|
||
return { id: newId("t"), kind: "text", text, start, end: round3(Math.min(project.source.hi, start + 1.5)), y: big ? 0.42 : 0.3, size: big ? 150 : 72, color: "#FFFFFF", box: null, anim: "pop" };
|
||
}
|
||
|
||
export function newZoom(project: EditProject, playhead: number, aspect: Aspect = "vertical"): ZoomOverlay | null {
|
||
const start = round3(clamp(playhead, project.source.lo, project.source.hi - 0.3)), end = round3(Math.min(project.source.hi, start + 1.5));
|
||
if (project.overlays.some((z) => z.kind === "zoom" && start < z.end && end > z.start)) return null;
|
||
return { id: newId("z"), kind: "zoom", start, end, scale: 1.35, ...zoomFocusDefault(aspect), ramp: 0.2 };
|
||
}
|
||
|
||
function TextsLayer({ project, cfg, frame, playhead, onProject, onSelect }: InspectorProps) {
|
||
const hook = project.overlays.find((o): o is TextOverlay => o.kind === "hook");
|
||
const texts = project.overlays.filter((o): o is TextOverlay => o.kind === "text");
|
||
const add = (text?: string, big?: boolean) => {
|
||
const o = newText(project, playhead, text, big);
|
||
onProject((p) => ({ ...p, overlays: [...p.overlays, o] }));
|
||
onSelect({ kind: "overlay", id: o.id });
|
||
};
|
||
return (
|
||
<>
|
||
<PropSection title="Gancho (primeiros segundos)">
|
||
{hook ? <RowButton label={hook.text} meta={sec(hook.end - hook.start)} onClick={() => onSelect({ kind: "overlay", id: hook.id })} />
|
||
: <Btn className="justify-self-start" onClick={() => { const h = newHook(cfg, frame); onProject((p) => ({ ...p, overlays: [h, ...p.overlays] })); onSelect({ kind: "overlay", id: "hook" }); }}><PlusIcon size={13} />Adicionar gancho</Btn>}
|
||
<Hint>Os 2 primeiros segundos decidem: texto curto que promete o que o vídeo paga.</Hint>
|
||
</PropSection>
|
||
<PropSection title={`Textos (${texts.length})`} actions={<Btn variant="ghost" className="h-5 px-1.5 text-[11px]" onClick={() => add()}><PlusIcon size={12} />No playhead</Btn>}>
|
||
{texts.map((o) => <RowButton key={o.id} label={o.text} meta={sessionClock(o.start)} onClick={() => onSelect({ kind: "overlay", id: o.id })} />)}
|
||
<div className="flex flex-wrap gap-1 pt-1">
|
||
{EMOJIS.map((e) => <Btn key={e} variant="ghost" className="px-1.5" aria-label={`Inserir ${e}`} onClick={() => add(e, true)}>{e}</Btn>)}
|
||
</div>
|
||
<Hint>No vídeo final o emoji sai em uma cor só (o FFmpeg não desenha emoji colorido).</Hint>
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
function TextProps({ project, cfg, catalog, playhead, onProject, onSelect, onSeek, text: o }: InspectorProps & { text: TextOverlay }) {
|
||
const hook = o.kind === "hook";
|
||
const banner = o.style === "banner";
|
||
const total = outputDuration(project.cuts);
|
||
const hk = hookOf(cfg);
|
||
const font = o.font ?? (banner ? hk.font : "Arial Black");
|
||
// Updater puro: o patch é calculado aqui fora (o React em dev roda o updater duas vezes).
|
||
const set = (patch: Partial<TextOverlay>, key: string) =>
|
||
onProject((p) => ({ ...p, overlays: p.overlays.map((x) => (x.id === o.id ? { ...x, ...patch } as TextOverlay : x)) }), `${key}-${o.id}`);
|
||
/** Simples ↔ tarja. Na tarja entram a cor da tarja, a fonte e a animação do gancho padrão (se o texto ainda não tinha). */
|
||
const setStyle = (style: "plain" | "banner") => onProject((p) => ({
|
||
...p, overlays: p.overlays.map((x) => {
|
||
if (x.id !== o.id || (x.kind !== "hook" && x.kind !== "text")) return x;
|
||
if (style === "plain") { const { style: _drop, ...rest } = x; return rest as TextOverlay; }
|
||
return { ...x, style: "banner", bg: x.bg ?? hk.bg, font: x.font ?? hk.font, anim: x.anim === "pop" ? hk.anim : x.anim } as TextOverlay;
|
||
}),
|
||
}));
|
||
/** Início do gancho/texto em tempo da sessão (para "Ver a entrada"). */
|
||
const startS = hook ? toSession(o.start, project.cuts) : o.start;
|
||
return (
|
||
<>
|
||
<PropSection title="Texto">
|
||
<textarea aria-label="Texto" rows={2} maxLength={120} className={cx(fieldClass, "resize-none")} value={o.text} onChange={(e) => set({ text: e.target.value }, "txt")} />
|
||
{banner && <Hint>Na tarja o texto sai em MAIÚSCULAS, em até 2 linhas; se não couber, a fonte diminui (nunca corta palavra).</Hint>}
|
||
{hook ? (
|
||
<PropRow label="Tempo na tela"><Scrub label="Tempo na tela" min={0.5} max={Math.max(1, Math.min(8, total))} step={0.1} value={round3(o.end - o.start)} format={sec} onChange={(v) => set({ end: round3(o.start + v) }, "dur")} /></PropRow>
|
||
) : (
|
||
<PropRow label="Gravação"><Hot>{sessionClock(o.start)}</Hot><span className="text-nle-faint">{sec(o.end - o.start)} · arraste na timeline</span></PropRow>
|
||
)}
|
||
</PropSection>
|
||
<PropSection title="Estilo">
|
||
<div role="radiogroup" aria-label="Estilo do texto" className="grid grid-cols-2 gap-1">
|
||
{([["plain", "Simples"], ["banner", "Tarja"]] as const).map(([v, label]) => (
|
||
<button key={v} type="button" role="radio" aria-checked={(v === "banner") === banner} onClick={() => setStyle(v)}
|
||
className={cx("h-7 cursor-pointer truncate rounded-[3px] border px-2 text-left text-[12px] focus-visible:outline-1 focus-visible:outline-nle-focus",
|
||
(v === "banner") === banner ? "border-nle-accent bg-nle-accent/25 text-white" : "border-nle-line text-nle-dim hover:bg-nle-hover hover:text-nle-text")}>
|
||
{label}<span className="ml-1.5 text-[10.5px] text-nle-faint">{v === "banner" ? "faixa na largura toda" : "texto solto"}</span>
|
||
</button>
|
||
))}
|
||
</div>
|
||
{banner && <PropRow label="Cor da tarja"><ColorDot label="Cor da tarja" value={o.bg ?? hk.bg} onChange={(v) => set({ bg: v }, "bg")} /></PropRow>}
|
||
<PropRow label="Cor do texto"><ColorDot label="Cor do texto" value={o.color} onChange={(v) => set({ color: v }, "c")} /></PropRow>
|
||
{!banner && (
|
||
<PropRow label="Caixa atrás">
|
||
<Check label="" checked={o.box !== null} onChange={(v) => set({ box: v ? "#E11D48" : null }, "b")} />
|
||
{o.box && <ColorDot label="Cor da caixa" value={o.box} onChange={(v) => set({ box: v }, "bc")} />}
|
||
</PropRow>
|
||
)}
|
||
<PropRow label="Fonte" top>
|
||
<FontPicker label={hook ? "Fonte do gancho" : "Fonte do texto"} fonts={catalog.fonts} packaged={Object.keys(catalog.fontFiles)} value={font}
|
||
onChange={(v) => set({ font: v }, "font")} collapsible />
|
||
</PropRow>
|
||
<PropRow label="Animação">
|
||
<Pick label="Animação" value={o.anim} onChange={(v) => set({ anim: v as HookAnim }, "a")}>
|
||
{(["slide", "pop", "fade", "none"] as HookAnim[]).map((a) => <option key={a} value={a}>{HOOK_ANIM_LABEL[a]}</option>)}
|
||
</Pick>
|
||
</PropRow>
|
||
{o.anim === "slide" && <Hint>{banner ? "A tarja atravessa a tela e o texto entra borrado e fica nítido (0,4 s)." : "O texto entra pela direita, borrado, e fica nítido (0,4 s)."}</Hint>}
|
||
<Btn variant="ghost" className="justify-self-start" disabled={Math.abs(playhead - startS) < 0.01} onClick={() => onSeek(startS)}
|
||
title="Põe o playhead no começo: toque (Espaço) para ver a entrada">Ir para a entrada</Btn>
|
||
</PropSection>
|
||
<PropSection title="Posição e tamanho">
|
||
{!banner && <PropRow label="Posição horizontal"><Scrub label="Posição horizontal" min={0.05} max={0.95} step={0.01} value={o.x ?? 0.5} format={pct} onChange={(v) => set({ x: v }, "x")} /></PropRow>}
|
||
<PropRow label="Altura na tela"><Scrub label="Altura" min={0.04} max={0.96} step={0.01} value={o.y} format={pct} onChange={(v) => set({ y: v }, "y")} /></PropRow>
|
||
<PropRow label="Tamanho"><Scrub label="Tamanho" min={24} max={180} step={2} value={o.size} onChange={(v) => set({ size: v }, "s")} /></PropRow>
|
||
<Hint>{banner ? "Arraste a tarja no vídeo para mudar a altura (ela ocupa a largura toda)." : "Também dá para arrastar o texto direto no vídeo."}</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: "texts" }); }}><TrashIcon size={13} />Remover {hook ? "o gancho" : "o texto"}</Btn>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Zoom ---------------- */
|
||
|
||
function ZoomsLayer({ project, playhead, onProject, onSelect, onNotice, frame }: InspectorProps) {
|
||
const zooms = project.overlays.filter((o): o is ZoomOverlay => o.kind === "zoom");
|
||
return (
|
||
<PropSection title={`Zoom / punch-in (${zooms.length})`} actions={<Btn variant="ghost" className="h-5 px-1.5 text-[11px]" onClick={() => {
|
||
const z = newZoom(project, playhead, frame.aspect);
|
||
if (!z) return onNotice(false, "Já há um zoom nesse instante.");
|
||
onProject((p) => ({ ...p, overlays: [...p.overlays, z] }));
|
||
onSelect({ kind: "overlay", id: z.id });
|
||
}}><PlusIcon size={12} />No playhead</Btn>}>
|
||
{!zooms.length && <p className="text-nle-dim">Nenhum zoom. Ponha o playhead na reação e clique em “No playhead”.</p>}
|
||
{zooms.map((z) => <RowButton key={z.id} label={`Zoom ${z.scale.toFixed(2).replace(".", ",")}×`} meta={sessionClock(z.start)} onClick={() => onSelect({ kind: "overlay", id: z.id })} />)}
|
||
<Hint>Aproxima a imagem na reação. A legenda e os textos não sofrem zoom.</Hint>
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
function ZoomProps({ onProject, onSelect, zoom: z }: InspectorProps & { zoom: ZoomOverlay }) {
|
||
const set = (patch: Partial<ZoomOverlay>, key: string) =>
|
||
onProject((p) => ({ ...p, overlays: p.overlays.map((o) => (o.id === z.id ? { ...o, ...patch } as ZoomOverlay : o)) }), `${key}-${z.id}`);
|
||
return (
|
||
<>
|
||
<PropSection title="Movimento">
|
||
<PropRow label="Gravação"><Hot>{sessionClock(z.start)}</Hot><span className="text-nle-faint">{sec(z.end - z.start)} · arraste na timeline</span></PropRow>
|
||
<PropRow label="Escala"><Scrub label="Escala" min={1.05} max={2.5} step={0.05} value={z.scale} format={(v) => `${v.toFixed(2).replace(".", ",")}×`} onChange={(v) => set({ scale: v }, "zs")} /></PropRow>
|
||
<PropRow label="Foco horizontal"><Scrub label="Foco horizontal" min={0} max={1} step={0.01} value={z.x} format={pct} onChange={(v) => set({ x: v }, "zx")} /></PropRow>
|
||
<PropRow label="Foco vertical"><Scrub label="Foco vertical" min={0} max={1} step={0.01} value={z.y} format={pct} onChange={(v) => set({ y: v }, "zy")} /></PropRow>
|
||
<PropRow label="Rampa" hint="0 = corte seco (crash zoom); maior = suave"><Scrub label="Rampa" min={0} max={1.5} step={0.05} value={z.ramp} format={sec} onChange={(v) => set({ ramp: v }, "zr")} /></PropRow>
|
||
</PropSection>
|
||
<div className="p-3">
|
||
<Btn variant="danger" onClick={() => { onProject((p) => ({ ...p, overlays: p.overlays.filter((o) => o.id !== z.id) })); onSelect({ kind: "layer", layer: "zooms" }); }}><TrashIcon size={13} />Remover o zoom</Btn>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Áudio ---------------- */
|
||
|
||
function AudioLayer({ project, onProject }: InspectorProps) {
|
||
return (
|
||
<PropSection title="Áudio da live">
|
||
<PropRow label="Volume"><Scrub label="Volume da live" min={0} max={2} step={0.05} value={project.audio.volume} format={pct} onChange={(v) => onProject((p) => produce(p, (d) => { d.audio.volume = v; }), "vol")} /></PropRow>
|
||
<Hint>O áudio acompanha os clipes do vídeo: cortar o vídeo corta o som junto.</Hint>
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
function NarrationLayer({ project, onSelect, onModal, bundle }: InspectorProps) {
|
||
const list = project.audio.narration;
|
||
return (
|
||
<PropSection title={`Narração (${list.length})`} actions={<Btn variant="ghost" className="h-5 px-1.5 text-[11px]" onClick={() => onModal("narration")}><PlusIcon size={12} />Nova…</Btn>}>
|
||
{!bundle.voiceConfigured && <Hint tone="warn">Serviço de voz não instalado.</Hint>}
|
||
{!list.length && <p className="text-nle-dim">Nenhuma narração. “Nova…” gera a voz e põe no playhead.</p>}
|
||
{list.map((n) => <RowButton key={n.id} label={n.text} meta={sessionClock(n.at)} onClick={() => onSelect({ kind: "narration", id: n.id })} />)}
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
function NarrationProps({ playhead, onProject, onSelect, n }: InspectorProps & { n: Narration }) {
|
||
const set = (fn: (x: Narration) => void, key: string) => onProject((p) => produce(p, (d) => { const x = d.audio.narration.find((y) => y.id === n.id); if (x) fn(x); }), `${key}-${n.id}`);
|
||
return (
|
||
<>
|
||
<PropSection title="Narração">
|
||
<p className="text-nle-dim">“{n.text}”</p>
|
||
<PropRow label="Voz"><span className="truncate">{n.voice}</span></PropRow>
|
||
<PropRow label="Gravação"><Hot>{sessionClock(n.at)}</Hot><span className="text-nle-faint">{sec(n.durationS)}</span></PropRow>
|
||
<audio controls preload="none" src={fileUrl(n.file)} className="h-7 w-full" />
|
||
<PropRow label="Volume"><Scrub label="Volume da narração" min={0} max={2} step={0.05} value={n.volume} format={pct} onChange={(v) => set((x) => { x.volume = v; }, "nv")} /></PropRow>
|
||
<PropRow label="Live por baixo"><Scrub label="Volume da live por baixo" min={0} max={1} step={0.05} value={n.duck} format={pct} onChange={(v) => set((x) => { x.duck = v; }, "nd")} /></PropRow>
|
||
</PropSection>
|
||
<div className="flex flex-wrap gap-1.5 p-3">
|
||
<Btn onClick={() => set((x) => { x.at = round3(playhead); }, "nat")}>Mover para o playhead</Btn>
|
||
<Btn variant="danger" onClick={() => { onProject((p) => produce(p, (d) => { d.audio.narration = d.audio.narration.filter((x) => x.id !== n.id); })); onSelect({ kind: "layer", layer: "narration" }); }}><TrashIcon size={13} />Remover</Btn>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
function MusicLayer({ bundle, project, playhead, onProject }: InspectorProps) {
|
||
const a = project.audio;
|
||
const [sfxFile, setSfxFile] = useState("");
|
||
const none = !bundle.audioLibrary.length;
|
||
return (
|
||
<>
|
||
<PropSection title="Música de fundo">
|
||
{none && <Hint>Nenhum áudio em <code>assets/</code>. Coloque um .mp3 ou .wav lá (com licença de uso) para aparecer aqui.</Hint>}
|
||
<PropRow label="Faixa">
|
||
<Pick label="Música" value={a.music?.file ?? ""}
|
||
onChange={(v) => onProject((p) => produce(p, (d) => { d.audio.music = v ? { file: v, volume: d.audio.music?.volume ?? 0.18, duck: d.audio.music?.duck ?? true } : null; }))}>
|
||
<option value="">Sem música</option>
|
||
{bundle.audioLibrary.map((f) => <option key={f.file} value={f.file}>{f.name}</option>)}
|
||
</Pick>
|
||
</PropRow>
|
||
{a.music && <>
|
||
<PropRow label="Volume"><Scrub label="Volume da música" min={0} max={1} step={0.02} value={a.music.volume} format={pct} onChange={(v) => onProject((p) => produce(p, (d) => { d.audio.music!.volume = v; }), "mv")} /></PropRow>
|
||
<Check label="Abaixar sob a fala" checked={a.music.duck} onChange={(v) => onProject((p) => produce(p, (d) => { d.audio.music!.duck = v; }))} />
|
||
</>}
|
||
</PropSection>
|
||
<PropSection title={`Efeitos sonoros (${a.sfx.length})`}>
|
||
<div className="flex gap-1.5">
|
||
<Pick label="Efeito" value={sfxFile} onChange={setSfxFile}>
|
||
<option value="">Escolha um áudio de assets/</option>
|
||
{bundle.audioLibrary.map((f) => <option key={f.file} value={f.file}>{f.name}</option>)}
|
||
</Pick>
|
||
<Btn disabled={!sfxFile} onClick={() => onProject((p) => produce(p, (d) => { d.audio.sfx.push({ id: newId("s"), file: sfxFile, at: round3(playhead), volume: 0.8 }); }))}>No playhead</Btn>
|
||
</div>
|
||
{a.sfx.map((s) => (
|
||
<div key={s.id} className="flex h-6 items-center gap-2">
|
||
<Hot>{sessionClock(s.at)}</Hot><span className="truncate">{s.file.split("/").pop()}</span>
|
||
<Btn variant="ghost" className="ml-auto px-1" aria-label="Remover efeito" onClick={() => onProject((p) => produce(p, (d) => { d.audio.sfx = d.audio.sfx.filter((x) => x.id !== s.id); }))}><TrashIcon size={13} /></Btn>
|
||
</div>
|
||
))}
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Câmera e layout ---------------- */
|
||
|
||
const MODES: LayoutMode[] = ["cam_top", "cam_only", "game_only", "blur"];
|
||
/**
|
||
* No horizontal só há dois resultados (layout.resolved_mode): "Quadro inteiro" (gravado como `game_only`, que volta a
|
||
* ser "Só o jogo" se o corte for para o vertical) e "Câmera inteira".
|
||
*/
|
||
const HORIZONTAL_MODES: LayoutMode[] = ["game_only", "cam_only"];
|
||
|
||
/** Nome do modo no formato: no horizontal, todo modo que não é câmera inteira vira "Quadro inteiro". */
|
||
function modeName(m: LayoutMode, aspect: Aspect): string {
|
||
if (aspect === "horizontal") return m === "cam_only" ? MODE_LABEL.cam_only.label : RESOLVED_MODE_LABEL.full.label;
|
||
return MODE_LABEL[m].label;
|
||
}
|
||
|
||
/** Valor mostrado no horizontal: os modos do vertical (câmera em cima, desfoque…) aparecem como "Quadro inteiro". */
|
||
function horizontalValue(m: LayoutMode | null): LayoutMode | "" {
|
||
return m === null ? "" : m === "cam_only" ? "cam_only" : "game_only";
|
||
}
|
||
|
||
/** Botões de layout: câmera em cima, câmera inteira, só o jogo, desfoque (+ "do corte"/"da sessão" quando faz sentido). */
|
||
function ModeButtons({ value: raw, onChange, allowDefault = false, defaultLabel = "O do corte", aspect = "vertical" }: {
|
||
value: LayoutMode | null; onChange: (m: LayoutMode | null) => void; allowDefault?: boolean; defaultLabel?: string; aspect?: Aspect;
|
||
}) {
|
||
const horizontal = aspect === "horizontal";
|
||
const value = horizontal ? (horizontalValue(raw) || null) : raw;
|
||
const options: [LayoutMode | null, string][] = [...(allowDefault ? [[null, defaultLabel] as [null, string]] : []),
|
||
...(horizontal ? HORIZONTAL_MODES : MODES).map((m) => [m, modeName(m, aspect)] as [LayoutMode, string])];
|
||
return (
|
||
<div role="radiogroup" aria-label="Layout" className="grid grid-cols-2 gap-1">
|
||
{options.map(([m, label]) => (
|
||
<button key={m ?? "default"} type="button" role="radio" aria-checked={value === m} onClick={() => onChange(m)}
|
||
className={cx("h-7 cursor-pointer truncate rounded-[3px] border px-2 text-left text-[12px] focus-visible:outline-1 focus-visible:outline-nle-focus",
|
||
value === m ? "border-nle-accent bg-nle-accent/25 text-white" : "border-nle-line text-nle-dim hover:bg-nle-hover hover:text-nle-text")}>
|
||
{label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function CameraLayer(props: InspectorProps) {
|
||
const { bundle, project, onProject, onSelect, onSeek, frame } = props;
|
||
const own = project.settings.layout ?? {};
|
||
const horizontal = frame.aspect === "horizontal";
|
||
return (
|
||
<>
|
||
<PropSection title="Câmera e área do jogo">
|
||
<CameraControls {...props} />
|
||
</PropSection>
|
||
<PropSection title="Layout do corte inteiro">
|
||
<ModeButtons value={own.mode ?? null} allowDefault aspect={frame.aspect}
|
||
defaultLabel={`Da sessão (${modeName(bundle.settings.layout.mode, frame.aspect)})`}
|
||
onChange={(m) => onProject((p) => editLayout(p, (l) => { if (m) l.mode = m; else delete l.mode; }))} />
|
||
</PropSection>
|
||
<PropSection title="Por trecho">
|
||
{project.cuts.map((c, i) => (
|
||
<div key={`${i}-${c.start}`} className="grid grid-cols-[62px_minmax(0,1fr)] items-center gap-2">
|
||
<button type="button" className="cursor-pointer text-left hover:text-white" onClick={() => { onSelect({ kind: "cut", index: i }); onSeek(c.start); }}>Trecho {i + 1}</button>
|
||
<Pick label={`Layout do trecho ${i + 1}`} value={horizontal ? horizontalValue(c.mode) : c.mode ?? ""} onChange={(v) => onProject((p) => produce(p, (d) => { d.cuts[i].mode = (v || null) as LayoutMode | null; }))}>
|
||
<option value="">O do corte</option>
|
||
{(horizontal ? HORIZONTAL_MODES : MODES).map((m) => <option key={m} value={m}>{modeName(m, frame.aspect)}</option>)}
|
||
</Pick>
|
||
</div>
|
||
))}
|
||
<Hint>Para a câmera ocupar a tela só num momento, divida o trecho ali (lâmina ou S) e escolha “Câmera inteira”.</Hint>
|
||
</PropSection>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/** Subtítulo dentro de uma seção, com o alcance do ajuste ("só este trecho", "corte inteiro"). */
|
||
function SubHead({ children, scope }: { children: ReactNode; scope: string }) {
|
||
return (
|
||
<p className="flex items-center gap-2 pt-1 text-[11.5px] font-semibold text-nle-text">
|
||
{children}
|
||
<span className="rounded-[2px] bg-nle-row px-1.5 py-px text-[10.5px] font-normal text-nle-dim">{scope}</span>
|
||
</p>
|
||
);
|
||
}
|
||
|
||
const rectText = (r: Rect | null) => (r ? `${pct(r.w)} × ${pct(r.h)} em ${pct(r.x)}, ${pct(r.y)}` : null);
|
||
|
||
/**
|
||
* Câmera do streamer e área do jogo DESTE CORTE: área atual, "Editar na fonte", campos em %, "Achar câmera com IA",
|
||
* altura da câmera, "Voltar para a da sessão" e "Usar nos próximos cortes da sessão". Uma implementação só, usada com
|
||
* um trecho selecionado (CutProps) e na camada "Câmera" (CameraLayer). A posição vale para o corte inteiro.
|
||
*/
|
||
function CameraControls({ project, cfg, onProject, onNotice, source, frame }: InspectorProps) {
|
||
const [busy, setBusy] = useState<"detect" | "session" | null>(null);
|
||
const own = project.settings.layout ?? {};
|
||
const { target } = source;
|
||
const rect = cfg.layout[target];
|
||
const sessionId = project.source.sessionId;
|
||
const label = target === "cam" ? "Câmera" : "Área do jogo";
|
||
|
||
async function detect() {
|
||
setBusy("detect");
|
||
const r = await clipperCall<CamDetect>(`sessions/${sessionId}/detect-cam`, "POST");
|
||
setBusy(null);
|
||
if (!r.ok) return onNotice(false, r.error);
|
||
if (r.data.hasWebcam && r.data.cam) {
|
||
const cam = clampRect(r.data.cam);
|
||
onProject((p) => editLayout(p, (l) => { l.cam = cam; }));
|
||
source.onTarget("cam");
|
||
onNotice(true, `Câmera encontrada${r.data.fullFrame ? " (ocupa o quadro inteiro)" : ""}. Confira o retângulo na Fonte (Ctrl+Z desfaz).`);
|
||
} else {
|
||
onNotice(false, "A IA não achou webcam na tela. Marque à mão na Fonte, ou use “Só o jogo” ou “Desfoque”.");
|
||
}
|
||
}
|
||
|
||
async function useForSession() {
|
||
const cam = cfg.layout.cam;
|
||
if (!cam) return;
|
||
const withGame = "game" in own;
|
||
if (!(await askConfirm({ title: `Usar esta câmera${withGame ? " e esta área do jogo" : ""} nos próximos cortes da sessão?`,
|
||
message: "Os cortes que já existem não mudam.", confirmLabel: "Usar na sessão" }))) return;
|
||
setBusy("session");
|
||
const current = await clipperCall<SettingsPayload>(`sessions/${sessionId}/settings`);
|
||
if (!current.ok) { setBusy(null); return onNotice(false, current.error); }
|
||
// O PUT troca a camada inteira da sessão: manda o que ela já fixava, com a câmera (e o jogo) deste corte.
|
||
const layer = current.data.own ?? {};
|
||
const body = { ...layer, layout: { ...(layer.layout ?? {}), cam, ...(withGame ? { game: cfg.layout.game } : {}) } };
|
||
const r = await clipperCall<SettingsPayload>(`sessions/${sessionId}/settings`, "PUT", body);
|
||
setBusy(null);
|
||
if (!r.ok) return onNotice(false, r.error);
|
||
if (r.data?.effective?.layout) source.onSessionLayout(r.data.effective.layout);
|
||
onNotice(true, "Câmera gravada na sessão: vale para os próximos cortes.");
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<SubHead scope="corte inteiro">Posição da câmera</SubHead>
|
||
<PropRow label="Câmera">
|
||
<span className={cx("truncate", !cfg.layout.cam && "text-[#e2b340]")}>{rectText(cfg.layout.cam) ?? "não marcada"}</span>
|
||
<span className="ml-auto shrink-0 text-[11px] text-nle-faint">{"cam" in own ? "deste corte" : "da sessão"}</span>
|
||
</PropRow>
|
||
<PropRow label="Área do jogo">
|
||
<span className="truncate">{rectText(cfg.layout.game) ?? "quadro inteiro"}</span>
|
||
<span className="ml-auto shrink-0 text-[11px] text-nle-faint">{"game" in own ? "deste corte" : "da sessão"}</span>
|
||
</PropRow>
|
||
<div className="flex flex-wrap items-center gap-1.5 pt-0.5">
|
||
<SourceTargetToggle target={target} onTarget={source.onTarget} />
|
||
<Btn variant={source.editing ? "primary" : "default"} aria-pressed={source.editing} onClick={() => source.onEdit(!source.editing, target)}
|
||
title="Mostra o quadro original (Fonte) com o retângulo pronto para arrastar">
|
||
{source.editing ? "Concluir" : "Editar na fonte"}
|
||
</Btn>
|
||
</div>
|
||
<RectFields label={label} rect={rect} onChange={(r, field) => onProject((p) => editLayout(p, (l) => { l[target] = r; }), `rect-${target}-${field}`)} />
|
||
{!rect && <Hint>{target === "cam" ? "Sem câmera marcada: desenhe um retângulo sobre o rosto na Fonte." : "Sem área marcada, o corte usa o quadro inteiro. Desenhe na Fonte para recortar bordas ou o chat da live."}</Hint>}
|
||
<div className="flex flex-wrap gap-1.5">
|
||
<Btn disabled={busy !== null} onClick={() => void detect()} title="Procura a webcam no quadro da gravação">
|
||
{busy === "detect" ? <Spinner className="size-3" /> : <SparkIcon size={13} />}{busy === "detect" ? "Procurando…" : "Achar câmera com IA"}
|
||
</Btn>
|
||
{target in own && (
|
||
<Btn variant="ghost" onClick={() => onProject((p) => editLayout(p, (l) => { delete l[target]; }))}
|
||
title={`Tira o ajuste deste corte: ${target === "cam" ? "a câmera" : "a área do jogo"} volta a ser a da sessão`}>
|
||
Voltar para a da sessão
|
||
</Btn>
|
||
)}
|
||
</div>
|
||
{frame.aspect === "vertical" && (
|
||
<PropRow label="Altura da câmera" hint="No layout “Câmera em cima”: quanto da tela fica com a câmera">
|
||
<Scrub label="Altura da câmera" min={0.2} max={0.6} step={0.01} value={cfg.layout.camHeight} format={pct}
|
||
onChange={(v) => onProject((p) => editLayout(p, (l) => { l.camHeight = v; }), "camH")} />
|
||
</PropRow>
|
||
)}
|
||
{!cfg.layout.cam && <Hint tone="warn">{frame.aspect === "horizontal" ? "Sem câmera marcada, “Câmera inteira” vira quadro inteiro." : "Sem câmera marcada, “Câmera em cima” e “Câmera inteira” viram desfoque."}</Hint>}
|
||
<Hint>Na Fonte: arraste o retângulo para mover e as alças para redimensionar; numa área vazia, desenha um novo. Setas movem e Shift + setas mudam o tamanho. A posição vale para o corte inteiro; o layout é que muda por trecho.</Hint>
|
||
<Btn className="justify-self-start" disabled={!cfg.layout.cam || busy !== null} onClick={() => void useForSession()}
|
||
title="Grava a câmera deste corte na configuração da sessão (a mesma de “Configurar corte”)">
|
||
{busy === "session" && <Spinner className="size-3" />}Usar esta câmera nos próximos cortes da sessão
|
||
</Btn>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Chat na tela ---------------- */
|
||
|
||
function ChatLayer({ bundle, project, onProject, frame }: InspectorProps) {
|
||
const chat = project.chat ?? chatDefault(frame.aspect);
|
||
const set = (patch: Partial<typeof chat>, key?: string) => onProject((p) => ({ ...p, chat: { ...(p.chat ?? chatDefault(frame.aspect)), ...patch } }), key);
|
||
return (
|
||
<PropSection title="Chat da live na tela">
|
||
<Check label="Mostrar o chat no vídeo" checked={chat.enabled} onChange={(v) => { if (v !== chat.enabled) onProject((p) => toggleChat(p, frame.aspect)); }} />
|
||
{!bundle.chat.length && <Hint tone="warn">Não há mensagens do chat nesta janela da gravação.</Hint>}
|
||
<PropRow label="Mensagens"><Scrub label="Mensagens visíveis" min={1} max={10} step={1} value={chat.lines} onChange={(v) => set({ lines: v }, "chat-lines")} /></PropRow>
|
||
<PropRow label="Tamanho"><Scrub label="Tamanho do texto" min={18} max={64} step={1} value={chat.size} onChange={(v) => set({ size: v }, "chat-size")} /></PropRow>
|
||
<PropRow label="Largura"><Scrub label="Largura do bloco" min={0.25} max={0.96} step={0.01} value={chat.width} format={pct} onChange={(v) => set({ width: v }, "chat-w")} /></PropRow>
|
||
<PropRow label="Posição horizontal"><Scrub label="Posição horizontal" min={0} max={0.9} step={0.01} value={chat.x} format={pct} onChange={(v) => set({ x: v }, "chat-x")} /></PropRow>
|
||
<PropRow label="Base do bloco"><Scrub label="Base do bloco" min={0.1} max={0.98} step={0.01} value={chat.y} format={pct} onChange={(v) => set({ y: v }, "chat-y")} /></PropRow>
|
||
<Check label="Mostrar o nome de quem escreveu" checked={chat.showUser} onChange={(v) => set({ showUser: v })} />
|
||
<Hint>Arraste o bloco direto no vídeo para posicionar. Cada mensagem fica até chegar a próxima (no máximo 9 s).</Hint>
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Barra e capa ---------------- */
|
||
|
||
function ProgressLayer({ project, onProject }: InspectorProps) {
|
||
return (
|
||
<PropSection title="Barra de progresso">
|
||
<Check label="Mostrar no rodapé do vídeo" checked={project.progress.enabled} onChange={(v) => onProject((p) => produce(p, (d) => { d.progress.enabled = v; }))} />
|
||
{project.progress.enabled && <>
|
||
<PropRow label="Cor"><ColorDot label="Cor da barra" value={project.progress.color} onChange={(v) => onProject((p) => produce(p, (d) => { d.progress.color = v; }), "pc")} /></PropRow>
|
||
<PropRow label="Altura"><Scrub label="Altura da barra" min={4} max={40} step={1} value={project.progress.height} format={(v) => `${v} px`} onChange={(v) => onProject((p) => produce(p, (d) => { d.progress.height = v; }), "ph")} /></PropRow>
|
||
</>}
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
function CoverLayer({ bundle, project, playhead, onProject, onSeek }: InspectorProps) {
|
||
return (
|
||
<PropSection title="Capa (thumbnail)">
|
||
<Check label="Gerar a capa ao exportar" checked={project.cover.enabled} onChange={(v) => onProject((p) => produce(p, (d) => { d.cover.enabled = v; }))} />
|
||
<Check label="Capa também no início do vídeo (0 s)" checked={Boolean(project.cover.atStart)}
|
||
onChange={(v) => onProject((p) => produce(p, (d) => { d.cover.atStart = v; if (v) d.cover.enabled = true; }))} />
|
||
<Hint>No início do vídeo a capa ocupa os 2 primeiros quadros: TikTok, Reels e Shorts usam o quadro 0 como miniatura padrão.</Hint>
|
||
<input aria-label="Texto da capa" className={fieldClass} maxLength={60} placeholder="Texto curto (até 4 palavras)" value={project.cover.text}
|
||
onChange={(e) => onProject((p) => produce(p, (d) => { d.cover.text = e.target.value; }), "cover-text")} />
|
||
<PropRow label="Quadro">
|
||
<Hot>{sessionClock(project.cover.t)}</Hot>
|
||
<Btn variant="ghost" className="px-1.5" onClick={() => onSeek(project.cover.t)}>Ver</Btn>
|
||
<Btn className="px-1.5" onClick={() => onProject((p) => produce(p, (d) => { d.cover.t = round3(playhead); }))}>Usar o playhead</Btn>
|
||
</PropRow>
|
||
{bundle.cover && <img src={fileUrl(bundle.cover)} alt="Capa gerada no último export" className="w-28 rounded-[3px] border border-nle-line" />}
|
||
<Hint>Rosto com expressão forte e até 4 palavras; o assunto no centro (a capa do Shorts é cortada).</Hint>
|
||
</PropSection>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Modal: nova narração ---------------- */
|
||
|
||
type Voice = { id: string; name: string; languages?: string[] };
|
||
|
||
export function NarrationModal({ open, onClose, bundle, playhead, onProject, onSelect, onNotice }: {
|
||
open: boolean; onClose: () => void; bundle: EditBundle; playhead: number; onProject: Update; onSelect: (s: Selection) => void; onNotice: Notice;
|
||
}) {
|
||
const [voices, setVoices] = useState<Voice[] | null>(null);
|
||
const [voice, setVoice] = useState("");
|
||
const [text, setText] = useState("");
|
||
const [speed, setSpeed] = useState(1);
|
||
const [busy, setBusy] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!open || voices) return;
|
||
void fetch("/api/voice/status", { cache: "no-store" }).then((r) => r.json()).then((s: { voices?: Voice[] }) => {
|
||
const list = (s.voices ?? []).filter((v) => (v.languages ?? []).some((l) => l.toLowerCase().startsWith("pt")) || v.id.startsWith("pt-br"));
|
||
setVoices(list);
|
||
setVoice((cur) => cur || list[0]?.id || "");
|
||
}).catch(() => setVoices([]));
|
||
}, [open, voices]);
|
||
|
||
async function narrate() {
|
||
if (!text.trim() || !voice) return;
|
||
setBusy(true);
|
||
setError(null);
|
||
const r = await clipperCall<{ file: string; durationS: number; text: string; voice: string }>(`clips/${bundle.clip.id}/tts`, "POST", { text, voice, speed });
|
||
setBusy(false);
|
||
if (!r.ok) return setError(r.error);
|
||
const id = newId("n");
|
||
onProject((p) => ({ ...p, audio: { ...p.audio, narration: [...p.audio.narration, {
|
||
id, file: r.data.file, at: round3(clamp(playhead, p.source.lo, p.source.hi)), volume: 1, durationS: r.data.durationS, duck: 0.35, text: r.data.text, voice: r.data.voice,
|
||
}] } }));
|
||
onSelect({ kind: "narration", id });
|
||
setText("");
|
||
onNotice(true, `Narração de ${sec(r.data.durationS)} inserida no playhead.`);
|
||
onClose();
|
||
}
|
||
|
||
return (
|
||
<Modal open={open} onClose={onClose} title="Nova narração" width={480}
|
||
footer={<><Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
|
||
<Btn variant="primary" disabled={busy || !text.trim() || !voice} onClick={() => void narrate()}>{busy ? <Spinner className="size-3" /> : <MicIcon size={13} />}Gerar e pôr no playhead</Btn></>}>
|
||
<div className="grid gap-2.5">
|
||
{!bundle.voiceConfigured && <Hint tone="warn">Serviço de voz não instalado.</Hint>}
|
||
<PropRow label="Voz">
|
||
<Pick label="Voz" value={voice} onChange={setVoice}>
|
||
{voices === null && <option value="">Carregando as vozes…</option>}
|
||
{voices?.length === 0 && <option value="">Serviço de voz fora do ar</option>}
|
||
{voices?.map((v) => <option key={v.id} value={v.id}>{v.name} ({v.id})</option>)}
|
||
</Pick>
|
||
</PropRow>
|
||
<textarea aria-label="Texto da narração" rows={3} maxLength={300} autoFocus className={cx(fieldClass, "resize-none")}
|
||
placeholder="Ex.: Olha o que aconteceu quando o servidor caiu…" value={text} onChange={(e) => setText(e.target.value)} />
|
||
<PropRow label="Velocidade"><Scrub label="Velocidade" min={0.5} max={2} step={0.05} value={speed} format={(v) => `${v.toFixed(2).replace(".", ",")}×`} onChange={setSpeed} /></PropRow>
|
||
<Hint>A voz entra em {sessionClock(playhead)} da gravação, com a live abaixada por baixo. Depois dá para ajustar o volume e mover.</Hint>
|
||
{error && <Hint tone="bad">{error}</Hint>}
|
||
</div>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Modal: IA sugere ---------------- */
|
||
|
||
export function AiModal({ open, onClose, bundle, project, onProject, onNotice, onWindow, clip, onClip, cfg, frame }: {
|
||
open: boolean; onClose: () => void; bundle: EditBundle; project: EditProject; onProject: Update; onNotice: Notice;
|
||
onWindow: (lo: number, hi: number) => Promise<boolean>; clip: Clip; onClip: (clip: Clip) => void; cfg: CutSettings; frame: Frame;
|
||
}) {
|
||
const [busy, setBusy] = useState(false);
|
||
const [s, setS] = useState<Suggestion | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
async function ask() {
|
||
setBusy(true);
|
||
setError(null);
|
||
const r = await clipperCall<Suggestion>(`clips/${bundle.clip.id}/suggest`, "POST", { project });
|
||
setBusy(false);
|
||
if (!r.ok) return setError(r.error);
|
||
setS(r.data);
|
||
}
|
||
const useHook = () => {
|
||
if (!s) return;
|
||
const fresh = newHook(cfg, frame, s.hook);
|
||
onProject((p) => {
|
||
const hook = p.overlays.find((o) => o.kind === "hook");
|
||
if (hook) return { ...p, overlays: p.overlays.map((o) => (o.kind === "hook" ? { ...o, text: s.hook } : o)) };
|
||
return { ...p, overlays: [fresh, ...p.overlays] };
|
||
});
|
||
};
|
||
const applySpan = async () => {
|
||
if (!s) return;
|
||
if (s.start < project.source.lo || s.end > project.source.hi) await onWindow(Math.min(project.source.lo, s.start), Math.max(project.source.hi, s.end));
|
||
onProject((p) => {
|
||
let cuts = keepRange(p.cuts, s.start, s.end);
|
||
cuts = removeRange(cuts, cuts[0].start, s.start);
|
||
cuts = removeRange(cuts, s.end, cuts[cuts.length - 1].end);
|
||
return { ...p, cuts };
|
||
});
|
||
};
|
||
const applyRemove = () => s && onProject((p) => ({ ...p, cuts: s.remove.reduce((c, r) => removeRange(c, r.start, r.end), p.cuts) }));
|
||
// Ids gerados fora do updater (ele precisa ser puro: o React em dev roda duas vezes).
|
||
const ids = s ? s.zooms.map(() => newId("z")) : [];
|
||
const applyZooms = () => s && onProject((p) => {
|
||
const existing = p.overlays.filter((o) => o.kind === "zoom");
|
||
const add = s.zooms.map((z, i) => ({ id: ids[i], kind: "zoom" as const, start: round3(Math.max(p.source.lo, z.t - 0.3)), end: round3(Math.min(p.source.hi, z.t + 1.2)), scale: 1.35, ...zoomFocusDefault(frame.aspect), ramp: 0.15 }))
|
||
.filter((z) => !existing.some((e) => z.start < e.end && z.end > e.start));
|
||
return { ...p, overlays: [...p.overlays, ...add] };
|
||
});
|
||
async function useTitle() {
|
||
if (!s) return;
|
||
const r = await clipperCall<Clip>(`clips/${clip.id}`, "PATCH", { title: s.title });
|
||
if (!r.ok) return setError(r.error);
|
||
onClip(r.data);
|
||
onNotice(true, "Título do corte atualizado.");
|
||
}
|
||
return (
|
||
<Modal open={open} onClose={onClose} title="IA sugere" width={600}
|
||
footer={<>
|
||
<Btn variant="ghost" onClick={onClose}>Fechar</Btn>
|
||
{s && <Btn onClick={async () => { useHook(); await applySpan(); applyRemove(); applyZooms(); onNotice(true, "Sugestões aplicadas (Ctrl+Z desfaz passo a passo)."); onClose(); }}><CheckIcon size={13} />Aplicar tudo, menos o título</Btn>}
|
||
<Btn variant="primary" disabled={busy || !bundle.judgeEnabled} onClick={() => void ask()}>{busy ? <Spinner className="size-3" /> : <WandIcon size={13} />}{busy ? "Pensando…" : s ? "Pedir de novo" : "Pedir sugestões"}</Btn>
|
||
</>}>
|
||
<div className="grid gap-2.5">
|
||
<p className="text-nle-dim">A IA lê a transcrição, o chat e a análise do juiz e propõe gancho, título, início e fim, trechos mortos e zooms. Nada é aplicado sem você clicar.</p>
|
||
{!bundle.judgeEnabled && <Hint tone="warn">A IA está desligada na aba Juiz do Clipador.</Hint>}
|
||
{error && <Hint tone="bad">{error}</Hint>}
|
||
{s && <>
|
||
<Suggest label="Gancho" value={`“${s.hook}”`} onApply={useHook} />
|
||
<Suggest label="Título" value={s.title} onApply={() => void useTitle()} />
|
||
<Suggest label="Início e fim" value={`${sessionClock(s.start)} → ${sessionClock(s.end)} (${sec(s.end - s.start)})`} onApply={() => void applySpan()} />
|
||
<Suggest label={`Tirar ${s.remove.length} trecho(s)`} value={s.remove.map((r) => `${sessionClock(r.start)}–${sessionClock(r.end)} (${r.why})`).join("; ") || "nenhum"} onApply={s.remove.length ? applyRemove : undefined} />
|
||
<Suggest label={`${s.zooms.length} zoom(s)`} value={s.zooms.map((z) => `${sessionClock(z.t)} (${z.why})`).join("; ") || "nenhum"} onApply={s.zooms.length ? applyZooms : undefined} />
|
||
<p className="text-nle-dim">{s.reason}</p>
|
||
<Hint>{s.model} · {sec(s.seconds)}</Hint>
|
||
</>}
|
||
</div>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
function Suggest({ label, value, onApply }: { label: string; value: string; onApply?: () => void }) {
|
||
return (
|
||
<div className="grid grid-cols-[96px_minmax(0,1fr)_auto] items-start gap-2 rounded-[3px] border border-nle-line bg-nle-row px-2.5 py-2">
|
||
<span className="font-semibold text-nle-dim">{label}</span>
|
||
<span className="text-nle-text">{value}</span>
|
||
{onApply ? <Btn className="px-2" onClick={onApply}>Aplicar</Btn> : <span />}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---------------- Modal: exportar ---------------- */
|
||
|
||
export function ExportModal({ open, onClose, bundle, project, playhead, onNotice, clip, onExport, exporting, onSelect, frame, durationIssue }: {
|
||
open: boolean; onClose: () => void; bundle: EditBundle; project: EditProject; playhead: number; onNotice: Notice;
|
||
clip: Clip; onExport: () => void; exporting: boolean; onSelect: (s: Selection) => void; frame: Frame; durationIssue: string | null;
|
||
}) {
|
||
const horizontal = frame.aspect === "horizontal";
|
||
const [preview, setPreview] = useState<{ file: string; version: string; seconds: number } | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const out = toOutput(playhead, project.cuts).t;
|
||
const total = outputDuration(project.cuts);
|
||
const rendering = ["pending", "rendering"].includes(clip.status);
|
||
|
||
async function realPreview() {
|
||
setBusy(true);
|
||
const r = await clipperCall<{ file: string; version: string; seconds: number }>(`clips/${bundle.clip.id}/preview-render`, "POST",
|
||
{ project, fromS: Math.max(0, out - 0.5), durationS: 5 });
|
||
setBusy(false);
|
||
if (!r.ok) return onNotice(false, r.error);
|
||
setPreview(r.data);
|
||
}
|
||
|
||
const shown = preview ? { src: `${fileUrl(preview.file)}&v=${encodeURIComponent(preview.version)}`, key: preview.version, label: `Prévia real de 5 s (gerada em ${sec(preview.seconds)})` }
|
||
: clip.file && !rendering ? { src: `${fileUrl(clip.file)}&v=${encodeURIComponent(clip.updatedAt)}`, key: clip.updatedAt, label: "Último vídeo exportado" } : null;
|
||
return (
|
||
<Modal open={open} onClose={onClose} title="Exportar o corte" width={720}
|
||
footer={<>
|
||
<span className="mr-auto text-nle-faint">MP4 {frame.width}×{frame.height} ({horizontal ? "16:9" : "9:16"}) · 30 fps · H.264 + AAC · {sec(total)}</span>
|
||
<Btn variant="ghost" onClick={onClose}>Fechar</Btn>
|
||
<Btn disabled={busy} onClick={() => void realPreview()}>{busy ? <Spinner className="size-3" /> : <PlayIcon size={13} />}Prévia real de 5 s</Btn>
|
||
<Btn variant="primary" disabled={rendering || exporting} onClick={onExport}>{exporting || rendering ? <Spinner className="size-3" /> : <DownloadIcon size={13} />}{rendering ? "Renderizando…" : "Exportar"}</Btn>
|
||
</>}>
|
||
<div className={cx("grid gap-4", horizontal ? "grid-cols-[minmax(0,1fr)_340px]" : "grid-cols-[minmax(0,1fr)_230px]")}>
|
||
<div className="grid content-start gap-2.5">
|
||
<PropRow label="Situação">
|
||
<span className={cx(clip.status === "error" ? "text-[#f08a7a]" : rendering ? "text-nle-hot" : "text-nle-text")}>
|
||
{rendering ? "renderizando…" : clip.status === "ready" ? "pronto para aprovar" : clip.status === "approved" ? "aprovado" : clip.status === "error" ? "erro no render" : clip.status}
|
||
</span>
|
||
{clip.edit?.exportedAt && <span className="text-nle-faint">último export {new Date(clip.edit.exportedAt).toLocaleTimeString("pt-BR")}</span>}
|
||
</PropRow>
|
||
{clip.status === "error" && clip.error && <Hint tone="bad">{clip.error}</Hint>}
|
||
<PropRow label="Formato"><span>{ASPECT_LABEL[frame.aspect]} · {frame.width}×{frame.height}</span></PropRow>
|
||
{clip.file && aspectOfClip(clip) !== frame.aspect && <Hint>O último vídeo exportado está em {ASPECT_LABEL[aspectOfClip(clip)].toLowerCase()}; exporte de novo para sair em {ASPECT_LABEL[frame.aspect].toLowerCase()}.</Hint>}
|
||
<PropRow label="Duração"><Hot className={cx("shrink-0", durationIssue && "!text-[#e2b340]")}>{sec(total)}</Hot>{durationIssue && <span className="text-[#e2b340]">{durationIssue}</span>}</PropRow>
|
||
<PropRow label="Capa">
|
||
<span>{project.cover.enabled ? `“${project.cover.text || "sem texto"}” em ${sessionClock(project.cover.t)}` : "desligada"}</span>
|
||
<Btn variant="ghost" className="px-1.5" onClick={() => { onSelect({ kind: "layer", layer: "cover" }); onClose(); }}>Ajustar</Btn>
|
||
</PropRow>
|
||
<p className="text-nle-dim">
|
||
Exportar grava o projeto, substitui o vídeo do corte e devolve o corte para a fila “Para aprovar”. A prévia real renderiza 5 s a partir do
|
||
playhead com o mesmo caminho do export — fonte, contorno e zoom exatos.
|
||
</p>
|
||
{clip.file && !rendering && <a href="/clipper" className="text-nle-hot hover:underline">Voltar à fila para aprovar →</a>}
|
||
</div>
|
||
<div className="grid content-start gap-1.5">
|
||
{shown ? <>
|
||
<video key={shown.key} controls autoPlay={Boolean(preview)} src={shown.src} className={cx("w-full rounded-[3px] bg-black object-contain", horizontal ? "aspect-video" : "aspect-[9/16]")} />
|
||
<Hint>{shown.label}</Hint>
|
||
</> : <div className={cx("grid w-full place-items-center rounded-[3px] bg-nle-well p-3 text-center text-nle-faint", horizontal ? "aspect-video" : "aspect-[9/16]")}>{rendering ? "Renderizando…" : "Sem vídeo ainda"}</div>}
|
||
</div>
|
||
</div>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
function aspectOfClip(clip: Clip): Aspect {
|
||
return clip.aspect === "horizontal" ? "horizontal" : "vertical";
|
||
}
|
||
|
||
/* ---------------- Modal: atalhos ---------------- */
|
||
|
||
const KEYS: [string[], string][] = [
|
||
[["Espaço"], "Tocar / pausar"], [["J"], "Voltar 2 s"], [["K"], "Pausar"], [["L"], "Tocar / avançar 2 s"],
|
||
[["←", "→"], "Um quadro (Shift = 1 s)"], [["Home", "End"], "Início / fim do corte"],
|
||
[["V"], "Ferramenta de seleção"], [["C"], "Lâmina: clique no clipe para dividir"], [["S"], "Dividir no playhead"],
|
||
[["Ctrl", "K"], "Dividir no playhead (igual ao S)"], [["Ctrl", "Shift", "clique"], "Dividir o clipe onde clicar"],
|
||
[["Arrastar"], "Mover palavra, texto, zoom, narração ou trecho"], [["Bordas"], "Aparar: encurtar ou esticar dos dois lados"],
|
||
[["Q"], "Começar o trecho no playhead"], [["W"], "Terminar o trecho no playhead"], [["Delete"], "Tirar a seleção do corte"],
|
||
[["N"], "Ligar / desligar o ímã"], [["Ctrl", "roda"], "Zoom da timeline"], [["Shift", "arrastar na régua"], "Selecionar um trecho"],
|
||
[["Ctrl", "Z"], "Desfazer"], [["Ctrl", "Shift", "Z"], "Refazer"], [["Ctrl", "S"], "Salvar agora"], [["Ctrl", "E"], "Exportar"],
|
||
[["Setas"], "Câmera na Fonte: mover (Shift = tamanho)"], [["Esc"], "Limpar a seleção / concluir a Fonte"],
|
||
[["[", "]"], "Keyframe anterior / seguinte"], [["Ctrl", "C"], "Copiar o keyframe selecionado"], [["Ctrl", "V"], "Colar o keyframe no playhead"],
|
||
[["Duplo clique", "◆"], "Trocar a curva do keyframe"], [["Shift", "↑ ↓"], "Janela do jogo na Fonte: zoom"],
|
||
];
|
||
|
||
export function ShortcutsModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||
return (
|
||
<Modal open={open} onClose={onClose} title="Atalhos do editor" width={560}>
|
||
<div className="grid grid-cols-2 gap-x-6 gap-y-1.5">
|
||
{KEYS.map(([keys, what]) => (
|
||
<div key={what} className="flex items-center gap-2">
|
||
<span className="flex shrink-0 items-center gap-1">{keys.map((k) => <Keycap key={k}>{k}</Keycap>)}</span>
|
||
<span className="truncate text-nle-dim">{what}</span>
|
||
</div>
|
||
))}
|
||
</div>
|
||
</Modal>
|
||
);
|
||
}
|