Add Remaster enhancement and timeline interaction fixes (#10)
* Add comprehensive GEO search foundation * Enable free positioning for timeline clips * Add Remaster enhancement and timeline interaction fixes --------- Co-authored-by: haixin.yang <haixin.yang@weimob.com>
This commit is contained in:
1 parent
bacf0804b1
commit
184f57c63d
26 files changed
+1158
-20
No files matched your search
@@ -0,0 +1,13 @@
|
||||
export function float16BitsToFloat32(value) {
|
||||
const sign = value & 0x8000 ? -1 : 1;
|
||||
const exponent = (value >>> 10) & 0x1f;
|
||||
const mantissa = value & 0x3ff;
|
||||
if (exponent === 0) return sign * 2 ** -14 * (mantissa / 1024);
|
||||
if (exponent === 0x1f) return mantissa ? Number.NaN : sign * Infinity;
|
||||
return sign * 2 ** (exponent - 15) * (1 + mantissa / 1024);
|
||||
}
|
||||
|
||||
export function readFloat16TensorValue(data, index) {
|
||||
if (data?.constructor?.name === "Float16Array") return Number(data[index]);
|
||||
return float16BitsToFloat32(data[index]);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { float16BitsToFloat32, readFloat16TensorValue } from "./float16.js";
|
||||
|
||||
describe("float16 tensor decoding", () => {
|
||||
it("decodes legacy Uint16 bit patterns", () => {
|
||||
expect(float16BitsToFloat32(0x3c00)).toBe(1);
|
||||
expect(readFloat16TensorValue(new Uint16Array([0x3800]), 0)).toBe(0.5);
|
||||
});
|
||||
|
||||
it("does not decode native Float16Array values twice", () => {
|
||||
const NativeFloat16Like = class Float16Array extends Array {};
|
||||
const values = new NativeFloat16Like();
|
||||
values.push(0.625);
|
||||
expect(readFloat16TensorValue(values, 0)).toBe(0.625);
|
||||
});
|
||||
});
|
||||
@@ -29,8 +29,13 @@ export function createImageResizeControl(d) {
|
||||
d.musicBlob && d.musicDuration > 0 ? { time: Math.min(MAX_TIMELINE_DURATION_SECONDS, d.musicDuration), label: "音乐结尾" } : null,
|
||||
].filter(Boolean);
|
||||
let activeLabel = "";
|
||||
let editingStarted = false;
|
||||
const apply = (clientX) => {
|
||||
if (!rect) return;
|
||||
if (!editingStarted) {
|
||||
editingStarted = true;
|
||||
d.pauseForTimelineEdit?.();
|
||||
}
|
||||
const pointerX = clientX - rect.left;
|
||||
const inTrackX = Math.max(0, Math.min(rect.width, pointerX));
|
||||
const raw = (inTrackX / Math.max(rect.width, 1)) * timelineDuration + Math.max(0, pointerX - rect.width) * overflowRate;
|
||||
|
||||
@@ -1147,6 +1147,97 @@ function runFfmpegTask(task) {
|
||||
return nextTask;
|
||||
}
|
||||
|
||||
function createAbortError(message = "任务已取消") {
|
||||
const error = new Error(message);
|
||||
error.name = "AbortError";
|
||||
return error;
|
||||
}
|
||||
|
||||
function getAbortableFfmpeg(signal) {
|
||||
const loading = getFfmpeg();
|
||||
if (!signal) return loading;
|
||||
if (signal.aborted) return Promise.reject(createAbortError("整段增强已取消"));
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const abort = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(createAbortError("整段增强已取消"));
|
||||
};
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
loading.then((ffmpeg) => {
|
||||
signal.removeEventListener("abort", abort);
|
||||
if (settled || signal.aborted) {
|
||||
try { ffmpeg.terminate(); } catch { /* The loader may already be closed. */ }
|
||||
ffmpegLoadPromise = null;
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
resolve(ffmpeg);
|
||||
}, (error) => {
|
||||
signal.removeEventListener("abort", abort);
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function encodePngFrameSequence({ totalFrames, frameRate, produceFrame, signal, onProgress }) {
|
||||
return runFfmpegTask(async () => {
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
let ffmpeg = null;
|
||||
const id = makeId("remaster");
|
||||
const prefix = `${id}-frame`;
|
||||
const outputName = `${id}.mp4`;
|
||||
const frameNames = [];
|
||||
const frameBlobs = [];
|
||||
let terminated = false;
|
||||
const abort = () => {
|
||||
terminated = true;
|
||||
try { ffmpeg.terminate(); } catch { /* FFmpeg may already be stopped. */ }
|
||||
ffmpegLoadPromise = null;
|
||||
};
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
for (let index = 0; index < totalFrames; index += 1) {
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
const blob = await produceFrame(index);
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
frameBlobs.push(blob);
|
||||
}
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
onProgress?.({ progress: 91, phaseKey: "remasterPhaseLoadEncoder" });
|
||||
ffmpeg = await getAbortableFfmpeg(signal);
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
for (let index = 0; index < frameBlobs.length; index += 1) {
|
||||
const name = `${prefix}-${String(index).padStart(6, "0")}.png`;
|
||||
frameNames.push(name);
|
||||
await ffmpeg.writeFile(name, new Uint8Array(await frameBlobs[index].arrayBuffer()));
|
||||
}
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
onProgress?.({ progress: 92, phaseKey: "remasterPhaseEncodeVideo" });
|
||||
await ffmpeg.exec([
|
||||
"-framerate", String(frameRate),
|
||||
"-i", `${prefix}-%06d.png`,
|
||||
"-an", "-c:v", "libx264", "-preset", "veryfast",
|
||||
"-crf", "18", "-pix_fmt", "yuv420p", "-movflags", "faststart",
|
||||
outputName,
|
||||
]);
|
||||
if (signal?.aborted) throw createAbortError("整段增强已取消");
|
||||
const data = await ffmpeg.readFile(outputName);
|
||||
onProgress?.({ progress: 99, phaseKey: "remasterPhaseCreateAsset" });
|
||||
return new Blob([data], { type: "video/mp4" });
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
if (!terminated && ffmpeg) {
|
||||
await Promise.all(frameNames.map((name) => ffmpeg.deleteFile(name).catch(() => {})));
|
||||
await ffmpeg.deleteFile(outputName).catch(() => {});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function transcodeWebmToMp4(webmBlob) {
|
||||
return runFfmpegTask(async () => {
|
||||
const [{ fetchFile }, ffmpeg] = await Promise.all([import("@ffmpeg/util"), getFfmpeg()]);
|
||||
|
||||
@@ -33,7 +33,12 @@ export function createPlaybackControls(deps) {
|
||||
};
|
||||
const startTimelineSeek = (event) => {
|
||||
if (event.button !== 0 || deps.timelineDuration <= 0) return;
|
||||
event.preventDefault(); event.stopPropagation(); seekTo(getTimelineTimeFromClientX(event.clientX));
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (deps.isPlaying) {
|
||||
pauseTimelineMedia();
|
||||
deps.setIsPlaying(false);
|
||||
}
|
||||
seekTo(getTimelineTimeFromClientX(event.clientX));
|
||||
const move = (e) => seekTo(getTimelineTimeFromClientX(e.clientX));
|
||||
const up = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); };
|
||||
addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createPlaybackControls } from "./playbackControls.js";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
function createDeps(overrides = {}) {
|
||||
return {
|
||||
isPlaying: true,
|
||||
timelineDuration: 10,
|
||||
timelineDurationRef: { current: 10 },
|
||||
trackScrollRef: { current: { getBoundingClientRect: () => ({ left: 100, width: 500 }) } },
|
||||
currentTimeRef: { current: 0 },
|
||||
setCurrentTime: vi.fn(), setIsPlaying: vi.fn(),
|
||||
audioSegments: [], audioSegmentRefs: { current: new Map() },
|
||||
sourceAudioRef: { current: { pause: vi.fn(), currentTime: 0 } },
|
||||
musicRef: { current: { pause: vi.fn(), currentTime: 0 } },
|
||||
previewVideoRef: { current: { pause: vi.fn() } },
|
||||
sourceAudioLinked: false, sourceAudioStart: 0, sourceAudioDuration: 0,
|
||||
musicStart: 0, musicDuration: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("timeline playhead seeking", () => {
|
||||
it("pauses playback immediately on pointer-down before any move", () => {
|
||||
const pointerListeners = new Map();
|
||||
vi.stubGlobal("addEventListener", vi.fn((type, listener) => pointerListeners.set(type, listener)));
|
||||
vi.stubGlobal("removeEventListener", vi.fn());
|
||||
const deps = createDeps();
|
||||
const controls = createPlaybackControls(deps);
|
||||
controls.startTimelineSeek({
|
||||
button: 0, clientX: 250, preventDefault: vi.fn(), stopPropagation: vi.fn(),
|
||||
});
|
||||
expect(deps.sourceAudioRef.current.pause).toHaveBeenCalledTimes(1);
|
||||
expect(deps.musicRef.current.pause).toHaveBeenCalledTimes(1);
|
||||
expect(deps.previewVideoRef.current.pause).toHaveBeenCalledTimes(1);
|
||||
expect(deps.setIsPlaying).toHaveBeenCalledWith(false);
|
||||
expect(deps.setCurrentTime).toHaveBeenCalledWith(3);
|
||||
expect(pointerListeners.has("pointermove")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not issue a redundant pause when playback is already stopped", () => {
|
||||
vi.stubGlobal("addEventListener", vi.fn());
|
||||
vi.stubGlobal("removeEventListener", vi.fn());
|
||||
const deps = createDeps({ isPlaying: false });
|
||||
createPlaybackControls(deps).startTimelineSeek({
|
||||
button: 0, clientX: 350, preventDefault: vi.fn(), stopPropagation: vi.fn(),
|
||||
});
|
||||
expect(deps.previewVideoRef.current.pause).not.toHaveBeenCalled();
|
||||
expect(deps.setIsPlaying).not.toHaveBeenCalled();
|
||||
expect(deps.setCurrentTime).toHaveBeenCalledWith(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { encodePngFrameSequence } from "./media.js";
|
||||
import { enhanceRemasterFrame } from "./remasterEnhancement.js";
|
||||
|
||||
function createAbortError() {
|
||||
const error = new Error("整段增强已取消");
|
||||
error.name = "AbortError";
|
||||
return error;
|
||||
}
|
||||
|
||||
function throwIfAborted(signal) {
|
||||
if (signal?.aborted) throw createAbortError();
|
||||
}
|
||||
|
||||
function waitForVideo(video, eventName, signal, timeoutMs = 15000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = 0;
|
||||
const cleanup = () => {
|
||||
video.removeEventListener(eventName, ready);
|
||||
video.removeEventListener("error", failed);
|
||||
signal?.removeEventListener("abort", aborted);
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
const ready = () => { cleanup(); resolve(); };
|
||||
const failed = () => { cleanup(); reject(new Error("无法读取待增强视频")); };
|
||||
const aborted = () => { cleanup(); reject(createAbortError()); };
|
||||
video.addEventListener(eventName, ready, { once: true });
|
||||
video.addEventListener("error", failed, { once: true });
|
||||
signal?.addEventListener("abort", aborted, { once: true });
|
||||
timer = window.setTimeout(() => {
|
||||
if (video.readyState >= 2) ready();
|
||||
else { cleanup(); reject(new Error("读取视频帧超时,请重新选择片段后重试")); }
|
||||
}, timeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadVideo(src, signal) {
|
||||
const video = document.createElement("video");
|
||||
video.muted = true; video.playsInline = true; video.preload = "auto";
|
||||
video.src = src;
|
||||
video.load();
|
||||
if (video.readyState < 1) await waitForVideo(video, "loadedmetadata", signal);
|
||||
if (video.readyState < 2) await waitForVideo(video, "loadeddata", signal);
|
||||
return video;
|
||||
}
|
||||
|
||||
async function seekVideo(video, time, signal) {
|
||||
throwIfAborted(signal);
|
||||
const maximum = Math.max(0, (Number(video.duration) || 0) - 0.001);
|
||||
const target = Math.max(0, Math.min(maximum, time));
|
||||
if (Math.abs(video.currentTime - target) <= 0.0005 && video.readyState >= 2) return;
|
||||
const waiting = waitForVideo(video, "seeked", signal);
|
||||
video.currentTime = target;
|
||||
await waiting;
|
||||
}
|
||||
|
||||
export async function enhanceRemasterClip({ segment, videoElement = null, frameRate = 30, maxLongEdge = 960, signal, onProgress }) {
|
||||
if (!segment?.src || segment.type !== "video") throw new Error("请选择一个视频片段");
|
||||
throwIfAborted(signal);
|
||||
onProgress?.({ progress: 1, phaseKey: "remasterPhaseReadClip", frameIndex: 0, totalFrames: 0 });
|
||||
const expectedSrc = new URL(segment.src, window.location.href).href;
|
||||
const reusableVideo = videoElement
|
||||
&& videoElement.readyState >= 2
|
||||
&& videoElement.videoWidth > 0
|
||||
&& (videoElement.currentSrc === expectedSrc || videoElement.src === expectedSrc);
|
||||
const video = reusableVideo ? videoElement : await loadVideo(segment.src, signal);
|
||||
if (reusableVideo) onProgress?.({ progress: 2, phaseKey: "remasterPhaseReuseVideo", frameIndex: 0, totalFrames: 0 });
|
||||
const restoreTime = reusableVideo ? video.currentTime : 0;
|
||||
const sourceStart = Math.max(0, Math.min(Number(video.duration) || 0, Number(segment.sourceStart) || 0));
|
||||
const availableDuration = Math.max(0.001, (Number(video.duration) || 0) - sourceStart);
|
||||
const sourceDuration = Math.max(0.001, Math.min(
|
||||
availableDuration,
|
||||
Number(segment.sourceDuration) || Number(segment.duration) || availableDuration,
|
||||
));
|
||||
const safeFrameRate = Math.max(1, Math.min(60, Math.round(Number(frameRate) || 30)));
|
||||
const totalFrames = Math.max(1, Math.ceil(sourceDuration * safeFrameRate));
|
||||
let outputSize = null;
|
||||
let backend = "";
|
||||
try {
|
||||
const blob = await encodePngFrameSequence({
|
||||
totalFrames,
|
||||
frameRate: safeFrameRate,
|
||||
signal,
|
||||
onProgress,
|
||||
produceFrame: async (index) => {
|
||||
throwIfAborted(signal);
|
||||
await seekVideo(video, sourceStart + index / safeFrameRate, signal);
|
||||
const bitmap = await createImageBitmap(video);
|
||||
const result = await enhanceRemasterFrame({
|
||||
bitmap,
|
||||
maxLongEdge,
|
||||
signal,
|
||||
onProgress: ({ progress: frameProgress, backend: frameBackend }) => {
|
||||
if (frameBackend) backend = frameBackend;
|
||||
onProgress?.({
|
||||
progress: Math.min(90, 4 + ((index + Math.max(0, Math.min(100, frameProgress || 0)) / 100) / totalFrames) * 86),
|
||||
phaseKey: "remasterPhaseEnhancingFrame",
|
||||
phaseParams: { current: index + 1, total: totalFrames },
|
||||
frameIndex: index + 1,
|
||||
totalFrames,
|
||||
backend,
|
||||
});
|
||||
},
|
||||
});
|
||||
if (result.backend) backend = result.backend;
|
||||
outputSize ??= { width: result.width, height: result.height };
|
||||
onProgress?.({
|
||||
progress: Math.min(90, 4 + ((index + 1) / totalFrames) * 86),
|
||||
phaseKey: "remasterPhaseFrameEnhanced",
|
||||
phaseParams: { current: index + 1, total: totalFrames },
|
||||
frameIndex: index + 1,
|
||||
totalFrames,
|
||||
backend,
|
||||
});
|
||||
return result.blob;
|
||||
},
|
||||
});
|
||||
return {
|
||||
blob,
|
||||
width: outputSize?.width || video.videoWidth,
|
||||
height: outputSize?.height || video.videoHeight,
|
||||
sourceDuration,
|
||||
frameRate: safeFrameRate,
|
||||
totalFrames,
|
||||
backend,
|
||||
};
|
||||
} finally {
|
||||
video.pause();
|
||||
if (reusableVideo) {
|
||||
if (Number.isFinite(restoreTime)) video.currentTime = Math.min(Math.max(0, restoreTime), Math.max(0, (Number(video.duration) || 0) - 0.001));
|
||||
} else {
|
||||
video.removeAttribute("src"); video.load();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { REMASTER_DRUNET_MODEL, REMASTER_DRUNET_MODEL_URL } from "../config/models.js";
|
||||
|
||||
export const REMASTER_DRUNET_MODEL_LABEL = REMASTER_DRUNET_MODEL.label;
|
||||
export { REMASTER_DRUNET_MODEL_URL };
|
||||
|
||||
let worker = null;
|
||||
const pending = new Map();
|
||||
|
||||
function getWorker() {
|
||||
if (worker) return worker;
|
||||
worker = new Worker(new URL("../workers/remaster.worker.js", import.meta.url), { type: "module" });
|
||||
worker.addEventListener("message", (event) => {
|
||||
const message = event.data ?? {};
|
||||
const request = pending.get(message.requestId);
|
||||
if (!request) return;
|
||||
if (message.type === "progress") { request.onProgress?.(message); return; }
|
||||
pending.delete(message.requestId);
|
||||
request.signal?.removeEventListener("abort", request.abort);
|
||||
if (message.type === "result") request.resolve(message.result);
|
||||
else request.reject(new Error(message.error || "视频增强失败"));
|
||||
});
|
||||
worker.addEventListener("error", (event) => {
|
||||
const error = new Error(event.message || "视频增强 Worker 运行失败");
|
||||
pending.forEach((request) => request.reject(error)); pending.clear();
|
||||
worker?.terminate(); worker = null;
|
||||
});
|
||||
return worker;
|
||||
}
|
||||
|
||||
export function enhanceRemasterFrame({ bitmap, maxLongEdge = 960, onProgress, signal }) {
|
||||
if (!bitmap) return Promise.reject(new Error("没有可增强的画面"));
|
||||
const requestId = `remaster-${crypto.randomUUID?.() ?? Date.now()}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const activeWorker = getWorker();
|
||||
const abort = () => {
|
||||
pending.delete(requestId);
|
||||
bitmap.close?.();
|
||||
if (worker === activeWorker) {
|
||||
activeWorker.terminate();
|
||||
worker = null;
|
||||
pending.clear();
|
||||
}
|
||||
const error = new Error("视频增强已取消"); error.name = "AbortError"; reject(error);
|
||||
};
|
||||
if (signal?.aborted) { abort(); return; }
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
pending.set(requestId, { resolve, reject, onProgress, signal, abort });
|
||||
activeWorker.postMessage({ type: "enhance", requestId, bitmap, maxLongEdge }, [bitmap]);
|
||||
});
|
||||
}
|
||||
|
||||
export async function captureRemasterSource({ type, src, video }) {
|
||||
if (type === "video") {
|
||||
if (!video || video.readyState < 2 || !video.videoWidth || !video.videoHeight) {
|
||||
throw new Error("当前视频帧尚未准备好,请稍后重试");
|
||||
}
|
||||
return createImageBitmap(video);
|
||||
}
|
||||
const response = await fetch(src);
|
||||
if (!response.ok) throw new Error(`读取画面失败(HTTP ${response.status})`);
|
||||
return createImageBitmap(await response.blob());
|
||||
}
|
||||
|
||||
export function disposeRemasterWorker() {
|
||||
worker?.terminate(); worker = null;
|
||||
pending.forEach((request) => request.reject(new Error("视频增强 Worker 已关闭")));
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.dispose(disposeRemasterWorker);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function translateRemasterPhase(job, t, fallbackKey = "remasterProcessing") {
|
||||
const template = job?.phaseKey ? t(job.phaseKey) : job?.phase || t(fallbackKey);
|
||||
return Object.entries(job?.phaseParams || {}).reduce(
|
||||
(text, [key, value]) => text.replaceAll(`{${key}}`, String(value)),
|
||||
template,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { translateRemasterPhase } from "./remasterProgress.js";
|
||||
|
||||
describe("translateRemasterPhase", () => {
|
||||
const t = (key) => ({
|
||||
remasterProcessing: "Enhancing",
|
||||
remasterPhaseEnhancingFrame: "Enhancing frame {current} / {total}",
|
||||
})[key] || key;
|
||||
|
||||
it("translates phase keys and replaces variables", () => {
|
||||
expect(translateRemasterPhase({
|
||||
phaseKey: "remasterPhaseEnhancingFrame",
|
||||
phaseParams: { current: 9, total: 301 },
|
||||
}, t)).toBe("Enhancing frame 9 / 301");
|
||||
});
|
||||
|
||||
it("keeps legacy phase strings and supplies a translated fallback", () => {
|
||||
expect(translateRemasterPhase({ phase: "Legacy phase" }, t)).toBe("Legacy phase");
|
||||
expect(translateRemasterPhase({}, t)).toBe("Enhancing");
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { DEFAULT_STICKER_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS, MIN_VIS
|
||||
export function createTimelineMoveControls(d) {
|
||||
const startSingleTrackMove = (event, track) => {
|
||||
if (event.button !== 0) return;
|
||||
d.pauseForTimelineEdit?.();
|
||||
const isSource = track === "source";
|
||||
const clipDuration = isSource ? d.sourceAudioDuration : d.musicDuration;
|
||||
const start = isSource ? d.sourceAudioStart : d.musicStart;
|
||||
@@ -25,6 +26,7 @@ export function createTimelineMoveControls(d) {
|
||||
};
|
||||
const startAudioSegmentMove = (event, id = "") => {
|
||||
if (event.button !== 0) return;
|
||||
d.pauseForTimelineEdit?.();
|
||||
const segment = d.audioSegments.find((item) => item.id === id); if (!segment) return;
|
||||
if (d.trackLocks.audio) return void d.notify(d.t("audioTrackLockedMove"));
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect(); const duration = d.timelineDurationRef.current || 10;
|
||||
@@ -51,6 +53,7 @@ export function createTimelineMoveControls(d) {
|
||||
};
|
||||
const startStickerSegmentMove = (event, id = "") => {
|
||||
if (event.button !== 0) return;
|
||||
d.pauseForTimelineEdit?.();
|
||||
const segment = d.stickerSegments.find((item) => item.id === id); if (!segment) return;
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法移动贴纸");
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect();
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTimelineMoveControls } from "./timelineMoveControls.js";
|
||||
import { createTimelineReorderControls } from "./timelineReorderControls.js";
|
||||
|
||||
function installPointerListeners() {
|
||||
const listeners = new Map();
|
||||
vi.stubGlobal("addEventListener", vi.fn((type, listener) => listeners.set(type, listener)));
|
||||
vi.stubGlobal("removeEventListener", vi.fn((type, listener) => {
|
||||
if (listeners.get(type) === listener) listeners.delete(type);
|
||||
}));
|
||||
return listeners;
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("timeline drag playback behavior", () => {
|
||||
it("pauses immediately when a sticker clip is pressed", () => {
|
||||
const listeners = installPointerListeners();
|
||||
const pauseForTimelineEdit = vi.fn();
|
||||
const setStickerSegments = vi.fn();
|
||||
const controls = createTimelineMoveControls({
|
||||
stickerSegments: [{ id: "sticker-1", start: 1, duration: 2, stickerId: "spark" }],
|
||||
trackLocks: { sticker: false },
|
||||
trackScrollRef: { current: { getBoundingClientRect: () => ({ width: 100 }) } },
|
||||
timelineDurationRef: { current: 10 },
|
||||
estimatedDuration: 10,
|
||||
setSelectedTrack: vi.fn(), setActiveTool: vi.fn(), setSelectedStickerSegmentId: vi.fn(),
|
||||
setSelectedStickerId: vi.fn(), setStickerSegments, suppressTimelineClipClickRef: { current: "" },
|
||||
seekTo: vi.fn(), notify: vi.fn(), pauseForTimelineEdit,
|
||||
});
|
||||
controls.startStickerSegmentMove({ button: 0, clientX: 20, clientY: 10, preventDefault: vi.fn(), stopPropagation: vi.fn() }, "sticker-1");
|
||||
expect(pauseForTimelineEdit).toHaveBeenCalledTimes(1);
|
||||
listeners.get("pointermove")({ clientX: 22, clientY: 11, preventDefault: vi.fn() });
|
||||
expect(pauseForTimelineEdit).toHaveBeenCalledTimes(1);
|
||||
listeners.get("pointermove")({ clientX: 30, clientY: 10, preventDefault: vi.fn() });
|
||||
listeners.get("pointermove")({ clientX: 35, clientY: 10, preventDefault: vi.fn() });
|
||||
expect(pauseForTimelineEdit).toHaveBeenCalledTimes(1);
|
||||
expect(setStickerSegments).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("pauses immediately when a caption clip is pressed", () => {
|
||||
const listeners = installPointerListeners();
|
||||
vi.stubGlobal("document", {
|
||||
querySelector: vi.fn(() => ({
|
||||
getBoundingClientRect: () => ({ width: 200, top: 0, bottom: 46 }),
|
||||
querySelectorAll: () => [],
|
||||
})),
|
||||
});
|
||||
const pauseForTimelineEdit = vi.fn();
|
||||
const timelineClipDragRef = { current: null };
|
||||
const controls = createTimelineReorderControls({
|
||||
captionSegments: [{ id: "caption-1", text: "test", start: 1, end: 2 }],
|
||||
captionTargetDuration: 5,
|
||||
trackLocks: { caption: false },
|
||||
timelineDuration: 10,
|
||||
timelineClipDragRef,
|
||||
setTimelineClipDrag: vi.fn(), setSelectedTrack: vi.fn(), setSelectedSegmentId: vi.fn(),
|
||||
commitCaptionSegments: vi.fn(), seekTo: vi.fn(), suppressTimelineClipClickRef: { current: "" },
|
||||
pauseForTimelineEdit, notify: vi.fn(),
|
||||
});
|
||||
controls.startTimelineClipDrag({ button: 0, clientX: 40, clientY: 10, target: { closest: () => null }, preventDefault: vi.fn(), stopPropagation: vi.fn() }, "caption", "caption-1", 0);
|
||||
listeners.get("pointermove")({ clientX: 42, clientY: 10 });
|
||||
expect(pauseForTimelineEdit).toHaveBeenCalledTimes(1);
|
||||
listeners.get("pointermove")({ clientX: 50, clientY: 10 });
|
||||
listeners.get("pointermove")({ clientX: 60, clientY: 10 });
|
||||
expect(pauseForTimelineEdit).toHaveBeenCalledTimes(1);
|
||||
expect(timelineClipDragRef.current.dragging).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,7 @@ export function createTimelineReorderControls(d) {
|
||||
};
|
||||
const startTimelineClipDrag = (event, track, segmentId, index) => {
|
||||
if (event.button !== 0 || event.target.closest(".image-resize-handle")) return;
|
||||
d.pauseForTimelineEdit?.();
|
||||
if (d.trackLocks[track]) return void d.notify(track === "image" ? "图片轨已锁定,无法拖动片段" : "字幕轨已锁定,无法拖动片段");
|
||||
if (track === "image") { d.setSelectedTrack("image"); d.setSelectedVisualSegmentId(segmentId); }
|
||||
else { d.setSelectedTrack("caption"); d.setSelectedSegmentId(segmentId); }
|
||||
|
||||
Reference in new issue
Block a user