Merge pull request #34 from MartinDelophy/codex/mobile-responsive-editor
Release Timeline Studio v0.6.0
This commit is contained in:
commit
d5391bffbf
57 files changed
+2790
-197
No files matched your search
@@ -1,5 +1,57 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("linked 2x source audio exports at half duration without doubling pitch", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async () => {
|
||||
const { exportOfflineVideo, } = await import("/src/lib/offlineVideoExport.js");
|
||||
const { exportBrowserVideo } = await import("/src/lib/media.js");
|
||||
const canvas = document.createElement("canvas"); canvas.width = 160; canvas.height = 90;
|
||||
const context = canvas.getContext("2d"); context.fillStyle = "#18253d"; context.fillRect(0, 0, 160, 90);
|
||||
const image = canvas.toDataURL("image/png");
|
||||
const sampleRate = 48_000; const frames = sampleRate * 2;
|
||||
const wav = new ArrayBuffer(44 + frames * 2); const view = new DataView(wav);
|
||||
const write = (offset, value) => [...value].forEach((char, index) => view.setUint8(offset + index, char.charCodeAt(0)));
|
||||
write(0, "RIFF"); view.setUint32(4, 36 + frames * 2, true); write(8, "WAVEfmt ");
|
||||
view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
|
||||
view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true);
|
||||
view.setUint16(32, 2, true); view.setUint16(34, 16, true); write(36, "data"); view.setUint32(40, frames * 2, true);
|
||||
for (let index = 0; index < frames; index += 1) view.setInt16(44 + index * 2, Math.sin(index / sampleRate * Math.PI * 2 * 440) * 12000, true);
|
||||
const sourceAudio = new Blob([wav], { type: "audio/wav" });
|
||||
const options = {
|
||||
imageSrc: image, visualType: "image", visualSegments: [{ id: "image", src: image, type: "image", duration: 1 }],
|
||||
voiceAudioSegments: [], sourceAudioBlob: sourceAudio,
|
||||
sourceAudioSegments: [{ id: "linked", start: 0, duration: 1, sourceStart: 0, sourceDuration: 2, playbackRate: 2 }],
|
||||
sourceAudioVolume: 1, musicBlob: null, text: "", captionSegments: [], duration: 1,
|
||||
ratio: { width: 16, height: 9 }, fitMode: "cover", filter: "none", captionsEnabled: false,
|
||||
captionSize: 12, captionStyle: {}, captionReferenceSize: { width: 160, height: 90 }, stickerSegments: [],
|
||||
exportSettings: { codec: "vp9", width: 160, height: 90, frameRate: 24, videoBitsPerSecond: 800_000 },
|
||||
};
|
||||
const [offline, compatibility] = await Promise.all([
|
||||
exportOfflineVideo(options),
|
||||
exportBrowserVideo(options),
|
||||
]);
|
||||
const audioContext = new AudioContext();
|
||||
const inspect = async (blob) => {
|
||||
const decoded = await audioContext.decodeAudioData((await blob.arrayBuffer()).slice(0));
|
||||
const samples = decoded.getChannelData(0); const start = Math.floor(samples.length * 0.2); const end = Math.floor(samples.length * 0.8);
|
||||
let crossings = 0;
|
||||
for (let index = start + 1; index < end; index += 1) if (samples[index - 1] <= 0 && samples[index] > 0) crossings += 1;
|
||||
return { duration: decoded.duration, frequency: crossings / ((end - start) / decoded.sampleRate), samples: decoded.length };
|
||||
};
|
||||
const inspected = { offline: await inspect(offline.blob), compatibility: await inspect(compatibility.blob) };
|
||||
await audioContext.close();
|
||||
return inspected;
|
||||
});
|
||||
for (const exported of [result.offline, result.compatibility]) {
|
||||
expect(exported.duration).toBeGreaterThan(0.9);
|
||||
expect(exported.duration).toBeLessThan(1.1);
|
||||
expect(exported.frequency).toBeGreaterThan(420);
|
||||
expect(exported.frequency).toBeLessThan(460);
|
||||
expect(exported.samples).toBeGreaterThan(40_000);
|
||||
}
|
||||
});
|
||||
|
||||
test("offline export restores enabled embedded video audio when no separated source track exists", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.goto("/");
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const ONE_PIXEL_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
|
||||
function createSilentWav(durationSeconds = 2) {
|
||||
const sampleRate = 8_000;
|
||||
const sampleCount = Math.round(sampleRate * durationSeconds);
|
||||
const buffer = Buffer.alloc(44 + sampleCount * 2);
|
||||
buffer.write("RIFF", 0);
|
||||
buffer.writeUInt32LE(buffer.length - 8, 4);
|
||||
buffer.write("WAVEfmt ", 8);
|
||||
buffer.writeUInt32LE(16, 16);
|
||||
buffer.writeUInt16LE(1, 20);
|
||||
buffer.writeUInt16LE(1, 22);
|
||||
buffer.writeUInt32LE(sampleRate, 24);
|
||||
buffer.writeUInt32LE(sampleRate * 2, 28);
|
||||
buffer.writeUInt16LE(2, 32);
|
||||
buffer.writeUInt16LE(16, 34);
|
||||
buffer.write("data", 36);
|
||||
buffer.writeUInt32LE(sampleCount * 2, 40);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
test("mobile Music action opens direct clip properties and exposes real speed control", async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem("ai-voiceover-ui-language", "zh");
|
||||
});
|
||||
await page.goto("/");
|
||||
|
||||
const input = page.locator('input[type="file"][multiple]');
|
||||
await input.setInputFiles({ name: "visual.png", mimeType: "image/png", buffer: ONE_PIXEL_PNG });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator(".image-clip")).toBeVisible();
|
||||
|
||||
await page.getByText("媒体", { exact: true }).last().click();
|
||||
await input.setInputFiles({ name: "music-speed.wav", mimeType: "audio/wav", buffer: createSilentWav(2) });
|
||||
await page.getByRole("button", { name: "添加到音乐轨" }).click();
|
||||
|
||||
const musicClip = page.locator(".audio-clip.is-music").first();
|
||||
await expect(musicClip).toBeVisible();
|
||||
await musicClip.click();
|
||||
const clipActions = page.locator(".timeline-mobile-clip-actions");
|
||||
await expect(clipActions).toBeVisible();
|
||||
await clipActions.getByRole("button", { name: "音频" }).click();
|
||||
|
||||
const propertySheet = page.locator(".voice-panel.is-audio-clip-context");
|
||||
await expect(propertySheet).toBeVisible();
|
||||
await expect(page.locator(".mobile-sheet-nav strong")).toHaveText("音频片段属性");
|
||||
await expect(page.locator(".mobile-sheet-nav [role='tab']")).toHaveCount(0);
|
||||
await expect(propertySheet.getByText("播放速度", { exact: true })).toBeVisible();
|
||||
await expect(page.locator(".timeline-mobile-clip-actions")).toBeVisible();
|
||||
await expect(page.locator(".media-panel")).toBeHidden();
|
||||
|
||||
const durationBefore = await musicClip.locator(".audio-clip-duration").getAttribute("data-compact-duration");
|
||||
await propertySheet.getByRole("button", { name: "2×", exact: true }).click();
|
||||
await expect(propertySheet.locator(".audio-property-slider em").filter({ hasText: "2×" })).toBeVisible();
|
||||
await expect(musicClip.locator(".audio-clip-duration")).toHaveAttribute("data-compact-duration", "1.0s");
|
||||
expect(durationBefore).not.toBe("1.0s");
|
||||
await expect(page.locator(".timeline-mobile-clip-actions")).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("mobile-music-direct-properties-2x.png") });
|
||||
|
||||
await page.locator(".mobile-sheet-close").click();
|
||||
await expect(propertySheet).toBeHidden();
|
||||
await expect(page.locator(".timeline-mobile-clip-actions")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("mobile large-canvas close does not click through to the topbar", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
|
||||
await page.getByRole("button", { name: "大画布预览与编辑" }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "大画布编辑" });
|
||||
await expect(dialog).toBeVisible();
|
||||
|
||||
const closeButton = dialog.locator(".focus-preview-close");
|
||||
const closeBox = await closeButton.boundingBox();
|
||||
if (!closeBox) throw new Error("Large-canvas close button is unavailable");
|
||||
|
||||
const client = await page.context().newCDPSession(page);
|
||||
await client.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
|
||||
const touchPoint = {
|
||||
id: 1,
|
||||
x: closeBox.x + closeBox.width / 2,
|
||||
y: closeBox.y + closeBox.height / 2,
|
||||
radiusX: 6,
|
||||
radiusY: 6,
|
||||
force: 1,
|
||||
};
|
||||
await client.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [touchPoint] });
|
||||
await expect(dialog).toBeVisible();
|
||||
await client.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
|
||||
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(page.locator(".settings-panel")).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("mobile linked source audio follows video speed and can be separated again after deletion", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const videoPath = testInfo.outputPath("mobile-video-with-audio.webm");
|
||||
execFileSync("ffmpeg", [
|
||||
"-hide_banner", "-loglevel", "error", "-y",
|
||||
"-f", "lavfi", "-i", "color=c=#244b68:s=320x180:d=1.2",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1.2",
|
||||
"-c:v", "libvpx-vp9", "-b:v", "300k", "-pix_fmt", "yuv420p", "-c:a", "libopus", "-shortest",
|
||||
videoPath,
|
||||
]);
|
||||
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem("ai-voiceover-ui-language", "zh");
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.locator('input[type="file"][multiple]').setInputFiles(videoPath);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
const visualClip = page.locator(".image-clip").first();
|
||||
await expect(visualClip).toBeVisible();
|
||||
await expect(visualClip.locator(".image-clip-duration")).toHaveText("00:01");
|
||||
await visualClip.click();
|
||||
|
||||
const actionBar = page.locator(".timeline-mobile-clip-actions");
|
||||
const separateAudio = actionBar.getByText("分离音频", { exact: true });
|
||||
await expect(actionBar).toBeVisible();
|
||||
await expect(separateAudio).toBeVisible();
|
||||
await separateAudio.click();
|
||||
|
||||
await expect(page.locator(".source-track")).toBeVisible({ timeout: 120_000 });
|
||||
await expect(page.locator(".audio-clip.is-source").first()).toBeVisible({ timeout: 120_000 });
|
||||
await expect(actionBar.getByText("分离音频", { exact: true })).toHaveCount(0);
|
||||
await expect(visualClip).toBeVisible();
|
||||
|
||||
await visualClip.click();
|
||||
await actionBar.getByText("编辑", { exact: true }).click();
|
||||
await page.getByRole("tab", { name: "变速", exact: true }).click();
|
||||
await page.locator(".visual-speed-presets").getByText("2×", { exact: true }).click();
|
||||
await expect(page.locator(".visual-speed-summary")).toContainText("0.60s");
|
||||
await expect(page.locator(".visual-speed-hint")).toHaveText("画面原声已同步");
|
||||
await expect(page.locator(".audio-clip.is-source .audio-clip-duration")).toHaveText("00:00.60");
|
||||
|
||||
await page.locator(".mobile-sheet-close").click();
|
||||
const sourceClip = page.locator(".audio-clip.is-source");
|
||||
await sourceClip.click();
|
||||
await actionBar.locator("button.is-danger").click();
|
||||
await expect(sourceClip).toHaveCount(0);
|
||||
await expect(page.locator(".source-track")).toHaveCount(0);
|
||||
|
||||
await visualClip.click();
|
||||
await expect(actionBar.getByText("分离音频", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("mobile sticker clip exposes direct properties, copy, and delete actions", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem("ai-voiceover-ui-language", "zh");
|
||||
});
|
||||
await page.goto("/");
|
||||
|
||||
await page.locator(".tool-rail").getByRole("button", { name: "贴纸" }).click();
|
||||
await page.getByRole("button", { name: "热度火焰" }).click();
|
||||
await page.getByRole("button", { name: "添加贴纸" }).click();
|
||||
|
||||
const stickerClip = page.locator(".sticker-segment");
|
||||
await expect(stickerClip).toBeVisible();
|
||||
await stickerClip.click();
|
||||
|
||||
const actions = page.locator(".timeline-mobile-clip-actions");
|
||||
await expect(actions).toBeVisible();
|
||||
await expect(actions.getByRole("button")).toHaveCount(4);
|
||||
await expect(actions.getByRole("button", { name: "返回" })).toBeVisible();
|
||||
await expect(actions.getByRole("button", { name: "属性" })).toBeVisible();
|
||||
await expect(actions.getByRole("button", { name: "复制" })).toBeVisible();
|
||||
await expect(actions.getByRole("button", { name: "删除" })).toBeVisible();
|
||||
await expect(actions.getByRole("button", { name: "分割" })).toHaveCount(0);
|
||||
|
||||
await actions.getByRole("button", { name: "属性" }).click();
|
||||
const properties = page.locator(".voice-panel.is-sticker-context");
|
||||
await expect(properties).toBeVisible();
|
||||
await expect(page.locator(".mobile-sheet-nav strong")).toHaveText("贴纸属性");
|
||||
await expect(page.locator(".mobile-sheet-nav [role='tab']")).toHaveCount(0);
|
||||
await expect(properties.getByText("不透明度", { exact: true })).toBeVisible();
|
||||
await expect(actions).toBeVisible();
|
||||
|
||||
await page.locator(".mobile-sheet-close").click();
|
||||
await expect(properties).toBeHidden();
|
||||
await expect(actions).toBeVisible();
|
||||
|
||||
await actions.getByRole("button", { name: "删除" }).click();
|
||||
await expect(stickerClip).toHaveCount(0);
|
||||
await expect(page.locator(".sticker-track")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("desktop sticker selection keeps the mobile action bar hidden", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
await expect(page.locator(".timeline-mobile-clip-actions")).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const ONE_PIXEL_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
|
||||
function createSilentWav(durationSeconds = 1) {
|
||||
const sampleRate = 8_000;
|
||||
const sampleCount = Math.round(sampleRate * durationSeconds);
|
||||
const buffer = Buffer.alloc(44 + sampleCount * 2);
|
||||
buffer.write("RIFF", 0);
|
||||
buffer.writeUInt32LE(buffer.length - 8, 4);
|
||||
buffer.write("WAVEfmt ", 8);
|
||||
buffer.writeUInt32LE(16, 16);
|
||||
buffer.writeUInt16LE(1, 20);
|
||||
buffer.writeUInt16LE(1, 22);
|
||||
buffer.writeUInt32LE(sampleRate, 24);
|
||||
buffer.writeUInt32LE(sampleRate * 2, 28);
|
||||
buffer.writeUInt16LE(2, 32);
|
||||
buffer.writeUInt16LE(16, 34);
|
||||
buffer.write("data", 36);
|
||||
buffer.writeUInt32LE(sampleCount * 2, 40);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
async function readTimelineState(page) {
|
||||
return page.evaluate(() => {
|
||||
const labels = Array.from(document.querySelectorAll(".ruler-tick.is-major"))
|
||||
.map((tick) => tick.textContent?.trim() || "")
|
||||
.filter(Boolean)
|
||||
.map((label) => {
|
||||
const [minutes, seconds] = label.split(":");
|
||||
return Number(minutes) * 60 + Number(seconds);
|
||||
})
|
||||
.filter(Number.isFinite)
|
||||
.sort((a, b) => a - b);
|
||||
const steps = labels.slice(1).map((value, index) => value - labels[index]).filter((value) => value > 0);
|
||||
return {
|
||||
currentTime: Number(document.querySelector(".scrubber")?.value || 0),
|
||||
labelStep: steps.length ? Math.min(...steps) : null,
|
||||
trackWidth: document.querySelector(".track-scroll")?.getBoundingClientRect().width || 0,
|
||||
scrollLeft: document.querySelector(".tracks")?.scrollLeft || 0,
|
||||
geometryTime: (() => {
|
||||
const track = document.querySelector(".track-scroll")?.getBoundingClientRect();
|
||||
const viewport = document.querySelector(".tracks")?.getBoundingClientRect();
|
||||
const duration = Number(document.querySelector(".scrubber")?.max || 0);
|
||||
if (!track || !viewport || !duration) return 0;
|
||||
return Math.max(0, Math.min(duration, ((viewport.left + viewport.width / 2 - track.left) / track.width) * duration));
|
||||
})(),
|
||||
zoomText: document.querySelector("[data-testid='timeline-zoom-readout']")?.textContent || "",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
test("mobile pinch zoom keeps the visible frame and ruler scale stable on release", async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
await page.locator('input[type="file"][multiple]').setInputFiles({
|
||||
name: "pinch-fixture.png",
|
||||
mimeType: "image/png",
|
||||
buffer: ONE_PIXEL_PNG,
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator(".image-clip")).toBeVisible();
|
||||
|
||||
const tracks = page.locator(".tracks");
|
||||
await tracks.evaluate((element) => {
|
||||
element.scrollLeft = Math.min(120, element.scrollWidth - element.clientWidth);
|
||||
element.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
});
|
||||
await page.waitForTimeout(80);
|
||||
|
||||
const box = await tracks.boundingBox();
|
||||
if (!box) throw new Error("Timeline tracks are not visible");
|
||||
const centerX = box.x + box.width / 2;
|
||||
const centerY = box.y + Math.min(60, box.height / 2);
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 2 });
|
||||
const touchPoint = (id, x) => ({ id, x, y: centerY, radiusX: 6, radiusY: 6, force: 1 });
|
||||
|
||||
const before = await readTimelineState(page);
|
||||
await page.screenshot({ path: testInfo.outputPath("01-before-pinch.png") });
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
type: "touchStart",
|
||||
touchPoints: [touchPoint(1, centerX - 45), touchPoint(2, centerX + 45)],
|
||||
});
|
||||
const frameStates = [];
|
||||
for (let distance = 55; distance <= 105; distance += 10) {
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
type: "touchMove",
|
||||
touchPoints: [touchPoint(1, centerX - distance), touchPoint(2, centerX + distance)],
|
||||
});
|
||||
await page.waitForTimeout(20);
|
||||
frameStates.push({ distance: distance * 2, state: await readTimelineState(page) });
|
||||
}
|
||||
const visibleBeforeRelease = await readTimelineState(page);
|
||||
await page.screenshot({ path: testInfo.outputPath("02-visible-before-release.png") });
|
||||
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
|
||||
await page.waitForTimeout(100);
|
||||
const afterRelease = await readTimelineState(page);
|
||||
await page.screenshot({ path: testInfo.outputPath("03-after-release.png") });
|
||||
|
||||
expect(visibleBeforeRelease.trackWidth).toBeGreaterThan(before.trackWidth);
|
||||
expect(visibleBeforeRelease.trackWidth / before.trackWidth).toBeCloseTo(210 / 90, 1);
|
||||
for (const frame of frameStates) {
|
||||
expect(frame.state.trackWidth / before.trackWidth).toBeCloseTo(frame.distance / 90, 1);
|
||||
expect(frame.state.geometryTime).toBeCloseTo(before.geometryTime, 2);
|
||||
}
|
||||
expect(afterRelease.trackWidth).toBeCloseTo(visibleBeforeRelease.trackWidth, 0);
|
||||
expect(afterRelease.currentTime).toBeCloseTo(visibleBeforeRelease.currentTime, 2);
|
||||
expect(afterRelease.labelStep).toBe(before.labelStep);
|
||||
expect(afterRelease.labelStep).toBe(visibleBeforeRelease.labelStep);
|
||||
expect(afterRelease.zoomText).toBe(visibleBeforeRelease.zoomText);
|
||||
});
|
||||
|
||||
test("desktop timeline keeps its existing draggable playhead behavior", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
await expect(page.locator(".playhead")).toHaveCSS("cursor", "ew-resize");
|
||||
await expect(page.locator(".mobile-fixed-playhead")).toBeHidden();
|
||||
});
|
||||
|
||||
test("mobile trackpad wheel zoom uses pixels and does not jump when committed", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
await page.locator('input[type="file"][multiple]').setInputFiles({
|
||||
name: "wheel-pinch-fixture.png",
|
||||
mimeType: "image/png",
|
||||
buffer: ONE_PIXEL_PNG,
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
const clip = page.locator(".image-clip");
|
||||
await expect(clip).toBeVisible();
|
||||
const box = await clip.boundingBox();
|
||||
if (!box) throw new Error("Timeline clip is unavailable");
|
||||
const before = await readTimelineState(page);
|
||||
const deltaY = -40;
|
||||
await clip.dispatchEvent("wheel", {
|
||||
deltaY,
|
||||
deltaX: 0,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
clientX: box.x + box.width / 2,
|
||||
clientY: box.y + box.height / 2,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await page.waitForTimeout(32);
|
||||
const during = await readTimelineState(page);
|
||||
await page.waitForTimeout(260);
|
||||
const committed = await readTimelineState(page);
|
||||
|
||||
expect(during.trackWidth / before.trackWidth).toBeCloseTo(Math.exp(40 * 0.00056), 2);
|
||||
expect(committed.trackWidth).toBeCloseTo(during.trackWidth, 0);
|
||||
expect(committed.geometryTime).toBeCloseTo(before.geometryTime, 2);
|
||||
expect(committed.currentTime).toBeCloseTo(before.currentTime, 2);
|
||||
});
|
||||
|
||||
test("mobile pinch beginning on a voiceover never moves the timed clip", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
const input = page.locator('input[type="file"][multiple]');
|
||||
await input.setInputFiles({
|
||||
name: "pinch-fixture.png",
|
||||
mimeType: "image/png",
|
||||
buffer: ONE_PIXEL_PNG,
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByText("媒体", { exact: true }).last().click();
|
||||
await input.setInputFiles({
|
||||
name: "voice-pinch.wav",
|
||||
mimeType: "audio/wav",
|
||||
buffer: createSilentWav(),
|
||||
});
|
||||
await page.getByRole("button", { name: "添加到配音轨" }).click();
|
||||
|
||||
const clip = page.locator(".audio-clip:not(.is-source):not(.is-music)").first();
|
||||
await expect(clip).toBeVisible();
|
||||
const tracks = page.locator(".tracks");
|
||||
await page.getByRole("button", { name: "放大" }).click();
|
||||
await page.getByRole("button", { name: "放大" }).click();
|
||||
await page.waitForTimeout(180);
|
||||
await tracks.evaluate((element) => {
|
||||
element.scrollLeft = Math.min(80, element.scrollWidth - element.clientWidth);
|
||||
element.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
});
|
||||
await page.waitForTimeout(80);
|
||||
const clipBox = await clip.boundingBox();
|
||||
const tracksBox = await tracks.boundingBox();
|
||||
if (!clipBox || !tracksBox) throw new Error("Voiceover timeline geometry is unavailable");
|
||||
const startLeft = await clip.evaluate((element) => element.style.left);
|
||||
const startWidth = await clip.evaluate((element) => element.style.width);
|
||||
const startState = await readTimelineState(page);
|
||||
const y = tracksBox.y + Math.min(62, tracksBox.height / 3);
|
||||
const firstX = tracksBox.x + tracksBox.width / 2 - 45;
|
||||
const secondX = Math.min(tracksBox.x + tracksBox.width - 12, firstX + 90);
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 2 });
|
||||
const touchPoint = (id, x) => ({ id, x, y, radiusX: 6, radiusY: 6, force: 1 });
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
type: "touchStart",
|
||||
touchPoints: [touchPoint(1, firstX)],
|
||||
});
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
type: "touchMove",
|
||||
touchPoints: [touchPoint(1, firstX + 8)],
|
||||
});
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
type: "touchStart",
|
||||
touchPoints: [touchPoint(1, firstX + 8), touchPoint(2, secondX)],
|
||||
});
|
||||
const handoffState = await readTimelineState(page);
|
||||
const midpoint = (firstX + secondX) / 2;
|
||||
for (let progress = 0; progress <= 0.65; progress += 0.13) {
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
type: "touchMove",
|
||||
touchPoints: [
|
||||
touchPoint(1, firstX + (midpoint - firstX) * progress),
|
||||
touchPoint(2, secondX + (midpoint - secondX) * progress),
|
||||
],
|
||||
});
|
||||
await page.waitForTimeout(18);
|
||||
}
|
||||
await page.waitForTimeout(32);
|
||||
const visibleBeforeRelease = {
|
||||
timeline: await readTimelineState(page),
|
||||
clip: await clip.boundingBox(),
|
||||
};
|
||||
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
|
||||
await page.waitForTimeout(100);
|
||||
const afterRelease = {
|
||||
timeline: await readTimelineState(page),
|
||||
clip: await clip.boundingBox(),
|
||||
};
|
||||
await page.waitForTimeout(450);
|
||||
const afterMomentumWindow = {
|
||||
timeline: await readTimelineState(page),
|
||||
clip: await clip.boundingBox(),
|
||||
};
|
||||
|
||||
expect(visibleBeforeRelease.timeline.trackWidth).toBeLessThan(startState.trackWidth);
|
||||
expect(afterRelease.timeline.trackWidth).toBeCloseTo(visibleBeforeRelease.timeline.trackWidth, 0);
|
||||
expect(afterRelease.timeline.currentTime).toBeCloseTo(handoffState.currentTime, 2);
|
||||
expect(afterRelease.timeline.currentTime).toBeCloseTo(visibleBeforeRelease.timeline.currentTime, 2);
|
||||
expect(afterRelease.clip?.x).toBeCloseTo(visibleBeforeRelease.clip?.x || 0, 0);
|
||||
expect(afterRelease.clip?.width).toBeCloseTo(visibleBeforeRelease.clip?.width || 0, 0);
|
||||
expect(afterMomentumWindow.timeline.currentTime).toBeCloseTo(afterRelease.timeline.currentTime, 2);
|
||||
expect(afterMomentumWindow.clip?.x).toBeCloseTo(afterRelease.clip?.x || 0, 0);
|
||||
expect(await clip.evaluate((element) => element.style.left)).toBe(startLeft);
|
||||
expect(await clip.evaluate((element) => element.style.width)).toBe(startWidth);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const ONE_PIXEL_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
|
||||
test("mobile Visuals lock blocks destructive clip actions until unlocked", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 412, height: 915 });
|
||||
await page.addInitScript(() => localStorage.setItem("ai-voiceover-ui-language", "zh"));
|
||||
await page.goto("/");
|
||||
await page.locator('input[type="file"][multiple]').setInputFiles({
|
||||
name: "locked-visual.png",
|
||||
mimeType: "image/png",
|
||||
buffer: ONE_PIXEL_PNG,
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
const clip = page.locator(".image-clip");
|
||||
const lock = page.locator('.track-labels > div').first().locator('button[aria-pressed]');
|
||||
await expect(clip).toBeVisible();
|
||||
await expect(lock).toHaveAttribute("aria-pressed", "false");
|
||||
await lock.click();
|
||||
await expect(lock).toHaveAttribute("aria-pressed", "true");
|
||||
|
||||
await clip.click();
|
||||
await page.locator(".timeline-mobile-clip-actions .is-danger").click();
|
||||
await expect(clip).toBeVisible();
|
||||
|
||||
await lock.click();
|
||||
await expect(lock).toHaveAttribute("aria-pressed", "false");
|
||||
await clip.click();
|
||||
await page.locator(".timeline-mobile-clip-actions .is-danger").click();
|
||||
await expect(clip).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("same-asset sticker instances remain independent during cross-subtrack drag", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem("ai-voiceover-ui-language", "zh");
|
||||
});
|
||||
await page.goto("/");
|
||||
|
||||
const project = {
|
||||
format: "timeline-studio-project",
|
||||
project: {
|
||||
script: "",
|
||||
captionSegments: [],
|
||||
selectedStickerId: "trend-spark",
|
||||
stickerSegments: [
|
||||
{ id: "spark-a", stickerId: "trend-spark", name: "闪光爆点", src: "/assets/stickers/trend-spark.png", start: 5, duration: 3, lane: 0 },
|
||||
{ id: "spark-b", stickerId: "trend-spark", name: "闪光爆点", src: "/assets/stickers/trend-spark.png", start: 5, duration: 3, lane: 1 },
|
||||
{ id: "flame", stickerId: "trend-flame", name: "热度火焰", src: "/assets/stickers/trend-flame.png", start: 0, duration: 4, lane: 2 },
|
||||
],
|
||||
},
|
||||
};
|
||||
await page.locator(".project-file-input").setInputFiles({
|
||||
name: "sticker-lanes.timeline",
|
||||
mimeType: "application/json",
|
||||
buffer: Buffer.from(JSON.stringify(project)),
|
||||
});
|
||||
|
||||
await expect(page.locator(".sticker-track")).toHaveCount(3);
|
||||
const moving = page.locator('[data-timeline-segment-id="spark-b"]');
|
||||
const untouched = page.locator('[data-timeline-segment-id="spark-a"]');
|
||||
const thirdLane = page.locator('[data-sticker-lane-index="2"]');
|
||||
await expect(moving).toBeVisible();
|
||||
const movingBox = await moving.boundingBox();
|
||||
const thirdLaneBox = await thirdLane.boundingBox();
|
||||
if (!movingBox || !thirdLaneBox) throw new Error("Sticker subtracks are unavailable");
|
||||
|
||||
await page.mouse.move(movingBox.x + movingBox.width / 2, movingBox.y + movingBox.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(movingBox.x + movingBox.width / 2 + 8, thirdLaneBox.y + thirdLaneBox.height / 2, { steps: 6 });
|
||||
|
||||
await expect(thirdLane.getByTestId("sticker-drop-preview")).toBeVisible();
|
||||
await expect(moving).toHaveClass(/is-timeline-dragging/);
|
||||
await expect(page.locator('[data-sticker-lane-index="1"] [data-timeline-segment-id="spark-b"]')).toHaveCount(1);
|
||||
await page.mouse.up();
|
||||
|
||||
await expect(page.getByTestId("sticker-drop-preview")).toHaveCount(0);
|
||||
await expect(thirdLane.locator('[data-timeline-segment-id="spark-b"]')).toHaveCount(1);
|
||||
await expect(page.locator('[data-timeline-segment-id="spark-b"]')).toHaveCount(1);
|
||||
await expect(page.locator('[data-timeline-segment-id="spark-a"]')).toHaveCount(1);
|
||||
await expect(untouched).toHaveAttribute("data-timeline-segment-id", "spark-a");
|
||||
});
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "web-player",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "web-player",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@diffusionstudio/vits-web": "^1.0.3",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "web-player",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"description": "A local-first browser AI video editor for voiceovers, captions, talking avatars, and multi-track timeline export.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -27,13 +27,23 @@ Run these across empty and pre-populated projects where applicable:
|
||||
5. Verify the first-visual coach guide: persistent completion only through the user's explicit action; temporary dismissal through close or Escape.
|
||||
6. Trim, split, reorder, delete, undo, redo, save, reopen, and compare media identity and source-time mapping. Include a sub-second split where mute controls and handles consume most of the clip width; verify clip-scoped context-menu deletion and immediate recovery from a deliberately detected wrong-target action.
|
||||
7. Add and move captions, stickers, voiceover, music, source audio, and picture-in-picture; verify lane visibility and overlap packing.
|
||||
- On mobile, tapping a sticker must stage it without changing the timeline, reveal one fixed Cancel/Add sticker bar, add exactly one timed sticker only after confirmation, and close without mutation on Cancel. Verify a dense four-column grid at 412×915. Desktop remains a three-column grid with its existing click-to-add behavior and no mobile confirmation bar.
|
||||
- In both desktop and mobile Captions properties, verify the empty state shows exactly one visible Add caption action and one Import SRT action. Add caption creates a localized default caption at the current playhead, selects it, focuses its text editor, and remains available beside the populated caption list without duplicating the empty-state controls.
|
||||
- At both the 48px desktop row height and 40px mobile row height, verify voiceover, source-audio, and music clip bodies are vertically centered with their complete waveform border and selection outline visible above the row divider; the transparent touch target may be larger than the 32px visible body.
|
||||
- Verify every visible source-audio, voiceover, and music clip has waveform bars on desktop and mobile. With decoded peaks, bars reflect those peaks; with deliberately empty peaks during restore/editing, a stable low-emphasis placeholder remains visible instead of a blank clip.
|
||||
8. Verify embedded video audio, mute, Separate audio, derived-piece deletion, link modes, preview playback, and export without doubled or missing sound. Separate audio from a clip trimmed at both ends and assert the project duration, source-audio piece duration, source start, source duration, and waveform range remain mapped to that clip rather than the full original asset.
|
||||
9. Change transforms, masks, keyframes, speed, effects, animations, and aspect ratio; compare preview with deterministic export.
|
||||
- For both a video clip and a voiceover/independent-audio clip, test 0.5×, 1×, 1.5×, and 2× on desktop and mobile. Verify the timeline width and linked caption end update from preserved source duration, seeking resolves the correct source timestamp, splitting advances source offsets by timeline duration multiplied by rate, and decoded export duration/audio match preview. Use a known-frequency or voiced fixture to verify linked-audio speed changes preserve pitch in preview, deterministic export, and compatibility export.
|
||||
10. Export MP4/WebM and decode the entire result to verify dimensions, duration, frame count, visible captions/overlays, and a real non-silent audio track when expected. Extract frames inside every caption range and visually verify the burned-in text. Test both a captured browser download event and the fallback where the event times out but a new artifact exists on disk.
|
||||
11. Compare same-tab autosave, a newly opened same-origin tab, and explicit `.timeline` save/reopen. Verify duration, ordering, assets, track state, selections that should persist, and generated media links; never treat an “Autosaved” label as proof that local blobs will reopen.
|
||||
12. Repeat critical flows in every supported interface language, narrow desktop panels, reduced motion, and at least the supported Chromium path; include Firefox/Windows regressions when available.
|
||||
13. Exercise AI paths with cold and warm caches, unavailable models, download failure, cancellation, WASM/WebGPU fallback, and truthful backend reporting.
|
||||
14. Test handoff-only requests separately from concrete editing requests so the Agent never invents creative changes.
|
||||
13. On mobile, select visual, caption, sticker, source-audio, voiceover, and music clips by ordinary tap and verify that the fixed action bar is track-specific. Voiceover and music must expose Audio, Split, Captions, Vocal Separation, and Delete; source audio must omit unsupported vocal separation; visual clips must not expose audio-only actions. At desktop width, the mobile bar stays hidden and the corresponding right-click context menu remains available.
|
||||
- Sticker clips expose Back, Properties, Copy, and Delete. Properties opens the selected sticker's dedicated property drawer directly while the selected clip and fixed action bar remain visible; closing the drawer preserves both, and Delete removes the clip and hides the empty sticker lane.
|
||||
- Repeat after first selecting a Visuals clip. Press a voiceover clip before the prior selection state settles, then press Edit; the explicit pressed-track target must win and open audio-clip properties rather than Visuals properties.
|
||||
14. Still on mobile, verify that selecting a source-audio, voiceover, or music clip pans the timeline just enough to keep the full time-accurate clip visible when it fits. For all three audio types, the clip action bar's Audio action opens the dedicated audio-clip property sheet directly above the current action bar; the selected clip and its Back/Audio/Split/Captions/Separation/Delete menu remain visible and unchanged throughout opening, editing, and closing, and neither the Audio feature home nor the persistent Media/Captions/Smart/Audio/Stickers rail may replace it. Verify that voiceover and music speed changes update time-accurate clip width, pitch-preserving preview, and export; linked source-audio speed changes its associated video clip. Long localized audio-track labels remain one ellipsized line inside the label column, and desktop behavior remains unchanged.
|
||||
- Verify one-second and sub-second audio clips at mobile zoom: clips rendered at 220px or narrower hide the duration badge entirely so the waveform and clip body remain unobstructed; wider mobile clips may use compact copy without intercepting dragging or selection. Desktop retains the precise full duration label.
|
||||
15. Exercise AI paths with cold and warm caches, unavailable models, download failure, cancellation, WASM/WebGPU fallback, and truthful backend reporting.
|
||||
16. Test handoff-only requests separately from concrete editing requests so the Agent never invents creative changes.
|
||||
|
||||
## Observation record
|
||||
|
||||
|
||||
+85
-21
@@ -47,7 +47,7 @@ import { appendImportedCaptions } from "./lib/subtitles.js";
|
||||
import { createTimelineCutActions } from "./lib/timelineCutActions.js";
|
||||
import { createTimelineSegmentCountActions } from "./lib/timelineSegmentCountActions.js";
|
||||
import { createTimelineDurationActions } from "./lib/timelineDurationActions.js";
|
||||
import { createAudioClipActions } from "./lib/audioClipActions.js";
|
||||
import { createAudioClipActions, updateAudioSegmentPlaybackRate } from "./lib/audioClipActions.js";
|
||||
import { createCaptionEditingActions } from "./lib/captionEditingActions.js";
|
||||
import { createAudioTrackActions } from "./lib/audioTrackActions.js";
|
||||
import { createVisualTimelineActions } from "./lib/visualTimelineActions.js";
|
||||
@@ -57,22 +57,26 @@ import { createEditorCommandActions } from "./lib/editorCommandActions.js";
|
||||
import { createTimelineViewModel } from "./lib/timelineViewModel.js";
|
||||
import { createTranslator, getStoredLanguage, translateOptionName } from "./i18n.js";
|
||||
import { decodeWaveform, downloadBlob } from "./lib/media.js";
|
||||
import { getImageThumbnailCount, getVisualSegmentsTotal } from "./lib/timeline.js";
|
||||
import { getImageThumbnailCount, getVisualSegmentsTotal, normalizeTimedSegmentIds } from "./lib/timeline.js";
|
||||
import { normalizeVisualTransform, removeVisualPropertyKeyframe, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./lib/visualEffects.js";
|
||||
import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments, shouldMuteEmbeddedVideoAudio } from "./lib/sourceAudioSync.js";
|
||||
import { getTimelineInitialContentZoom } from "./lib/timelineScale.js";
|
||||
import { getExportBitrate, getExportDimensions } from "./lib/exportSettings.js";
|
||||
import { createVisualOverlaySegment, getVisualOverlayPreset, updateVisualOverlayTransform } from "./lib/visualOverlayTimeline.js";
|
||||
import { getMobileClipPanelOrigin } from "./lib/mobileClipActions.js";
|
||||
|
||||
export function App() {
|
||||
const [uiLanguage, setUiLanguage] = useState(() => getStoredLanguage());
|
||||
const [mobilePanel, setMobilePanel] = useState("");
|
||||
const [mobilePanelClosing, setMobilePanelClosing] = useState(false);
|
||||
const mobilePanelTimerRef = useRef(null);
|
||||
const [mobilePanelOrigin, setMobilePanelOrigin] = useState("");
|
||||
const [showExportMenu, setShowExportMenu] = useState(false);
|
||||
const [exportSettings, setExportSettings] = useState({ resolution: "1080", frameRate: 30, codec: "h264", quality: "high" });
|
||||
const [captionVoiceFocusRequest, setCaptionVoiceFocusRequest] = useState(0);
|
||||
const [selectedSourceAudioSegmentId, setSelectedSourceAudioSegmentId] = useState("");
|
||||
const [selectedMusicSegmentId, setSelectedMusicSegmentId] = useState("");
|
||||
const [stickerTimelineDrag, setStickerTimelineDrag] = useState(null);
|
||||
const [canvasVisualTarget, setCanvasVisualTarget] = useState("");
|
||||
const [showFirstVisualGuide, setShowFirstVisualGuide] = useState(false);
|
||||
const firstVisualGuideShownRef = useRef(false);
|
||||
@@ -84,6 +88,7 @@ export function App() {
|
||||
mobilePanelTimerRef.current = window.setTimeout(() => {
|
||||
setMobilePanel("");
|
||||
setMobilePanelClosing(false);
|
||||
setMobilePanelOrigin("");
|
||||
mobilePanelTimerRef.current = null;
|
||||
}, 170);
|
||||
return;
|
||||
@@ -215,6 +220,9 @@ export function App() {
|
||||
const sourceAudioTimelineEnd = sourceAudioLinked && linkedSourceAudioSegments.length
|
||||
? getLinkedSourceAudioEnd(linkedSourceAudioSegments)
|
||||
: sourceAudioStart + sourceAudioDuration;
|
||||
const musicTimelineEnd = musicSegments.length
|
||||
? musicSegments.reduce((end, segment) => Math.max(end, segment.start + segment.duration), 0)
|
||||
: musicStart + musicDuration;
|
||||
|
||||
const {
|
||||
activePreviewFilter, audioBlob, audioDuration, audioUrl, canPreview, captionDuration,
|
||||
@@ -346,7 +354,7 @@ export function App() {
|
||||
const {
|
||||
canDropAssetOnTrack, findAssetById, getActiveDraggedAsset, getDraggedAsset,
|
||||
getTimelineDropPercent, handleAssetClick, handleAssetDragEnd, handleAssetDragStart,
|
||||
handleAssetPointerDown, handleStickerClick, handleTrackAssetDragLeave,
|
||||
confirmStickerSelection, handleAssetPointerDown, handleStickerClick, handleTrackAssetDragLeave,
|
||||
handleTrackAssetDragOver, triggerAssetDropPulse,
|
||||
} = createAssetDragControls({
|
||||
addStickerAssetToTimeline: (...args) => addStickerAssetToTimeline(...args), applyAssetToTrack: (...args) => applyAssetToTrack(...args), assetDropPulseTimerRef, builtInAssets, currentTime, draggedAssetId,
|
||||
@@ -420,12 +428,16 @@ export function App() {
|
||||
sourceAudioBlob, sourceAudioName, replaceAudio, replaceSourceAudio, replaceMusic, notify, t,
|
||||
});
|
||||
const selectedSourceAudioPiece = linkedSourceAudioSegments.find((segment) => segment.id === selectedSourceAudioSegmentId) ?? null;
|
||||
const selectedMusicSegment = musicSegments.find((segment) => segment.id === selectedMusicSegmentId) ?? null;
|
||||
useEffect(() => {
|
||||
if (selectedMusicSegmentId && !selectedMusicSegment) setSelectedMusicSegmentId("");
|
||||
}, [selectedMusicSegment, selectedMusicSegmentId]);
|
||||
const selectedAudioToolTarget = selectedTrack === "audio" && selectedAudioSegmentId && selectedAudioSegment
|
||||
? { blob: selectedAudioSegment.blob, name: selectedAudioSegment.name, start: selectedAudioSegment.start, sourceStart: selectedAudioSegment.sourceStart || 0, duration: selectedAudioSegment.duration, segmentId: selectedAudioSegment.id, track: "audio" }
|
||||
? { ...selectedAudioSegment, segmentId: selectedAudioSegment.id, track: "audio", canChangeSpeed: true }
|
||||
: selectedTrack === "music" && musicBlob
|
||||
? { blob: musicBlob, name: musicName || t("musicTrack"), start: musicStart, sourceStart: 0, duration: musicDuration, segmentId: musicSegments[0]?.id || "music-audio", track: "music" }
|
||||
? { ...(selectedMusicSegment ?? musicSegments[0] ?? { id: "music-audio", start: musicStart, duration: musicDuration, sourceStart: 0, sourceDuration: musicDuration, playbackRate: 1 }), blob: musicBlob, name: musicName || t("musicTrack"), segmentId: selectedMusicSegment?.id || musicSegments[0]?.id || "music-audio", track: "music", volume: musicVolume, canChangeSpeed: true }
|
||||
: selectedTrack === "source" && sourceAudioBlob
|
||||
? { blob: sourceAudioBlob, name: sourceAudioName, start: selectedSourceAudioPiece?.start ?? sourceAudioStart, sourceStart: selectedSourceAudioPiece?.sourceStart ?? 0, duration: selectedSourceAudioPiece?.duration ?? sourceAudioDuration, segmentId: selectedSourceAudioSegmentId || "source-audio", track: "source" }
|
||||
? { ...(selectedSourceAudioPiece ?? {}), blob: sourceAudioBlob, name: sourceAudioName, start: selectedSourceAudioPiece?.start ?? sourceAudioStart, sourceStart: selectedSourceAudioPiece?.sourceStart ?? 0, duration: selectedSourceAudioPiece?.duration ?? sourceAudioDuration, sourceDuration: selectedSourceAudioPiece?.sourceDuration ?? sourceAudioDuration, playbackRate: selectedSourceAudioPiece?.playbackRate ?? 1, segmentId: selectedSourceAudioSegmentId || "source-audio", track: "source", volume: sourceAudioVolume, canChangeStart: !sourceAudioLinked, canChangeSpeed: Boolean(sourceAudioLinked && selectedSourceAudioPiece) }
|
||||
: null;
|
||||
const separateSelectedAudioVocals = () => selectedAudioToolTarget?.track === "source"
|
||||
? separateSourceVocals()
|
||||
@@ -465,6 +477,10 @@ export function App() {
|
||||
setStickerSegments, stickerSegments, t, timelineDurationRef, trackLocks,
|
||||
});
|
||||
const selectedStickerSegment = stickerSegments.find((segment) => segment.id === selectedStickerSegmentId) ?? currentStickerSegment;
|
||||
useEffect(() => {
|
||||
const normalized = normalizeTimedSegmentIds(stickerSegments, "sticker");
|
||||
if (normalized !== stickerSegments) setStickerSegments(normalized);
|
||||
}, [setStickerSegments, stickerSegments]);
|
||||
const updateSelectedStickerSegment = (change) => {
|
||||
if (!selectedStickerSegment?.id) return;
|
||||
setStickerSegments((segments) => segments.map((segment) => segment.id === selectedStickerSegment.id ? { ...segment, ...change } : segment));
|
||||
@@ -507,8 +523,42 @@ export function App() {
|
||||
audioSegmentRefs, audioSegments, notify, setAudioSegments, setCaptionSegments,
|
||||
setSelectedAudioSegmentId, setTimelineHorizon, t,
|
||||
});
|
||||
const updateSelectedTrackAudioSegment = (id, patch) => {
|
||||
if (selectedTrack === "audio") return updateAudioSegment(id, patch);
|
||||
if (selectedTrack === "music") {
|
||||
if (Number.isFinite(patch.volume)) setMusicVolume(Math.max(0, Math.min(1, patch.volume)));
|
||||
setMusicSegments((segments) => {
|
||||
const source = segments.length ? segments : [{ id: "music-audio", start: musicStart, duration: musicDuration, sourceStart: 0, sourceDuration: musicDuration, playbackRate: 1, peaks: musicPeaks }];
|
||||
const next = source.map((segment) => {
|
||||
if (segment.id !== id) return segment;
|
||||
return Number.isFinite(patch.playbackRate)
|
||||
? { ...updateAudioSegmentPlaybackRate(segment, patch.playbackRate), ...patch }
|
||||
: { ...segment, ...patch };
|
||||
});
|
||||
const nextStart = Math.min(...next.map((segment) => segment.start));
|
||||
const nextEnd = Math.max(...next.map((segment) => segment.start + segment.duration));
|
||||
setMusicStart(nextStart);
|
||||
setMusicDuration(Math.max(0, nextEnd - nextStart));
|
||||
return next;
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (selectedTrack === "source") {
|
||||
if (Number.isFinite(patch.volume)) setSourceAudioVolume(Math.max(0, Math.min(1, patch.volume)));
|
||||
if (!sourceAudioLinked && Number.isFinite(patch.start)) setSourceAudioStart(Math.max(0, patch.start));
|
||||
if (sourceAudioLinked && id !== "source-audio" && Number.isFinite(patch.playbackRate)) {
|
||||
setVisualSegments((segments) => {
|
||||
const next = segments.map((segment) => segment.id === id ? updateVisualSegmentPlaybackRate(segment, patch.playbackRate) : segment);
|
||||
const nextDuration = getVisualSegmentsTotal(next);
|
||||
setImageDuration(nextDuration);
|
||||
setImageClipCount(getImageThumbnailCount(nextDuration));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const { handleAddSegment, handleRemoveSegment } = createTimelineSegmentCountActions({
|
||||
const { handleAddCaptionSegment, handleAddSegment, handleRemoveSegment } = createTimelineSegmentCountActions({
|
||||
captionSegments, clearImageTrack, commitCaptionSegments, commitStickerSegments,
|
||||
commitVisualSegments, currentStickerSegmentIndex, currentTime,
|
||||
currentVisualSegmentIndex, deleteCaptionSegment, focusedSegmentIndex,
|
||||
@@ -538,7 +588,7 @@ export function App() {
|
||||
selectedSegmentIndex, selectedStickerSegmentId, selectedTrack,
|
||||
selectedVisualSegmentId, selectedVisualSegmentIndex, setAudioSegments,
|
||||
setCaptionSegments, setSelectedAudioSegmentId, setUserAssets, sourceAudioBlob,
|
||||
sourceAudioLinked, sourceAudioName, selectedSourceAudioSegmentId,
|
||||
sourceAudioLinked, sourceAudioName, selectedSourceAudioSegmentId, linkedSourceAudioSegments,
|
||||
setSelectedSourceAudioSegmentId, stickerSegments, t, trackLocks, visualSegments, visualType,
|
||||
visualOverlaySegments, selectedVisualOverlayId, setVisualOverlaySegments, setSelectedVisualOverlayId,
|
||||
});
|
||||
@@ -570,7 +620,7 @@ export function App() {
|
||||
|
||||
const { getTimelineTimeFromClientX, handlePlayToggle, pauseTimelineMedia, seekTo, startTimelineSeek } = createPlaybackControls({
|
||||
audioSegmentRefs, audioSegments, canPreview, currentTimeRef, currentVisualRange,
|
||||
estimatedDuration, isPlaying, musicDuration, musicRef, musicStart, musicUrl, notify,
|
||||
estimatedDuration, isPlaying, musicDuration, musicSegments, musicRef, musicStart, musicUrl, notify,
|
||||
linkedSourceAudioSegments, previewVideoRef, previewVisualType, setCurrentTime, setIsPlaying, sourceAudioDuration,
|
||||
sourceAudioLinked,
|
||||
sourceAudioRef, sourceAudioStart, sourceAudioUrl, timelineDuration,
|
||||
@@ -584,7 +634,7 @@ export function App() {
|
||||
|
||||
useMediaSync({
|
||||
audioRef, audioSegmentRefs, audioSegments, currentTime, currentTimeRef, estimatedDuration,
|
||||
isPlaying, musicDuration, musicRef, musicStart, musicUrl, musicVolume, pauseTimelineMedia, previewVideoRef,
|
||||
isPlaying, musicDuration, musicSegments, musicRef, musicStart, musicUrl, musicVolume, pauseTimelineMedia, previewVideoRef,
|
||||
previewVisualSegment, previewVisualSourceTime, previewVisualSrc, previewVisualType,
|
||||
linkedSourceAudioSegments, setCurrentTime, setIsPlaying, setPreviewVideoMediaTime, sourceAudioDuration,
|
||||
sourceAudioLinked,
|
||||
@@ -593,13 +643,14 @@ export function App() {
|
||||
visualPlaybackStartedAtRef, visualPlaybackStartTimeRef,
|
||||
});
|
||||
|
||||
const { startAudioSegmentMove, startMusicMove, startSourceAudioMove, startStickerSegmentMove } = createTimelineMoveControls({
|
||||
const { startAudioSegmentMove, startMusicMove, startSourceAudioMove, startStickerSegmentMove, startStickerSegmentResize } = createTimelineMoveControls({
|
||||
audioSegments, captionSegments, captionTargetDuration, estimatedDuration, notify, seekTo, setActiveTool,
|
||||
setAudioSegments, setCaptionSegments, setSelectedAudioSegmentId, setSelectedStickerId,
|
||||
setSelectedStickerSegmentId, setSelectedTrack, setStickerSegments, setTimelineHorizon,
|
||||
setMusicStart, setSourceAudioLinked, setSourceAudioStart, musicDuration, musicSegments, musicStart, setMusicSegments,
|
||||
sourceAudioDuration, sourceAudioStart, stickerSegments, suppressTimelineClipClickRef, t, timelineDurationRef,
|
||||
trackLocks, trackScrollRef, pauseForTimelineEdit, visualSegments, setSnapGuide,
|
||||
trackLocks, trackScrollRef, pauseForTimelineEdit, visualSegments, setSnapGuide, commitStickerSegments,
|
||||
setStickerTimelineDrag,
|
||||
});
|
||||
|
||||
const startImageResize = createImageResizeControl({
|
||||
@@ -705,7 +756,7 @@ export function App() {
|
||||
const handleExportVideo = useVideoExport({
|
||||
audioSegments, captionDuration, captionPlacement, captionPosition, captionSegments,
|
||||
captionSize, captionStyle, captionsEnabled, exporting, exportStartRef, fitMode,
|
||||
imageDuration, imageSrc, musicBlob, musicDuration, musicStart, musicVolume, notify,
|
||||
imageDuration, imageSrc, musicBlob, musicDuration, musicSegments, musicStart, musicTimelineEnd, musicVolume, notify,
|
||||
previewFrameSize, ratio, renderedVisualSegments, script, selectedFilter,
|
||||
selectedSticker, selectedTransitionId, setExporting, setExportPhase,
|
||||
setExportProgress, setStatus, setStatusText, sourceAudioBlob, sourceAudioDuration,
|
||||
@@ -795,7 +846,7 @@ export function App() {
|
||||
clearVisionAnalysis, compactRail, currentSegmentIndex, deleteCaptionSegment,
|
||||
deleteUserAsset, downloadBlob, downloadVisionCutout, draggedAssetId,
|
||||
estimatedDuration, fileInputRef, generateCaptionsFromSourceAudio, handleAssetClick,
|
||||
handleAssetPointerDown, handleCaptionPositionChange, handleFiles, handleStickerClick,
|
||||
handleAssetPointerDown, handleCaptionPositionChange, handleFiles, handleStickerClick, confirmStickerSelection,
|
||||
imageSrc, isDragging, mediaTab, musicBlob, musicDuration, musicName, musicVolume,
|
||||
libraryType, libraryQuery, setLibraryQuery, selectLibraryType, libraryStatus, libraryError, libraryProvider,
|
||||
assetDownloadStates, prefetchLibraryAsset,
|
||||
@@ -973,6 +1024,7 @@ export function App() {
|
||||
toggleCaptionSegmentHidden={toggleCaptionSegmentHidden}
|
||||
deleteCaptionSegment={deleteCaptionSegment}
|
||||
importCaptionSegments={importCaptionSegments}
|
||||
addCaptionSegment={handleAddCaptionSegment}
|
||||
seekTo={seekTo}
|
||||
sourceAudioBlob={sourceAudioBlob}
|
||||
sourceAudioLinked={sourceAudioLinked}
|
||||
@@ -999,6 +1051,10 @@ export function App() {
|
||||
generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame}
|
||||
selectedTrack={selectedTrack}
|
||||
selectedAudioSegment={selectedAudioSegment}
|
||||
selectedTrackAudioSegment={selectedAudioToolTarget}
|
||||
audioClipInspectorOpen={mobilePanel === "inspector" && mobilePanelOrigin === "audio-clip"}
|
||||
updateSelectedTrackAudioSegment={updateSelectedTrackAudioSegment}
|
||||
deleteSelectedTrackAudioSegment={() => handleDeleteTrack()}
|
||||
updateAudioSegment={updateAudioSegment}
|
||||
toggleAudioSegmentReverse={toggleAudioSegmentReverse}
|
||||
deleteAudioSegment={deleteAudioSegment}
|
||||
@@ -1026,6 +1082,7 @@ export function App() {
|
||||
<Timeline
|
||||
t={t}
|
||||
trOption={trOption}
|
||||
notify={notify}
|
||||
undo={undo}
|
||||
redo={redo}
|
||||
handleDeleteTrack={handleDeleteTrack}
|
||||
@@ -1044,11 +1101,12 @@ export function App() {
|
||||
selectedTrack={selectedTrack}
|
||||
setSelectedTrack={setSelectedTrack}
|
||||
setActiveTool={setActiveTool}
|
||||
openMobileMediaPicker={() => {
|
||||
setActiveTool("media");
|
||||
setMediaTab("upload");
|
||||
changeMobilePanel("tools");
|
||||
openMobileInspector={(track) => {
|
||||
setMobilePanelOrigin(getMobileClipPanelOrigin(track));
|
||||
changeMobilePanel("inspector");
|
||||
}}
|
||||
openMobileTools={() => changeMobilePanel("tools")}
|
||||
openMobileFilePicker={() => fileInputRef.current?.click()}
|
||||
requestCaptionVoiceFocus={() => setCaptionVoiceFocusRequest((request) => request + 1)}
|
||||
trackVisibility={trackVisibility}
|
||||
toggleTrackVisibility={toggleTrackVisibility}
|
||||
@@ -1075,6 +1133,7 @@ export function App() {
|
||||
currentStickerSegment={currentStickerSegment}
|
||||
selectedStickerSegmentId={selectedStickerSegmentId}
|
||||
setSelectedStickerSegmentId={setSelectedStickerSegmentId}
|
||||
stickerTimelineDrag={stickerTimelineDrag}
|
||||
imageSrc={imageSrc}
|
||||
displayedVisualSegments={displayedVisualSegments}
|
||||
setVisualSegments={setVisualSegments}
|
||||
@@ -1100,6 +1159,7 @@ export function App() {
|
||||
startCaptionResize={startCaptionResize}
|
||||
startImageResize={startImageResize}
|
||||
startStickerSegmentMove={startStickerSegmentMove}
|
||||
startStickerSegmentResize={startStickerSegmentResize}
|
||||
displayedCaptionSegments={displayedCaptionSegments}
|
||||
displayedCaptionTimeline={displayedCaptionTimeline}
|
||||
currentCaptionSegment={currentCaptionSegment}
|
||||
@@ -1127,6 +1187,8 @@ export function App() {
|
||||
startSourceAudioMove={startSourceAudioMove}
|
||||
musicBlob={musicBlob}
|
||||
musicSegments={musicSegments}
|
||||
selectedMusicSegmentId={selectedMusicSegmentId}
|
||||
setSelectedMusicSegmentId={setSelectedMusicSegmentId}
|
||||
musicPeaks={musicPeaks}
|
||||
musicStartPercent={musicStartPercent}
|
||||
musicDuration={musicDuration}
|
||||
@@ -1135,10 +1197,12 @@ export function App() {
|
||||
|
||||
{mobilePanel ? (
|
||||
<header className="mobile-sheet-nav">
|
||||
<strong>{t(activeTool)}</strong>
|
||||
<strong>{mobilePanelOrigin === "audio-clip" ? t("audioClipProperties") : mobilePanelOrigin === "sticker-clip" ? t("stickerProperties") : t(activeTool)}</strong>
|
||||
<div role="tablist" aria-label={t("mobilePanelView")}>
|
||||
<button className={mobilePanel === "tools" ? "is-active" : ""} type="button" role="tab" aria-selected={mobilePanel === "tools"} onClick={() => changeMobilePanel("tools")}>{t("mobileDrawerTools")}</button>
|
||||
<button className={mobilePanel === "inspector" ? "is-active" : ""} type="button" role="tab" aria-selected={mobilePanel === "inspector"} onClick={() => changeMobilePanel("inspector")}>{t("properties")}</button>
|
||||
{!(["audio-clip", "sticker-clip"].includes(mobilePanelOrigin)) ? <>
|
||||
<button className={mobilePanel === "tools" ? "is-active" : ""} type="button" role="tab" aria-selected={mobilePanel === "tools"} onClick={() => changeMobilePanel("tools")}>{t("mobileDrawerTools")}</button>
|
||||
<button className={mobilePanel === "inspector" ? "is-active" : ""} type="button" role="tab" aria-selected={mobilePanel === "inspector"} onClick={() => changeMobilePanel("inspector")}>{t("properties")}</button>
|
||||
</> : null}
|
||||
<button className="mobile-sheet-close" type="button" aria-label={t("close", "关闭")} onClick={() => changeMobilePanel("")}>×</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -23,7 +23,7 @@ export function EditorSidebar({ model: d }) {
|
||||
))}
|
||||
</aside>
|
||||
|
||||
<aside className={`media-panel ${d.mobilePanel === "tools" && d.selectedLibraryAssetId ? "has-mobile-asset-actions" : ""}`}>
|
||||
<aside className={`media-panel ${d.mobilePanel === "tools" && d.selectedLibraryAssetId ? "has-mobile-asset-actions" : ""} ${d.mobilePanel === "tools" && d.activeTool === "stickers" && d.selectedStickerId && d.selectedStickerId !== "none" ? "has-mobile-sticker-actions" : ""}`}>
|
||||
{d.activeTool === "media" ? (
|
||||
<MediaPanel
|
||||
t={d.t}
|
||||
@@ -90,6 +90,9 @@ export function EditorSidebar({ model: d }) {
|
||||
setSelectedStickerId={d.setSelectedStickerId}
|
||||
handleStickerPointerDown={d.handleAssetPointerDown}
|
||||
handleStickerClick={d.handleStickerClick}
|
||||
confirmStickerSelection={d.confirmStickerSelection}
|
||||
closeMobilePanel={() => d.setMobilePanel?.("")}
|
||||
mobilePanelOpen={d.mobilePanel === "tools"}
|
||||
audioBlob={d.audioBlob}
|
||||
audioDuration={d.audioDuration}
|
||||
sourceAudioBlob={d.sourceAudioBlob}
|
||||
|
||||
@@ -383,11 +383,13 @@ export function PreviewStage({
|
||||
aria-label={t("closeFocusPreview", "关闭大画布预览")}
|
||||
title={t("closeFocusPreview", "关闭大画布预览")}
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setIsFocusPreviewOpen(false);
|
||||
}}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<X size={22} />
|
||||
</button>
|
||||
|
||||
+561
-56
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import {
|
||||
ArrowClockwise,
|
||||
ArrowCounterClockwise,
|
||||
ArrowLeft,
|
||||
ArrowsInLineHorizontal,
|
||||
ArrowsOutLineHorizontal,
|
||||
CopySimple,
|
||||
@@ -32,14 +34,18 @@ import {
|
||||
} from "@phosphor-icons/react";
|
||||
|
||||
import { IMAGE_SEGMENT_SECONDS, MAX_IMAGE_THUMBNAILS, TRANSITIONS } from "../config/editor.js";
|
||||
import { formatClock, formatTime, getSegmentStartTime, getVisualSegmentStartTime, packCaptionSegmentsIntoLanes, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
|
||||
import { formatClock, formatCompactDuration, formatTime, getSegmentStartTime, getVisualSegmentStartTime, packCaptionSegmentsIntoLanes, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
|
||||
import { sliceSourceAudioPeaks } from "../lib/sourceAudioSync.js";
|
||||
import { createMainVisualFromOverlay } from "../lib/visualOverlayTimeline.js";
|
||||
import { getMobileClipActionIds, getMobileClipPanel, resolveMobileClipActionTrack, shouldActivateToolRailForClip } from "../lib/mobileClipActions.js";
|
||||
import {
|
||||
clampTimelineZoom,
|
||||
getTimelineRulerTicks,
|
||||
getTimelineAutoFitZoom,
|
||||
getMobilePinchAnchorScrollLeft,
|
||||
getMobilePinchZoomState,
|
||||
getTimelineTrackWidthPercent,
|
||||
getTimelineZoomForVisibleDuration,
|
||||
getTimelineZoomLabel,
|
||||
} from "../lib/timelineScale.js";
|
||||
import { IconButton, WaveformStrip } from "./ui.jsx";
|
||||
@@ -111,6 +117,7 @@ function getImageTimelineThumbnailCount({ duration, timelineDuration, contentWid
|
||||
export function Timeline({
|
||||
t,
|
||||
trOption,
|
||||
notify,
|
||||
undo,
|
||||
redo,
|
||||
handleDeleteTrack,
|
||||
@@ -129,7 +136,9 @@ export function Timeline({
|
||||
selectedTrack,
|
||||
setSelectedTrack,
|
||||
setActiveTool,
|
||||
openMobileMediaPicker,
|
||||
openMobileInspector,
|
||||
openMobileTools,
|
||||
openMobileFilePicker,
|
||||
requestCaptionVoiceFocus,
|
||||
trackVisibility,
|
||||
toggleTrackVisibility,
|
||||
@@ -156,6 +165,7 @@ export function Timeline({
|
||||
currentStickerSegment,
|
||||
selectedStickerSegmentId,
|
||||
setSelectedStickerSegmentId,
|
||||
stickerTimelineDrag,
|
||||
imageSrc,
|
||||
displayedVisualSegments,
|
||||
setVisualSegments,
|
||||
@@ -181,6 +191,7 @@ export function Timeline({
|
||||
startCaptionResize,
|
||||
startImageResize,
|
||||
startStickerSegmentMove,
|
||||
startStickerSegmentResize,
|
||||
displayedCaptionSegments,
|
||||
displayedCaptionTimeline,
|
||||
currentCaptionSegment,
|
||||
@@ -208,15 +219,18 @@ export function Timeline({
|
||||
startSourceAudioMove,
|
||||
musicBlob,
|
||||
musicSegments = [],
|
||||
selectedMusicSegmentId,
|
||||
setSelectedMusicSegmentId,
|
||||
musicPeaks,
|
||||
musicStartPercent,
|
||||
musicDuration,
|
||||
startMusicMove,
|
||||
}) {
|
||||
const [transitionEditor, setTransitionEditor] = useState(null);
|
||||
const [musicClipSelected, setMusicClipSelected] = useState(false);
|
||||
const [overlayPromotionTarget, setOverlayPromotionTarget] = useState(null);
|
||||
const [sourceAudioExtractionPendingId, setSourceAudioExtractionPendingId] = useState("");
|
||||
const [mobileClipActionsVisible, setMobileClipActionsVisible] = useState(false);
|
||||
const [mobileClipActionTrack, setMobileClipActionTrack] = useState("");
|
||||
|
||||
const clearClipSelections = (except = "") => {
|
||||
if (except !== "overlay") setSelectedVisualOverlayId?.("");
|
||||
@@ -225,10 +239,115 @@ export function Timeline({
|
||||
if (except !== "caption") setSelectedSegmentId("");
|
||||
if (except !== "voice") setSelectedAudioSegmentId("");
|
||||
if (except !== "source") setSelectedSourceAudioSegmentId("");
|
||||
if (except !== "music") setMusicClipSelected(false);
|
||||
if (except !== "music") setSelectedMusicSegmentId?.("");
|
||||
};
|
||||
const selectedMobileClipTrack = resolveMobileClipActionTrack(mobileClipActionTrack, {
|
||||
visual: Boolean(selectedVisualSegmentId),
|
||||
overlay: Boolean(selectedVisualOverlayId),
|
||||
sticker: Boolean(selectedStickerSegmentId),
|
||||
caption: Boolean(selectedSegmentId),
|
||||
source: Boolean(selectedSourceAudioSegmentId),
|
||||
audio: Boolean(selectedAudioSegmentId),
|
||||
music: Boolean(selectedMusicSegmentId),
|
||||
});
|
||||
const openSelectedClipInspector = () => {
|
||||
if (!selectedMobileClipTrack) return;
|
||||
const panel = getMobileClipPanel(selectedMobileClipTrack);
|
||||
if (panel === "tools") {
|
||||
closeMobileClipActions();
|
||||
openTrackPanel(selectedMobileClipTrack);
|
||||
openMobileTools?.();
|
||||
return;
|
||||
}
|
||||
setSelectedTrack(selectedMobileClipTrack);
|
||||
openMobileInspector?.(selectedMobileClipTrack);
|
||||
};
|
||||
const selectedMobileAudioSegment = selectedMobileClipTrack === "audio"
|
||||
? audioSegments.find((segment) => segment.id === selectedAudioSegmentId) ?? null
|
||||
: selectedMobileClipTrack === "source"
|
||||
? linkedSourceAudioSegments.find((segment) => segment.id === selectedSourceAudioSegmentId) ?? null
|
||||
: selectedMobileClipTrack === "music" && selectedMusicSegmentId
|
||||
? (musicSegments.find((segment) => segment.id === selectedMusicSegmentId) ?? { id: "music-audio", start: musicStartPercent / 100 * timelineDuration, sourceStart: 0, duration: musicDuration, peaks: musicPeaks })
|
||||
: null;
|
||||
const selectedMobileVisualSegment = selectedMobileClipTrack === "image"
|
||||
? displayedVisualSegments.find((segment) => segment.id === selectedVisualSegmentId) ?? null
|
||||
: null;
|
||||
const canExtractSelectedMobileSourceAudio = selectedMobileVisualSegment?.type === "video"
|
||||
&& !Number.isFinite(selectedMobileVisualSegment.sourceAudioOffset);
|
||||
const mobileClipActionIds = getMobileClipActionIds(selectedMobileClipTrack, {
|
||||
canExtractSourceAudio: canExtractSelectedMobileSourceAudio,
|
||||
});
|
||||
const closeMobileClipActions = () => {
|
||||
setMobileClipActionsVisible(false);
|
||||
setMobileClipActionTrack("");
|
||||
};
|
||||
const runMobileClipAction = (action) => {
|
||||
closeMobileClipActions();
|
||||
action?.();
|
||||
};
|
||||
const revealMobileClipActions = (track) => {
|
||||
if (!window.matchMedia?.("(max-width: 760px)").matches) return;
|
||||
if (track) setMobileClipActionTrack(track);
|
||||
setMobileClipActionsVisible(true);
|
||||
};
|
||||
const activateAudioToolForClipSelection = () => {
|
||||
const isMobile = window.matchMedia?.("(max-width: 760px)").matches ?? false;
|
||||
if (shouldActivateToolRailForClip(isMobile)) setActiveTool("audio");
|
||||
};
|
||||
const activateStickerToolForClipSelection = () => {
|
||||
const isMobile = window.matchMedia?.("(max-width: 760px)").matches ?? false;
|
||||
if (shouldActivateToolRailForClip(isMobile)) setActiveTool("stickers");
|
||||
};
|
||||
const ensureMobileTimedClipVisible = (segmentId) => {
|
||||
if (!segmentId || !window.matchMedia?.("(max-width: 760px)").matches) return;
|
||||
window.requestAnimationFrame(() => {
|
||||
const trackElement = trackScrollRef.current;
|
||||
const scrollElement = trackElement?.parentElement;
|
||||
if (!trackElement || !scrollElement) return;
|
||||
const clipElement = Array.from(trackElement.querySelectorAll("[data-timeline-segment-id]"))
|
||||
.find((element) => element.dataset.timelineSegmentId === String(segmentId));
|
||||
if (!clipElement) return;
|
||||
const viewportRect = scrollElement.getBoundingClientRect();
|
||||
const clipRect = clipElement.getBoundingClientRect();
|
||||
const padding = 10;
|
||||
if (clipRect.width <= viewportRect.width - padding * 2) {
|
||||
if (clipRect.right > viewportRect.right - padding) {
|
||||
scrollElement.scrollLeft += clipRect.right - viewportRect.right + padding;
|
||||
} else if (clipRect.left < viewportRect.left + padding) {
|
||||
scrollElement.scrollLeft -= viewportRect.left + padding - clipRect.left;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
const generateSelectedMobileAudioCaptions = () => {
|
||||
if (!selectedMobileAudioSegment || !generateCaptionsFromAudioClip) return;
|
||||
const blob = selectedMobileClipTrack === "music" ? musicBlob : selectedMobileClipTrack === "source" ? sourceAudioBlob : selectedMobileAudioSegment.blob;
|
||||
if (!blob) return;
|
||||
runMobileClipAction(() => generateCaptionsFromAudioClip({
|
||||
blob,
|
||||
start: selectedMobileAudioSegment.start || 0,
|
||||
sourceStart: selectedMobileAudioSegment.sourceStart || 0,
|
||||
duration: selectedMobileAudioSegment.duration,
|
||||
append: selectedMobileClipTrack !== "source",
|
||||
}));
|
||||
};
|
||||
const separateSelectedMobileAudio = () => {
|
||||
if (!selectedMobileAudioSegment || !separateAudioClipVocals || !["audio", "music"].includes(selectedMobileClipTrack)) return;
|
||||
const blob = selectedMobileClipTrack === "music" ? musicBlob : selectedMobileAudioSegment.blob;
|
||||
if (!blob) return;
|
||||
runMobileClipAction(() => separateAudioClipVocals({
|
||||
blob,
|
||||
name: selectedMobileClipTrack === "music" ? t("musicTrack") : selectedMobileAudioSegment.name,
|
||||
start: selectedMobileAudioSegment.start || 0,
|
||||
sourceStart: selectedMobileAudioSegment.sourceStart || 0,
|
||||
duration: selectedMobileAudioSegment.duration,
|
||||
segmentId: selectedMobileAudioSegment.id,
|
||||
track: selectedMobileClipTrack,
|
||||
}));
|
||||
};
|
||||
|
||||
const updateJunctionTransition = (index, patch) => {
|
||||
if (trackLocks.image) return void notify("图片轨已锁定,无法修改转场");
|
||||
setVisualSegments((items) => items.map((item, itemIndex) => itemIndex === index
|
||||
? { ...item, transition: { id: item.transition?.id || "none", duration: item.transition?.duration || 0.5, ...patch } }
|
||||
: item));
|
||||
@@ -244,7 +363,10 @@ export function Timeline({
|
||||
const packedAudioLanes = useMemo(() => packTimedSegmentsIntoLanes(audioSegments), [audioSegments]);
|
||||
const showVoiceTrack = audioSegments.length > 0 || draggedAssetType === "audio";
|
||||
const audioLanes = showVoiceTrack ? (audioSegments.length ? packedAudioLanes : [[]]) : [];
|
||||
const stickerLanes = useMemo(() => packTimedSegmentsIntoLanes(stickerSegments), [stickerSegments]);
|
||||
const stickerLanes = useMemo(
|
||||
() => packTimedSegmentsIntoLanes(stickerSegments, { preferredLaneKey: "lane" }),
|
||||
[stickerSegments],
|
||||
);
|
||||
const showEmptyOverlayDropLane = !visualOverlaySegments.length && (
|
||||
draggedAssetType === "image" ||
|
||||
draggedAssetType === "video" ||
|
||||
@@ -308,8 +430,23 @@ export function Timeline({
|
||||
setSelectedTrack(track);
|
||||
setActiveTool(trackTool(track));
|
||||
};
|
||||
const handlePlayheadPointerDown = (event) => {
|
||||
if (window.matchMedia?.("(max-width: 760px)").matches) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
startTimelineSeek(event);
|
||||
};
|
||||
const handleTimelineSurfacePointerDown = (event) => {
|
||||
if (window.matchMedia?.("(max-width: 760px)").matches) return;
|
||||
startTimelineSeek(event);
|
||||
};
|
||||
const selectContextTarget = (track, segmentId = "") => {
|
||||
openTrackPanel(track);
|
||||
const isMobileDirectClip = ["audio", "source", "music", "sticker"].includes(track)
|
||||
&& !shouldActivateToolRailForClip(window.matchMedia?.("(max-width: 760px)").matches ?? false);
|
||||
if (isMobileDirectClip) setSelectedTrack(track);
|
||||
else openTrackPanel(track);
|
||||
const selectionType = { image: "visual", overlay: "overlay", sticker: "sticker", caption: "caption", audio: "voice", source: "source", music: "music" }[track];
|
||||
clearClipSelections(selectionType);
|
||||
if (track === "image" && segmentId) setSelectedVisualSegmentId(segmentId);
|
||||
@@ -318,11 +455,17 @@ export function Timeline({
|
||||
if (track === "caption" && segmentId) setSelectedSegmentId(segmentId);
|
||||
if (track === "audio" && segmentId) setSelectedAudioSegmentId(segmentId);
|
||||
if (track === "source" && segmentId) setSelectedSourceAudioSegmentId(segmentId);
|
||||
if (track === "music" && segmentId) setMusicClipSelected(true);
|
||||
if (track === "music" && segmentId) setSelectedMusicSegmentId?.(segmentId);
|
||||
};
|
||||
const showTrackContextMenu = (event, track, segmentId = "", visibilityKey = track) => {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
selectContextTarget(track, segmentId);
|
||||
if (segmentId && window.matchMedia?.("(max-width: 760px)").matches) {
|
||||
setContextMenu(null);
|
||||
setMobileClipActionTrack(track);
|
||||
setMobileClipActionsVisible(true);
|
||||
return;
|
||||
}
|
||||
const trackRect = trackScrollRef.current?.getBoundingClientRect();
|
||||
const targetTime = trackRect && timelineDuration > 0
|
||||
? Math.max(0, Math.min(timelineDuration, ((event.clientX - trackRect.left) / trackRect.width) * timelineDuration))
|
||||
@@ -388,6 +531,14 @@ export function Timeline({
|
||||
const pendingWheelDeltaRef = useRef(0);
|
||||
const pendingWheelAnchorRef = useRef(null);
|
||||
const timelineWheelHandlerRef = useRef(null);
|
||||
const mobilePinchPointersRef = useRef(new Map());
|
||||
const mobilePinchGestureRef = useRef(null);
|
||||
const mobilePinchActiveRef = useRef(false);
|
||||
const mobilePinchFrameRef = useRef(0);
|
||||
const mobilePinchReleaseFrameRef = useRef(0);
|
||||
const mobilePinchPendingDistanceRef = useRef(0);
|
||||
const mobileTimelineStateRef = useRef(null);
|
||||
mobileTimelineStateRef.current = { currentTime, isPlaying, seekTo, timelineDuration };
|
||||
useEffect(() => {
|
||||
const trackElement = trackScrollRef.current;
|
||||
const scrollElement = trackElement?.parentElement;
|
||||
@@ -400,9 +551,24 @@ export function Timeline({
|
||||
rulerCanvasRef.current.style.transform = `translateX(${-scrollElement.scrollLeft}px)`;
|
||||
}
|
||||
};
|
||||
const syncMobileTimelineTime = () => {
|
||||
const state = mobileTimelineStateRef.current;
|
||||
if (!window.matchMedia?.("(max-width: 760px)").matches || state?.isPlaying || state?.timelineDuration <= 0) {
|
||||
return;
|
||||
}
|
||||
const trackRect = trackElement.getBoundingClientRect();
|
||||
const scrollRect = scrollElement.getBoundingClientRect();
|
||||
const fixedPlayheadX = scrollRect.left + scrollRect.width / 2;
|
||||
const nextTime = Math.max(
|
||||
0,
|
||||
Math.min(state.timelineDuration, ((fixedPlayheadX - trackRect.left) / Math.max(trackRect.width, 1)) * state.timelineDuration),
|
||||
);
|
||||
if (Math.abs(nextTime - state.currentTime) > 0.01) state.seekTo(nextTime);
|
||||
};
|
||||
const applyRulerViewportUpdate = () => {
|
||||
rulerViewportFrameRef.current = 0;
|
||||
syncRulerPosition();
|
||||
syncMobileTimelineTime();
|
||||
const nextViewport = {
|
||||
scrollLeft: scrollElement.scrollLeft,
|
||||
viewportWidth: scrollElement.clientWidth,
|
||||
@@ -418,7 +584,7 @@ export function Timeline({
|
||||
};
|
||||
const scheduleRulerViewportUpdate = () => {
|
||||
syncRulerPosition();
|
||||
if (wheelZoomActiveRef.current) {
|
||||
if (wheelZoomActiveRef.current || mobilePinchActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
if (rulerViewportFrameRef.current) {
|
||||
@@ -447,6 +613,13 @@ export function Timeline({
|
||||
}
|
||||
};
|
||||
}, [trackScrollRef]);
|
||||
useEffect(() => {
|
||||
if (!isPlaying || !window.matchMedia?.("(max-width: 760px)").matches || timelineDuration <= 0) return;
|
||||
const trackElement = trackScrollRef.current;
|
||||
const scrollElement = trackElement?.parentElement;
|
||||
if (!trackElement || !scrollElement) return;
|
||||
scrollElement.scrollLeft = (Math.max(0, Math.min(timelineDuration, currentTime)) / timelineDuration) * trackElement.clientWidth;
|
||||
}, [currentTime, isPlaying, timelineDuration, trackScrollRef]);
|
||||
useEffect(() => {
|
||||
const nextZoom = clampTimelineZoom(timelineZoom);
|
||||
if (Math.abs(nextZoom - timelineZoomRef.current) < 0.0008) {
|
||||
@@ -455,6 +628,14 @@ export function Timeline({
|
||||
timelineZoomRef.current = nextZoom;
|
||||
setLocalTimelineZoom(nextZoom);
|
||||
}, [timelineZoom]);
|
||||
useEffect(() => {
|
||||
if (!window.matchMedia?.("(max-width: 760px)").matches || timelineDuration <= 0) return;
|
||||
const minimumZoom = getTimelineZoomForVisibleDuration(timelineDuration);
|
||||
if (timelineZoomRef.current >= minimumZoom - 0.0008) return;
|
||||
timelineZoomRef.current = minimumZoom;
|
||||
setLocalTimelineZoom(minimumZoom);
|
||||
setTimelineZoom(minimumZoom);
|
||||
}, [setTimelineZoom, timelineDuration]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (wheelZoomFrameRef.current) {
|
||||
@@ -466,6 +647,8 @@ export function Timeline({
|
||||
},
|
||||
[trackScrollRef],
|
||||
);
|
||||
const isMobileTimelineViewport = window.matchMedia?.("(max-width: 760px)").matches;
|
||||
const mobileTrackBaseWidth = window.matchMedia?.("(max-width: 390px)").matches ? 480 : 520;
|
||||
const secondsPerPixel =
|
||||
timelineDuration > 0 && rulerViewport.contentWidth > 0
|
||||
? timelineDuration / rulerViewport.contentWidth
|
||||
@@ -475,13 +658,28 @@ export function Timeline({
|
||||
timelineDuration,
|
||||
(rulerViewport.scrollLeft + rulerViewport.viewportWidth) * secondsPerPixel,
|
||||
);
|
||||
const rulerScaleZoom = isMobileTimelineViewport
|
||||
? getTimelineZoomForVisibleDuration(timelineDuration)
|
||||
: localTimelineZoom;
|
||||
const mobileRulerMinimumMajorStep = isMobileTimelineViewport
|
||||
? (timelineDuration * 88) / mobileTrackBaseWidth
|
||||
: 0;
|
||||
const rulerTicks = useMemo(
|
||||
() => getTimelineRulerTicks(timelineDuration, localTimelineZoom, rulerVisibleStart, rulerVisibleEnd),
|
||||
[timelineDuration, localTimelineZoom, rulerVisibleEnd, rulerVisibleStart],
|
||||
() => getTimelineRulerTicks(
|
||||
timelineDuration,
|
||||
rulerScaleZoom,
|
||||
rulerVisibleStart,
|
||||
rulerVisibleEnd,
|
||||
{ minimumMajorStep: mobileRulerMinimumMajorStep },
|
||||
),
|
||||
[timelineDuration, rulerScaleZoom, mobileRulerMinimumMajorStep, rulerVisibleEnd, rulerVisibleStart],
|
||||
);
|
||||
const zoomReadout = getTimelineZoomLabel(localTimelineZoom);
|
||||
const fitTimelineZoom = getTimelineAutoFitZoom(timelineDuration, 0.9);
|
||||
const localTrackWidth = `${getTimelineTrackWidthPercent(timelineDuration, localTimelineZoom)}%`;
|
||||
const localTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, localTimelineZoom);
|
||||
const localTrackWidth = isMobileTimelineViewport
|
||||
? `${mobileTrackBaseWidth * (localTrackWidthPercent / 100)}px`
|
||||
: `${localTrackWidthPercent}%`;
|
||||
const commitTimelineZoom = (nextZoom, delay = 0) => {
|
||||
window.clearTimeout(commitZoomTimerRef.current);
|
||||
if (delay <= 0) {
|
||||
@@ -521,28 +719,61 @@ export function Timeline({
|
||||
}
|
||||
|
||||
const currentZoom = clampTimelineZoom(timelineZoomRef.current);
|
||||
const nextZoom = clampTimelineZoom(
|
||||
currentZoom * Math.exp(-wheelDelta * TIMELINE_WHEEL_ZOOM_SENSITIVITY),
|
||||
);
|
||||
let nextZoom;
|
||||
let nextTrackWidth;
|
||||
let nextTrackWidthPercent;
|
||||
let nextScrollLeft;
|
||||
|
||||
if (Math.abs(nextZoom - currentZoom) < 0.0008) {
|
||||
return;
|
||||
if (anchor.isMobile) {
|
||||
const renderedVisibleDuration = timelineDuration > 0
|
||||
? (timelineDuration * mobileTrackBaseWidth) / Math.max(anchor.trackWidth, 1)
|
||||
: timelineDuration;
|
||||
const renderedStartZoom = getTimelineZoomForVisibleDuration(renderedVisibleDuration);
|
||||
const widthScale = Math.exp(-wheelDelta * TIMELINE_WHEEL_ZOOM_SENSITIVITY);
|
||||
const mobileState = getMobilePinchZoomState({
|
||||
timelineDuration,
|
||||
minimumZoom: getTimelineZoomForVisibleDuration(timelineDuration),
|
||||
startZoom: renderedStartZoom,
|
||||
startDistance: 1,
|
||||
distance: widthScale,
|
||||
startTrackWidth: anchor.trackWidth,
|
||||
baseTrackWidth: mobileTrackBaseWidth,
|
||||
});
|
||||
nextZoom = mobileState.nextZoom;
|
||||
nextTrackWidth = mobileState.nextTrackWidth;
|
||||
if (Math.abs(nextTrackWidth - anchor.trackWidth) < 0.01) return;
|
||||
} else {
|
||||
nextZoom = clampTimelineZoom(
|
||||
currentZoom * Math.exp(-wheelDelta * TIMELINE_WHEEL_ZOOM_SENSITIVITY),
|
||||
);
|
||||
if (Math.abs(nextZoom - currentZoom) < 0.0008) return;
|
||||
const currentTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, currentZoom);
|
||||
nextTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, nextZoom);
|
||||
nextTrackWidth =
|
||||
anchor.trackWidth * (nextTrackWidthPercent / Math.max(currentTrackWidthPercent, 0.001));
|
||||
nextScrollLeft =
|
||||
anchor.trackContentStart +
|
||||
anchor.pointerTrackRatio * nextTrackWidth -
|
||||
anchor.pointerViewportX;
|
||||
}
|
||||
|
||||
const currentTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, currentZoom);
|
||||
const nextTrackWidthPercent = getTimelineTrackWidthPercent(timelineDuration, nextZoom);
|
||||
const nextTrackWidth =
|
||||
anchor.trackWidth * (nextTrackWidthPercent / Math.max(currentTrackWidthPercent, 0.001));
|
||||
const nextScrollLeft =
|
||||
anchor.trackContentStart +
|
||||
anchor.pointerTrackRatio * nextTrackWidth -
|
||||
anchor.pointerViewportX;
|
||||
|
||||
wheelZoomActiveRef.current = true;
|
||||
timelineZoomRef.current = nextZoom;
|
||||
anchor.trackElement.classList.add("is-wheel-zooming");
|
||||
anchor.trackElement.style.width = `${nextTrackWidthPercent}%`;
|
||||
anchor.trackElement.style.width = anchor.isMobile ? `${nextTrackWidth}px` : `${nextTrackWidthPercent}%`;
|
||||
anchor.trackElement.style.setProperty("--timeline-zoom", String(nextZoom));
|
||||
if (anchor.isMobile) {
|
||||
const nextTrackRect = anchor.trackElement.getBoundingClientRect();
|
||||
const viewportRect = anchor.scrollElement.getBoundingClientRect();
|
||||
nextScrollLeft = getMobilePinchAnchorScrollLeft({
|
||||
currentScrollLeft: anchor.scrollElement.scrollLeft,
|
||||
trackLeft: nextTrackRect.left,
|
||||
trackWidth: nextTrackRect.width,
|
||||
viewportLeft: viewportRect.left,
|
||||
viewportWidth: viewportRect.width,
|
||||
anchorTimeRatio: anchor.anchorTimeRatio,
|
||||
});
|
||||
}
|
||||
anchor.scrollElement.scrollLeft = Math.max(0, nextScrollLeft);
|
||||
if (zoomReadoutRef.current) {
|
||||
zoomReadoutRef.current.textContent = getTimelineZoomLabel(nextZoom);
|
||||
@@ -590,6 +821,8 @@ export function Timeline({
|
||||
const trackRect = trackElement.getBoundingClientRect();
|
||||
const scrollRect = scrollElement.getBoundingClientRect();
|
||||
const trackContentStart = trackRect.left - scrollRect.left + scrollElement.scrollLeft;
|
||||
const isMobile = window.matchMedia?.("(max-width: 760px)").matches ?? false;
|
||||
const fixedPlayheadX = scrollRect.left + scrollRect.width / 2;
|
||||
const pointerTrackRatio = Math.max(
|
||||
0,
|
||||
Math.min(1, (event.clientX - trackRect.left) / Math.max(trackRect.width, 1)),
|
||||
@@ -612,6 +845,11 @@ export function Timeline({
|
||||
trackElement,
|
||||
trackContentStart,
|
||||
trackWidth: trackRect.width,
|
||||
isMobile,
|
||||
anchorTimeRatio: Math.max(
|
||||
0,
|
||||
Math.min(1, (fixedPlayheadX - trackRect.left) / Math.max(trackRect.width, 1)),
|
||||
),
|
||||
};
|
||||
|
||||
if (!wheelZoomFrameRef.current) {
|
||||
@@ -629,6 +867,189 @@ export function Timeline({
|
||||
scrollElement.addEventListener("wheel", handleWheel, { passive: false });
|
||||
return () => scrollElement.removeEventListener("wheel", handleWheel);
|
||||
}, [trackScrollRef]);
|
||||
useEffect(() => {
|
||||
const trackElement = trackScrollRef.current;
|
||||
const scrollElement = trackElement?.parentElement;
|
||||
if (!trackElement || !scrollElement) return undefined;
|
||||
const pinchPointers = mobilePinchPointersRef.current;
|
||||
let singleTouchPan = null;
|
||||
|
||||
const getPinchDistance = () => {
|
||||
const points = Array.from(pinchPointers.values());
|
||||
if (points.length < 2) return 0;
|
||||
return Math.hypot(points[1].x - points[0].x, points[1].y - points[0].y);
|
||||
};
|
||||
const alignPinchAnchor = (anchorTimeRatio) => {
|
||||
const trackRect = trackElement.getBoundingClientRect();
|
||||
const scrollRect = scrollElement.getBoundingClientRect();
|
||||
scrollElement.scrollLeft = getMobilePinchAnchorScrollLeft({
|
||||
currentScrollLeft: scrollElement.scrollLeft,
|
||||
trackLeft: trackRect.left,
|
||||
trackWidth: trackRect.width,
|
||||
viewportLeft: scrollRect.left,
|
||||
viewportWidth: scrollRect.width,
|
||||
anchorTimeRatio,
|
||||
});
|
||||
};
|
||||
const applyPinchZoom = () => {
|
||||
mobilePinchFrameRef.current = 0;
|
||||
const gesture = mobilePinchGestureRef.current;
|
||||
const distance = mobilePinchPendingDistanceRef.current;
|
||||
if (!gesture || distance <= 0) return;
|
||||
const { nextZoom, nextTrackWidth: nextWidth } = getMobilePinchZoomState({
|
||||
timelineDuration,
|
||||
minimumZoom: getTimelineZoomForVisibleDuration(timelineDuration),
|
||||
startZoom: gesture.startZoom,
|
||||
startDistance: gesture.startDistance,
|
||||
distance,
|
||||
startTrackWidth: gesture.startTrackWidth,
|
||||
baseTrackWidth: mobileTrackBaseWidth,
|
||||
});
|
||||
|
||||
gesture.nextZoom = nextZoom;
|
||||
trackElement.style.width = `${nextWidth}px`;
|
||||
trackElement.classList.add("is-pinching");
|
||||
rulerCanvasRef.current?.classList.add("is-pinching");
|
||||
if (rulerCanvasRef.current) rulerCanvasRef.current.style.width = `${nextWidth}px`;
|
||||
alignPinchAnchor(gesture.anchorTimeRatio);
|
||||
if (zoomReadoutRef.current) zoomReadoutRef.current.textContent = getTimelineZoomLabel(nextZoom);
|
||||
rulerViewportSyncRef.current?.();
|
||||
};
|
||||
const finishPinch = () => {
|
||||
const gesture = mobilePinchGestureRef.current;
|
||||
if (!gesture) return;
|
||||
if (mobilePinchFrameRef.current) {
|
||||
window.cancelAnimationFrame(mobilePinchFrameRef.current);
|
||||
mobilePinchFrameRef.current = 0;
|
||||
}
|
||||
const nextZoom = gesture.nextZoom ?? gesture.startZoom;
|
||||
mobilePinchGestureRef.current = null;
|
||||
timelineZoomRef.current = nextZoom;
|
||||
setLocalTimelineZoom(nextZoom);
|
||||
setTimelineZoom(nextZoom);
|
||||
if (mobilePinchReleaseFrameRef.current) window.cancelAnimationFrame(mobilePinchReleaseFrameRef.current);
|
||||
mobilePinchReleaseFrameRef.current = window.requestAnimationFrame(() => {
|
||||
mobilePinchReleaseFrameRef.current = window.requestAnimationFrame(() => {
|
||||
mobilePinchReleaseFrameRef.current = 0;
|
||||
trackElement.classList.remove("is-pinching");
|
||||
rulerCanvasRef.current?.classList.remove("is-pinching");
|
||||
alignPinchAnchor(gesture.anchorTimeRatio);
|
||||
const state = mobileTimelineStateRef.current;
|
||||
if (Math.abs((state?.currentTime ?? gesture.anchorTime) - gesture.anchorTime) > 0.001) {
|
||||
state?.seekTo(gesture.anchorTime);
|
||||
}
|
||||
mobilePinchActiveRef.current = false;
|
||||
rulerViewportSyncRef.current?.();
|
||||
});
|
||||
});
|
||||
};
|
||||
const handlePointerDown = (event) => {
|
||||
if (!window.matchMedia?.("(max-width: 760px)").matches || event.pointerType !== "touch") return;
|
||||
pinchPointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
|
||||
if (pinchPointers.size === 1) {
|
||||
singleTouchPan = {
|
||||
pointerId: event.pointerId,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
startScrollLeft: scrollElement.scrollLeft,
|
||||
interactive: Boolean(event.target?.closest?.(TIMELINE_WHEEL_ZOOM_CONTENT_SELECTOR)),
|
||||
};
|
||||
}
|
||||
if (pinchPointers.size !== 2) return;
|
||||
singleTouchPan = null;
|
||||
if (mobilePinchReleaseFrameRef.current) {
|
||||
window.cancelAnimationFrame(mobilePinchReleaseFrameRef.current);
|
||||
mobilePinchReleaseFrameRef.current = 0;
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent("timeline-mobile-pinch-start"));
|
||||
const state = mobileTimelineStateRef.current;
|
||||
const startDistance = getPinchDistance();
|
||||
// Freeze the exact rendered width before disabling transitions. A second
|
||||
// pinch can begin while a button/release zoom transition is still in
|
||||
// flight; using the stored zoom in that case makes the gesture start from
|
||||
// a different scale than the pixels under the user's fingers.
|
||||
const renderedTrackWidth = trackElement.getBoundingClientRect().width;
|
||||
const renderedTrackRect = trackElement.getBoundingClientRect();
|
||||
const renderedViewportRect = scrollElement.getBoundingClientRect();
|
||||
const fixedPlayheadX = renderedViewportRect.left + renderedViewportRect.width / 2;
|
||||
const renderedAnchorTimeRatio = Math.max(
|
||||
0,
|
||||
Math.min(1, (fixedPlayheadX - renderedTrackRect.left) / Math.max(renderedTrackWidth, 1)),
|
||||
);
|
||||
const renderedAnchorTime = renderedAnchorTimeRatio * Math.max(0, state?.timelineDuration || 0);
|
||||
trackElement.style.width = `${renderedTrackWidth}px`;
|
||||
trackElement.classList.add("is-pinching");
|
||||
rulerCanvasRef.current?.classList.add("is-pinching");
|
||||
if (rulerCanvasRef.current) rulerCanvasRef.current.style.width = `${renderedTrackWidth}px`;
|
||||
const renderedVisibleDuration = timelineDuration > 0
|
||||
? (timelineDuration * mobileTrackBaseWidth) / Math.max(renderedTrackWidth, 1)
|
||||
: timelineDuration;
|
||||
const renderedStartZoom = getTimelineZoomForVisibleDuration(renderedVisibleDuration);
|
||||
mobilePinchPendingDistanceRef.current = startDistance;
|
||||
mobilePinchGestureRef.current = {
|
||||
startDistance,
|
||||
startZoom: renderedStartZoom,
|
||||
startTrackWidth: renderedTrackWidth,
|
||||
// Geometry is authoritative here. React time can be one animation frame
|
||||
// behind a just-finished one-finger pan when the second finger lands.
|
||||
anchorTime: renderedAnchorTime,
|
||||
anchorTimeRatio: renderedAnchorTimeRatio,
|
||||
nextZoom: renderedStartZoom,
|
||||
};
|
||||
if (Math.abs((state?.currentTime ?? renderedAnchorTime) - renderedAnchorTime) > 0.001) {
|
||||
state?.seekTo(renderedAnchorTime);
|
||||
}
|
||||
mobilePinchActiveRef.current = true;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
};
|
||||
const handlePointerMove = (event) => {
|
||||
if (!pinchPointers.has(event.pointerId)) return;
|
||||
pinchPointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
|
||||
if (!mobilePinchGestureRef.current) {
|
||||
if (!singleTouchPan || singleTouchPan.pointerId !== event.pointerId || singleTouchPan.interactive) return;
|
||||
const deltaX = event.clientX - singleTouchPan.startX;
|
||||
const deltaY = event.clientY - singleTouchPan.startY;
|
||||
if (Math.abs(deltaX) < 3 || Math.abs(deltaX) < Math.abs(deltaY)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
scrollElement.scrollLeft = singleTouchPan.startScrollLeft - deltaX;
|
||||
rulerViewportSyncRef.current?.();
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
mobilePinchPendingDistanceRef.current = getPinchDistance();
|
||||
if (!mobilePinchFrameRef.current) mobilePinchFrameRef.current = window.requestAnimationFrame(applyPinchZoom);
|
||||
};
|
||||
const handlePointerEnd = (event) => {
|
||||
if (!pinchPointers.has(event.pointerId)) return;
|
||||
const wasPinching = Boolean(mobilePinchGestureRef.current);
|
||||
if (wasPinching) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
pinchPointers.delete(event.pointerId);
|
||||
if (!wasPinching && singleTouchPan?.pointerId === event.pointerId) singleTouchPan = null;
|
||||
if (wasPinching && pinchPointers.size === 0) finishPinch();
|
||||
};
|
||||
|
||||
scrollElement.addEventListener("pointerdown", handlePointerDown, { capture: true });
|
||||
window.addEventListener("pointermove", handlePointerMove, { capture: true, passive: false });
|
||||
window.addEventListener("pointerup", handlePointerEnd, { capture: true });
|
||||
window.addEventListener("pointercancel", handlePointerEnd, { capture: true });
|
||||
return () => {
|
||||
scrollElement.removeEventListener("pointerdown", handlePointerDown, { capture: true });
|
||||
window.removeEventListener("pointermove", handlePointerMove, { capture: true });
|
||||
window.removeEventListener("pointerup", handlePointerEnd, { capture: true });
|
||||
window.removeEventListener("pointercancel", handlePointerEnd, { capture: true });
|
||||
if (mobilePinchFrameRef.current) window.cancelAnimationFrame(mobilePinchFrameRef.current);
|
||||
if (mobilePinchReleaseFrameRef.current) window.cancelAnimationFrame(mobilePinchReleaseFrameRef.current);
|
||||
pinchPointers.clear();
|
||||
mobilePinchGestureRef.current = null;
|
||||
mobilePinchActiveRef.current = false;
|
||||
};
|
||||
}, [mobileTrackBaseWidth, setTimelineZoom, timelineDuration, trackScrollRef]);
|
||||
const renderAssetDropSlot = (track) =>
|
||||
assetDropTargetTrack === track ? (
|
||||
<div
|
||||
@@ -679,6 +1100,7 @@ export function Timeline({
|
||||
onDragLeave={(event) => handleTrackAssetDragLeave(event, "sticker")}
|
||||
onDrop={(event) => handleTrackAssetDrop(event, "sticker")}
|
||||
data-asset-drop-track="sticker"
|
||||
data-sticker-lane-index={laneIndex}
|
||||
onContextMenu={(event) => showTrackContextMenu(event, "sticker")}
|
||||
>
|
||||
{assetDropTargetTrack === "sticker" ? (
|
||||
@@ -697,14 +1119,18 @@ export function Timeline({
|
||||
<button
|
||||
className={`sticker-segment ${
|
||||
segment.id === currentStickerSegment?.id ? "is-current" : ""
|
||||
} ${segment.id === selectedStickerSegmentId ? "is-selected-segment" : ""}`}
|
||||
} ${segment.id === selectedStickerSegmentId ? "is-selected-segment" : ""} ${
|
||||
stickerTimelineDrag?.segmentId === segment.id ? "is-timeline-dragging" : ""
|
||||
}`}
|
||||
type="button"
|
||||
key={segment.id}
|
||||
data-timeline-segment-track="sticker"
|
||||
data-timeline-segment-id={segment.id}
|
||||
style={{
|
||||
"--sticker-left": `${segmentLeft}%`,
|
||||
"--sticker-width": `${segmentWidth}%`,
|
||||
}}
|
||||
onPointerDown={(event) => startStickerSegmentMove(event, segment.id)}
|
||||
onPointerDown={(event) => startStickerSegmentMove(event, segment.id, laneIndex)}
|
||||
onContextMenu={(event) => showTrackContextMenu(event, "sticker", segment.id)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
@@ -712,17 +1138,34 @@ export function Timeline({
|
||||
return;
|
||||
}
|
||||
setSelectedTrack("sticker");
|
||||
setActiveTool("stickers");
|
||||
activateStickerToolForClipSelection();
|
||||
clearClipSelections("sticker");
|
||||
setSelectedStickerSegmentId(segment.id);
|
||||
seekTo(segment.start || 0);
|
||||
ensureMobileTimedClipVisible(segment.id);
|
||||
revealMobileClipActions("sticker");
|
||||
}}
|
||||
>
|
||||
<img src={segment.src} alt="" draggable={false} />
|
||||
<span>{segment.name}</span>
|
||||
<i className="sticker-resize-handle is-start" onPointerDown={(event) => startStickerSegmentResize(event, segment.id, "start")} />
|
||||
<i className="sticker-resize-handle is-end" onPointerDown={(event) => startStickerSegmentResize(event, segment.id, "end")} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{stickerTimelineDrag?.lane === laneIndex && timelineDuration > 0 ? (
|
||||
<div
|
||||
className="sticker-drop-preview"
|
||||
data-testid="sticker-drop-preview"
|
||||
style={{
|
||||
"--sticker-drop-left": `${Math.max(0, Math.min(100, (stickerTimelineDrag.start / timelineDuration) * 100))}%`,
|
||||
"--sticker-drop-width": `${Math.max(0.4, Math.min(100, (stickerTimelineDrag.duration / timelineDuration) * 100))}%`,
|
||||
}}
|
||||
>
|
||||
{stickerTimelineDrag.src ? <img src={stickerTimelineDrag.src} alt="" /> : null}
|
||||
<span>{stickerTimelineDrag.name || t("assetSticker")}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{renderAssetDropSlot("sticker")}
|
||||
</div>
|
||||
) : null;
|
||||
@@ -752,16 +1195,22 @@ export function Timeline({
|
||||
: 1;
|
||||
const startOverlayEdit = (event, mode) => {
|
||||
if (trackLocks.overlay || !setVisualOverlaySegments) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const isMobileTouch = event.pointerType === "touch" && window.matchMedia?.("(max-width: 760px)").matches;
|
||||
if (!isMobileTouch) event.preventDefault();
|
||||
event.stopPropagation();
|
||||
clearClipSelections("overlay"); setSelectedVisualOverlayId?.(segment.id); setSelectedTrack("overlay");
|
||||
const track = event.currentTarget.closest(".visual-overlay-track");
|
||||
if (!track) return;
|
||||
const rect = track.getBoundingClientRect();
|
||||
const startX = event.clientX; const initialStart = segment.start; const initialDuration = segment.duration;
|
||||
const startX = event.clientX; const startY = event.clientY; const initialStart = segment.start; const initialDuration = segment.duration;
|
||||
let dragging = false; let promoteToMain = false; let mainInsertIndex = displayedVisualSegments.length;
|
||||
const move = (moveEvent) => {
|
||||
if (!dragging && Math.abs(moveEvent.clientX - startX) < 4) return;
|
||||
const deltaX = moveEvent.clientX - startX;
|
||||
const deltaY = moveEvent.clientY - startY;
|
||||
if (!dragging && isMobileTouch && Math.abs(deltaY) > Math.abs(deltaX)) return;
|
||||
if (!dragging && Math.abs(deltaX) < 4) return;
|
||||
if (!dragging) { dragging = true; if (isPlaying) handlePlayToggle(); }
|
||||
moveEvent.preventDefault();
|
||||
const mainTrack = mode === "move" ? document.elementFromPoint(moveEvent.clientX, moveEvent.clientY)?.closest?.('[data-asset-drop-track="image"]') : null;
|
||||
promoteToMain = Boolean(mainTrack);
|
||||
if (promoteToMain) {
|
||||
@@ -776,7 +1225,7 @@ export function Timeline({
|
||||
setOverlayPromotionTarget(null);
|
||||
}
|
||||
if (promoteToMain) return;
|
||||
const delta = (moveEvent.clientX - startX) / Math.max(1, rect.width) * timelineDuration;
|
||||
const delta = deltaX / Math.max(1, rect.width) * timelineDuration;
|
||||
setVisualOverlaySegments((items) => items.map((item) => {
|
||||
if (item.id !== segment.id) return item;
|
||||
if (mode === "move") return { ...item, start: Math.max(0, Math.min(timelineDuration - initialDuration, initialStart + delta)) };
|
||||
@@ -787,9 +1236,21 @@ export function Timeline({
|
||||
return { ...item, duration: Math.max(0.1, Math.min(timelineDuration - initialStart, initialDuration + delta)) };
|
||||
}));
|
||||
};
|
||||
const end = () => {
|
||||
window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end);
|
||||
const cleanup = () => {
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", end);
|
||||
window.removeEventListener("pointercancel", cancel);
|
||||
setOverlayPromotionTarget(null);
|
||||
};
|
||||
const cancel = () => {
|
||||
cleanup();
|
||||
if (!dragging || promoteToMain) return;
|
||||
setVisualOverlaySegments((items) => items.map((item) => item.id === segment.id
|
||||
? { ...item, start: initialStart, duration: initialDuration }
|
||||
: item));
|
||||
};
|
||||
const end = () => {
|
||||
cleanup();
|
||||
if (!dragging || !promoteToMain) return;
|
||||
const promoted = createMainVisualFromOverlay(segment);
|
||||
if (!promoted) return;
|
||||
@@ -803,7 +1264,9 @@ export function Timeline({
|
||||
setSelectedVisualSegmentId(promoted.id);
|
||||
setSelectedTrack("image");
|
||||
};
|
||||
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
|
||||
window.addEventListener("pointermove", move, { passive: false });
|
||||
window.addEventListener("pointerup", end, { once: true });
|
||||
window.addEventListener("pointercancel", cancel, { once: true });
|
||||
};
|
||||
return <div className={`visual-overlay-clip ${segment.type === "video" ? "is-video" : "is-image"} ${active ? "is-current" : ""} ${segment.id === selectedVisualOverlayId ? "is-selected-segment" : ""}`} role="button" tabIndex={0} key={segment.id} style={{ "--overlay-left": `${left}%`, "--overlay-width": `${width}%` }} onPointerDown={(event) => startOverlayEdit(event, "move")} onContextMenu={(event) => showTrackContextMenu(event, "overlay", segment.id)} onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
@@ -818,7 +1281,7 @@ export function Timeline({
|
||||
: <video src={segment.src} muted playsInline preload="metadata" />
|
||||
: Array.from({ length: overlayImageCount }, (_, thumbnailIndex) => <img src={segment.src} alt="" draggable={false} key={`${segment.id}-overlay-image-${thumbnailIndex}`} />)}
|
||||
</div>
|
||||
{segment.type === "video" ? <button className="clip-mute-toggle" type="button" aria-label={t(segment.muted ? "unmuteClip" : "muteClip", segment.muted ? "取消静音" : "静音")} title={t(segment.muted ? "unmuteClip" : "muteClip", segment.muted ? "取消静音" : "静音")} onPointerDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); setVisualOverlaySegments((items) => items.map((item) => item.id === segment.id ? { ...item, muted: !item.muted } : item)); }}>{segment.muted ? <SpeakerSlash size={13} /> : <SpeakerHigh size={13} />}</button> : null}
|
||||
{segment.type === "video" ? <button className="clip-mute-toggle" type="button" aria-label={t(segment.muted ? "unmuteClip" : "muteClip", segment.muted ? "取消静音" : "静音")} title={t(segment.muted ? "unmuteClip" : "muteClip", segment.muted ? "取消静音" : "静音")} onPointerDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); if (trackLocks.overlay) return void notify("画中画轨已锁定,无法切换静音"); setVisualOverlaySegments((items) => items.map((item) => item.id === segment.id ? { ...item, muted: !item.muted } : item)); }}>{segment.muted ? <SpeakerSlash size={13} /> : <SpeakerHigh size={13} />}</button> : null}
|
||||
<span>{segment.name || t("overlayTrack", "Overlay")}</span>
|
||||
<i className="visual-overlay-resize is-start" onPointerDown={(event) => startOverlayEdit(event, "resize-start")} />
|
||||
<i className="visual-overlay-resize is-end" onPointerDown={(event) => startOverlayEdit(event, "resize-end")} />
|
||||
@@ -842,7 +1305,17 @@ export function Timeline({
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="timeline">
|
||||
<section className="timeline" onPointerDownCapture={(event) => {
|
||||
if (!window.matchMedia?.("(max-width: 760px)").matches || !(event.target instanceof Element)) return;
|
||||
const pressedSegment = event.target.closest("[data-timeline-segment-track]");
|
||||
if (pressedSegment?.dataset.timelineSegmentTrack) {
|
||||
setMobileClipActionTrack(pressedSegment.dataset.timelineSegmentTrack);
|
||||
setMobileClipActionsVisible(true);
|
||||
} else if (event.target.closest(".track-scroll, .track-labels, .timeline-ruler-viewport")) {
|
||||
setMobileClipActionsVisible(false);
|
||||
setMobileClipActionTrack("");
|
||||
}
|
||||
}}>
|
||||
<div className="timeline-tools">
|
||||
<div className="timeline-icon-group">
|
||||
<IconButton label={t("undo")} onClick={undo}>
|
||||
@@ -917,6 +1390,8 @@ export function Timeline({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mobile-fixed-playhead" aria-hidden="true" />
|
||||
|
||||
<div className="timeline-board">
|
||||
<div className="track-labels-ruler-spacer" aria-hidden="true" />
|
||||
<div className="timeline-ruler-viewport">
|
||||
@@ -925,7 +1400,7 @@ export function Timeline({
|
||||
className="timeline-ruler-canvas"
|
||||
style={{ width: localTrackWidth, transform: `translateX(${-rulerViewport.scrollLeft}px)` }}
|
||||
>
|
||||
<div className="ruler" onPointerDown={startTimelineSeek}>
|
||||
<div className="ruler" onPointerDown={handleTimelineSurfacePointerDown}>
|
||||
{rulerTicks.map((tick) => (
|
||||
<span
|
||||
className={`ruler-tick ${tick.isMajor ? "is-major" : "is-minor"}`}
|
||||
@@ -939,7 +1414,7 @@ export function Timeline({
|
||||
<div
|
||||
className="playhead-ruler"
|
||||
style={{ left: `${playheadPercent}%` }}
|
||||
onPointerDown={startTimelineSeek}
|
||||
onPointerDown={handlePlayheadPointerDown}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -948,7 +1423,7 @@ export function Timeline({
|
||||
<div
|
||||
className={`${selectedTrack === track ? "is-selected" : ""} ${
|
||||
!isRowVisible(visibilityKey) ? "is-track-disabled" : ""
|
||||
}`}
|
||||
} ${trackLocks[track] ? "is-track-locked" : ""}`}
|
||||
key={rowId}
|
||||
onContextMenu={(event) => showTrackContextMenu(event, track, "", visibilityKey)}
|
||||
>
|
||||
@@ -965,6 +1440,7 @@ export function Timeline({
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${label} ${t("lock")}`}
|
||||
aria-pressed={Boolean(trackLocks[track])}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleTrackLock(track);
|
||||
@@ -992,7 +1468,7 @@ export function Timeline({
|
||||
) {
|
||||
return;
|
||||
}
|
||||
startTimelineSeek(event);
|
||||
handleTimelineSurfacePointerDown(event);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@@ -1003,7 +1479,7 @@ export function Timeline({
|
||||
aria-valuemax={Math.round(timelineDuration)}
|
||||
aria-valuenow={Math.round(currentTime)}
|
||||
style={{ left: `${playheadPercent}%` }}
|
||||
onPointerDown={startTimelineSeek}
|
||||
onPointerDown={handlePlayheadPointerDown}
|
||||
/>
|
||||
{snapGuide && timelineDuration > 0 ? (
|
||||
<div
|
||||
@@ -1044,7 +1520,7 @@ export function Timeline({
|
||||
aria-label={t("mobileAddMedia", "添加素材")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
openMobileMediaPicker?.();
|
||||
openMobileFilePicker?.();
|
||||
}}
|
||||
>
|
||||
<PlusCircle size={20} weight="bold" />
|
||||
@@ -1156,6 +1632,7 @@ export function Timeline({
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (trackLocks.image) return void notify("图片轨已锁定,无法切换静音");
|
||||
setVisualSegments((items) => items.map((item) => item.id === segment.id ? { ...item, sourceAudioDisabled: !item.sourceAudioDisabled } : item));
|
||||
}}
|
||||
>
|
||||
@@ -1370,6 +1847,8 @@ export function Timeline({
|
||||
<div
|
||||
className={`audio-clip is-source is-linked ${selectedSourceAudioSegmentId === segment.id ? "is-selected" : ""}`}
|
||||
key={segment.id}
|
||||
data-timeline-segment-track="source"
|
||||
data-timeline-segment-id={segment.id}
|
||||
style={{
|
||||
width: `${timelineDuration > 0 ? Math.max(0.01, Math.min(100, (segment.duration / timelineDuration) * 100)) : 0}%`,
|
||||
left: `${timelineDuration > 0 ? Math.max(0, Math.min(100, (segment.start / timelineDuration) * 100)) : 0}%`,
|
||||
@@ -1380,17 +1859,21 @@ export function Timeline({
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === "source") return void (suppressTimelineClipClickRef.current = "");
|
||||
setSelectedTrack("source");
|
||||
setActiveTool("audio");
|
||||
activateAudioToolForClipSelection();
|
||||
clearClipSelections("source");
|
||||
setSelectedSourceAudioSegmentId(segment.id);
|
||||
ensureMobileTimedClipVisible(segment.id);
|
||||
revealMobileClipActions("source");
|
||||
}}
|
||||
>
|
||||
<WaveformStrip peaks={sliceSourceAudioPeaks(sourceAudioPeaks, segment, sourceAudioDuration)} active />
|
||||
<span className="audio-clip-duration">{formatTime(segment.duration)}</span>
|
||||
<span className="audio-clip-duration" data-compact-duration={formatCompactDuration(segment.duration)}>{formatTime(segment.duration)}</span>
|
||||
</div>
|
||||
)) : sourceAudioBlob ? (
|
||||
<div
|
||||
className={`audio-clip is-source ${selectedSourceAudioSegmentId === "source-audio" ? "is-selected" : ""}`}
|
||||
data-timeline-segment-track="source"
|
||||
data-timeline-segment-id="source-audio"
|
||||
style={{
|
||||
width: `${sourceAudioClipPercent}%`,
|
||||
marginLeft: `${sourceAudioStartPercent}%`,
|
||||
@@ -1401,13 +1884,15 @@ export function Timeline({
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === "source") return void (suppressTimelineClipClickRef.current = "");
|
||||
setSelectedTrack("source");
|
||||
setActiveTool("audio");
|
||||
activateAudioToolForClipSelection();
|
||||
clearClipSelections("source");
|
||||
setSelectedSourceAudioSegmentId("source-audio");
|
||||
ensureMobileTimedClipVisible("source-audio");
|
||||
revealMobileClipActions("source");
|
||||
}}
|
||||
>
|
||||
<WaveformStrip peaks={sourceAudioPeaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(sourceAudioDuration)}</span>
|
||||
<span className="audio-clip-duration" data-compact-duration={formatCompactDuration(sourceAudioDuration)}>{formatTime(sourceAudioDuration)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</button> : null}
|
||||
@@ -1438,6 +1923,8 @@ export function Timeline({
|
||||
<div
|
||||
className={`audio-clip ${selectedAudioSegmentId === segment.id ? "is-selected" : ""}`}
|
||||
key={segment.id}
|
||||
data-timeline-segment-track="audio"
|
||||
data-timeline-segment-id={segment.id}
|
||||
style={{ left: `${left}%`, width: `${width}%` }}
|
||||
onPointerDown={(event) => startAudioSegmentMove(event, segment.id)}
|
||||
onContextMenu={(event) => showTrackContextMenu(event, "audio", segment.id)}
|
||||
@@ -1445,14 +1932,16 @@ export function Timeline({
|
||||
event.stopPropagation();
|
||||
if (suppressTimelineClipClickRef.current === segment.id) return void (suppressTimelineClipClickRef.current = "");
|
||||
setSelectedTrack("audio");
|
||||
setActiveTool("audio");
|
||||
activateAudioToolForClipSelection();
|
||||
clearClipSelections("voice");
|
||||
setSelectedAudioSegmentId(segment.id);
|
||||
seekTo(segment.start);
|
||||
if (window.matchMedia?.("(max-width: 760px)").matches) ensureMobileTimedClipVisible(segment.id);
|
||||
else seekTo(segment.start);
|
||||
revealMobileClipActions("audio");
|
||||
}}
|
||||
>
|
||||
<WaveformStrip peaks={segment.peaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(segment.duration)}</span>
|
||||
<span className="audio-clip-duration" data-compact-duration={formatCompactDuration(segment.duration)}>{formatTime(segment.duration)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -1467,7 +1956,7 @@ export function Timeline({
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedTrack("music");
|
||||
setMusicClipSelected(false);
|
||||
setSelectedMusicSegmentId?.("");
|
||||
}}
|
||||
onDragOver={(event) => handleTrackAssetDragOver(event, "music")}
|
||||
onDragLeave={(event) => handleTrackAssetDragLeave(event, "music")}
|
||||
@@ -1480,9 +1969,9 @@ export function Timeline({
|
||||
) : null}
|
||||
{renderAssetDropSlot("music")}
|
||||
{musicBlob ? (musicSegments.length ? musicSegments : [{ id: "music-audio", start: musicStartPercent / 100 * timelineDuration, duration: musicDuration, peaks: musicPeaks }]).map((segment) => (
|
||||
<div className={`audio-clip is-music ${musicClipSelected ? "is-selected" : ""}`} key={segment.id} style={{ width: `${timelineDuration > 0 ? segment.duration / timelineDuration * 100 : 0}%`, left: `${timelineDuration > 0 ? segment.start / timelineDuration * 100 : 0}%` }} onPointerDown={startMusicMove} onContextMenu={(event) => showTrackContextMenu(event, "music", segment.id)} onClick={(event) => { event.stopPropagation(); if (suppressTimelineClipClickRef.current === "music") return void (suppressTimelineClipClickRef.current = ""); setSelectedTrack("music"); setActiveTool("audio"); clearClipSelections("music"); setMusicClipSelected(true); }}>
|
||||
<div className={`audio-clip is-music ${selectedMusicSegmentId === segment.id ? "is-selected" : ""}`} key={segment.id} data-timeline-segment-track="music" data-timeline-segment-id={segment.id} style={{ width: `${timelineDuration > 0 ? segment.duration / timelineDuration * 100 : 0}%`, left: `${timelineDuration > 0 ? segment.start / timelineDuration * 100 : 0}%` }} onPointerDown={startMusicMove} onContextMenu={(event) => showTrackContextMenu(event, "music", segment.id)} onClick={(event) => { event.stopPropagation(); if (suppressTimelineClipClickRef.current === "music") return void (suppressTimelineClipClickRef.current = ""); setSelectedTrack("music"); activateAudioToolForClipSelection(); clearClipSelections("music"); setSelectedMusicSegmentId?.(segment.id); ensureMobileTimedClipVisible(segment.id); revealMobileClipActions("music"); }}>
|
||||
<WaveformStrip peaks={segment.peaks?.length ? segment.peaks : musicPeaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(segment.duration)}</span>
|
||||
<span className="audio-clip-duration" data-compact-duration={formatCompactDuration(segment.duration)}>{formatTime(segment.duration)}</span>
|
||||
</div>
|
||||
)) : null}
|
||||
</button> : null}
|
||||
@@ -1513,6 +2002,22 @@ export function Timeline({
|
||||
<strong>{draggingCaptionSegment.text}</strong>
|
||||
</div>
|
||||
) : null}
|
||||
{mobileClipActionsVisible && selectedMobileClipTrack && typeof document !== "undefined" ? createPortal((
|
||||
<nav className={`timeline-mobile-clip-actions ${mobileClipActionIds.length > 5 ? "is-scroll-actions" : ""}`} aria-label={t("clipActions")}>
|
||||
{mobileClipActionIds.map((actionId) => {
|
||||
if (actionId === "dismiss") return <button className="is-back" type="button" key={actionId} onClick={() => { closeMobileClipActions(); clearClipSelections(); }}><ArrowLeft size={21} /><span>{t("mobileClipDismiss")}</span></button>;
|
||||
if (actionId === "edit") return <button type="button" key={actionId} onClick={openSelectedClipInspector}><SlidersHorizontal size={20} /><span>{t("mobileClipEdit")}</span></button>;
|
||||
if (actionId === "properties") return <button type="button" key={actionId} onClick={openSelectedClipInspector}><SlidersHorizontal size={20} /><span>{t("properties")}</span></button>;
|
||||
if (actionId === "audio") return <button type="button" key={actionId} onClick={openSelectedClipInspector}><SlidersHorizontal size={20} /><span>{t("mobileClipAudio")}</span></button>;
|
||||
if (actionId === "split") return <button type="button" key={actionId} onClick={() => runMobileClipAction(handleCutTrack)}><Scissors size={20} /><span>{t("mobileClipSplit")}</span></button>;
|
||||
if (actionId === "copy") return <button type="button" key={actionId} onClick={() => runMobileClipAction(handleDuplicateTrack)}><CopySimple size={20} /><span>{t("mobileClipCopy")}</span></button>;
|
||||
if (actionId === "captions") return <button type="button" key={actionId} disabled={audioProcessingBusy || !selectedMobileAudioSegment} onClick={generateSelectedMobileAudioCaptions}><ClosedCaptioning size={20} /><span>{t("mobileClipCaptions")}</span></button>;
|
||||
if (actionId === "separate") return <button type="button" key={actionId} disabled={audioProcessingBusy || !selectedMobileAudioSegment} onClick={separateSelectedMobileAudio}><Waveform size={20} /><span>{t("mobileClipSeparate")}</span></button>;
|
||||
if (actionId === "extract-source-audio") return <button type="button" key={actionId} disabled={Boolean(sourceAudioExtractionPendingId) || !selectedMobileVisualSegment} onClick={() => void runSourceAudioExtraction(selectedMobileVisualSegment)}>{sourceAudioExtractionPendingId === selectedMobileVisualSegment?.id ? <CircleNotch className="spin" size={20} /> : <Waveform size={20} />}<span>{t(sourceAudioExtractionPendingId === selectedMobileVisualSegment?.id ? "separatingSourceAudio" : "separateSourceAudio", sourceAudioExtractionPendingId === selectedMobileVisualSegment?.id ? "正在分离音频…" : "分离音频")}</span></button>;
|
||||
return <button className="is-danger" type="button" key={actionId} onClick={() => runMobileClipAction(handleDeleteTrack)}><Trash size={20} /><span>{t("mobileClipDelete")}</span></button>;
|
||||
})}
|
||||
</nav>
|
||||
), document.body) : null}
|
||||
{contextMenu ? (
|
||||
<div className="timeline-context-menu" role="menu" aria-label={t("timelineContextMenu")} style={{ left: contextMenu.x, top: contextMenu.y }} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? t("clipActions") : t("trackActions")}<span>{t({ image: "imageTrack", overlay: "overlayTrack", caption: "caption", sticker: "stickerTrack", source: "sourceTrack", audio: "voiceTrack", music: "musicTrack" }[contextMenu.track], contextMenu.track)}</span></div>
|
||||
@@ -1532,14 +2037,14 @@ export function Timeline({
|
||||
</button>
|
||||
) : null}
|
||||
{contextMenu.track === "image" && contextImageSegment?.type === "video" ? <>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => setVisualSegments((items) => items.map((item) => item.id === contextImageSegment.id ? { ...item, sourceAudioDisabled: !item.sourceAudioDisabled } : item)))}>{contextImageSegment.sourceAudioDisabled ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextImageSegment.sourceAudioDisabled ? "unmuteClip" : "muteClip", contextImageSegment.sourceAudioDisabled ? "取消静音" : "静音")}</button>
|
||||
<button type="button" role="menuitem" disabled={Boolean(trackLocks.image)} onClick={() => runContextAction(() => setVisualSegments((items) => items.map((item) => item.id === contextImageSegment.id ? { ...item, sourceAudioDisabled: !item.sourceAudioDisabled } : item)))}>{contextImageSegment.sourceAudioDisabled ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextImageSegment.sourceAudioDisabled ? "unmuteClip" : "muteClip", contextImageSegment.sourceAudioDisabled ? "取消静音" : "静音")}</button>
|
||||
<button type="button" role="menuitem" disabled={Boolean(sourceAudioExtractionPendingId)} onClick={() => void runSourceAudioExtraction(contextImageSegment)}>
|
||||
{sourceAudioExtractionPendingId === contextImageSegment.id ? <CircleNotch size={16} /> : <Waveform size={16} />}
|
||||
{t(sourceAudioExtractionPendingId === contextImageSegment.id ? "separatingSourceAudio" : "separateSourceAudio", sourceAudioExtractionPendingId === contextImageSegment.id ? "正在分离音频…" : "分离音频")}
|
||||
</button>
|
||||
</> : null}
|
||||
{contextMenu.track === "overlay" && contextOverlaySegment?.type === "video" ? (
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => setVisualOverlaySegments((items) => items.map((item) => item.id === contextOverlaySegment.id ? { ...item, muted: !item.muted } : item)))}>{contextOverlaySegment.muted ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextOverlaySegment.muted ? "unmuteClip" : "muteClip", contextOverlaySegment.muted ? "取消静音" : "静音")}</button>
|
||||
<button type="button" role="menuitem" disabled={Boolean(trackLocks.overlay)} onClick={() => runContextAction(() => setVisualOverlaySegments((items) => items.map((item) => item.id === contextOverlaySegment.id ? { ...item, muted: !item.muted } : item)))}>{contextOverlaySegment.muted ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextOverlaySegment.muted ? "unmuteClip" : "muteClip", contextOverlaySegment.muted ? "取消静音" : "静音")}</button>
|
||||
) : null}
|
||||
{contextMenu.track === "audio" && contextAudioSegment ? <>
|
||||
<button type="button" role="menuitem" disabled={audioProcessingBusy} onClick={() => runContextAction(() => separateAudioClipVocals?.({ blob: contextAudioSegment.blob, name: contextAudioSegment.name, start: contextAudioSegment.start, sourceStart: contextAudioSegment.sourceStart || 0, duration: contextAudioSegment.duration, segmentId: contextAudioSegment.id, track: "audio" }))}><Waveform size={16} />{t("separateVocalsFromClip")}</button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
ImageSquare,
|
||||
ListBullets,
|
||||
PersonSimpleRun,
|
||||
Plus,
|
||||
Scissors,
|
||||
Sparkle,
|
||||
Trash,
|
||||
@@ -116,8 +117,10 @@ function CaptionContextPanel({
|
||||
isGeneratingCaptions,
|
||||
automaticCaptionProgress,
|
||||
importCaptionSegments,
|
||||
addCaptionSegment,
|
||||
}) {
|
||||
const srtInputRef = useRef(null);
|
||||
const focusNewCaptionRef = useRef(false);
|
||||
const [pendingSrt, setPendingSrt] = useState(null);
|
||||
const selectedIndex = Math.max(
|
||||
0,
|
||||
@@ -127,6 +130,18 @@ function CaptionContextPanel({
|
||||
? getSegmentStartTime(captionSegments, selectedIndex, captionTargetDuration)
|
||||
: 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusNewCaptionRef.current || !selectedCaptionSegment) return;
|
||||
focusNewCaptionRef.current = false;
|
||||
const frame = requestAnimationFrame(() => document.getElementById("caption-context-input")?.focus());
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [selectedCaptionSegment]);
|
||||
|
||||
function handleAddCaption() {
|
||||
focusNewCaptionRef.current = true;
|
||||
addCaptionSegment();
|
||||
}
|
||||
|
||||
async function handleSrtFile(file) {
|
||||
if (!file) return;
|
||||
try {
|
||||
@@ -171,9 +186,14 @@ function CaptionContextPanel({
|
||||
<ClosedCaptioning size={28} weight="duotone" />
|
||||
<strong>{t("noCaptionSegments")}</strong>
|
||||
<span>{t("captionEmptyHint", "字幕片段可拖动到字幕轨道,并在这里同步编辑。")}</span>
|
||||
<button className="caption-empty-import" type="button" onClick={() => srtInputRef.current?.click()}>
|
||||
<UploadSimple size={15} />{t("importSrt")}
|
||||
</button>
|
||||
<div className="caption-empty-actions">
|
||||
<button className="caption-add-button" type="button" onClick={handleAddCaption}>
|
||||
<Plus size={16} weight="bold" />{t("addCaption")}
|
||||
</button>
|
||||
<button className="caption-empty-import" type="button" onClick={() => srtInputRef.current?.click()}>
|
||||
<UploadSimple size={15} />{t("importSrt")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -220,9 +240,16 @@ function CaptionContextPanel({
|
||||
|
||||
<div className="caption-context-heading">
|
||||
<span><ListBullets size={16} />{t("captionList", "字幕列表")}</span>
|
||||
<button className="caption-import-button" type="button" onClick={() => srtInputRef.current?.click()}>
|
||||
<UploadSimple size={14} />{t("importSrt")}
|
||||
</button>
|
||||
{captionSegments.length ? (
|
||||
<>
|
||||
<button className="caption-add-inline" type="button" onClick={handleAddCaption}>
|
||||
<Plus size={14} weight="bold" />{t("addCaption")}
|
||||
</button>
|
||||
<button className="caption-import-button" type="button" onClick={() => srtInputRef.current?.click()}>
|
||||
<UploadSimple size={14} />{t("importSrt")}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
<input
|
||||
ref={srtInputRef}
|
||||
className="sr-only"
|
||||
@@ -275,33 +302,44 @@ function CaptionContextPanel({
|
||||
}
|
||||
|
||||
function AudioClipContextPanel({ t, segment, updateAudioSegment, toggleAudioSegmentReverse, deleteAudioSegment, downloadBlob }) {
|
||||
const isVoiceClip = segment.track === "audio";
|
||||
const trackLabel = segment.track === "music" ? t("musicTrack") : segment.track === "source" ? t("sourceTrack") : t("voiceTrack");
|
||||
return (
|
||||
<div className="audio-clip-context-panel">
|
||||
<div className="avatar-context-hero">
|
||||
<span><Waveform size={22} weight="duotone" /></span>
|
||||
<div><small>{t("voiceTrack")}</small><strong>{segment.name || t("audioClip")}</strong><em>{formatTime(segment.duration)}</em></div>
|
||||
<div><small>{trackLabel}</small><strong>{segment.name || t("audioClip")}</strong><em>{formatTime(segment.duration)}</em></div>
|
||||
</div>
|
||||
<label className="audio-property-row">
|
||||
{segment.canChangeStart !== false ? <label className="audio-property-row">
|
||||
<span>{t("audioClipStart")}</span>
|
||||
<input type="number" min="0" step="0.1" value={Number(segment.start.toFixed(1))} onChange={(event) => updateAudioSegment(segment.id, { start: Math.max(0, Number(event.target.value) || 0) })} />
|
||||
</label>
|
||||
</label> : null}
|
||||
<label className="audio-property-slider">
|
||||
<span><b>{t("volume")}</b><em>{Math.round((segment.volume ?? 1) * 100)}%</em></span>
|
||||
<input type="range" min="0" max="1" step="0.01" value={segment.volume ?? 1} onChange={(event) => updateAudioSegment(segment.id, { volume: Number(event.target.value) })} />
|
||||
</label>
|
||||
<label className="audio-property-slider">
|
||||
{segment.canChangeSpeed !== false ? <div className="audio-property-slider">
|
||||
<span><b>{t("visualSpeed")}</b><em>{(segment.playbackRate ?? 1).toFixed((segment.playbackRate ?? 1) % 1 ? 2 : 0)}×</em></span>
|
||||
<div className="visual-speed-presets" aria-label={t("visualSpeed")}>
|
||||
{[0.5, 1, 1.5, 2, 3, 4].map((rate) => (
|
||||
<button type="button" className={Math.abs((segment.playbackRate ?? 1) - rate) < 0.001 ? "is-active" : ""} key={rate} onClick={() => updateAudioSegment(segment.id, { playbackRate: rate })}>{rate}×</button>
|
||||
))}
|
||||
</div>
|
||||
<input aria-label={t("visualSpeed")} type="range" min="0.25" max="4" step="0.05" value={segment.playbackRate ?? 1} onChange={(event) => updateAudioSegment(segment.id, { playbackRate: Number(event.target.value) })} />
|
||||
</div> : null}
|
||||
{isVoiceClip ? <label className="audio-property-slider">
|
||||
<span><b>{t("fadeIn")}</b><em>{(segment.fadeIn ?? 0).toFixed(1)}s</em></span>
|
||||
<input type="range" min="0" max={Math.min(3, segment.duration / 2)} step="0.1" value={segment.fadeIn ?? 0} onChange={(event) => updateAudioSegment(segment.id, { fadeIn: Number(event.target.value) })} />
|
||||
</label>
|
||||
<label className="audio-property-slider">
|
||||
</label> : null}
|
||||
{isVoiceClip ? <label className="audio-property-slider">
|
||||
<span><b>{t("fadeOut")}</b><em>{(segment.fadeOut ?? 0).toFixed(1)}s</em></span>
|
||||
<input type="range" min="0" max={Math.min(3, segment.duration / 2)} step="0.1" value={segment.fadeOut ?? 0} onChange={(event) => updateAudioSegment(segment.id, { fadeOut: Number(event.target.value) })} />
|
||||
</label>
|
||||
</label> : null}
|
||||
<div className="audio-context-actions">
|
||||
<button className={`panel-secondary ${segment.reversed ? "is-active" : ""}`} type="button" disabled={segment.reversing} onClick={() => toggleAudioSegmentReverse(segment.id)}>
|
||||
{isVoiceClip ? <button className={`panel-secondary ${segment.reversed ? "is-active" : ""}`} type="button" disabled={segment.reversing} onClick={() => toggleAudioSegmentReverse(segment.id)}>
|
||||
{segment.reversing ? t("audioReversing") : segment.reversed ? t("audioReverseRestore") : t("audioReverse")}
|
||||
</button>
|
||||
<button className="panel-secondary" type="button" onClick={() => downloadBlob(segment.blob, `${segment.name || "voiceover"}.wav`)}>{t("downloadAudioClip")}</button>
|
||||
</button> : null}
|
||||
<button className="panel-secondary" type="button" onClick={() => downloadBlob(segment.blob, `${segment.name || "audio"}.wav`)}>{t("downloadAudioClip")}</button>
|
||||
<button className="panel-secondary is-danger" type="button" onClick={() => deleteAudioSegment(segment.id)}><Trash size={15} />{t("deleteAudioClip")}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -463,6 +501,7 @@ export function VoicePanel({
|
||||
toggleCaptionSegmentHidden,
|
||||
deleteCaptionSegment,
|
||||
importCaptionSegments,
|
||||
addCaptionSegment,
|
||||
seekTo,
|
||||
sourceAudioBlob,
|
||||
sourceAudioLinked,
|
||||
@@ -489,6 +528,10 @@ export function VoicePanel({
|
||||
generateAvatarAcceptanceFrame,
|
||||
selectedTrack,
|
||||
selectedAudioSegment,
|
||||
selectedTrackAudioSegment,
|
||||
audioClipInspectorOpen = false,
|
||||
updateSelectedTrackAudioSegment,
|
||||
deleteSelectedTrackAudioSegment,
|
||||
updateAudioSegment,
|
||||
toggleAudioSegmentReverse,
|
||||
deleteAudioSegment,
|
||||
@@ -515,7 +558,9 @@ export function VoicePanel({
|
||||
const isAvatarContext = isSmartContext && smartMode === "avatar" && avatarPanelOpen;
|
||||
const isSmartAutoContext = isSmartContext && smartMode === "auto-edit";
|
||||
const isSmartFrameContext = isSmartContext && smartMode === "smart-frame";
|
||||
const isAudioClipContext = selectedTrack === "audio" && Boolean(selectedAudioSegment);
|
||||
const audioPropertySegment = selectedTrack === "audio" ? selectedAudioSegment : selectedTrackAudioSegment;
|
||||
const isAudioClipContext = Boolean(selectedTrack === "audio" && selectedAudioSegment)
|
||||
|| Boolean(audioClipInspectorOpen && ["source", "music"].includes(selectedTrack) && audioPropertySegment);
|
||||
const isVisualContext = !isSmartContext && selectedTrack === "image";
|
||||
const isStickerContext = selectedTrack === "sticker" && Boolean(selectedStickerSegment);
|
||||
const isOverlayContext = selectedTrack === "overlay" && Boolean(selectedVisualOverlay);
|
||||
@@ -536,7 +581,7 @@ export function VoicePanel({
|
||||
: isAvatarContext
|
||||
? t("avatarPortingStatus")
|
||||
: isAudioClipContext
|
||||
? `${formatTime(selectedAudioSegment.duration)} · ${selectedAudioSegment.start.toFixed(1)}s`
|
||||
? `${formatTime(audioPropertySegment.duration)} · ${audioPropertySegment.start.toFixed(1)}s`
|
||||
: statusText === "模型待命"
|
||||
? t("modelReady")
|
||||
: statusText;
|
||||
@@ -557,7 +602,7 @@ export function VoicePanel({
|
||||
}, [activeTool, smartMode]);
|
||||
|
||||
return (
|
||||
<aside ref={panelRef} className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""} ${isVisualContext ? "is-visual-context" : ""}`}>
|
||||
<aside ref={panelRef} className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""} ${isStickerContext ? "is-sticker-context" : ""} ${isVisualContext ? "is-visual-context" : ""}`}>
|
||||
<div className="panel-title-row">
|
||||
<h1>{title}</h1>
|
||||
<span className={`status-pill ${isCaptionContext ? "done" : status}`}>
|
||||
@@ -656,6 +701,7 @@ export function VoicePanel({
|
||||
toggleCaptionSegmentHidden={toggleCaptionSegmentHidden}
|
||||
deleteCaptionSegment={deleteCaptionSegment}
|
||||
importCaptionSegments={importCaptionSegments}
|
||||
addCaptionSegment={addCaptionSegment}
|
||||
seekTo={seekTo}
|
||||
sourceAudioBlob={sourceAudioBlob}
|
||||
generateCaptionsFromSourceAudio={generateCaptionsFromSourceAudio}
|
||||
@@ -701,7 +747,7 @@ export function VoicePanel({
|
||||
|
||||
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} avatarJob={avatarJob} generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame} /> : null}
|
||||
|
||||
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={selectedAudioSegment} updateAudioSegment={updateAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={deleteAudioSegment} downloadBlob={downloadBlob} /> : null}
|
||||
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={{ ...audioPropertySegment, id: audioPropertySegment.id || audioPropertySegment.segmentId }} updateAudioSegment={selectedTrack === "audio" ? updateAudioSegment : updateSelectedTrackAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={selectedTrack === "audio" ? deleteAudioSegment : deleteSelectedTrackAudioSegment} downloadBlob={downloadBlob} /> : null}
|
||||
|
||||
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && !isOverlayContext && voiceTab === "synthesis" ? (
|
||||
<VoiceSynthesisPanel
|
||||
|
||||
@@ -482,6 +482,9 @@ export function ToolPanel(props) {
|
||||
setSelectedStickerId,
|
||||
handleStickerPointerDown,
|
||||
handleStickerClick,
|
||||
confirmStickerSelection,
|
||||
closeMobilePanel,
|
||||
mobilePanelOpen,
|
||||
audioBlob,
|
||||
audioDuration,
|
||||
sourceAudioBlob,
|
||||
@@ -784,6 +787,9 @@ export function ToolPanel(props) {
|
||||
t={t}
|
||||
onStickerPointerDown={handleStickerPointerDown}
|
||||
onStickerClick={handleStickerClick}
|
||||
onStickerConfirm={confirmStickerSelection}
|
||||
closeMobilePanel={closeMobilePanel}
|
||||
mobilePanelOpen={mobilePanelOpen}
|
||||
onSelect={(id) => {
|
||||
setSelectedStickerId(id);
|
||||
notify(t("stickerApplied"));
|
||||
@@ -1207,6 +1213,9 @@ function StickerPanel({
|
||||
t,
|
||||
onStickerPointerDown,
|
||||
onStickerClick,
|
||||
onStickerConfirm,
|
||||
closeMobilePanel,
|
||||
mobilePanelOpen,
|
||||
}) {
|
||||
const [activeCategory, setActiveCategory] = useState("all");
|
||||
const [visibleCount, setVisibleCount] = useState(STICKER_PAGE_SIZE);
|
||||
@@ -1222,6 +1231,7 @@ function StickerPanel({
|
||||
);
|
||||
const visibleStickers = filteredStickers.slice(0, visibleCount);
|
||||
const hasMore = visibleCount < filteredStickers.length;
|
||||
const selectedSticker = stickerOptions.find((option) => option.id === selectedId) ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
setVisibleCount(STICKER_PAGE_SIZE);
|
||||
@@ -1319,6 +1329,18 @@ function StickerPanel({
|
||||
) : (
|
||||
<span className="sticker-load-sentinel" ref={loadMoreRef} aria-hidden="true" />
|
||||
)}
|
||||
{selectedSticker && mobilePanelOpen ? createPortal((
|
||||
<div className="mobile-sticker-actions" aria-label={t("mobileStickerActions")}>
|
||||
<button type="button" className="is-secondary" onClick={() => {
|
||||
onSelect(emptySticker.id);
|
||||
closeMobilePanel?.();
|
||||
}}>{t("mobileStickerCancel")}</button>
|
||||
<button type="button" onClick={() => {
|
||||
onStickerConfirm?.(selectedSticker);
|
||||
closeMobilePanel?.();
|
||||
}}>{t("addSticker")}</button>
|
||||
</div>
|
||||
), document.body) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { X } from "@phosphor-icons/react";
|
||||
import { getWaveformDisplayPeaks, isWaveformPlaceholder } from "../lib/waveform.js";
|
||||
|
||||
export function IconButton({ label, children, active = false, disabled = false, onClick }) {
|
||||
return (
|
||||
@@ -45,10 +46,11 @@ export function Popover({ children, onClose, className = "" }) {
|
||||
}
|
||||
|
||||
export function WaveformStrip({ peaks, active = false, hidden = false }) {
|
||||
const safePeaks = Array.isArray(peaks) ? peaks : [];
|
||||
const safePeaks = getWaveformDisplayPeaks(peaks);
|
||||
const placeholder = isWaveformPlaceholder(peaks);
|
||||
return (
|
||||
<div
|
||||
className={`waveform-strip ${active ? "is-active" : ""} ${hidden ? "is-muted" : ""}`}
|
||||
className={`waveform-strip ${active ? "is-active" : ""} ${hidden ? "is-muted" : ""} ${placeholder ? "is-placeholder" : ""}`}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{safePeaks.map((peak, index) => (
|
||||
|
||||
@@ -39,7 +39,7 @@ export function useFileUpload(deps) {
|
||||
video.onloadedmetadata = () => {
|
||||
const duration = Math.min(MAX_TIMELINE_DURATION_SECONDS, Math.max(0.5, video.duration || 1));
|
||||
const width = video.videoWidth || 0; const height = video.videoHeight || 0;
|
||||
const patch = { meta: `${width || "?"} x ${height || "?"} · ${formatClock(duration)}`, duration, width, height, type: "video" };
|
||||
const patch = { meta: `${width || "?"} x ${height || "?"} · ${formatClock(duration)}`, duration, width, height, type: "video", src: asset.src };
|
||||
update(asset.id, patch); deps.updateVisualAssetInTimeline(asset.id, patch);
|
||||
extractVideoTrackFrames(asset.src, { duration, width, height }).then((trackFrames) => {
|
||||
if (!trackFrames.length) return;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getLinkedSourceAudioState } from "../lib/sourceAudioSync.js";
|
||||
export function syncTimelineAudioElement(media, { active, shouldPlay, expectedTime, playbackRate = 1 }) {
|
||||
if (!media) return;
|
||||
media.playbackRate = playbackRate;
|
||||
if ("preservesPitch" in media) media.preservesPitch = true;
|
||||
if (!shouldPlay || !active) {
|
||||
if (!media.paused) media.pause();
|
||||
return;
|
||||
@@ -28,8 +29,9 @@ export function syncVoiceAudioSegments({ segments, refs, timelineTime, isPlaying
|
||||
return;
|
||||
}
|
||||
const active = isTimelineTimeInsideTrack(timelineTime, segment.start, segment.duration);
|
||||
const expected = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
|
||||
syncTimelineAudioElement(audio, { active, shouldPlay: true, expectedTime: expected });
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(segment.playbackRate) || 1));
|
||||
const expected = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration) * playbackRate;
|
||||
syncTimelineAudioElement(audio, { active, shouldPlay: true, expectedTime: expected, playbackRate });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -56,16 +58,20 @@ export function useMediaSync(d) {
|
||||
useEffect(() => { if (d.musicRef.current) d.musicRef.current.volume = d.musicVolume; }, [d.musicVolume, d.musicUrl]);
|
||||
useEffect(() => {
|
||||
const music = d.musicRef.current; if (!music || !d.musicUrl) return;
|
||||
const active = isTimelineTimeInsideTrack(d.currentTime, d.musicStart, d.musicDuration);
|
||||
const expected = getTimelineTrackLocalTime(d.currentTime, d.musicStart, d.musicDuration);
|
||||
const segments = d.musicSegments?.length ? d.musicSegments : [{ start: d.musicStart, duration: d.musicDuration, sourceStart: 0, playbackRate: 1 }];
|
||||
const segment = segments.find((item) => isTimelineTimeInsideTrack(d.currentTime, item.start, item.duration));
|
||||
const active = Boolean(segment);
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(segment?.playbackRate) || 1));
|
||||
const expected = segment ? Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(d.currentTime, segment.start, segment.duration) * playbackRate : 0;
|
||||
const play = d.isPlaying && d.trackVisibility?.music !== false && active;
|
||||
syncTimelineAudioElement(music, { active, shouldPlay: play, expectedTime: expected });
|
||||
}, [d.currentTime, d.isPlaying, d.musicDuration, d.musicStart, d.musicUrl, d.trackVisibility.music]);
|
||||
syncTimelineAudioElement(music, { active, shouldPlay: play, expectedTime: expected, playbackRate });
|
||||
}, [d.currentTime, d.isPlaying, d.musicDuration, d.musicSegments, d.musicStart, d.musicUrl, d.trackVisibility.music]);
|
||||
useEffect(() => { d.currentTimeRef.current = d.currentTime; }, [d.currentTime]);
|
||||
useEffect(() => { d.setPreviewVideoMediaTime(d.previewVisualType === "video" ? Math.max(0, Number(d.previewVisualSegment?.sourceStart) || 0) : 0); }, [d.previewVisualSegment?.id, d.previewVisualSrc, d.previewVisualType]);
|
||||
useEffect(() => {
|
||||
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
|
||||
v.playbackRate = Math.max(0.25, Math.min(4, Number(d.previewVisualSegment?.playbackRate) || 1));
|
||||
if ("preservesPitch" in v) v.preservesPitch = true;
|
||||
}, [d.previewVisualSegment?.playbackRate, d.previewVisualSrc, d.previewVisualType]);
|
||||
useEffect(() => {
|
||||
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
|
||||
@@ -114,7 +120,13 @@ export function useMediaSync(d) {
|
||||
if (d.sourceAudioRef.current && clamped !== time) d.sourceAudioRef.current.currentTime = d.sourceAudioLinked && d.linkedSourceAudioSegments?.length
|
||||
? getLinkedSourceAudioState(d.linkedSourceAudioSegments, clamped).sourceTime
|
||||
: getTimelineTrackLocalTime(clamped, d.sourceAudioStart, d.sourceAudioDuration);
|
||||
if (d.musicRef.current && clamped !== time) d.musicRef.current.currentTime = getTimelineTrackLocalTime(clamped, d.musicStart, d.musicDuration);
|
||||
if (d.musicRef.current && clamped !== time) {
|
||||
const segment = d.musicSegments?.find((item) => isTimelineTimeInsideTrack(clamped, item.start, item.duration));
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(segment?.playbackRate) || 1));
|
||||
d.musicRef.current.currentTime = segment
|
||||
? Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(clamped, segment.start, segment.duration) * playbackRate
|
||||
: getTimelineTrackLocalTime(clamped, d.musicStart, d.musicDuration);
|
||||
}
|
||||
return clamped;
|
||||
}); }, [d.linkedSourceAudioSegments, d.musicDuration, d.musicStart, d.sourceAudioDuration, d.sourceAudioLinked, d.sourceAudioStart, d.timelineDuration]);
|
||||
}); }, [d.linkedSourceAudioSegments, d.musicDuration, d.musicSegments, d.musicStart, d.sourceAudioDuration, d.sourceAudioLinked, d.sourceAudioStart, d.timelineDuration]);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ function makeMedia(overrides = {}) {
|
||||
currentTime: 0,
|
||||
paused: true,
|
||||
playbackRate: 1,
|
||||
preservesPitch: true,
|
||||
play: vi.fn(() => Promise.resolve()),
|
||||
pause: vi.fn(),
|
||||
...overrides,
|
||||
@@ -40,6 +41,20 @@ describe("syncTimelineAudioElement", () => {
|
||||
expect(media.play).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("maps a sped-up voice to source time and native playback rate", () => {
|
||||
const media = makeMedia({ paused: true });
|
||||
syncVoiceAudioSegments({
|
||||
segments: [{ id: "fast", start: 1, duration: 4, sourceStart: 0.5, playbackRate: 2 }],
|
||||
refs: { current: new Map([["fast", media]]) },
|
||||
timelineTime: 2.5,
|
||||
isPlaying: true,
|
||||
audible: true,
|
||||
});
|
||||
expect(media.currentTime).toBe(3.5);
|
||||
expect(media.playbackRate).toBe(2);
|
||||
expect(media.preservesPitch).toBe(true);
|
||||
});
|
||||
|
||||
it("aligns once when native playback starts", () => {
|
||||
const media = makeMedia({ currentTime: 0.2 });
|
||||
syncTimelineAudioElement(media, { active: true, shouldPlay: true, expectedTime: 3.5 });
|
||||
|
||||
@@ -44,10 +44,10 @@ export function useVideoExport(d) {
|
||||
sourceAudioBlob: exportSourceAudioBlob, sourceAudioVolume: d.sourceAudioBlob ? d.sourceAudioVolume : 1,
|
||||
sourceAudioSegments: exportSourceAudioSegments,
|
||||
sourceAudioStart: d.sourceAudioStart, musicBlob: d.trackVisibility.music ? d.musicBlob : null,
|
||||
musicVolume: d.musicVolume, musicStart: d.musicStart, text: d.script, captionSegments: d.captionSegments,
|
||||
musicVolume: d.musicVolume, musicStart: d.musicStart, musicSegments: d.musicSegments, text: d.script, captionSegments: d.captionSegments,
|
||||
duration: Math.max(d.trackVisibility.audio ? d.voiceTrackDuration : 0, d.captionDuration,
|
||||
d.trackVisibility.source && d.sourceAudioBlob ? d.sourceAudioTimelineEnd : 0,
|
||||
d.trackVisibility.music && d.musicBlob ? d.musicStart + d.musicDuration : 0,
|
||||
d.trackVisibility.music && d.musicBlob ? d.musicTimelineEnd : 0,
|
||||
d.trackVisibility.sticker ? d.stickerDuration : 0, d.imageDuration, estimateDuration(d.script)),
|
||||
ratio: d.ratio, fitMode: d.fitMode, filter: d.selectedFilter.css,
|
||||
captionsEnabled: d.captionsEnabled && d.trackVisibility.caption,
|
||||
|
||||
+42
-11
@@ -41,6 +41,20 @@ const MOBILE_DRAWER_COPY = {
|
||||
ru: { mobilePanelView: "Вид панели", mobileDrawerTools: "Инструменты", properties: "Свойства", mobileAddMedia: "Добавить медиа", mobileAssetActions: "Добавить медиа", mobileAssetSelected: "Выбранный материал", mobileAssetChooseDestination: "Выберите, куда его добавить", mobileAddToMainTrack: "На основную дорожку", mobileAddToVoice: "В озвучку", mobileAddToMusic: "В музыку" },
|
||||
};
|
||||
|
||||
const MOBILE_CLIP_ACTION_COPY = {
|
||||
zh: { mobileClipEdit: "编辑", mobileClipAudio: "音频", mobileClipCaptions: "字幕", mobileClipSeparate: "人声分离", mobileClipSplit: "分割", mobileClipCopy: "复制", mobileClipDelete: "删除", mobileClipDismiss: "返回" },
|
||||
en: { mobileClipEdit: "Edit", mobileClipAudio: "Audio", mobileClipCaptions: "Captions", mobileClipSeparate: "Separate", mobileClipSplit: "Split", mobileClipCopy: "Copy", mobileClipDelete: "Delete", mobileClipDismiss: "Back" },
|
||||
ja: { mobileClipEdit: "編集", mobileClipAudio: "音声", mobileClipCaptions: "字幕", mobileClipSeparate: "分離", mobileClipSplit: "分割", mobileClipCopy: "複製", mobileClipDelete: "削除", mobileClipDismiss: "戻る" },
|
||||
ko: { mobileClipEdit: "편집", mobileClipAudio: "오디오", mobileClipCaptions: "자막", mobileClipSeparate: "분리", mobileClipSplit: "분할", mobileClipCopy: "복제", mobileClipDelete: "삭제", mobileClipDismiss: "뒤로" },
|
||||
es: { mobileClipEdit: "Editar", mobileClipAudio: "Audio", mobileClipCaptions: "Subtítulos", mobileClipSeparate: "Separar", mobileClipSplit: "Dividir", mobileClipCopy: "Copiar", mobileClipDelete: "Eliminar", mobileClipDismiss: "Volver" },
|
||||
fr: { mobileClipEdit: "Modifier", mobileClipAudio: "Audio", mobileClipCaptions: "Sous-titres", mobileClipSeparate: "Séparer", mobileClipSplit: "Scinder", mobileClipCopy: "Copier", mobileClipDelete: "Supprimer", mobileClipDismiss: "Retour" },
|
||||
de: { mobileClipEdit: "Bearbeiten", mobileClipAudio: "Audio", mobileClipCaptions: "Untertitel", mobileClipSeparate: "Trennen", mobileClipSplit: "Teilen", mobileClipCopy: "Kopieren", mobileClipDelete: "Löschen", mobileClipDismiss: "Zurück" },
|
||||
pt: { mobileClipEdit: "Editar", mobileClipAudio: "Áudio", mobileClipCaptions: "Legendas", mobileClipSeparate: "Separar", mobileClipSplit: "Dividir", mobileClipCopy: "Copiar", mobileClipDelete: "Excluir", mobileClipDismiss: "Voltar" },
|
||||
th: { mobileClipEdit: "แก้ไข", mobileClipAudio: "เสียง", mobileClipCaptions: "คำบรรยาย", mobileClipSeparate: "แยกเสียง", mobileClipSplit: "แบ่ง", mobileClipCopy: "คัดลอก", mobileClipDelete: "ลบ", mobileClipDismiss: "กลับ" },
|
||||
vi: { mobileClipEdit: "Sửa", mobileClipAudio: "Âm thanh", mobileClipCaptions: "Phụ đề", mobileClipSeparate: "Tách giọng", mobileClipSplit: "Tách", mobileClipCopy: "Sao chép", mobileClipDelete: "Xóa", mobileClipDismiss: "Quay lại" },
|
||||
ru: { mobileClipEdit: "Изменить", mobileClipAudio: "Аудио", mobileClipCaptions: "Субтитры", mobileClipSeparate: "Разделить", mobileClipSplit: "Разделить", mobileClipCopy: "Копировать", mobileClipDelete: "Удалить", mobileClipDismiss: "Назад" },
|
||||
};
|
||||
|
||||
const VISUAL_EDITOR_COPY = {
|
||||
zh: { visualSelectClip: "请先选择 Visuals 轨上的片段", visualKeyframes: "关键帧", visualFrames: "帧", visualScale: "缩放", visualPositionX: "水平位置", visualPositionY: "垂直位置", visualRotation: "旋转", visualOpacity: "不透明度", visualDeleteKeyframe: "删除当前位置关键帧", visualMask: "蒙版", visualMaskResize: "调整蒙版大小", visualClipScoped: "片段级", visualMaskNone: "无", visualMaskRectangle: "矩形", visualMaskRounded: "圆角", visualMaskCircle: "圆形", visualFeather: "羽化", visualHorizontal: "水平", visualVertical: "垂直", visualWidth: "宽度", visualHeight: "高度", visualDiameter: "直径", visualCornerRadius: "圆角半径", visualMaskNoneHint: "选择一种蒙版后显示对应参数", visualInvertMask: "反向蒙版", visualEffects: "画面效果" },
|
||||
en: { visualSelectClip: "Select a clip on the Visuals track", visualKeyframes: "Keyframes", visualFrames: "frames", visualScale: "Scale", visualPositionX: "Horizontal position", visualPositionY: "Vertical position", visualRotation: "Rotation", visualOpacity: "Opacity", visualDeleteKeyframe: "Delete keyframe at playhead", visualMask: "Mask", visualMaskResize: "Resize mask", visualClipScoped: "Clip", visualMaskNone: "None", visualMaskRectangle: "Rectangle", visualMaskRounded: "Rounded", visualMaskCircle: "Circle", visualFeather: "Feather", visualHorizontal: "Horizontal", visualVertical: "Vertical", visualWidth: "Width", visualHeight: "Height", visualDiameter: "Diameter", visualCornerRadius: "Corner radius", visualMaskNoneHint: "Choose a mask to show its parameters", visualInvertMask: "Invert mask", visualEffects: "Visual effects" },
|
||||
@@ -324,17 +338,32 @@ const STICKER_EDITOR_COPY = {
|
||||
vi: { stickerProperties: "Thuộc tính nhãn dán", stickerHorizontalPosition: "Vị trí ngang", stickerVerticalPosition: "Vị trí dọc", stickerScale: "Tỷ lệ", stickerRotation: "Xoay", stickerOpacity: "Độ mờ", deleteSticker: "Xóa nhãn dán", stickerAddedToTrack: "Đã thêm nhãn dán vào rãnh" },
|
||||
};
|
||||
|
||||
const MOBILE_STICKER_COPY = {
|
||||
zh: { addSticker: "添加贴纸", mobileStickerCancel: "取消", mobileStickerActions: "贴纸选择操作" },
|
||||
en: { addSticker: "Add sticker", mobileStickerCancel: "Cancel", mobileStickerActions: "Sticker selection actions" },
|
||||
ja: { addSticker: "ステッカーを追加", mobileStickerCancel: "キャンセル", mobileStickerActions: "ステッカー選択操作" },
|
||||
ko: { addSticker: "스티커 추가", mobileStickerCancel: "취소", mobileStickerActions: "스티커 선택 작업" },
|
||||
es: { addSticker: "Añadir sticker", mobileStickerCancel: "Cancelar", mobileStickerActions: "Acciones de selección de sticker" },
|
||||
fr: { addSticker: "Ajouter le sticker", mobileStickerCancel: "Annuler", mobileStickerActions: "Actions de sélection du sticker" },
|
||||
de: { addSticker: "Sticker hinzufügen", mobileStickerCancel: "Abbrechen", mobileStickerActions: "Sticker-Auswahlaktionen" },
|
||||
pt: { addSticker: "Adicionar sticker", mobileStickerCancel: "Cancelar", mobileStickerActions: "Ações de seleção de sticker" },
|
||||
th: { addSticker: "เพิ่มสติกเกอร์", mobileStickerCancel: "ยกเลิก", mobileStickerActions: "การทำงานสำหรับเลือกสติกเกอร์" },
|
||||
vi: { addSticker: "Thêm sticker", mobileStickerCancel: "Hủy", mobileStickerActions: "Thao tác chọn sticker" },
|
||||
ru: { addSticker: "Добавить стикер", mobileStickerCancel: "Отмена", mobileStickerActions: "Действия с выбранным стикером" },
|
||||
};
|
||||
|
||||
const CAPTION_DEFAULT_COPY = {
|
||||
zh: { newCaptionDefault: "新的字幕片段" },
|
||||
en: { newCaptionDefault: "New caption" },
|
||||
ja: { newCaptionDefault: "新しい字幕" },
|
||||
ko: { newCaptionDefault: "새 자막" },
|
||||
es: { newCaptionDefault: "Nuevo subtítulo" },
|
||||
fr: { newCaptionDefault: "Nouveau sous-titre" },
|
||||
de: { newCaptionDefault: "Neue Untertitelzeile" },
|
||||
pt: { newCaptionDefault: "Nova legenda" },
|
||||
th: { newCaptionDefault: "คำบรรยายใหม่" },
|
||||
vi: { newCaptionDefault: "Phụ đề mới" },
|
||||
zh: { newCaptionDefault: "新的字幕片段", addCaption: "添加字幕", captionTrackLocked: "字幕轨已锁定,无法新增字幕片段" },
|
||||
en: { newCaptionDefault: "New caption", addCaption: "Add caption", captionTrackLocked: "Unlock the caption track to add a caption" },
|
||||
ja: { newCaptionDefault: "新しい字幕", addCaption: "字幕を追加", captionTrackLocked: "字幕を追加するには字幕トラックのロックを解除してください" },
|
||||
ko: { newCaptionDefault: "새 자막", addCaption: "자막 추가", captionTrackLocked: "자막을 추가하려면 자막 트랙 잠금을 해제하세요" },
|
||||
es: { newCaptionDefault: "Nuevo subtítulo", addCaption: "Añadir subtítulo", captionTrackLocked: "Desbloquea la pista de subtítulos para añadir uno" },
|
||||
fr: { newCaptionDefault: "Nouveau sous-titre", addCaption: "Ajouter un sous-titre", captionTrackLocked: "Déverrouillez la piste de sous-titres pour en ajouter un" },
|
||||
de: { newCaptionDefault: "Neue Untertitelzeile", addCaption: "Untertitel hinzufügen", captionTrackLocked: "Entsperre die Untertitelspur, um einen Untertitel hinzuzufügen" },
|
||||
pt: { newCaptionDefault: "Nova legenda", addCaption: "Adicionar legenda", captionTrackLocked: "Desbloqueie a faixa de legendas para adicionar uma legenda" },
|
||||
th: { newCaptionDefault: "คำบรรยายใหม่", addCaption: "เพิ่มคำบรรยาย", captionTrackLocked: "ปลดล็อกแทร็กคำบรรยายเพื่อเพิ่มคำบรรยาย" },
|
||||
vi: { newCaptionDefault: "Phụ đề mới", addCaption: "Thêm phụ đề", captionTrackLocked: "Mở khóa rãnh phụ đề để thêm phụ đề" },
|
||||
ru: { newCaptionDefault: "Новые субтитры", addCaption: "Добавить субтитры", captionTrackLocked: "Разблокируйте дорожку субтитров, чтобы добавить фрагмент" },
|
||||
};
|
||||
|
||||
const SMART_WORKSPACE_COPY = {
|
||||
@@ -1848,7 +1877,9 @@ export function createTranslator(languageId) {
|
||||
const assetDropCopy = ASSET_DROP_COPY[copyLanguage] ?? ASSET_DROP_COPY.en;
|
||||
const autoCaptionStatusCopy = AUTO_CAPTION_STATUS_COPY[copyLanguage] ?? AUTO_CAPTION_STATUS_COPY.en;
|
||||
const mobileDrawerCopy = MOBILE_DRAWER_COPY[languageId] ?? MOBILE_DRAWER_COPY.en;
|
||||
return (key, fallbackText) => mobileDrawerCopy[key] ?? MOBILE_DRAWER_COPY.en[key] ?? srtImportCopy[key] ?? exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? assetPreviewCopy[key] ?? ASSET_PREVIEW_COPY.en[key] ?? assetDropCopy[key] ?? ASSET_DROP_COPY.en[key] ?? autoCaptionStatusCopy[key] ?? AUTO_CAPTION_STATUS_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
|
||||
const mobileClipActionCopy = MOBILE_CLIP_ACTION_COPY[languageId] ?? MOBILE_CLIP_ACTION_COPY.en;
|
||||
const mobileStickerCopy = MOBILE_STICKER_COPY[languageId] ?? MOBILE_STICKER_COPY.en;
|
||||
return (key, fallbackText) => mobileStickerCopy[key] ?? MOBILE_STICKER_COPY.en[key] ?? mobileClipActionCopy[key] ?? MOBILE_CLIP_ACTION_COPY.en[key] ?? mobileDrawerCopy[key] ?? MOBILE_DRAWER_COPY.en[key] ?? srtImportCopy[key] ?? exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? assetPreviewCopy[key] ?? ASSET_PREVIEW_COPY.en[key] ?? assetDropCopy[key] ?? ASSET_DROP_COPY.en[key] ?? autoCaptionStatusCopy[key] ?? AUTO_CAPTION_STATUS_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
|
||||
}
|
||||
|
||||
export function translateOptionName(languageId, name) {
|
||||
|
||||
@@ -13,6 +13,16 @@ describe("mobile drawer translations", () => {
|
||||
expect(t("mobileAddToMainTrack")).not.toBe("mobileAddToMainTrack");
|
||||
expect(t("mobileAddToVoice")).not.toBe("mobileAddToVoice");
|
||||
expect(t("mobileAddToMusic")).not.toBe("mobileAddToMusic");
|
||||
expect(t("mobileClipEdit")).not.toBe("mobileClipEdit");
|
||||
expect(t("mobileClipAudio")).not.toBe("mobileClipAudio");
|
||||
expect(t("mobileClipCaptions")).not.toBe("mobileClipCaptions");
|
||||
expect(t("mobileClipSeparate")).not.toBe("mobileClipSeparate");
|
||||
expect(t("mobileClipSplit")).not.toBe("mobileClipSplit");
|
||||
expect(t("mobileClipCopy")).not.toBe("mobileClipCopy");
|
||||
expect(t("mobileClipDelete")).not.toBe("mobileClipDelete");
|
||||
expect(t("addSticker")).not.toBe("addSticker");
|
||||
expect(t("mobileStickerActions")).not.toBe("mobileStickerActions");
|
||||
expect(t("mobileStickerCancel")).not.toBe("mobileStickerCancel");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -10,4 +10,10 @@ describe("SRT import translations", () => {
|
||||
}
|
||||
expect(createTranslator("ru")("importSrt")).toBe("Импорт SRT");
|
||||
});
|
||||
|
||||
it("localizes the manual add-caption action in every supported language", () => {
|
||||
for (const language of APP_LANGUAGES) {
|
||||
expect(createTranslator(language.id)("addCaption"), language.id).not.toBe("addCaption");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,10 @@ export function resolveVisualDropIntent({ track = "image" } = {}) {
|
||||
return track === "overlay" ? "overlay" : "image";
|
||||
}
|
||||
|
||||
export function resolveStickerSelectionIntent({ isMobile = false } = {}) {
|
||||
return isMobile ? "stage" : "add";
|
||||
}
|
||||
|
||||
export function createAssetDragControls(deps) {
|
||||
const findAssetById = (id) => {
|
||||
if (!id) return null;
|
||||
@@ -92,6 +96,12 @@ export function createAssetDragControls(deps) {
|
||||
const handleStickerClick = (event, sticker) => {
|
||||
if (deps.suppressAssetClickRef.current === sticker.id) { deps.suppressAssetClickRef.current = ""; event.preventDefault(); event.stopPropagation(); return; }
|
||||
deps.setSelectedStickerId(sticker.id);
|
||||
if (resolveStickerSelectionIntent({ isMobile: window.matchMedia?.("(max-width: 760px)").matches })) return;
|
||||
deps.addStickerAssetToTimeline(sticker, { startTime: deps.currentTime });
|
||||
};
|
||||
const confirmStickerSelection = (sticker) => {
|
||||
if (!sticker?.src) return;
|
||||
deps.setSelectedStickerId(sticker.id);
|
||||
deps.addStickerAssetToTimeline(sticker, { startTime: deps.currentTime });
|
||||
};
|
||||
const handleTrackAssetDragOver = (event, track) => {
|
||||
@@ -109,6 +119,6 @@ export function createAssetDragControls(deps) {
|
||||
deps.setAssetDropPosition((current) => current.track === target ? { track: "", percent: 50 } : current);
|
||||
};
|
||||
return { canDropAssetOnTrack, findAssetById, getActiveDraggedAsset, getDraggedAsset, getTimelineDropPercent,
|
||||
handleAssetClick, handleAssetDragEnd, handleAssetDragStart, handleAssetPointerDown, handleStickerClick,
|
||||
confirmStickerSelection, handleAssetClick, handleAssetDragEnd, handleAssetDragStart, handleAssetPointerDown, handleStickerClick,
|
||||
handleTrackAssetDragLeave, handleTrackAssetDragOver, triggerAssetDropPulse };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveVisualDropIntent } from "./assetDragControls.js";
|
||||
import { resolveStickerSelectionIntent, resolveVisualDropIntent } from "./assetDragControls.js";
|
||||
|
||||
describe("visual asset drop intent", () => {
|
||||
it("uses the explicit target track instead of guessing from pointer position", () => {
|
||||
@@ -7,3 +7,10 @@ describe("visual asset drop intent", () => {
|
||||
expect(resolveVisualDropIntent({ track: "overlay" })).toBe("overlay");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sticker selection intent", () => {
|
||||
it("stages a mobile tap and keeps desktop click-to-add behavior", () => {
|
||||
expect(resolveStickerSelectionIntent({ isMobile: true })).toBe("stage");
|
||||
expect(resolveStickerSelectionIntent({ isMobile: false })).toBe("add");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,38 @@
|
||||
import { reverseAudioBlob } from "./media.js";
|
||||
|
||||
export function normalizeAudioPlaybackRate(value) {
|
||||
return Math.max(0.25, Math.min(4, Number(value) || 1));
|
||||
}
|
||||
|
||||
export function updateAudioSegmentPlaybackRate(segment, value) {
|
||||
const previousRate = normalizeAudioPlaybackRate(segment?.playbackRate);
|
||||
const playbackRate = normalizeAudioPlaybackRate(value);
|
||||
const sourceDuration = Math.max(0.01, Number(segment?.sourceDuration) || (Number(segment?.duration) || 0.01) * previousRate);
|
||||
return {
|
||||
...segment,
|
||||
playbackRate,
|
||||
sourceDuration,
|
||||
duration: sourceDuration / playbackRate,
|
||||
fadeIn: Math.min(Number(segment?.fadeIn) || 0, sourceDuration / playbackRate / 2),
|
||||
fadeOut: Math.min(Number(segment?.fadeOut) || 0, sourceDuration / playbackRate / 2),
|
||||
};
|
||||
}
|
||||
|
||||
export function createAudioClipActions(d) {
|
||||
const updateAudioSegment = (id, patch) => d.setAudioSegments((segments) => segments.map((segment) => {
|
||||
if (segment.id !== id) return segment;
|
||||
const next = { ...segment, ...patch };
|
||||
const next = Number.isFinite(patch.playbackRate)
|
||||
? { ...updateAudioSegmentPlaybackRate(segment, patch.playbackRate), ...patch, playbackRate: normalizeAudioPlaybackRate(patch.playbackRate) }
|
||||
: { ...segment, ...patch };
|
||||
if (Number.isFinite(patch.start) && patch.start !== segment.start) {
|
||||
const delta = patch.start - segment.start;
|
||||
d.setCaptionSegments((captions) => captions.map((caption) => caption.audioSegmentId === id
|
||||
? { ...caption, start: caption.start + delta, end: caption.end + delta } : caption));
|
||||
}
|
||||
if (Number.isFinite(patch.playbackRate) && next.duration !== segment.duration) {
|
||||
d.setCaptionSegments((captions) => captions.map((caption) => caption.audioSegmentId === id
|
||||
? { ...caption, end: next.start + next.duration } : caption));
|
||||
}
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((next.start + next.duration + 5) / 10) * 10));
|
||||
return next;
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeAudioPlaybackRate, updateAudioSegmentPlaybackRate } from "./audioClipActions.js";
|
||||
|
||||
describe("audio clip playback speed", () => {
|
||||
it("changes timeline duration while preserving source duration", () => {
|
||||
const segment = updateAudioSegmentPlaybackRate({ duration: 4, playbackRate: 1, fadeIn: 1, fadeOut: 1 }, 2);
|
||||
expect(segment).toMatchObject({ playbackRate: 2, sourceDuration: 4, duration: 2, fadeIn: 1, fadeOut: 1 });
|
||||
});
|
||||
|
||||
it("restores the original duration when returning to normal speed", () => {
|
||||
const fast = updateAudioSegmentPlaybackRate({ duration: 4, playbackRate: 1 }, 2);
|
||||
const normal = updateAudioSegmentPlaybackRate(fast, 1);
|
||||
expect(normal.duration).toBe(4);
|
||||
});
|
||||
|
||||
it("clamps supported playback speed", () => {
|
||||
expect(normalizeAudioPlaybackRate(0.1)).toBe(0.25);
|
||||
expect(normalizeAudioPlaybackRate(8)).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,8 @@ export function createAudioTrackActions(d) {
|
||||
url: nextUrl,
|
||||
start,
|
||||
duration: nextDuration,
|
||||
sourceDuration: nextDuration,
|
||||
playbackRate: 1,
|
||||
peaks: Array.isArray(nextPeaks) ? nextPeaks : [],
|
||||
volume: 1,
|
||||
fadeIn: 0,
|
||||
@@ -79,7 +81,7 @@ export function createAudioTrackActions(d) {
|
||||
const nextStart = Math.max(0, Number(options.start) || 0);
|
||||
d.setMusicStart(nextStart);
|
||||
d.setMusicPeaks(nextPeaks);
|
||||
d.setMusicSegments?.([{ id: crypto.randomUUID(), start: nextStart, duration: nextDuration, sourceStart: 0, peaks: nextPeaks }]);
|
||||
d.setMusicSegments?.([{ id: crypto.randomUUID(), start: nextStart, duration: nextDuration, sourceStart: 0, sourceDuration: nextDuration, playbackRate: 1, peaks: nextPeaks }]);
|
||||
d.setSelectedTrack("music");
|
||||
if (options.focusAudio !== false) d.setActiveTool("audio");
|
||||
d.notify(message);
|
||||
|
||||
+23
-6
@@ -26,6 +26,7 @@ import {
|
||||
} from "./visualEffects.js";
|
||||
import { resolveVisualClipAnimation } from "./visualClipAnimations.js";
|
||||
import { getStickerRenderGeometry } from "./stickerGeometry.js";
|
||||
import { createPitchPreservedAudioBuffer } from "./pitchPreservingTimeStretch.js";
|
||||
|
||||
export function getAudioRecordingFormat() {
|
||||
if (typeof MediaRecorder === "undefined") {
|
||||
@@ -796,6 +797,7 @@ export async function exportBrowserVideo({
|
||||
musicBlob,
|
||||
musicVolume = 0.35,
|
||||
musicStart = 0,
|
||||
musicSegments = [],
|
||||
text,
|
||||
captionSegments,
|
||||
duration,
|
||||
@@ -924,7 +926,13 @@ export async function exportBrowserVideo({
|
||||
: sourceAudioBlob
|
||||
? [{ blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source", start: Math.max(0, sourceAudioStart || 0) }]
|
||||
: []),
|
||||
musicBlob ? { blob: musicBlob, volume: musicVolume, role: "music", start: Math.max(0, musicStart || 0) } : null,
|
||||
...(musicBlob ? (musicSegments.length ? musicSegments.map((segment) => ({
|
||||
blob: musicBlob, volume: segment.volume ?? musicVolume, role: "music",
|
||||
start: Math.max(0, segment.start || 0), sourceOffset: Math.max(0, segment.sourceStart || 0),
|
||||
sourceDuration: Math.max(0, segment.sourceDuration || (segment.duration || 0) * normalizeVisualPlaybackRate(segment.playbackRate)),
|
||||
playbackRate: normalizeVisualPlaybackRate(segment.playbackRate), outputDuration: Math.max(0, segment.duration || 0),
|
||||
fadeIn: Math.max(0, segment.fadeIn || 0), fadeOut: Math.max(0, segment.fadeOut || 0),
|
||||
})) : [{ blob: musicBlob, volume: musicVolume, role: "music", start: Math.max(0, musicStart || 0) }]) : []),
|
||||
].filter(Boolean);
|
||||
|
||||
if (audioInputs.length) {
|
||||
@@ -949,13 +957,22 @@ export async function exportBrowserVideo({
|
||||
Number(input.sourceDuration) || decoded.duration - sourceOffset,
|
||||
decoded.duration - sourceOffset,
|
||||
));
|
||||
const outputDuration = Number(input.outputDuration) || sourceDuration / playbackRate;
|
||||
const preservePitch = Math.abs(playbackRate - 1) > 0.0001;
|
||||
const prepared = preservePitch
|
||||
? createPitchPreservedAudioBuffer(audioContext, decoded, {
|
||||
sourceOffset,
|
||||
sourceDuration,
|
||||
playbackRate,
|
||||
})
|
||||
: decoded;
|
||||
return {
|
||||
...input,
|
||||
decoded,
|
||||
playbackRate,
|
||||
sourceOffset,
|
||||
sourceDuration,
|
||||
outputDuration: Number(input.outputDuration) || sourceDuration / playbackRate,
|
||||
decoded: prepared,
|
||||
playbackRate: 1,
|
||||
sourceOffset: preservePitch ? 0 : sourceOffset,
|
||||
sourceDuration: preservePitch ? outputDuration : sourceDuration,
|
||||
outputDuration,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
const GENERIC_CLIP_ACTIONS = ["dismiss", "edit", "split", "copy", "delete"];
|
||||
const AUDIO_CLIP_ACTIONS = ["dismiss", "edit", "split", "captions", "separate", "delete"];
|
||||
const MUSIC_CLIP_ACTIONS = ["dismiss", "audio", "split", "captions", "separate", "delete"];
|
||||
const SOURCE_AUDIO_CLIP_ACTIONS = ["dismiss", "audio", "split", "captions", "delete"];
|
||||
const STICKER_CLIP_ACTIONS = ["dismiss", "properties", "copy", "delete"];
|
||||
|
||||
export function getMobileClipActionIds(track, options = {}) {
|
||||
if (track === "audio") return AUDIO_CLIP_ACTIONS;
|
||||
if (track === "music") return MUSIC_CLIP_ACTIONS;
|
||||
if (track === "source") return SOURCE_AUDIO_CLIP_ACTIONS;
|
||||
if (track === "sticker") return STICKER_CLIP_ACTIONS;
|
||||
if (track === "image" && options.canExtractSourceAudio) {
|
||||
return ["dismiss", "edit", "split", "copy", "extract-source-audio", "delete"];
|
||||
}
|
||||
return GENERIC_CLIP_ACTIONS;
|
||||
}
|
||||
|
||||
export function getMobileClipPanel() {
|
||||
return "inspector";
|
||||
}
|
||||
|
||||
export function getMobileClipPanelOrigin(track) {
|
||||
if (track === "sticker") return "sticker-clip";
|
||||
return ["audio", "source", "music"].includes(track) ? "audio-clip" : "";
|
||||
}
|
||||
|
||||
export function shouldActivateToolRailForClip(isMobile) {
|
||||
return !isMobile;
|
||||
}
|
||||
|
||||
export function resolveMobileClipActionTrack(explicitTrack, selections = {}) {
|
||||
if (explicitTrack) return explicitTrack;
|
||||
if (selections.visual) return "image";
|
||||
if (selections.overlay) return "overlay";
|
||||
if (selections.sticker) return "sticker";
|
||||
if (selections.caption) return "caption";
|
||||
if (selections.source) return "source";
|
||||
if (selections.audio) return "audio";
|
||||
if (selections.music) return "music";
|
||||
return "";
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getMobileClipActionIds,
|
||||
getMobileClipPanel,
|
||||
getMobileClipPanelOrigin,
|
||||
resolveMobileClipActionTrack,
|
||||
shouldActivateToolRailForClip,
|
||||
} from "./mobileClipActions.js";
|
||||
|
||||
describe("mobile clip actions", () => {
|
||||
it("shows audio-specific actions for voiceover and music clips", () => {
|
||||
expect(getMobileClipActionIds("audio")).toEqual(["dismiss", "edit", "split", "captions", "separate", "delete"]);
|
||||
expect(getMobileClipActionIds("music")).toEqual(["dismiss", "audio", "split", "captions", "separate", "delete"]);
|
||||
});
|
||||
|
||||
it("does not offer vocal separation for linked source-audio pieces", () => {
|
||||
expect(getMobileClipActionIds("source")).toEqual(["dismiss", "audio", "split", "captions", "delete"]);
|
||||
});
|
||||
|
||||
it("keeps visual clip actions free of audio-only commands", () => {
|
||||
expect(getMobileClipActionIds("image")).toEqual(["dismiss", "edit", "split", "copy", "delete"]);
|
||||
});
|
||||
|
||||
it("shows a compact direct-property menu for sticker clips", () => {
|
||||
expect(getMobileClipActionIds("sticker")).toEqual(["dismiss", "properties", "copy", "delete"]);
|
||||
expect(getMobileClipPanelOrigin("sticker")).toBe("sticker-clip");
|
||||
});
|
||||
|
||||
it("offers source-audio extraction only for an eligible mobile visual clip", () => {
|
||||
expect(getMobileClipActionIds("image", { canExtractSourceAudio: true })).toEqual([
|
||||
"dismiss", "edit", "split", "copy", "extract-source-audio", "delete",
|
||||
]);
|
||||
expect(getMobileClipActionIds("caption", { canExtractSourceAudio: true })).not.toContain("extract-source-audio");
|
||||
});
|
||||
|
||||
it("routes every mobile audio clip directly to its property inspector", () => {
|
||||
expect(getMobileClipPanel("audio")).toBe("inspector");
|
||||
expect(getMobileClipPanel("source")).toBe("inspector");
|
||||
expect(getMobileClipPanel("music")).toBe("inspector");
|
||||
expect(getMobileClipPanel("image")).toBe("inspector");
|
||||
});
|
||||
|
||||
it("marks all audio clips as a dedicated property-sheet session", () => {
|
||||
expect(getMobileClipPanelOrigin("audio")).toBe("audio-clip");
|
||||
expect(getMobileClipPanelOrigin("source")).toBe("audio-clip");
|
||||
expect(getMobileClipPanelOrigin("music")).toBe("audio-clip");
|
||||
});
|
||||
|
||||
it("keeps the persistent tool rail unchanged for mobile clip selection", () => {
|
||||
expect(shouldActivateToolRailForClip(true)).toBe(false);
|
||||
expect(shouldActivateToolRailForClip(false)).toBe(true);
|
||||
});
|
||||
|
||||
it("uses the pressed audio clip instead of a stale visual selection", () => {
|
||||
expect(resolveMobileClipActionTrack("audio", { visual: true, audio: true })).toBe("audio");
|
||||
expect(resolveMobileClipActionTrack("", { visual: true })).toBe("image");
|
||||
});
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from "./timeline.js";
|
||||
import { resolveVisionAnalysisAtTime } from "./vision.js";
|
||||
import { getVisualSourceTime } from "./visualEffects.js";
|
||||
import { createPitchPreservedAudioBuffer } from "./pitchPreservingTimeStretch.js";
|
||||
|
||||
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
|
||||
let aacFallbackRegistered = false;
|
||||
@@ -88,11 +89,12 @@ export async function mixOfflineAudio({
|
||||
musicBlob = null,
|
||||
musicVolume = 0.35,
|
||||
musicStart = 0,
|
||||
musicSegments = [],
|
||||
}) {
|
||||
const inputs = [
|
||||
...voiceAudioSegments.filter((item) => item.blob).map((item) => ({
|
||||
blob: item.blob, start: Math.max(0, item.start || 0), volume: item.volume ?? 1,
|
||||
sourceOffset: Math.max(0, item.sourceStart || 0), sourceDuration: Math.max(0, item.duration || 0), playbackRate: 1,
|
||||
sourceOffset: Math.max(0, item.sourceStart || 0), sourceDuration: Math.max(0, item.sourceDuration || (item.duration || 0) * (Number(item.playbackRate) || 1)), playbackRate: clamp(Number(item.playbackRate) || 1, 0.25, 4),
|
||||
fadeIn: Math.max(0, item.fadeIn || 0), fadeOut: Math.max(0, item.fadeOut || 0),
|
||||
})),
|
||||
...(sourceAudioBlob && sourceAudioSegments.length ? sourceAudioSegments.map((item) => ({
|
||||
@@ -100,7 +102,11 @@ export async function mixOfflineAudio({
|
||||
sourceOffset: Math.max(0, item.sourceStart || 0), sourceDuration: Math.max(0, item.sourceDuration || 0),
|
||||
playbackRate: clamp(Number(item.playbackRate) || 1, 0.25, 4), fadeIn: 0, fadeOut: 0,
|
||||
})) : sourceAudioBlob ? [{ blob: sourceAudioBlob, start: Math.max(0, sourceAudioStart), volume: sourceAudioVolume, sourceOffset: 0, sourceDuration: 0, playbackRate: 1, fadeIn: 0, fadeOut: 0 }] : []),
|
||||
...(musicBlob ? [{ blob: musicBlob, start: Math.max(0, musicStart), volume: musicVolume, sourceOffset: 0, sourceDuration: 0, playbackRate: 1, fadeIn: 0, fadeOut: 0 }] : []),
|
||||
...(musicBlob ? (musicSegments.length ? musicSegments.map((item) => ({
|
||||
blob: musicBlob, start: Math.max(0, item.start || 0), volume: item.volume ?? musicVolume,
|
||||
sourceOffset: Math.max(0, item.sourceStart || 0), sourceDuration: Math.max(0, item.sourceDuration || (item.duration || 0) * (Number(item.playbackRate) || 1)),
|
||||
playbackRate: clamp(Number(item.playbackRate) || 1, 0.25, 4), fadeIn: Math.max(0, item.fadeIn || 0), fadeOut: Math.max(0, item.fadeOut || 0),
|
||||
})) : [{ blob: musicBlob, start: Math.max(0, musicStart), volume: musicVolume, sourceOffset: 0, sourceDuration: 0, playbackRate: 1, fadeIn: 0, fadeOut: 0 }]) : []),
|
||||
];
|
||||
if (!inputs.length) return null;
|
||||
const decoded = await decodeAudioInputs(inputs);
|
||||
@@ -111,12 +117,19 @@ export async function mixOfflineAudio({
|
||||
decoded.forEach((input) => {
|
||||
const source = context.createBufferSource();
|
||||
const gain = context.createGain();
|
||||
source.buffer = input.decoded;
|
||||
source.playbackRate.value = input.playbackRate;
|
||||
const offset = Math.min(input.decoded.duration, input.sourceOffset);
|
||||
const available = Math.max(0, input.decoded.duration - offset);
|
||||
const sourceDuration = Math.min(available, input.sourceDuration || available);
|
||||
const outputDuration = sourceDuration / input.playbackRate;
|
||||
const preservePitch = Math.abs(input.playbackRate - 1) > 0.0001;
|
||||
source.buffer = preservePitch
|
||||
? createPitchPreservedAudioBuffer(context, input.decoded, {
|
||||
sourceOffset: offset,
|
||||
sourceDuration,
|
||||
playbackRate: input.playbackRate,
|
||||
})
|
||||
: input.decoded;
|
||||
source.playbackRate.value = 1;
|
||||
gain.gain.setValueAtTime(input.volume, input.start);
|
||||
if (input.fadeIn > 0) {
|
||||
gain.gain.setValueAtTime(0, input.start);
|
||||
@@ -128,7 +141,7 @@ export async function mixOfflineAudio({
|
||||
gain.gain.linearRampToValueAtTime(0, input.start + outputDuration);
|
||||
}
|
||||
source.connect(gain).connect(context.destination);
|
||||
source.start(input.start, offset, sourceDuration);
|
||||
source.start(input.start, preservePitch ? 0 : offset, preservePitch ? outputDuration : sourceDuration);
|
||||
});
|
||||
return context.startRendering();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
const clampRate = (value) => Math.max(0.25, Math.min(4, Number(value) || 1));
|
||||
|
||||
function findAlignedSourceStart(input, previousStart, expectedStart, frameSize, synthesisHop) {
|
||||
const overlap = frameSize - synthesisHop;
|
||||
const referenceStart = previousStart + synthesisHop;
|
||||
const searchRadius = Math.min(256, Math.max(32, Math.floor(frameSize / 8)));
|
||||
let bestStart = Math.max(0, Math.min(input.length - 1, Math.round(expectedStart)));
|
||||
let bestScore = -Infinity;
|
||||
for (let offset = -searchRadius; offset <= searchRadius; offset += 4) {
|
||||
const candidate = Math.max(0, Math.min(input.length - 1, Math.round(expectedStart + offset)));
|
||||
let dot = 0;
|
||||
let leftEnergy = 0;
|
||||
let rightEnergy = 0;
|
||||
for (let index = 0; index < overlap; index += 16) {
|
||||
const left = input[referenceStart + index] || 0;
|
||||
const right = input[candidate + index] || 0;
|
||||
dot += left * right;
|
||||
leftEnergy += left * left;
|
||||
rightEnergy += right * right;
|
||||
}
|
||||
const score = dot / Math.sqrt(Math.max(1e-12, leftEnergy * rightEnergy));
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestStart = candidate;
|
||||
}
|
||||
}
|
||||
return bestStart;
|
||||
}
|
||||
|
||||
export function timeStretchChannelData(input, playbackRate, { frameSize = 2048 } = {}) {
|
||||
const rate = clampRate(playbackRate);
|
||||
const source = input instanceof Float32Array ? input : Float32Array.from(input || []);
|
||||
if (!source.length) return new Float32Array(1);
|
||||
if (Math.abs(rate - 1) < 0.0001) return source.slice();
|
||||
|
||||
const safeFrameSize = Math.max(256, Math.min(frameSize, source.length));
|
||||
const synthesisHop = Math.max(64, Math.floor(safeFrameSize / 4));
|
||||
const analysisHop = synthesisHop * rate;
|
||||
const outputLength = Math.max(1, Math.round(source.length / rate));
|
||||
const output = new Float32Array(outputLength);
|
||||
const weights = new Float32Array(outputLength);
|
||||
let previousSourceStart = 0;
|
||||
|
||||
for (let outputStart = 0, grain = 0; outputStart < outputLength; outputStart += synthesisHop, grain += 1) {
|
||||
const expectedSourceStart = grain * analysisHop;
|
||||
if (expectedSourceStart >= source.length) break;
|
||||
const sourceStart = grain === 0
|
||||
? 0
|
||||
: findAlignedSourceStart(source, previousSourceStart, expectedSourceStart, safeFrameSize, synthesisHop);
|
||||
previousSourceStart = sourceStart;
|
||||
const available = Math.min(safeFrameSize, source.length - sourceStart, outputLength - outputStart);
|
||||
for (let index = 0; index < available; index += 1) {
|
||||
const window = Math.sin(Math.PI * index / Math.max(1, safeFrameSize - 1)) ** 2;
|
||||
output[outputStart + index] += source[sourceStart + index] * window;
|
||||
weights[outputStart + index] += window;
|
||||
}
|
||||
}
|
||||
|
||||
for (let index = 0; index < output.length; index += 1) {
|
||||
if (weights[index] > 1e-5) output[index] /= weights[index];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export function createPitchPreservedAudioBuffer(context, decoded, {
|
||||
sourceOffset = 0,
|
||||
sourceDuration = 0,
|
||||
playbackRate = 1,
|
||||
} = {}) {
|
||||
const rate = clampRate(playbackRate);
|
||||
const sampleRate = decoded.sampleRate;
|
||||
const offsetSamples = Math.max(0, Math.min(decoded.length, Math.round(sourceOffset * sampleRate)));
|
||||
const availableSamples = Math.max(0, decoded.length - offsetSamples);
|
||||
const requestedSamples = sourceDuration > 0 ? Math.round(sourceDuration * sampleRate) : availableSamples;
|
||||
const sourceSamples = Math.max(1, Math.min(availableSamples, requestedSamples));
|
||||
const outputLength = Math.max(1, Math.round(sourceSamples / rate));
|
||||
const output = context.createBuffer(decoded.numberOfChannels, outputLength, sampleRate);
|
||||
for (let channel = 0; channel < decoded.numberOfChannels; channel += 1) {
|
||||
const input = decoded.getChannelData(channel).subarray(offsetSamples, offsetSamples + sourceSamples);
|
||||
output.copyToChannel(timeStretchChannelData(input, rate), channel);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { timeStretchChannelData } from "./pitchPreservingTimeStretch.js";
|
||||
|
||||
function makeSine(frequency, duration, sampleRate = 48_000) {
|
||||
return Float32Array.from({ length: Math.round(duration * sampleRate) }, (_, index) =>
|
||||
Math.sin(2 * Math.PI * frequency * index / sampleRate));
|
||||
}
|
||||
|
||||
function estimateFrequency(samples, sampleRate = 48_000) {
|
||||
const start = Math.floor(samples.length * 0.2);
|
||||
const end = Math.floor(samples.length * 0.8);
|
||||
let crossings = 0;
|
||||
for (let index = start + 1; index < end; index += 1) {
|
||||
if (samples[index - 1] <= 0 && samples[index] > 0) crossings += 1;
|
||||
}
|
||||
return crossings / ((end - start) / sampleRate);
|
||||
}
|
||||
|
||||
describe("pitch-preserving time stretch", () => {
|
||||
it.each([0.5, 2])("changes duration at %sx while retaining a 440 Hz tone", (rate) => {
|
||||
const source = makeSine(440, 2);
|
||||
const stretched = timeStretchChannelData(source, rate);
|
||||
|
||||
expect(stretched.length).toBeCloseTo(source.length / rate, 0);
|
||||
expect(estimateFrequency(stretched)).toBeGreaterThan(420);
|
||||
expect(estimateFrequency(stretched)).toBeLessThan(460);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,17 @@ export function createPlaybackControls(deps) {
|
||||
sourceTime: getTimelineTrackLocalTime(timelineTime, deps.sourceAudioStart, deps.sourceAudioDuration),
|
||||
playbackRate: 1,
|
||||
};
|
||||
const getMusicState = (timelineTime) => {
|
||||
const segments = deps.musicSegments?.length ? deps.musicSegments : [{ start: deps.musicStart, duration: deps.musicDuration, sourceStart: 0, playbackRate: 1 }];
|
||||
const segment = segments.find((item) => isTimelineTimeInsideTrack(timelineTime, item.start, item.duration));
|
||||
if (!segment) return { active: false, sourceTime: 0, playbackRate: 1 };
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(segment.playbackRate) || 1));
|
||||
return {
|
||||
active: true,
|
||||
playbackRate,
|
||||
sourceTime: Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration) * playbackRate,
|
||||
};
|
||||
};
|
||||
const pauseTimelineMedia = () => {
|
||||
deps.audioSegmentRefs.current.forEach((audio) => audio.pause()); deps.sourceAudioRef.current?.pause();
|
||||
deps.musicRef.current?.pause(); deps.previewVideoRef.current?.pause();
|
||||
@@ -22,10 +33,10 @@ 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 = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(clamped, segment.start, segment.duration);
|
||||
if (audio) audio.currentTime = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(clamped, segment.start, segment.duration) * Math.max(0.25, Math.min(4, Number(segment.playbackRate) || 1));
|
||||
});
|
||||
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);
|
||||
if (deps.musicRef.current) deps.musicRef.current.currentTime = getMusicState(clamped).sourceTime;
|
||||
};
|
||||
const getTimelineTimeFromClientX = (clientX) => {
|
||||
const rect = deps.trackScrollRef.current?.getBoundingClientRect(); const duration = deps.timelineDurationRef.current;
|
||||
@@ -56,22 +67,27 @@ export function createPlaybackControls(deps) {
|
||||
const playIf = (media, ready) => ready ? requestTimelineMediaPlay(media) : media?.pause();
|
||||
voices.forEach(({ segment, audio }) => {
|
||||
const active = isTimelineTimeInsideTrack(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);
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(segment.playbackRate) || 1));
|
||||
audio.currentTime = Math.max(0, Number(segment.sourceStart) || 0) + getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration) * playbackRate;
|
||||
audio.volume = getAudioSegmentPreviewVolume(segment, timelineTime); audio.playbackRate = playbackRate;
|
||||
if ("preservesPitch" in audio) audio.preservesPitch = true;
|
||||
playIf(audio, active);
|
||||
});
|
||||
if (source && deps.sourceAudioUrl) {
|
||||
const sourceState = getSourceState(timelineTime);
|
||||
source.currentTime = sourceState.sourceTime;
|
||||
source.playbackRate = sourceState.playbackRate;
|
||||
if ("preservesPitch" in source) source.preservesPitch = true;
|
||||
playIf(source, sourceState.active);
|
||||
}
|
||||
if (music && deps.musicUrl) { const active = isTimelineTimeInsideTrack(timelineTime, deps.musicStart, deps.musicDuration); music.currentTime = getTimelineTrackLocalTime(timelineTime, deps.musicStart, deps.musicDuration); playIf(music, active); }
|
||||
if (music && deps.musicUrl) { const state = getMusicState(timelineTime); music.currentTime = state.sourceTime; music.playbackRate = state.playbackRate; if ("preservesPitch" in music) music.preservesPitch = true; playIf(music, state.active); }
|
||||
if (video && deps.previewVisualType === "video") {
|
||||
const index = getVisualSegmentIndexAtTime(deps.visualSegments, timelineTime);
|
||||
const range = deps.visualTimeline[Math.max(0, index)] ?? deps.currentVisualRange;
|
||||
const local = range ? Math.max(0, timelineTime - range.start) : timelineTime;
|
||||
const segment = deps.visualSegments[Math.max(0, index)];
|
||||
video.playbackRate = normalizeVisualPlaybackRate(segment?.playbackRate);
|
||||
if ("preservesPitch" in video) video.preservesPitch = true;
|
||||
const sourceTime = getVisualSourceTime(segment, local);
|
||||
video.currentTime = Math.min(sourceTime, video.duration || sourceTime); playIf(video, true);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,20 @@ function createDeps(overrides = {}) {
|
||||
}
|
||||
|
||||
describe("timeline playhead seeking", () => {
|
||||
it("preserves pitch while previewing a sped-up video", () => {
|
||||
const video = { currentTime: 0, duration: 4, paused: true, playbackRate: 1, preservesPitch: false, play: vi.fn(() => Promise.resolve()), pause: vi.fn() };
|
||||
const deps = createDeps({
|
||||
isPlaying: false, canPreview: true, estimatedDuration: 2, notify: vi.fn(),
|
||||
previewVideoRef: { current: video }, previewVisualType: "video",
|
||||
visualSegments: [{ id: "video", type: "video", duration: 2, sourceStart: 0, sourceDuration: 4, playbackRate: 2 }],
|
||||
visualTimeline: [{ start: 0, end: 2 }], currentVisualRange: { start: 0, end: 2 },
|
||||
});
|
||||
|
||||
createPlaybackControls(deps).handlePlayToggle();
|
||||
expect(video.playbackRate).toBe(2);
|
||||
expect(video.preservesPitch).toBe(true);
|
||||
});
|
||||
|
||||
it("starts voice and music together when visibility defaults are absent", async () => {
|
||||
const voice = { currentTime: 0, paused: true, playbackRate: 1, volume: 1, play: vi.fn(() => Promise.resolve()), pause: vi.fn() };
|
||||
const music = { currentTime: 0, paused: true, playbackRate: 1, play: vi.fn(() => Promise.resolve()), pause: vi.fn() };
|
||||
@@ -48,6 +62,30 @@ describe("timeline playhead seeking", () => {
|
||||
expect(deps.setIsPlaying).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("maps a sped-up music clip to source time and preserves pitch", () => {
|
||||
const music = { currentTime: 0, paused: true, playbackRate: 1, preservesPitch: false, play: vi.fn(() => Promise.resolve()), pause: vi.fn() };
|
||||
const deps = createDeps({
|
||||
isPlaying: false,
|
||||
canPreview: true,
|
||||
currentTimeRef: { current: 2 },
|
||||
estimatedDuration: 4,
|
||||
musicRef: { current: music },
|
||||
musicUrl: "blob:music",
|
||||
musicSegments: [{ id: "music-1", start: 1, duration: 2, sourceStart: 0.5, sourceDuration: 4, playbackRate: 2 }],
|
||||
notify: vi.fn(),
|
||||
previewVisualType: "image",
|
||||
visualSegments: [],
|
||||
visualTimeline: [],
|
||||
});
|
||||
|
||||
createPlaybackControls(deps).handlePlayToggle();
|
||||
|
||||
expect(music.currentTime).toBeCloseTo(2.5, 5);
|
||||
expect(music.playbackRate).toBe(2);
|
||||
expect(music.preservesPitch).toBe(true);
|
||||
expect(music.play).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
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)));
|
||||
|
||||
@@ -35,7 +35,9 @@ export function getLinkedSourceAudioSegments(visualSegments = [], sourceAudioAss
|
||||
const timeline = getVisualSegmentTimeline(visualSegments);
|
||||
const maximumSourceTime = Math.max(0, Number(sourceAudioDuration) || 0);
|
||||
return visualSegments.flatMap((segment, index) => {
|
||||
if (segment.type !== "video" || segment.sourceAudioDisabled || (!hasMappedOffsets && segment.assetId !== linkedAssetId)) return [];
|
||||
const hasSegmentMapping = Number.isFinite(segment.sourceAudioOffset);
|
||||
const matchesLegacyAssetMapping = !hasMappedOffsets && segment.assetId === linkedAssetId;
|
||||
if (segment.type !== "video" || segment.sourceAudioDisabled || (!hasSegmentMapping && !matchesLegacyAssetMapping)) return [];
|
||||
const range = timeline[index];
|
||||
const playbackRate = normalizeVisualPlaybackRate(segment.playbackRate);
|
||||
const sourceStart = Math.max(0, Number(segment.sourceAudioOffset) || 0) + Math.max(0, Number(segment.sourceStart) || 0);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getSourceAudioAssetId,
|
||||
shouldMuteEmbeddedVideoAudio,
|
||||
} from "./sourceAudioSync.js";
|
||||
import { updateVisualSegmentPlaybackRate } from "./visualEffects.js";
|
||||
|
||||
describe("linked source audio", () => {
|
||||
const visualSegments = [
|
||||
@@ -31,6 +32,17 @@ describe("linked source audio", () => {
|
||||
expect(getLinkedSourceAudioState(segments, 4)).toMatchObject({ active: true, sourceTime: 5, playbackRate: 1 });
|
||||
});
|
||||
|
||||
it("updates linked source-audio duration and rate when its video speed changes", () => {
|
||||
const video = {
|
||||
id: "speed-video", assetId: "video-speed", type: "video",
|
||||
duration: 4, sourceStart: 0, sourceDuration: 4, sourceAudioOffset: 0, playbackRate: 1,
|
||||
};
|
||||
const fasterVideo = updateVisualSegmentPlaybackRate(video, 2);
|
||||
expect(getLinkedSourceAudioSegments([fasterVideo], "video-speed", 4)).toMatchObject([{
|
||||
id: "speed-video", duration: 2, sourceDuration: 4, playbackRate: 2,
|
||||
}]);
|
||||
});
|
||||
|
||||
it("keeps source audio mappings for multiple imported video assets", () => {
|
||||
const clips = [
|
||||
{ id: "first", assetId: "video-1", type: "video", duration: 4, sourceStart: 0, sourceDuration: 4, sourceAudioOffset: 0 },
|
||||
@@ -45,6 +57,14 @@ describe("linked source audio", () => {
|
||||
expect(getLinkedSourceAudioState(segments, 5)).toMatchObject({ active: true, sourceTime: 5 });
|
||||
});
|
||||
|
||||
it("does not recreate a removed mapped piece from the remaining shared audio blob", () => {
|
||||
const clips = [
|
||||
{ id: "removed", assetId: "video-1", type: "video", duration: 2 },
|
||||
{ id: "remaining", assetId: "video-2", type: "video", duration: 2, sourceAudioOffset: 2 },
|
||||
];
|
||||
expect(getLinkedSourceAudioSegments(clips, "", 4).map((segment) => segment.id)).toEqual(["remaining"]);
|
||||
});
|
||||
|
||||
it("omits only the linked audio piece disabled on its visual clip", () => {
|
||||
const segments = getLinkedSourceAudioSegments(
|
||||
visualSegments.map((segment) => segment.id === "a" ? { ...segment, sourceAudioDisabled: true } : segment),
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { normalizeTimedSegmentIds, packTimedSegmentsIntoLanes } from "./timeline.js";
|
||||
import { createTimelineMoveControls } from "./timelineMoveControls.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("sticker subtrack placement", () => {
|
||||
it("keeps a same-asset sticker in the third subtrack after a cross-lane drag", () => {
|
||||
const listeners = installPointerListeners();
|
||||
const original = [
|
||||
{ id: "spark-a", stickerId: "spark", start: 5, duration: 3, lane: 0 },
|
||||
{ id: "spark-b", stickerId: "spark", start: 5, duration: 3, lane: 1 },
|
||||
{ id: "flame", stickerId: "flame", start: 0, duration: 4, lane: 2 },
|
||||
];
|
||||
let stickerSegments = original;
|
||||
const setStickerSegments = vi.fn((update) => { stickerSegments = update(stickerSegments); });
|
||||
const commitStickerSegments = vi.fn((next) => { stickerSegments = next; });
|
||||
const setStickerTimelineDrag = vi.fn();
|
||||
vi.stubGlobal("document", {
|
||||
elementFromPoint: vi.fn(() => ({
|
||||
closest: () => ({ dataset: { stickerLaneIndex: "2" } }),
|
||||
})),
|
||||
});
|
||||
const controls = createTimelineMoveControls({
|
||||
stickerSegments: original,
|
||||
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, commitStickerSegments,
|
||||
setStickerTimelineDrag,
|
||||
suppressTimelineClipClickRef: { current: "" }, setSnapGuide: vi.fn(),
|
||||
seekTo: vi.fn(), notify: vi.fn(), pauseForTimelineEdit: vi.fn(),
|
||||
});
|
||||
|
||||
controls.startStickerSegmentMove(
|
||||
{ button: 0, clientX: 50, clientY: 60, preventDefault: vi.fn(), stopPropagation: vi.fn() },
|
||||
"spark-b",
|
||||
1,
|
||||
);
|
||||
listeners.get("pointermove")({ clientX: 55, clientY: 108, preventDefault: vi.fn() });
|
||||
expect(stickerSegments).toBe(original);
|
||||
expect(setStickerTimelineDrag).toHaveBeenLastCalledWith(expect.objectContaining({ segmentId: "spark-b", lane: 2 }));
|
||||
listeners.get("pointerup")();
|
||||
|
||||
const moved = stickerSegments.find((segment) => segment.id === "spark-b");
|
||||
const untouched = stickerSegments.find((segment) => segment.id === "spark-a");
|
||||
expect(moved).toMatchObject({ lane: 2, stickerId: "spark" });
|
||||
expect(untouched).toMatchObject({ lane: 0, start: 5 });
|
||||
const lanes = packTimedSegmentsIntoLanes(stickerSegments, { preferredLaneKey: "lane" });
|
||||
expect(lanes[2].map((segment) => segment.id)).toEqual(["flame", "spark-b"]);
|
||||
expect(setStickerTimelineDrag).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
|
||||
it("repairs duplicate instance ids without changing sticker asset identity", () => {
|
||||
const source = [
|
||||
{ id: "duplicate", stickerId: "spark" },
|
||||
{ id: "duplicate", stickerId: "spark" },
|
||||
];
|
||||
const normalized = normalizeTimedSegmentIds(source, "sticker");
|
||||
expect(normalized[0].id).toBe("duplicate");
|
||||
expect(normalized[1].id).not.toBe("duplicate");
|
||||
expect(normalized.map((segment) => segment.stickerId)).toEqual(["spark", "spark"]);
|
||||
});
|
||||
});
|
||||
+36
-3
@@ -84,13 +84,37 @@ export function getTimedSegmentsEnd(segments) {
|
||||
);
|
||||
}
|
||||
|
||||
export function packTimedSegmentsIntoLanes(segments) {
|
||||
export function normalizeTimedSegmentIds(segments, prefix = "segment") {
|
||||
const seen = new Set();
|
||||
let changed = false;
|
||||
const normalized = segments.map((segment) => {
|
||||
const id = String(segment?.id || "");
|
||||
if (id && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
return segment;
|
||||
}
|
||||
const next = { ...segment, id: makeId(prefix) };
|
||||
seen.add(next.id);
|
||||
changed = true;
|
||||
return next;
|
||||
});
|
||||
return changed ? normalized : segments;
|
||||
}
|
||||
|
||||
export function packTimedSegmentsIntoLanes(segments, { preferredLaneKey = "" } = {}) {
|
||||
const lanes = [];
|
||||
[...segments].sort((a, b) => (a.start || 0) - (b.start || 0) || String(a.id).localeCompare(String(b.id))).forEach((segment) => {
|
||||
const laneIndex = lanes.findIndex((lane) => {
|
||||
const laneAccepts = (lane = []) => {
|
||||
const last = lane.at(-1);
|
||||
return !last || (last.start || 0) + (last.duration || 0) <= (segment.start || 0) + 0.001;
|
||||
});
|
||||
};
|
||||
const preferredLane = preferredLaneKey && Number.isInteger(segment?.[preferredLaneKey])
|
||||
? Math.max(0, segment[preferredLaneKey])
|
||||
: -1;
|
||||
while (preferredLane >= lanes.length) lanes.push([]);
|
||||
const laneIndex = preferredLane >= 0 && laneAccepts(lanes[preferredLane])
|
||||
? preferredLane
|
||||
: lanes.findIndex(laneAccepts);
|
||||
if (laneIndex >= 0) lanes[laneIndex].push(segment);
|
||||
else lanes.push([segment]);
|
||||
});
|
||||
@@ -312,6 +336,15 @@ export function formatTime(value) {
|
||||
)}.${String(centiseconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function formatCompactDuration(value) {
|
||||
const seconds = Math.max(0, Number.isFinite(value) ? value : 0);
|
||||
if (seconds < 10) return `${seconds.toFixed(1)}s`;
|
||||
const roundedSeconds = Math.round(seconds);
|
||||
if (roundedSeconds < 60) return `${roundedSeconds}s`;
|
||||
const minutes = Math.floor(roundedSeconds / 60);
|
||||
return `${minutes}:${String(roundedSeconds % 60).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function formatClock(value) {
|
||||
const seconds = Math.max(0, Number.isFinite(value) ? value : 0);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createCaptionSegments,
|
||||
createStickerSegment,
|
||||
formatCompactDuration,
|
||||
getCaptionScript,
|
||||
getCaptionTimeline,
|
||||
getTimedSegmentIndexAtTime,
|
||||
@@ -25,6 +26,12 @@ import {
|
||||
} from "./timelineScale.js";
|
||||
|
||||
describe("timeline primitives", () => {
|
||||
it("formats narrow mobile audio durations compactly", () => {
|
||||
expect(formatCompactDuration(1)).toBe("1.0s");
|
||||
expect(formatCompactDuration(12.4)).toBe("12s");
|
||||
expect(formatCompactDuration(65)).toBe("1:05");
|
||||
});
|
||||
|
||||
it("computes a visual clip start without treating visual clips as captions", () => {
|
||||
const clips = [{ duration: 1.25 }, { duration: 2.5 }, { duration: 4 }];
|
||||
expect(getVisualSegmentStartTime(clips, 0)).toBe(0);
|
||||
|
||||
@@ -41,10 +41,16 @@ export function createTimelineClipboardActions(d) {
|
||||
if (d.sourceAudioLinked && d.selectedSourceAudioSegmentId && d.selectedSourceAudioSegmentId !== "source-audio") {
|
||||
const index = d.visualSegments.findIndex((segment) => segment.id === d.selectedSourceAudioSegmentId);
|
||||
if (index < 0) return void d.notify("当前没有选中的原声音频片段");
|
||||
const next = d.visualSegments.map((segment, position) => position === index
|
||||
? { ...segment, sourceAudioDisabled: true }
|
||||
: segment);
|
||||
const next = d.visualSegments.map((segment, position) => {
|
||||
if (position !== index) return segment;
|
||||
const detached = { ...segment, sourceAudioDisabled: false };
|
||||
delete detached.sourceAudioOffset;
|
||||
return detached;
|
||||
});
|
||||
const hasRemainingLinkedAudio = (d.linkedSourceAudioSegments ?? [])
|
||||
.some((segment) => segment.id !== d.selectedSourceAudioSegmentId);
|
||||
d.commitVisualSegments(next, "已删除当前原声音频片段", Math.max(0, index));
|
||||
if (!hasRemainingLinkedAudio) d.clearSourceAudioTrack("");
|
||||
d.setSelectedSourceAudioSegmentId("");
|
||||
return;
|
||||
}
|
||||
@@ -56,6 +62,7 @@ export function createTimelineClipboardActions(d) {
|
||||
d.clearImageTrack();
|
||||
};
|
||||
const handleDuplicateTrack = () => {
|
||||
if (d.trackLocks[d.selectedTrack]) return void d.notify("当前轨道已锁定,无法复制");
|
||||
if (d.selectedTrack === "overlay") {
|
||||
const source = d.visualOverlaySegments.find((segment) => segment.id === d.selectedVisualOverlayId);
|
||||
if (!source) return void d.notify("请先选择一个画中画片段");
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createTimelineClipboardActions } from "./timelineClipboardActions.js";
|
||||
|
||||
function createSourceDeleteHarness(linkedSourceAudioSegments) {
|
||||
const commitVisualSegments = vi.fn();
|
||||
const clearSourceAudioTrack = vi.fn();
|
||||
const setSelectedSourceAudioSegmentId = vi.fn();
|
||||
const visualSegments = [
|
||||
{ id: "selected-video", type: "video", duration: 2, sourceAudioOffset: 0, sourceAudioDisabled: true },
|
||||
{ id: "other-video", type: "video", duration: 2, sourceAudioOffset: 2 },
|
||||
];
|
||||
const actions = createTimelineClipboardActions({
|
||||
trackLocks: {}, selectedTrack: "source", sourceAudioLinked: true,
|
||||
selectedSourceAudioSegmentId: "selected-video", visualSegments, linkedSourceAudioSegments,
|
||||
commitVisualSegments, clearSourceAudioTrack, setSelectedSourceAudioSegmentId,
|
||||
notify: vi.fn(),
|
||||
});
|
||||
return { actions, clearSourceAudioTrack, commitVisualSegments, setSelectedSourceAudioSegmentId };
|
||||
}
|
||||
|
||||
describe("source-audio deletion", () => {
|
||||
it("removes only the selected mapping and restores embedded video audio", () => {
|
||||
const harness = createSourceDeleteHarness([
|
||||
{ id: "selected-video" },
|
||||
{ id: "other-video" },
|
||||
]);
|
||||
harness.actions.handleDeleteTrack();
|
||||
|
||||
const [segments] = harness.commitVisualSegments.mock.calls[0];
|
||||
expect(segments[0]).not.toHaveProperty("sourceAudioOffset");
|
||||
expect(segments[0].sourceAudioDisabled).toBe(false);
|
||||
expect(segments[1].sourceAudioOffset).toBe(2);
|
||||
expect(harness.clearSourceAudioTrack).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears the shared source track when its final mapped piece is deleted", () => {
|
||||
const harness = createSourceDeleteHarness([{ id: "selected-video" }]);
|
||||
harness.actions.handleDeleteTrack();
|
||||
|
||||
expect(harness.clearSourceAudioTrack).toHaveBeenCalledWith("");
|
||||
expect(harness.setSelectedSourceAudioSegmentId).toHaveBeenCalledWith("");
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,7 @@ export function createTimelineCutActions(d) {
|
||||
}
|
||||
const firstDuration = time - source.start;
|
||||
const secondDuration = source.duration - firstDuration;
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(source.playbackRate) || 1));
|
||||
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");
|
||||
@@ -58,6 +59,7 @@ export function createTimelineCutActions(d) {
|
||||
id: firstId,
|
||||
url: firstUrl,
|
||||
duration: firstDuration,
|
||||
sourceDuration: firstDuration * playbackRate,
|
||||
peaks: source.peaks?.slice(0, peakSplit) || [],
|
||||
fadeOut: 0,
|
||||
};
|
||||
@@ -67,7 +69,8 @@ export function createTimelineCutActions(d) {
|
||||
url: secondUrl,
|
||||
start: time,
|
||||
duration: secondDuration,
|
||||
sourceStart: Math.max(0, Number(source.sourceStart) || 0) + firstDuration,
|
||||
sourceDuration: secondDuration * playbackRate,
|
||||
sourceStart: Math.max(0, Number(source.sourceStart) || 0) + firstDuration * playbackRate,
|
||||
peaks: source.peaks?.slice(peakSplit) || [],
|
||||
fadeIn: 0,
|
||||
};
|
||||
@@ -95,11 +98,15 @@ export function createTimelineCutActions(d) {
|
||||
if (!source) return void d.notify("请把播放头放在音乐片段中间再剪切");
|
||||
const firstDuration = d.currentTime - source.start;
|
||||
const secondDuration = source.duration - firstDuration;
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(source.playbackRate) || 1));
|
||||
const peakCount = source.peaks?.length || 0;
|
||||
const peakSplit = peakCount > 1 ? Math.max(1, Math.min(peakCount - 1, Math.round(firstDuration / source.duration * peakCount))) : 0;
|
||||
const first = { ...source, id: makeId("music"), duration: firstDuration, peaks: peakCount ? source.peaks.slice(0, peakSplit) : [] };
|
||||
const first = { ...source, id: makeId("music"), duration: firstDuration,
|
||||
sourceDuration: firstDuration * playbackRate,
|
||||
peaks: peakCount ? source.peaks.slice(0, peakSplit) : [] };
|
||||
const second = { ...source, id: makeId("music"), start: d.currentTime, duration: secondDuration,
|
||||
sourceStart: Math.max(0, Number(source.sourceStart) || 0) + firstDuration,
|
||||
sourceDuration: secondDuration * playbackRate,
|
||||
sourceStart: Math.max(0, Number(source.sourceStart) || 0) + firstDuration * playbackRate,
|
||||
peaks: peakCount ? source.peaks.slice(peakSplit) : [] };
|
||||
const next = [...segments];
|
||||
next.splice(index, 1, first, second);
|
||||
|
||||
+105
-13
@@ -1,5 +1,5 @@
|
||||
import { DEFAULT_STICKER_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
|
||||
import { collectTimelineSnapPoints, snapTimelineRange } from "./timelineSnap.js";
|
||||
import { collectTimelineSnapPoints, findClosestTimelineSnap, snapTimelineRange } from "./timelineSnap.js";
|
||||
|
||||
export function createTimelineMoveControls(d) {
|
||||
const startSingleTrackMove = (event, track) => {
|
||||
@@ -48,8 +48,9 @@ export function createTimelineMoveControls(d) {
|
||||
const startX = event.clientX; const start = segment.start || 0;
|
||||
const snapPoints = collectTimelineSnapPoints(d, { track: "audio", id: segment.id });
|
||||
const captions = d.captionSegments.filter((caption) => caption.audioSegmentId === segment.id);
|
||||
let moved = false; let latest = start;
|
||||
let moved = false; let latest = start; let cancelledByPinch = false;
|
||||
const move = (e) => {
|
||||
if (cancelledByPinch || d.trackScrollRef.current?.classList.contains("is-pinching")) return;
|
||||
if (!moved && Math.abs(e.clientX - startX) < 4) return;
|
||||
moved = true; e.preventDefault();
|
||||
const unsnapped = start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration;
|
||||
@@ -64,15 +65,33 @@ export function createTimelineMoveControls(d) {
|
||||
}));
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((latest + segment.duration + 5) / 10) * 10));
|
||||
};
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); d.setSnapGuide?.(null); };
|
||||
const cancelForPinch = () => {
|
||||
cancelledByPinch = true;
|
||||
if (moved) {
|
||||
d.setAudioSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start } : item));
|
||||
d.setCaptionSegments((items) => items.map((caption) => {
|
||||
const original = captions.find((item) => item.id === caption.id);
|
||||
return original ? { ...caption, start: original.start, end: original.end } : caption;
|
||||
}));
|
||||
}
|
||||
cleanup();
|
||||
};
|
||||
const cleanup = () => {
|
||||
removeEventListener("pointermove", move);
|
||||
removeEventListener("pointerup", up);
|
||||
removeEventListener("pointercancel", cleanup);
|
||||
removeEventListener("timeline-mobile-pinch-start", cancelForPinch);
|
||||
d.setSnapGuide?.(null);
|
||||
};
|
||||
const up = () => { cleanup(); if (moved) {
|
||||
if (cancelledByPinch) return;
|
||||
d.suppressTimelineClipClickRef.current = segment.id;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segment.id) d.suppressTimelineClipClickRef.current = ""; }, 160);
|
||||
d.seekTo(latest); d.notify(d.t("audioClipMoved"));
|
||||
} };
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup); addEventListener("timeline-mobile-pinch-start", cancelForPinch);
|
||||
};
|
||||
const startStickerSegmentMove = (event, id = "") => {
|
||||
const startStickerSegmentMove = (event, id = "", initialLane = 0) => {
|
||||
if (event.button !== 0) return;
|
||||
d.pauseForTimelineEdit?.();
|
||||
const segment = d.stickerSegments.find((item) => item.id === id); if (!segment) return;
|
||||
@@ -80,34 +99,107 @@ export function createTimelineMoveControls(d) {
|
||||
const rect = d.trackScrollRef.current?.getBoundingClientRect();
|
||||
const duration = d.timelineDurationRef.current || Math.max(d.estimatedDuration, segment.start + segment.duration, 10);
|
||||
if (!rect || duration <= 0) return;
|
||||
event.preventDefault(); event.stopPropagation(); d.setSelectedTrack("sticker"); d.setActiveTool("stickers"); d.setSelectedStickerSegmentId(segment.id);
|
||||
const isMobileTouch = event.pointerType === "touch" && globalThis.window?.matchMedia?.("(max-width: 760px)").matches;
|
||||
if (!isMobileTouch) event.preventDefault();
|
||||
event.stopPropagation(); d.setSelectedTrack("sticker"); d.setActiveTool("stickers"); d.setSelectedStickerSegmentId(segment.id);
|
||||
if (segment.stickerId) d.setSelectedStickerId(segment.stickerId);
|
||||
const startX = event.clientX; const startY = event.clientY; const start = segment.start || 0;
|
||||
const segmentDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, segment.duration || DEFAULT_STICKER_SEGMENT_SECONDS);
|
||||
let moved = false; let latest = start;
|
||||
let moved = false; let latest = start; let latestLane = Math.max(0, Number(initialLane) || 0);
|
||||
const snapPoints = collectTimelineSnapPoints(d, { track: "sticker", id: segment.id });
|
||||
const move = (e) => {
|
||||
if (!moved && Math.hypot(e.clientX - startX, e.clientY - startY) < 4) return;
|
||||
const deltaX = e.clientX - startX; const deltaY = e.clientY - startY;
|
||||
if (!moved && isMobileTouch && Math.abs(deltaY) > Math.abs(deltaX)) return;
|
||||
if (!moved && Math.hypot(deltaX, deltaY) < 4) return;
|
||||
moved = true; e.preventDefault();
|
||||
const unsnapped = start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration;
|
||||
const unsnapped = start + (deltaX / Math.max(rect.width, 1)) * duration;
|
||||
const snapped = snapTimelineRange(unsnapped, segmentDuration, snapPoints, (10 / Math.max(rect.width, 1)) * duration);
|
||||
latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segmentDuration, snapped.start));
|
||||
const laneElement = globalThis.document?.elementFromPoint?.(e.clientX, e.clientY)?.closest?.("[data-sticker-lane-index]");
|
||||
const pointedLane = Number(laneElement?.dataset?.stickerLaneIndex);
|
||||
if (Number.isInteger(pointedLane) && pointedLane >= 0) latestLane = pointedLane;
|
||||
d.setSnapGuide?.(snapped.guide);
|
||||
d.setStickerSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start: latest } : item));
|
||||
d.setStickerTimelineDrag?.({
|
||||
segmentId: segment.id,
|
||||
start: latest,
|
||||
duration: segmentDuration,
|
||||
lane: latestLane,
|
||||
name: segment.name,
|
||||
src: segment.src,
|
||||
});
|
||||
};
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); d.setSnapGuide?.(null); };
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cancel); d.setSnapGuide?.(null); };
|
||||
const cancel = () => { cleanup(); d.setStickerTimelineDrag?.(null); };
|
||||
const up = () => {
|
||||
cleanup(); d.setStickerTimelineDrag?.(null); if (!moved) return;
|
||||
d.suppressTimelineClipClickRef.current = segment.id;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segment.id) d.suppressTimelineClipClickRef.current = ""; }, 160);
|
||||
const next = d.stickerSegments.map((item) => item.id === segment.id ? { ...item, start: latest, lane: latestLane } : item);
|
||||
if (d.commitStickerSegments) d.commitStickerSegments(next, "已调整贴纸片段位置", segment.id);
|
||||
else d.notify("贴纸片段位置已调整");
|
||||
d.seekTo(latest);
|
||||
};
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cancel);
|
||||
};
|
||||
const startStickerSegmentResize = (event, id = "", edge = "end") => {
|
||||
if (event.button !== 0) return;
|
||||
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();
|
||||
const timelineDuration = d.timelineDurationRef.current || Math.max(d.estimatedDuration, segment.start + segment.duration, 10);
|
||||
if (!rect || timelineDuration <= 0) return;
|
||||
const isMobileTouch = event.pointerType === "touch" && globalThis.window?.matchMedia?.("(max-width: 760px)").matches;
|
||||
if (!isMobileTouch) event.preventDefault();
|
||||
event.stopPropagation();
|
||||
d.setSelectedTrack("sticker"); d.setActiveTool("stickers"); d.setSelectedStickerSegmentId(segment.id);
|
||||
if (segment.stickerId) d.setSelectedStickerId(segment.stickerId);
|
||||
const startX = event.clientX; const startY = event.clientY;
|
||||
const originalStart = segment.start || 0; const originalDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, segment.duration || DEFAULT_STICKER_SEGMENT_SECONDS);
|
||||
const originalEnd = originalStart + originalDuration;
|
||||
const snapPoints = collectTimelineSnapPoints(d, { track: "sticker", id: segment.id });
|
||||
let moved = false; let latestStart = originalStart; let latestDuration = originalDuration;
|
||||
const applyRange = (start, duration) => d.setStickerSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start, duration } : item));
|
||||
const move = (e) => {
|
||||
const deltaX = e.clientX - startX; const deltaY = e.clientY - startY;
|
||||
if (!moved && isMobileTouch && Math.abs(deltaY) > Math.abs(deltaX)) return;
|
||||
if (!moved && Math.abs(deltaX) < 3) return;
|
||||
if (!moved) d.pauseForTimelineEdit?.();
|
||||
moved = true; e.preventDefault();
|
||||
const delta = (deltaX / Math.max(rect.width, 1)) * timelineDuration;
|
||||
let nextStart = edge === "start"
|
||||
? Math.max(0, Math.min(originalEnd - MIN_VISUAL_SEGMENT_SECONDS, originalStart + delta))
|
||||
: originalStart;
|
||||
let nextEnd = edge === "end"
|
||||
? Math.min(MAX_TIMELINE_DURATION_SECONDS, Math.max(originalStart + MIN_VISUAL_SEGMENT_SECONDS, originalEnd + delta))
|
||||
: originalEnd;
|
||||
const movingValue = edge === "start" ? nextStart : nextEnd;
|
||||
const snap = findClosestTimelineSnap(movingValue, snapPoints, (10 / Math.max(rect.width, 1)) * timelineDuration);
|
||||
if (snap) {
|
||||
if (edge === "start") nextStart = Math.max(0, Math.min(originalEnd - MIN_VISUAL_SEGMENT_SECONDS, snap.time));
|
||||
else nextEnd = Math.min(MAX_TIMELINE_DURATION_SECONDS, Math.max(originalStart + MIN_VISUAL_SEGMENT_SECONDS, snap.time));
|
||||
}
|
||||
latestStart = nextStart; latestDuration = nextEnd - nextStart;
|
||||
applyRange(latestStart, latestDuration);
|
||||
d.setSnapGuide?.(snap ? { time: snap.time, label: `${snap.time.toFixed(2)}s` } : null);
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((nextEnd + 5) / 10) * 10));
|
||||
};
|
||||
const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cancel); d.setSnapGuide?.(null); };
|
||||
const cancel = () => { cleanup(); if (moved) applyRange(originalStart, originalDuration); };
|
||||
const up = () => {
|
||||
cleanup(); if (!moved) return;
|
||||
d.suppressTimelineClipClickRef.current = segment.id;
|
||||
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segment.id) d.suppressTimelineClipClickRef.current = ""; }, 160);
|
||||
d.seekTo(latest); d.notify("贴纸片段位置已调整");
|
||||
const next = d.stickerSegments.map((item) => item.id === segment.id ? { ...item, start: latestStart, duration: latestDuration } : item);
|
||||
if (d.commitStickerSegments) d.commitStickerSegments(next, "已调整贴纸片段时长", segment.id);
|
||||
else applyRange(latestStart, latestDuration);
|
||||
};
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
|
||||
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cancel);
|
||||
};
|
||||
return {
|
||||
startAudioSegmentMove,
|
||||
startMusicMove: (event) => startSingleTrackMove(event, "music"),
|
||||
startSourceAudioMove: (event) => startSingleTrackMove(event, "source"),
|
||||
startStickerSegmentMove,
|
||||
startStickerSegmentResize,
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,37 @@ function installPointerListeners() {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("timeline drag playback behavior", () => {
|
||||
it("rolls back a voiceover drag when a second touch turns the gesture into a mobile pinch", () => {
|
||||
const listeners = installPointerListeners();
|
||||
let audioSegments = [{ id: "voice-1", start: 1, duration: 2 }];
|
||||
const setAudioSegments = vi.fn((update) => { audioSegments = update(audioSegments); });
|
||||
const seekTo = vi.fn();
|
||||
const controls = createTimelineMoveControls({
|
||||
audioSegments,
|
||||
captionSegments: [],
|
||||
trackLocks: { audio: false },
|
||||
trackScrollRef: {
|
||||
current: {
|
||||
classList: { contains: () => false },
|
||||
getBoundingClientRect: () => ({ width: 200 }),
|
||||
},
|
||||
},
|
||||
timelineDurationRef: { current: 10 },
|
||||
setSelectedTrack: vi.fn(), setSelectedAudioSegmentId: vi.fn(), setAudioSegments,
|
||||
setCaptionSegments: vi.fn(), setTimelineHorizon: vi.fn(), setSnapGuide: vi.fn(),
|
||||
suppressTimelineClipClickRef: { current: "" }, seekTo, notify: vi.fn(),
|
||||
pauseForTimelineEdit: vi.fn(), t: (key) => key,
|
||||
});
|
||||
|
||||
controls.startAudioSegmentMove({ button: 0, clientX: 20, stopPropagation: vi.fn() }, "voice-1");
|
||||
listeners.get("pointermove")({ clientX: 60, preventDefault: vi.fn() });
|
||||
expect(audioSegments[0].start).not.toBe(1);
|
||||
|
||||
listeners.get("timeline-mobile-pinch-start")();
|
||||
expect(audioSegments[0].start).toBe(1);
|
||||
expect(seekTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reveals and commits a picture-in-picture target when a main visual is dragged downward", () => {
|
||||
const listeners = installPointerListeners();
|
||||
vi.stubGlobal("document", {
|
||||
@@ -50,6 +81,7 @@ describe("timeline drag playback behavior", () => {
|
||||
const listeners = installPointerListeners();
|
||||
const pauseForTimelineEdit = vi.fn();
|
||||
const setStickerSegments = vi.fn();
|
||||
const setStickerTimelineDrag = vi.fn();
|
||||
const controls = createTimelineMoveControls({
|
||||
stickerSegments: [{ id: "sticker-1", start: 1, duration: 2, stickerId: "spark" }],
|
||||
trackLocks: { sticker: false },
|
||||
@@ -58,6 +90,7 @@ describe("timeline drag playback behavior", () => {
|
||||
estimatedDuration: 10,
|
||||
setSelectedTrack: vi.fn(), setActiveTool: vi.fn(), setSelectedStickerSegmentId: vi.fn(),
|
||||
setSelectedStickerId: vi.fn(), setStickerSegments, suppressTimelineClipClickRef: { current: "" },
|
||||
setStickerTimelineDrag,
|
||||
seekTo: vi.fn(), notify: vi.fn(), pauseForTimelineEdit,
|
||||
});
|
||||
controls.startStickerSegmentMove({ button: 0, clientX: 20, clientY: 10, preventDefault: vi.fn(), stopPropagation: vi.fn() }, "sticker-1");
|
||||
@@ -67,7 +100,38 @@ describe("timeline drag playback behavior", () => {
|
||||
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();
|
||||
expect(setStickerSegments).not.toHaveBeenCalled();
|
||||
expect(setStickerTimelineDrag).toHaveBeenCalledWith(expect.objectContaining({ segmentId: "sticker-1" }));
|
||||
});
|
||||
|
||||
it("resizes either edge of a sticker clip while preserving the opposite edge", () => {
|
||||
const listeners = installPointerListeners();
|
||||
const stickerSegments = [{ id: "sticker-1", start: 2, duration: 3, stickerId: "spark" }];
|
||||
const setStickerSegments = vi.fn();
|
||||
const commitStickerSegments = vi.fn();
|
||||
const controls = createTimelineMoveControls({
|
||||
stickerSegments, estimatedDuration: 10, timelineDurationRef: { current: 10 },
|
||||
trackLocks: { sticker: false }, trackScrollRef: { current: { getBoundingClientRect: () => ({ width: 200 }) } },
|
||||
setSelectedTrack: vi.fn(), setActiveTool: vi.fn(), setSelectedStickerSegmentId: vi.fn(),
|
||||
setSelectedStickerId: vi.fn(), setStickerSegments, commitStickerSegments, setTimelineHorizon: vi.fn(),
|
||||
suppressTimelineClipClickRef: { current: "" }, notify: vi.fn(), pauseForTimelineEdit: vi.fn(),
|
||||
});
|
||||
|
||||
controls.startStickerSegmentResize(
|
||||
{ button: 0, clientX: 40, clientY: 10, preventDefault: vi.fn(), stopPropagation: vi.fn() },
|
||||
"sticker-1", "start",
|
||||
);
|
||||
listeners.get("pointermove")({ clientX: 60, clientY: 10, preventDefault: vi.fn() });
|
||||
listeners.get("pointerup")();
|
||||
expect(commitStickerSegments.mock.calls[0][0][0]).toMatchObject({ start: 3, duration: 2 });
|
||||
|
||||
controls.startStickerSegmentResize(
|
||||
{ button: 0, clientX: 100, clientY: 10, preventDefault: vi.fn(), stopPropagation: vi.fn() },
|
||||
"sticker-1", "end",
|
||||
);
|
||||
listeners.get("pointermove")({ clientX: 120, clientY: 10, preventDefault: vi.fn() });
|
||||
listeners.get("pointerup")();
|
||||
expect(commitStickerSegments.mock.calls[1][0][0]).toMatchObject({ start: 2, duration: 4 });
|
||||
});
|
||||
|
||||
it("pauses immediately when a caption clip is pressed", () => {
|
||||
|
||||
@@ -86,6 +86,59 @@ export function getTimelineTrackWidthPercent(timelineDuration, zoom) {
|
||||
return Math.max(100, (timelineDuration / visibleDuration) * 100);
|
||||
}
|
||||
|
||||
export function getMobilePinchZoomState({
|
||||
timelineDuration,
|
||||
minimumZoom = TIMELINE_MIN_ZOOM,
|
||||
startZoom,
|
||||
startDistance,
|
||||
distance,
|
||||
startTrackWidth,
|
||||
baseTrackWidth = 0,
|
||||
}) {
|
||||
const distanceScale = Math.max(0.01, distance) / Math.max(1, startDistance);
|
||||
const startWidthPercent = getTimelineTrackWidthPercent(timelineDuration, startZoom);
|
||||
const minimumWidthPercent = getTimelineTrackWidthPercent(timelineDuration, minimumZoom);
|
||||
const maximumWidthPercent = getTimelineTrackWidthPercent(timelineDuration, TIMELINE_MAX_ZOOM);
|
||||
const widthUnit = baseTrackWidth > 0
|
||||
? baseTrackWidth / 100
|
||||
: startTrackWidth / Math.max(startWidthPercent, 0.001);
|
||||
const minimumTrackWidth = widthUnit * minimumWidthPercent;
|
||||
const maximumTrackWidth = widthUnit * maximumWidthPercent;
|
||||
const nextTrackWidth = Math.max(
|
||||
minimumTrackWidth,
|
||||
Math.min(maximumTrackWidth, startTrackWidth * distanceScale),
|
||||
);
|
||||
const nextWidthPercent = nextTrackWidth / Math.max(widthUnit, 0.001);
|
||||
const nextVisibleDuration = timelineDuration > 0
|
||||
? timelineDuration / Math.max(nextWidthPercent / 100, 1)
|
||||
: getTimelineVisibleDuration(startZoom);
|
||||
const isAtMinimumWidth = Math.abs(nextTrackWidth - minimumTrackWidth) < 0.000001;
|
||||
const isAtMaximumWidth = Math.abs(nextTrackWidth - maximumTrackWidth) < 0.000001;
|
||||
const nextZoom = isAtMinimumWidth
|
||||
? minimumZoom
|
||||
: isAtMaximumWidth
|
||||
? TIMELINE_MAX_ZOOM
|
||||
: Math.max(minimumZoom, getTimelineZoomForVisibleDuration(nextVisibleDuration));
|
||||
|
||||
return {
|
||||
nextZoom,
|
||||
nextTrackWidth,
|
||||
};
|
||||
}
|
||||
|
||||
export function getMobilePinchAnchorScrollLeft({
|
||||
currentScrollLeft,
|
||||
trackLeft,
|
||||
trackWidth,
|
||||
viewportLeft,
|
||||
viewportWidth,
|
||||
anchorTimeRatio,
|
||||
}) {
|
||||
const fixedPlayheadX = viewportLeft + viewportWidth / 2;
|
||||
const anchorX = trackLeft + anchorTimeRatio * trackWidth;
|
||||
return currentScrollLeft + anchorX - fixedPlayheadX;
|
||||
}
|
||||
|
||||
export function getTimelineRulerScale(visibleDuration) {
|
||||
if (visibleDuration <= 0.75) {
|
||||
return { minorStep: 1 / TIMELINE_FRAME_RATE, majorStep: 0.5, labelMode: "frames" };
|
||||
@@ -114,13 +167,26 @@ export function getTimelineRulerScale(visibleDuration) {
|
||||
return { minorStep: 300, majorStep: 600, labelMode: "minutes" };
|
||||
}
|
||||
|
||||
export function getTimelineRulerTicks(timelineDuration, zoom, visibleStart = 0, visibleEnd = timelineDuration) {
|
||||
const RULER_MAJOR_STEPS = [0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];
|
||||
|
||||
export function getTimelineRulerTicks(
|
||||
timelineDuration,
|
||||
zoom,
|
||||
visibleStart = 0,
|
||||
visibleEnd = timelineDuration,
|
||||
{ minimumMajorStep = 0 } = {},
|
||||
) {
|
||||
if (timelineDuration <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const visibleDuration = getTimelineVisibleDuration(zoom);
|
||||
const { minorStep, majorStep, labelMode } = getTimelineRulerScale(visibleDuration);
|
||||
const scale = getTimelineRulerScale(visibleDuration);
|
||||
const majorStep = RULER_MAJOR_STEPS.find((step) => step >= Math.max(scale.majorStep, minimumMajorStep))
|
||||
?? RULER_MAJOR_STEPS.at(-1);
|
||||
const scaleWasRaised = majorStep > scale.majorStep;
|
||||
const minorStep = scaleWasRaised ? majorStep / 4 : scale.minorStep;
|
||||
const labelMode = scaleWasRaised && majorStep >= 1 ? "seconds" : scale.labelMode;
|
||||
const rangePadding = Math.max(visibleDuration * 0.35, majorStep);
|
||||
const rangeStart = Math.max(0, visibleStart - rangePadding);
|
||||
const rangeEnd = Math.min(timelineDuration, visibleEnd + rangePadding);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getMobilePinchAnchorScrollLeft,
|
||||
getMobilePinchZoomState,
|
||||
getTimelineRulerTicks,
|
||||
getTimelineTrackWidthPercent,
|
||||
getTimelineZoomForVisibleDuration,
|
||||
} from "./timelineScale.js";
|
||||
|
||||
describe("timeline ruler density", () => {
|
||||
it("raises mobile major tick spacing so short-timeline labels do not overlap", () => {
|
||||
const ticks = getTimelineRulerTicks(4, 3, 0, 4, { minimumMajorStep: 0.68 });
|
||||
const labels = ticks.filter((tick) => tick.isMajor).map((tick) => tick.label);
|
||||
|
||||
expect(labels).toEqual(["00:00", "00:01", "00:02", "00:03", "00:04"]);
|
||||
});
|
||||
|
||||
it("keeps subsecond labels when the rendered timeline has enough room", () => {
|
||||
const ticks = getTimelineRulerTicks(4, 3, 0, 4, { minimumMajorStep: 0.25 });
|
||||
|
||||
expect(ticks.filter((tick) => tick.isMajor).some((tick) => tick.label === "00:00.50")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mobile timeline pinch zoom", () => {
|
||||
it.each([
|
||||
[15.06, 1.01],
|
||||
[15.06, 1.02],
|
||||
[15.06, 1.05],
|
||||
[30.13, 1.01],
|
||||
[30.13, 1.02],
|
||||
[30.13, 1.05],
|
||||
])("maps finger distance linearly to pixels from a %ss fitted timeline at %sx", (timelineDuration, distanceScale) => {
|
||||
const startZoom = getTimelineZoomForVisibleDuration(timelineDuration);
|
||||
const result = getMobilePinchZoomState({
|
||||
timelineDuration,
|
||||
minimumZoom: startZoom,
|
||||
startZoom,
|
||||
startDistance: 100,
|
||||
distance: 100 * distanceScale,
|
||||
startTrackWidth: 520,
|
||||
baseTrackWidth: 520,
|
||||
});
|
||||
|
||||
expect(result.nextTrackWidth / 520).toBeCloseTo(distanceScale, 6);
|
||||
});
|
||||
|
||||
it("maps a large finger-distance change directly to track pixels", () => {
|
||||
const result = getMobilePinchZoomState({
|
||||
timelineDuration: 20,
|
||||
startZoom: 1,
|
||||
startDistance: 100,
|
||||
distance: 150,
|
||||
startTrackWidth: 1040,
|
||||
});
|
||||
|
||||
expect(result.nextZoom).toBeGreaterThan(1);
|
||||
expect(result.nextTrackWidth).toBe(1560);
|
||||
});
|
||||
|
||||
it("clamps aggressive pinch gestures to the supported zoom range", () => {
|
||||
const result = getMobilePinchZoomState({
|
||||
timelineDuration: 20,
|
||||
startZoom: 12,
|
||||
startDistance: 20,
|
||||
distance: 500,
|
||||
startTrackWidth: 1040,
|
||||
});
|
||||
|
||||
expect(result.nextZoom).toBe(16);
|
||||
expect(Number.isFinite(result.nextTrackWidth)).toBe(true);
|
||||
});
|
||||
|
||||
it("stops mobile pinch-out at the full-project fit instead of changing only the readout", () => {
|
||||
const result = getMobilePinchZoomState({
|
||||
timelineDuration: 10,
|
||||
minimumZoom: 1,
|
||||
startZoom: 1,
|
||||
startDistance: 120,
|
||||
distance: 30,
|
||||
startTrackWidth: 520,
|
||||
});
|
||||
|
||||
expect(result.nextZoom).toBe(1);
|
||||
expect(result.nextTrackWidth).toBe(520);
|
||||
});
|
||||
|
||||
it("uses the canonical mobile width so releasing the gesture cannot add a final nudge", () => {
|
||||
const result = getMobilePinchZoomState({
|
||||
timelineDuration: 20,
|
||||
minimumZoom: 1,
|
||||
startZoom: 2,
|
||||
startDistance: 100,
|
||||
distance: 140,
|
||||
startTrackWidth: 1107,
|
||||
baseTrackWidth: 520,
|
||||
});
|
||||
|
||||
expect(result.nextTrackWidth).toBeCloseTo(
|
||||
520 * (getTimelineTrackWidthPercent(20, result.nextZoom) / 100),
|
||||
5,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the same timeline time under the centered playhead after width changes", () => {
|
||||
const scrollLeft = getMobilePinchAnchorScrollLeft({
|
||||
currentScrollLeft: 180,
|
||||
trackLeft: 220,
|
||||
trackWidth: 900,
|
||||
viewportLeft: 100,
|
||||
viewportWidth: 300,
|
||||
anchorTimeRatio: 0.4,
|
||||
});
|
||||
|
||||
expect(scrollLeft).toBe(510);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,15 @@ export function createTimelineSegmentCountActions(d) {
|
||||
const index = stickerIndex(); const next = d.stickerSegments.filter((_, position) => position !== index);
|
||||
d.commitStickerSegments(next, next.length ? "已删除当前贴纸片段" : "已删除最后一个贴纸片段", next[Math.max(0, index - 1)]?.id ?? "");
|
||||
};
|
||||
const handleAddCaptionSegment = (requestedStart = null) => {
|
||||
if (d.trackLocks.caption) return void d.notify(d.t?.("captionTrackLocked") ?? "字幕轨已锁定,无法新增字幕片段");
|
||||
const insertionTime = Number.isFinite(requestedStart) ? requestedStart : d.currentTime;
|
||||
const start = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - 0.45, insertionTime));
|
||||
const segment = { id: makeId("caption"), text: d.t?.("newCaptionDefault") ?? "新的字幕片段", weight: 1, hidden: false,
|
||||
start, end: Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8) };
|
||||
const next = [...d.captionSegments, segment].sort((a, b) => (Number(a.start) || 0) - (Number(b.start) || 0));
|
||||
d.commitCaptionSegments(next, Number.isFinite(requestedStart) ? "已在点击位置新增字幕片段" : "已在播放头位置新增字幕片段", next.findIndex((item) => item.id === segment.id));
|
||||
};
|
||||
const handleAddSegment = (requestedStart = null) => {
|
||||
if (d.selectedTrack === "sticker") {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法新增贴纸片段");
|
||||
@@ -56,12 +65,7 @@ export function createTimelineSegmentCountActions(d) {
|
||||
return void d.commitVisualSegments([...source, segment], "已在播放头位置新增视觉片段", source.length);
|
||||
}
|
||||
if (["audio", "source", "music"].includes(d.selectedTrack)) return void d.notify(d.selectedTrack === "music" ? "背景音乐暂不支持切片,请删除后重新上传" : d.selectedTrack === "source" ? "视频原声暂不支持切片,可删除后重新上传视频" : "音频片段由生成结果决定,请重新生成或复制 WAV");
|
||||
const insertionTime = Number.isFinite(requestedStart) ? requestedStart : d.currentTime;
|
||||
const start = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - 0.45, insertionTime));
|
||||
const segment = { id: makeId("caption"), text: d.t?.("newCaptionDefault") ?? "新的字幕片段", weight: 1, hidden: false,
|
||||
start, end: Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8) };
|
||||
const next = [...d.captionSegments, segment].sort((a, b) => (Number(a.start) || 0) - (Number(b.start) || 0));
|
||||
d.commitCaptionSegments(next, Number.isFinite(requestedStart) ? "已在点击位置新增字幕片段" : "已在播放头位置新增字幕片段", next.findIndex((item) => item.id === segment.id));
|
||||
return handleAddCaptionSegment(requestedStart);
|
||||
};
|
||||
const handleRemoveSegment = () => {
|
||||
if (d.selectedTrack === "sticker") return void deleteSticker();
|
||||
@@ -80,5 +84,5 @@ export function createTimelineSegmentCountActions(d) {
|
||||
if (!d.captionSegments.length) return void d.notify("当前没有字幕片段可删除");
|
||||
d.deleteCaptionSegment(d.selectedSegmentId);
|
||||
};
|
||||
return { handleAddSegment, handleRemoveSegment };
|
||||
return { handleAddCaptionSegment, handleAddSegment, handleRemoveSegment };
|
||||
}
|
||||
@@ -13,6 +13,17 @@ describe("timeline segment insertion", () => {
|
||||
expect(commitCaptionSegments.mock.calls[0][0][0]).toMatchObject({ start: 4.25, end: 6.05, text: "New caption" });
|
||||
});
|
||||
|
||||
it("adds a caption from the caption panel without depending on a stale selected track", () => {
|
||||
const commitCaptionSegments = vi.fn();
|
||||
const controls = createTimelineSegmentCountActions({
|
||||
selectedTrack: "image", currentTime: 7.5, captionSegments: [], trackLocks: {},
|
||||
commitCaptionSegments, notify: vi.fn(), t: (key) => key === "newCaptionDefault" ? "New caption" : key,
|
||||
});
|
||||
controls.handleAddCaptionSegment();
|
||||
expect(commitCaptionSegments.mock.calls[0][0][0]).toMatchObject({ start: 7.5, end: 9.3, text: "New caption" });
|
||||
expect(commitCaptionSegments.mock.calls[0][2]).toBe(0);
|
||||
});
|
||||
|
||||
it("splits the active visual and inserts the new clip at the playhead", () => {
|
||||
const commitVisualSegments = vi.fn();
|
||||
const source = { id: "visual-1", type: "image", src: "image.png", duration: 8 };
|
||||
|
||||
@@ -121,7 +121,7 @@ export function createVisualTimelineActions(d) {
|
||||
if (!assetId) return;
|
||||
d.setVisualSegments((segments) => {
|
||||
const nextSegments = segments.map((segment) =>
|
||||
segment.assetId === assetId
|
||||
segment.assetId === assetId || (updates.src && segment.src === updates.src)
|
||||
? {
|
||||
...segment,
|
||||
...updates,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createVisualTimelineActions } from "./visualTimelineActions.js";
|
||||
|
||||
describe("visual asset metadata updates", () => {
|
||||
it("replaces the provisional imported-video duration by matching its source URL", () => {
|
||||
let visualSegments = [{
|
||||
id: "clip", assetId: "provisional-id", src: "blob:video", type: "video",
|
||||
duration: 4, sourceDuration: 0, playbackRate: 1,
|
||||
}];
|
||||
const actions = createVisualTimelineActions({
|
||||
visualSegments, previewVisualSegment: null, imageSrc: "", imageDuration: 4,
|
||||
setVisualSegments: (updater) => { visualSegments = updater(visualSegments); },
|
||||
setImageDuration: vi.fn(), setImageClipCount: vi.fn(), setImageMeta: vi.fn(),
|
||||
setVisualType: vi.fn(), setImageSrc: vi.fn(),
|
||||
});
|
||||
|
||||
actions.updateVisualAssetInTimeline("library-id", {
|
||||
src: "blob:video", type: "video", duration: 1.2, width: 320, height: 180,
|
||||
});
|
||||
|
||||
expect(visualSegments[0]).toMatchObject({ duration: 1.2, sourceDuration: 1.2, width: 320, height: 180 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
const FALLBACK_WAVEFORM_PEAKS = Array.from({ length: 48 }, (_, index) => {
|
||||
const envelope = 0.45 + 0.35 * Math.sin((index / 47) * Math.PI);
|
||||
const texture = 0.35 + 0.65 * Math.abs(Math.sin(index * 1.73 + 0.4));
|
||||
return Math.max(0.12, Math.min(0.88, envelope * texture));
|
||||
});
|
||||
|
||||
export function getWaveformDisplayPeaks(peaks) {
|
||||
if (Array.isArray(peaks) && peaks.length) return peaks;
|
||||
return FALLBACK_WAVEFORM_PEAKS;
|
||||
}
|
||||
|
||||
export function isWaveformPlaceholder(peaks) {
|
||||
return !Array.isArray(peaks) || peaks.length === 0;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getWaveformDisplayPeaks, isWaveformPlaceholder } from "./waveform.js";
|
||||
|
||||
describe("timeline waveform display", () => {
|
||||
it("preserves decoded peaks", () => {
|
||||
const peaks = [0.2, 0.8, 0.4];
|
||||
expect(getWaveformDisplayPeaks(peaks)).toBe(peaks);
|
||||
expect(isWaveformPlaceholder(peaks)).toBe(false);
|
||||
});
|
||||
|
||||
it("provides a stable visible fallback while peaks are unavailable", () => {
|
||||
const first = getWaveformDisplayPeaks([]);
|
||||
const second = getWaveformDisplayPeaks(null);
|
||||
expect(first).toEqual(second);
|
||||
expect(first).toHaveLength(48);
|
||||
expect(Math.min(...first)).toBeGreaterThan(0);
|
||||
expect(isWaveformPlaceholder([])).toBe(true);
|
||||
});
|
||||
});
|
||||
+310
-15
@@ -423,6 +423,8 @@ button:disabled {
|
||||
}
|
||||
|
||||
.mobile-ratio-select { display: none; }
|
||||
.timeline-mobile-clip-actions { display: none; }
|
||||
.mobile-fixed-playhead { display: none; }
|
||||
|
||||
.export-settings-popover { width: 360px; padding: 0; overflow: hidden; }
|
||||
.export-settings-card { display: grid; gap: 14px; padding: 18px; }
|
||||
@@ -3706,10 +3708,16 @@ button:disabled {
|
||||
font-weight: 760;
|
||||
}
|
||||
.caption-context-heading > span { display:flex; align-items:center; gap:7px; min-width:0; }
|
||||
.caption-import-button { margin-left:auto; display:inline-flex; align-items:center; gap:5px; border:1px solid rgba(109,225,255,.24); border-radius:7px; padding:5px 8px; color:#bcefff; background:rgba(40,174,215,.08); font-size:11px; cursor:pointer; }
|
||||
.caption-import-button { display:inline-flex; align-items:center; gap:5px; border:1px solid rgba(109,225,255,.24); border-radius:7px; padding:5px 8px; color:#bcefff; background:rgba(40,174,215,.08); font-size:11px; cursor:pointer; }
|
||||
.caption-import-button:hover { border-color:rgba(109,225,255,.5); background:rgba(40,174,215,.15); }
|
||||
.caption-empty-import { display:inline-flex; align-items:center; justify-content:center; gap:6px; margin-top:4px; min-height:34px; padding:0 12px; border:1px solid rgba(86,232,216,.4); border-radius:8px; color:#d9fffa; background:rgba(38,195,181,.12); font-size:12px; font-weight:700; cursor:pointer; }
|
||||
.caption-empty-import:hover { border-color:rgba(86,232,216,.72); background:rgba(38,195,181,.2); }
|
||||
.caption-empty-actions { display:flex; flex-wrap:wrap; align-items:center; justify-content:center; gap:8px; }
|
||||
.caption-add-button, .caption-add-inline { display:inline-flex; align-items:center; justify-content:center; gap:5px; border:1px solid rgba(71,235,219,.62); border-radius:8px; color:#071514; background:#35ead9; font-weight:800; cursor:pointer; }
|
||||
.caption-add-button { min-height:34px; padding:0 13px; font-size:12px; }
|
||||
.caption-add-inline { margin-left:auto; min-height:28px; padding:0 9px; font-size:11px; }
|
||||
.caption-add-button svg, .caption-add-inline svg { color:#073330; stroke-width:2.4; }
|
||||
.caption-add-button:hover, .caption-add-inline:hover { background:#69f2e5; }
|
||||
.srt-import-backdrop { position:fixed; inset:0; z-index:140; display:grid; place-items:center; padding:24px; background:rgba(3,7,11,.78); backdrop-filter:blur(8px); }
|
||||
.srt-import-dialog { width:min(420px, 100%); padding:22px; border:1px solid rgba(116,220,255,.22); border-radius:14px; background:#10171f; box-shadow:0 24px 70px rgba(0,0,0,.5); }
|
||||
.srt-import-dialog > strong { display:block; color:#f2f8fb; font-size:17px; }
|
||||
@@ -4331,6 +4339,11 @@ button:disabled {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.track-scroll.is-pinching,
|
||||
.timeline-ruler-canvas.is-pinching {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.ruler {
|
||||
position: relative;
|
||||
display: block;
|
||||
@@ -4945,7 +4958,7 @@ button:disabled {
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
width: var(--sticker-width, 8%);
|
||||
min-width: 76px;
|
||||
min-width: 0;
|
||||
max-width: calc(100% - var(--sticker-left, 0%));
|
||||
height: 36px;
|
||||
overflow: hidden;
|
||||
@@ -4989,6 +5002,49 @@ button:disabled {
|
||||
0 0 8px rgba(53, 234, 217, 0.2);
|
||||
}
|
||||
|
||||
.sticker-segment.is-timeline-dragging {
|
||||
opacity: 0.38;
|
||||
filter: grayscale(0.28) brightness(0.82);
|
||||
}
|
||||
|
||||
.sticker-drop-preview {
|
||||
position: absolute;
|
||||
z-index: 8;
|
||||
top: 50%;
|
||||
left: var(--sticker-drop-left, 0%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
width: var(--sticker-drop-width, 8%);
|
||||
max-width: calc(100% - var(--sticker-drop-left, 0%));
|
||||
height: 36px;
|
||||
overflow: hidden;
|
||||
border: 1px dashed rgba(53, 234, 217, 0.98);
|
||||
border-radius: 5px;
|
||||
padding: 3px 8px 3px 4px;
|
||||
color: #eafffd;
|
||||
font-size: 11px;
|
||||
font-weight: 760;
|
||||
white-space: nowrap;
|
||||
background: repeating-linear-gradient(-45deg, rgba(53, 234, 217, 0.24) 0 8px, rgba(53, 234, 217, 0.09) 8px 16px), rgba(8, 24, 28, 0.92);
|
||||
box-shadow: inset 0 0 0 1px rgba(196, 255, 249, 0.14), 0 0 18px rgba(53, 234, 217, 0.2);
|
||||
pointer-events: none;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.sticker-drop-preview img {
|
||||
flex: 0 0 auto;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.sticker-drop-preview span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.sticker-segment img {
|
||||
flex: 0 0 auto;
|
||||
width: 28px;
|
||||
@@ -5006,6 +5062,27 @@ button:disabled {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sticker-resize-handle {
|
||||
position: absolute;
|
||||
z-index: 5;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 10px;
|
||||
cursor: ew-resize;
|
||||
opacity: 0;
|
||||
transition: opacity 120ms ease, background 120ms ease;
|
||||
}
|
||||
|
||||
.sticker-resize-handle.is-start { left: 0; }
|
||||
.sticker-resize-handle.is-end { right: 0; }
|
||||
.sticker-segment:hover .sticker-resize-handle,
|
||||
.sticker-segment.is-selected-segment .sticker-resize-handle { opacity: 1; }
|
||||
.sticker-resize-handle:hover { background: rgba(53, 234, 217, 0.24); }
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.sticker-resize-handle { width: 14px; }
|
||||
}
|
||||
|
||||
.caption-segment.is-hidden {
|
||||
color: #8a98a5;
|
||||
opacity: 0.48;
|
||||
@@ -5176,10 +5253,12 @@ button:disabled {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
height: 40px;
|
||||
height: 32px;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.audio-clip > .waveform-strip { height: 100%; }
|
||||
|
||||
.audio-clip::before {
|
||||
position: absolute;
|
||||
inset: -4px -5px;
|
||||
@@ -5188,7 +5267,8 @@ button:disabled {
|
||||
|
||||
.audio-track:not(.source-track):not(.music-track) .audio-clip {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
@@ -5229,7 +5309,8 @@ button:disabled {
|
||||
|
||||
.audio-clip.is-source.is-linked {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.audio-clip.is-source .waveform-strip span {
|
||||
@@ -5514,6 +5595,7 @@ button:disabled {
|
||||
font-weight: 800;
|
||||
font-variant-numeric: tabular-nums;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@container (max-width: 68px) {
|
||||
@@ -5527,6 +5609,10 @@ button:disabled {
|
||||
background: #34ead8;
|
||||
}
|
||||
|
||||
.waveform-strip.is-placeholder span {
|
||||
opacity: 0.48;
|
||||
}
|
||||
|
||||
.waveform-strip.is-muted {
|
||||
opacity: 0.25;
|
||||
}
|
||||
@@ -5904,6 +5990,63 @@ button:disabled {
|
||||
}
|
||||
.tool-rail.is-compact .rail-tool span { display: block; }
|
||||
.rail-tool span { font-size: 10px; }
|
||||
.timeline-mobile-clip-actions {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 110;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
min-height: calc(64px + env(safe-area-inset-bottom));
|
||||
padding: 5px 5px env(safe-area-inset-bottom);
|
||||
border-top: 1px solid rgba(255, 255, 255, .09);
|
||||
background: rgba(13, 18, 24, .985);
|
||||
box-shadow: 0 -12px 28px rgba(0, 0, 0, .38);
|
||||
animation: mobile-clip-actions-enter 160ms ease-out both;
|
||||
}
|
||||
.timeline-mobile-clip-actions button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
align-content: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
min-height: 52px;
|
||||
border: 0;
|
||||
border-radius: 9px;
|
||||
padding: 3px 2px;
|
||||
color: #aab7c0;
|
||||
background: transparent;
|
||||
}
|
||||
.timeline-mobile-clip-actions button:active { color: #35ead9; background: rgba(53, 234, 217, .1); }
|
||||
.timeline-mobile-clip-actions button.is-back {
|
||||
border-right: 1px solid rgba(255, 255, 255, .08);
|
||||
border-radius: 0;
|
||||
color: #e6eff2;
|
||||
}
|
||||
.timeline-mobile-clip-actions button.is-danger { color: #ff8d92; }
|
||||
.timeline-mobile-clip-actions.is-scroll-actions {
|
||||
grid-template-columns: repeat(6, minmax(60px, 1fr));
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.timeline-mobile-clip-actions.is-scroll-actions::-webkit-scrollbar { display: none; }
|
||||
.timeline-mobile-clip-actions span {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
font-size: 9px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.image-clip,
|
||||
.visual-overlay-clip,
|
||||
.caption-segment,
|
||||
.sticker-segment,
|
||||
.audio-clip { touch-action: pan-y; }
|
||||
@keyframes mobile-clip-actions-enter {
|
||||
from { opacity: 0; transform: translateY(12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.media-panel,
|
||||
.voice-panel {
|
||||
@@ -5924,14 +6067,17 @@ button:disabled {
|
||||
padding-top: 62px;
|
||||
padding-bottom: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overflow-y: hidden;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
touch-action: pan-y;
|
||||
}
|
||||
.voice-panel { padding-top: 62px; }
|
||||
.voice-panel { padding-top: 62px; touch-action: pan-y; }
|
||||
.mobile-panel-inspector .voice-panel.is-audio-clip-context > .panel-title-row { display: none; }
|
||||
.mobile-panel-tools .media-panel,
|
||||
.mobile-panel-inspector .voice-panel {
|
||||
display: block;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
transform-origin: bottom center;
|
||||
animation: mobile-sheet-enter 240ms cubic-bezier(.2, .82, .24, 1) both;
|
||||
}
|
||||
@@ -5942,7 +6088,24 @@ button:disabled {
|
||||
}
|
||||
.media-panel > *,
|
||||
.voice-panel > * { min-width: 0; }
|
||||
.media-panel > .tabs,
|
||||
.media-panel > .drop-zone,
|
||||
.media-panel > .library-type-tabs,
|
||||
.media-panel > .library-search,
|
||||
.media-panel > .library-provider { flex: 0 0 auto; }
|
||||
.media-panel > .asset-list,
|
||||
.media-panel > .tool-panel,
|
||||
.voice-panel > .voice-tab-body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
touch-action: pan-y;
|
||||
}
|
||||
.media-panel.has-mobile-asset-actions { padding-bottom: 96px; }
|
||||
.media-panel.has-mobile-sticker-actions { padding-bottom: 72px; }
|
||||
.mobile-asset-actions {
|
||||
position: fixed;
|
||||
right: 7px;
|
||||
@@ -5987,6 +6150,46 @@ button:disabled {
|
||||
border-color: rgba(255, 255, 255, .13);
|
||||
background: rgba(255, 255, 255, .045);
|
||||
}
|
||||
.mobile-sticker-actions {
|
||||
position: fixed;
|
||||
right: 7px;
|
||||
bottom: calc(68px + env(safe-area-inset-bottom));
|
||||
left: 7px;
|
||||
z-index: 105;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
min-height: 64px;
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid rgba(255, 255, 255, .09);
|
||||
border-radius: 0 0 13px 13px;
|
||||
background: rgba(14, 20, 27, .98);
|
||||
box-shadow: 0 -10px 24px rgba(0, 0, 0, .28);
|
||||
}
|
||||
.mobile-sticker-actions button {
|
||||
min-height: 40px;
|
||||
border: 1px solid #35ead9;
|
||||
border-radius: 9px;
|
||||
color: #061312;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
background: #35ead9;
|
||||
}
|
||||
.mobile-sticker-actions button.is-secondary {
|
||||
border-color: rgba(255, 255, 255, .13);
|
||||
color: #c5d1d6;
|
||||
background: rgba(255, 255, 255, .045);
|
||||
}
|
||||
.sticker-panel { padding: 0 10px 12px; }
|
||||
.sticker-panel h2 { margin: 0 0 8px; font-size: 13px; }
|
||||
.sticker-none-button { min-height: 34px; padding: 0 10px; font-size: 11px; }
|
||||
.sticker-category-row { gap: 5px; margin: 8px 0; }
|
||||
.sticker-category-row button { min-height: 26px; padding: 0 8px; font-size: 10px; }
|
||||
.sticker-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
|
||||
.sticker-tile { aspect-ratio: 1 / 1.12; border-radius: 7px; padding: 4px; }
|
||||
.sticker-tile-thumb { border-radius: 6px; }
|
||||
.sticker-tile-thumb img { width: 72%; height: 72%; }
|
||||
.sticker-tile-label { margin-top: 4px; font-size: 9px; }
|
||||
.tool-panel { padding-bottom: 18px; }
|
||||
.asset-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.smart-hub-panel { gap: 12px; }
|
||||
@@ -6012,7 +6215,7 @@ button:disabled {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: #f0f7f8;
|
||||
font-size: 15px;
|
||||
font-size: 13px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -6023,6 +6226,7 @@ button:disabled {
|
||||
border-radius: 8px;
|
||||
padding: 0 10px;
|
||||
color: #94a2ac;
|
||||
font-size: 12px;
|
||||
background: transparent;
|
||||
}
|
||||
.mobile-sheet-nav button.is-active { color: #36ead9; background: rgba(54, 234, 217, .1); }
|
||||
@@ -6069,6 +6273,7 @@ button:disabled {
|
||||
}
|
||||
|
||||
.timeline {
|
||||
--mobile-track-label-width: 104px;
|
||||
grid-area: timeline;
|
||||
grid-template-rows: 40px minmax(0, 1fr);
|
||||
min-height: 0;
|
||||
@@ -6076,6 +6281,29 @@ button:disabled {
|
||||
margin: 6px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.mobile-fixed-playhead {
|
||||
position: absolute;
|
||||
top: 68px;
|
||||
bottom: 0;
|
||||
left: calc(var(--mobile-track-label-width) + (100% - var(--mobile-track-label-width)) / 2);
|
||||
z-index: 12;
|
||||
display: block;
|
||||
width: 2px;
|
||||
pointer-events: none;
|
||||
background: #f4fbff;
|
||||
box-shadow: 0 0 0 1px rgba(0, 0, 0, .18);
|
||||
}
|
||||
.mobile-fixed-playhead::before {
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
right: 50%;
|
||||
width: 18px;
|
||||
height: 10px;
|
||||
background: #f4fbff;
|
||||
clip-path: polygon(0 0, 100% 0, 50% 100%);
|
||||
transform: translateX(50%);
|
||||
content: "";
|
||||
}
|
||||
.timeline-tools { gap: 5px; padding: 0 7px; overflow-x: auto; }
|
||||
.timeline-tools .icon-button { flex: 0 0 auto; width: 36px; height: 36px; }
|
||||
.timeline-icon-group { flex: 0 0 auto; }
|
||||
@@ -6086,13 +6314,35 @@ button:disabled {
|
||||
.timeline-segment-tools > .timeline-play-button span { display: none; }
|
||||
.zoom-readout { min-width: 42px; font-size: 11px; }
|
||||
.timeline-board {
|
||||
grid-template-columns: 104px minmax(520px, 1fr);
|
||||
grid-template-columns: 104px minmax(0, 1fr);
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
max-height: none;
|
||||
overflow: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
.tracks {
|
||||
padding-bottom: 0;
|
||||
padding-right: 0;
|
||||
padding-left: 0;
|
||||
/* Horizontal touch movement is coordinated by Timeline so a two-finger
|
||||
scale never inherits WebKit's native pan momentum. */
|
||||
touch-action: none;
|
||||
}
|
||||
.timeline-ruler-viewport {
|
||||
padding-right: 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
.track-scroll,
|
||||
.timeline-ruler-canvas {
|
||||
min-width: 520px;
|
||||
margin-right: calc(50% - 1px);
|
||||
margin-left: calc(50% - 1px);
|
||||
}
|
||||
.playhead-ruler,
|
||||
.playhead {
|
||||
display: none;
|
||||
}
|
||||
.track-label { padding: 0 6px; }
|
||||
.track-label strong { font-size: 10px; }
|
||||
.track-labels,
|
||||
@@ -6100,9 +6350,38 @@ button:disabled {
|
||||
grid-template-rows: none !important;
|
||||
grid-auto-rows: 40px;
|
||||
}
|
||||
.track-labels div { gap: 3px; padding: 0 5px; }
|
||||
.track-labels div { min-width: 0; overflow: hidden; gap: 3px; padding: 0 5px; }
|
||||
.track-labels button { width: 20px; height: 20px; }
|
||||
.track-labels .track-name-button { font-size: 11px; }
|
||||
.track-labels > .is-track-locked { background: rgba(255, 255, 255, .025); }
|
||||
.track-labels > .is-track-locked button[aria-pressed="true"] { color: #45e8d8; }
|
||||
.track-labels button[aria-pressed] { width: 28px; height: 28px; }
|
||||
.track-labels .track-name-button {
|
||||
display: block;
|
||||
width: 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-size: 11px;
|
||||
line-height: 20px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.audio-clip-duration {
|
||||
right: 5px;
|
||||
bottom: 5px;
|
||||
max-width: calc(100% - 10px);
|
||||
padding: 1px 4px;
|
||||
overflow: hidden;
|
||||
font-size: 0;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.audio-clip-duration::after {
|
||||
font-size: 9px;
|
||||
content: attr(data-compact-duration);
|
||||
}
|
||||
@container (max-width: 220px) {
|
||||
.audio-clip-duration { display: none; }
|
||||
}
|
||||
.visual-segment,
|
||||
.caption-segment,
|
||||
.sticker-segment,
|
||||
@@ -6220,11 +6499,14 @@ button:disabled {
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.timeline { --mobile-track-label-width: 92px; }
|
||||
.project-title { display: none; }
|
||||
.export-button { padding: 0 10px; }
|
||||
.app-shell { grid-template-rows: auto minmax(260px, 43dvh) minmax(0, 1fr) auto; }
|
||||
.preview-stage { min-height: 260px; }
|
||||
.timeline-board { grid-template-columns: 92px minmax(480px, 1fr); }
|
||||
.timeline-board { grid-template-columns: 92px minmax(0, 1fr); }
|
||||
.track-scroll,
|
||||
.timeline-ruler-canvas { min-width: 480px; }
|
||||
}
|
||||
|
||||
/* Tool panels remain wheel/trackpad scrollable without persistent scrollbar chrome. */
|
||||
@@ -6243,7 +6525,20 @@ button:disabled {
|
||||
@media (max-width: 760px) {
|
||||
.media-panel .tool-panel {
|
||||
height: auto;
|
||||
min-height: 100%;
|
||||
overflow-y: visible;
|
||||
min-height: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
touch-action: pan-y;
|
||||
}
|
||||
.media-panel .tool-panel h2 { margin-bottom: 11px; font-size: 14px; }
|
||||
.media-panel .tool-panel,
|
||||
.voice-panel .voice-tab-body { font-size: 12px; }
|
||||
.media-panel .tool-panel p,
|
||||
.media-panel .tool-panel label,
|
||||
.media-panel .tool-panel button,
|
||||
.voice-panel .voice-tab-body p,
|
||||
.voice-panel .voice-tab-body label,
|
||||
.voice-panel .voice-tab-body button { font-size: 11px; }
|
||||
}
|
||||
Reference in new issue
Block a user