Publish editor updates

This commit is contained in:
haixin.yang committed 2026-07-20 10:29:42 +08:00
1 parent c1e5719e1f
commit 47d5f6315d
25 files changed
+584 -33

No files matched your search

+3 -2
View File
@@ -507,10 +507,11 @@ export function App() {
});
const { handleCutTrack } = createTimelineCutActions({
captionSegments, commitCaptionSegments, commitStickerSegments, commitVisualSegments,
audioSegments, captionSegments, commitCaptionSegments, commitStickerSegments, commitVisualSegments,
currentStickerSegmentIndex, currentTime, focusedSegmentIndex,
getCurrentVisualAssetSnapshot, imageDuration, imageSrc, notify,
selectedSegmentId, selectedSegmentIndex, selectedStickerSegmentId,
selectedAudioSegmentId, selectedSegmentId, selectedSegmentIndex, selectedStickerSegmentId,
setAudioSegments, setCaptionSegments, setSelectedAudioSegmentId,
selectedTrack, stickerSegments, trackLocks, visualSegments,
});
+14 -13
View File
@@ -21,6 +21,7 @@ import { getStickerBaseSize } from "../lib/stickerGeometry.js";
import { CaptionOverlay } from "./CaptionOverlay.jsx";
import { IconButton } from "./ui.jsx";
import { getVisualOverlayPixelBox, snapVisualOverlayTransform } from "../lib/visualOverlayTimeline.js";
import { getAnchoredResize } from "../lib/anchoredResize.js";
export function PreviewStage({
t,
@@ -216,7 +217,6 @@ export function PreviewStage({
const initial = { ...visualTransform };
const centerX = rect.left + rect.width * (0.5 + initial.x / 100);
const centerY = rect.top + rect.height * (0.5 + initial.y / 100);
const startDistance = Math.max(1, Math.hypot(startX - centerX, startY - centerY));
const startAngle = Math.atan2(startY - centerY, startX - centerX) * 180 / Math.PI;
const round = (value) => Math.round(value * 100) / 100;
const move = (moveEvent) => {
@@ -225,14 +225,14 @@ export function PreviewStage({
x: round(initial.x + (moveEvent.clientX - startX) / Math.max(1, rect.width) * 100),
y: round(initial.y + (moveEvent.clientY - startY) / Math.max(1, rect.height) * 100),
});
if (mode === "scale") {
const candidate = {
...initial,
scale: round(Math.max(0.1, Math.min(4, initial.scale * Math.hypot(moveEvent.clientX - centerX, moveEvent.clientY - centerY) / startDistance))),
};
if (mode.startsWith("scale-")) {
const handle = mode.slice(6);
let candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box: { width: rect.width, height: rect.height }, transform: initial });
candidate = { ...candidate, scale: Math.max(0.1, Math.min(4, candidate.scale)) };
const snapped = snapVisualScaleToFrameEdges(candidate, { width: rect.width, height: rect.height });
candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box: { width: rect.width, height: rect.height }, transform: initial, scale: snapped.transform.scale });
setOverlaySnapGuides(snapped.guides);
onUpdateVisualTransform({ ...snapped.transform, scale: round(snapped.transform.scale) });
onUpdateVisualTransform({ ...candidate, x: round(candidate.x), y: round(candidate.y), scale: round(candidate.scale) });
}
if (mode === "rotate") {
const angle = Math.atan2(moveEvent.clientY - centerY, moveEvent.clientX - centerX) * 180 / Math.PI;
@@ -254,7 +254,6 @@ export function PreviewStage({
const startX = event.clientX; const startY = event.clientY;
const centerX = rect.left + rect.width * (0.5 + initial.x / 100);
const centerY = rect.top + rect.height * (0.5 + initial.y / 100);
const startDistance = Math.max(1, Math.hypot(startX - centerX, startY - centerY));
const startAngle = Math.atan2(startY - centerY, startX - centerX) * 180 / Math.PI;
const round = (value) => Math.round(value * 100) / 100;
const move = (moveEvent) => {
@@ -265,10 +264,12 @@ export function PreviewStage({
onUpdateVisualOverlay(snapped.transform);
}
if (mode.startsWith("scale")) {
const horizontal = Math.abs(moveEvent.clientX - centerX) / Math.max(1, Math.abs(startX - centerX));
const vertical = Math.abs(moveEvent.clientY - centerY) / Math.max(1, Math.abs(startY - centerY));
const ratio = mode === "scale-e" || mode === "scale-w" ? horizontal : mode === "scale-n" || mode === "scale-s" ? vertical : Math.hypot(moveEvent.clientX - centerX, moveEvent.clientY - centerY) / startDistance;
onUpdateVisualOverlay({ ...initial, scale: round(Math.max(0.08, Math.min(4, initial.scale * ratio))) });
const handle = mode.slice(6);
const box = getVisualOverlayPixelBox(overlay, activePreviewFrameSize);
let candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box, transform: initial });
const clampedScale = Math.max(0.08, Math.min(4, candidate.scale));
candidate = getAnchoredResize({ handle, pointer: { x: moveEvent.clientX, y: moveEvent.clientY }, frame: rect, box, transform: initial, scale: clampedScale });
onUpdateVisualOverlay({ ...candidate, x: round(candidate.x), y: round(candidate.y), scale: round(candidate.scale) });
}
if (mode === "rotate") {
const angle = Math.atan2(moveEvent.clientY - centerY, moveEvent.clientX - centerX) * 180 / Math.PI;
@@ -452,7 +453,7 @@ export function PreviewStage({
<div className="visual-transform-box" style={visualTransformStyle} onPointerDown={(event) => startVisualTransform(event, "move")}>
<span className="visual-transform-label">{t("visualBasic", "画面")}</span>
<button className="visual-transform-rotate" type="button" aria-label={t("visualRotation", "旋转")} onPointerDown={(event) => startVisualTransform(event, "rotate")} />
{['nw', 'ne', 'sw', 'se'].map((corner) => <button key={corner} className={`visual-transform-handle is-${corner}`} type="button" aria-label={t("visualScale", "缩放")} onPointerDown={(event) => startVisualTransform(event, "scale")} />)}
{['nw', 'ne', 'sw', 'se'].map((corner) => <button key={corner} className={`visual-transform-handle is-${corner}`} type="button" aria-label={t("visualScale", "缩放")} onPointerDown={(event) => startVisualTransform(event, `scale-${corner}`)} />)}
</div>
) : null}
{previewTransition?.next?.src && trackVisibility.image ? (
+1 -1
View File
@@ -9,7 +9,7 @@ export function useMediaSync(d) {
d.audioSegments.forEach((s) => {
const a = d.audioSegmentRefs.current.get(s.id); if (!a) return;
const active = isTimelineTimeInsideTrack(d.currentTime, s.start, s.duration);
if (active) { const expected = getTimelineTrackLocalTime(d.currentTime, s.start, s.duration); if (Math.abs(a.currentTime - expected) > 0.2) a.currentTime = expected; if (a.paused) a.play().catch(() => {}); }
if (active) { const expected = Math.max(0, Number(s.sourceStart) || 0) + getTimelineTrackLocalTime(d.currentTime, s.start, s.duration); if (Math.abs(a.currentTime - expected) > 0.2) a.currentTime = expected; if (a.paused) a.play().catch(() => {}); }
else if (!a.paused) a.pause();
});
}, [d.audioSegments, d.currentTime, d.isPlaying, d.trackVisibility.audio]);
+2
View File
@@ -11,6 +11,7 @@ export const APP_LANGUAGES = [
{ id: "pt", name: "Portuguese", nativeName: "Português", hint: "Portuguese" },
{ id: "th", name: "Thai", nativeName: "ไทย", hint: "Thai" },
{ id: "vi", name: "Vietnamese", nativeName: "Tiếng Việt", hint: "Vietnamese" },
{ id: "ru", name: "Russian", nativeName: "Русский", hint: "Russian" },
];
const EXPORT_RENDER_COPY = {
@@ -1714,6 +1715,7 @@ export const LANGUAGE_FALLBACKS = {
pt: "en",
th: "en",
vi: "en",
ru: "en",
};
export function getStoredLanguage() {
+38
View File
@@ -0,0 +1,38 @@
const HANDLE_DIRECTIONS = {
nw: [-1, -1], n: [0, -1], ne: [1, -1], e: [1, 0],
se: [1, 1], s: [0, 1], sw: [-1, 1], w: [-1, 0],
};
const rotate = (x, y, radians) => ({
x: x * Math.cos(radians) - y * Math.sin(radians),
y: x * Math.sin(radians) + y * Math.cos(radians),
});
export function getAnchoredResize({ handle, pointer, frame, box, transform, scale }) {
const direction = HANDLE_DIRECTIONS[handle];
if (!direction) return transform;
const initialScale = Math.max(0.0001, Number(transform.scale) || 1);
const radians = (Number(transform.rotation) || 0) * Math.PI / 180;
const center = {
x: frame.left + frame.width * (0.5 + (Number(transform.x) || 0) / 100),
y: frame.top + frame.height * (0.5 + (Number(transform.y) || 0) / 100),
};
const diagonal = rotate(direction[0] * box.width, direction[1] * box.height, radians);
const anchor = {
x: center.x - diagonal.x * initialScale / 2,
y: center.y - diagonal.y * initialScale / 2,
};
const projectedScale = ((pointer.x - anchor.x) * diagonal.x + (pointer.y - anchor.y) * diagonal.y)
/ Math.max(1, diagonal.x ** 2 + diagonal.y ** 2);
const nextScale = Number.isFinite(scale) ? scale : projectedScale;
const nextCenter = {
x: anchor.x + diagonal.x * nextScale / 2,
y: anchor.y + diagonal.y * nextScale / 2,
};
return {
...transform,
scale: nextScale,
x: (nextCenter.x - frame.left - frame.width / 2) / Math.max(1, frame.width) * 100,
y: (nextCenter.y - frame.top - frame.height / 2) / Math.max(1, frame.height) * 100,
};
}
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { getAnchoredResize } from "./anchoredResize.js";
describe("getAnchoredResize", () => {
it("keeps the opposite corner fixed while resizing", () => {
const result = getAnchoredResize({
handle: "se", pointer: { x: 300, y: 300 },
frame: { left: 0, top: 0, width: 200, height: 200 },
box: { width: 200, height: 200 }, transform: { x: 0, y: 0, scale: 1, rotation: 0 },
});
expect(result).toMatchObject({ x: 25, y: 25, scale: 1.5 });
});
it("uses the opposite edge as the anchor for an edge handle", () => {
const result = getAnchoredResize({
handle: "e", pointer: { x: 250, y: 100 },
frame: { left: 0, top: 0, width: 200, height: 200 },
box: { width: 100, height: 80 }, transform: { x: 0, y: 0, scale: 1, rotation: 0 },
});
expect(result).toMatchObject({ x: 25, y: 0, scale: 2 });
});
});
+4 -1
View File
@@ -880,6 +880,9 @@ export async function exportBrowserVideo({
volume: segment.volume ?? 1,
role: "voice",
start: Math.max(0, segment.start || 0),
sourceOffset: Math.max(0, segment.sourceStart || 0),
sourceDuration: Math.max(0, segment.duration || 0),
outputDuration: Math.max(0, segment.duration || 0),
fadeIn: Math.max(0, segment.fadeIn || 0),
fadeOut: Math.max(0, segment.fadeOut || 0),
})),
@@ -936,7 +939,7 @@ export async function exportBrowserVideo({
}),
);
decodedDuration = Math.max(0, ...decodedInputs.filter((input) => input.role === "voice").map((input) => input.start + input.decoded.duration));
decodedDuration = Math.max(0, ...decodedInputs.filter((input) => input.role === "voice").map((input) => input.start + input.outputDuration));
decodedInputs.forEach((input) => {
const source = audioContext.createBufferSource();
+1 -1
View File
@@ -92,7 +92,7 @@ export async function mixOfflineAudio({
const inputs = [
...voiceAudioSegments.filter((item) => item.blob).map((item) => ({
blob: item.blob, start: Math.max(0, item.start || 0), volume: item.volume ?? 1,
sourceOffset: 0, sourceDuration: 0, playbackRate: 1,
sourceOffset: Math.max(0, item.sourceStart || 0), sourceDuration: Math.max(0, item.duration || 0), playbackRate: 1,
fadeIn: Math.max(0, item.fadeIn || 0), fadeOut: Math.max(0, item.fadeOut || 0),
})),
...(sourceAudioBlob && sourceAudioSegments.length ? sourceAudioSegments.map((item) => ({
+2 -2
View File
@@ -21,7 +21,7 @@ export function createPlaybackControls(deps) {
deps.currentTimeRef.current = clamped; deps.setCurrentTime(clamped);
deps.audioSegments.forEach((segment) => {
const audio = deps.audioSegmentRefs.current.get(segment.id);
if (audio) audio.currentTime = getTimelineTrackLocalTime(clamped, segment.start, segment.duration);
if (audio) audio.currentTime = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(clamped, segment.start, segment.duration);
});
if (deps.sourceAudioRef.current) deps.sourceAudioRef.current.currentTime = getSourceState(clamped).sourceTime;
if (deps.musicRef.current) deps.musicRef.current.currentTime = getTimelineTrackLocalTime(clamped, deps.musicStart, deps.musicDuration);
@@ -55,7 +55,7 @@ export function createPlaybackControls(deps) {
const playIf = (media, ready) => ready ? media?.play().catch(() => {}) : media?.pause();
voices.forEach(({ segment, audio }) => {
const active = isTimelineTimeInsideTrack(timelineTime, segment.start, segment.duration);
audio.currentTime = getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
audio.currentTime = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
audio.volume = getAudioSegmentPreviewVolume(segment, timelineTime); audio.playbackRate = 1; playIf(audio, active);
});
if (source && deps.sourceAudioUrl) {
+47
View File
@@ -37,9 +37,56 @@ export function createTimelineCutActions(d) {
{ ...source, id: makeId("caption"), text: source.text.slice(splitAt), weight: Math.max(0.7, (source.weight ?? 1) / 2), ...(splitTime ? { start: splitTime } : {}) });
d.commitCaptionSegments(next, "已把当前字幕片段拆成两段", index + 1);
};
const handleCutAudioSegment = () => {
if (d.trackLocks.audio) return void d.notify("配音轨已锁定,无法剪切");
const index = d.audioSegments.findIndex((segment) => segment.id === d.selectedAudioSegmentId);
const source = d.audioSegments[index];
if (!source) return void d.notify("请先选择一个配音片段");
const time = Math.max(source.start, Math.min(source.start + source.duration, d.currentTime));
if (time <= source.start + 0.05 || time >= source.start + source.duration - 0.05) {
return void d.notify("请把播放头放在配音片段中间再剪切");
}
const firstDuration = time - source.start;
const secondDuration = source.duration - firstDuration;
const peakSplit = Math.max(1, Math.min((source.peaks?.length || 1) - 1, Math.round((firstDuration / source.duration) * (source.peaks?.length || 0))));
const firstId = makeId("voice");
const secondId = makeId("voice");
const firstUrl = source.blob ? URL.createObjectURL(source.blob) : source.url;
const secondUrl = source.blob ? URL.createObjectURL(source.blob) : source.url;
const first = {
...source,
id: firstId,
url: firstUrl,
duration: firstDuration,
peaks: source.peaks?.slice(0, peakSplit) || [],
fadeOut: 0,
};
const second = {
...source,
id: secondId,
url: secondUrl,
start: time,
duration: secondDuration,
sourceStart: Math.max(0, Number(source.sourceStart) || 0) + firstDuration,
peaks: source.peaks?.slice(peakSplit) || [],
fadeIn: 0,
};
d.setAudioSegments((segments) => {
const next = [...segments];
next.splice(index, 1, first, second);
return next;
});
if (source.blob && source.url) URL.revokeObjectURL(source.url);
d.setCaptionSegments((captions) => captions.map((caption) => caption.audioSegmentId === source.id
? { ...caption, audioSegmentId: firstId, end: Math.min(caption.end, time) }
: caption));
d.setSelectedAudioSegmentId(secondId);
d.notify("已在播放头位置切开配音片段");
};
const handleCutTrack = () => {
if (d.selectedTrack === "image") return void handleCutVisualSegment();
if (d.selectedTrack === "caption") return void handleCutCaption();
if (d.selectedTrack === "audio") return void handleCutAudioSegment();
if (d.selectedTrack === "sticker") {
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法剪切");
const selected = d.selectedStickerSegmentId && d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId);
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it, vi } from "vitest";
import { createTimelineCutActions } from "./timelineCutActions.js";
describe("timeline cut actions", () => {
it("cuts a selected voiceover at the playhead and offsets the second source", () => {
const source = {
id: "voice-original",
blob: new Blob(["voice"]),
url: "blob:voice-original",
start: 2,
duration: 4,
sourceStart: 1,
peaks: [0.1, 0.2, 0.3, 0.4],
fadeIn: 0.2,
fadeOut: 0.3,
};
let audioSegments = [source];
let captions = [{ id: "caption", audioSegmentId: source.id, start: 2, end: 6 }];
let selectedId = source.id;
const createObjectURL = vi.spyOn(URL, "createObjectURL").mockReturnValueOnce("blob:first").mockReturnValueOnce("blob:second");
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
const actions = createTimelineCutActions({
audioSegments,
currentTime: 3.5,
notify: vi.fn(),
selectedAudioSegmentId: source.id,
selectedTrack: "audio",
setAudioSegments: (updater) => { audioSegments = updater(audioSegments); },
setCaptionSegments: (updater) => { captions = updater(captions); },
setSelectedAudioSegmentId: (id) => { selectedId = id; },
trackLocks: {},
});
actions.handleCutTrack();
expect(audioSegments).toHaveLength(2);
expect(audioSegments[0]).toMatchObject({ start: 2, duration: 1.5, sourceStart: 1, url: "blob:first", fadeOut: 0 });
expect(audioSegments[1]).toMatchObject({ start: 3.5, duration: 2.5, sourceStart: 2.5, url: "blob:second", fadeIn: 0 });
expect(audioSegments[0].peaks).toEqual([0.1, 0.2]);
expect(audioSegments[1].peaks).toEqual([0.3, 0.4]);
expect(captions[0]).toMatchObject({ audioSegmentId: audioSegments[0].id, end: 3.5 });
expect(selectedId).toBe(audioSegments[1].id);
expect(createObjectURL).toHaveBeenCalledTimes(2);
expect(revokeObjectURL).toHaveBeenCalledWith(source.url);
});
});
+10 -8
View File
@@ -37,6 +37,14 @@ export function getVisualOverlayPixelBox(overlay, frameSize) {
export function createVisualOverlaySegment(asset, start = 0, options = {}) {
const duration = Math.max(0.1, Number(options.duration ?? asset?.duration) || DEFAULT_OVERLAY_SECONDS);
const baseTransform = {
x: 27,
y: -24,
scale: 0.34,
rotation: 0,
opacity: 1,
...(options.baseTransform || {}),
};
return {
id: options.id || `overlay-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
assetId: asset?.id || "",
@@ -54,14 +62,8 @@ export function createVisualOverlaySegment(asset, start = 0, options = {}) {
duration,
muted: options.muted === true,
layer: Math.max(1, Number(options.layer) || 1),
keyframes: normalizeVisualKeyframes(options.keyframes?.length ? options.keyframes : [{
time: 0,
x: 27,
y: -24,
scale: 0.34,
rotation: 0,
opacity: 1,
}]),
baseTransform,
keyframes: normalizeVisualKeyframes(options.keyframes || []),
};
}
+2 -1
View File
@@ -13,7 +13,8 @@ describe("visual overlay timeline", () => {
it("creates a picture-in-picture clip at the requested time", () => {
const clip = createVisualOverlaySegment({ id: "asset", name: "camera", type: "video", src: "blob:test", duration: 3, trackFrames: ["frame-a", "frame-b"] }, 4, { id: "pip" });
expect(clip).toMatchObject({ id: "pip", start: 4, duration: 3, type: "video", layer: 1, muted: false, trackFrames: ["frame-a", "frame-b"] });
expect(clip.keyframes[0]).toMatchObject({ scale: 0.34, x: 27, y: -24 });
expect(clip.baseTransform).toMatchObject({ scale: 0.34, x: 27, y: -24 });
expect(clip.keyframes).toEqual([]);
});
it("preserves a square overlay box inside portrait and landscape frames", () => {