Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(video-editor): region copy/paste and shared text-editing guard

446f6e6e7933cf5c3d0b19
diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsx
index 5f9ec0f26..1ded512bb 100644
--- a/src/components/video-editor/VideoEditor.tsx
+++ b/src/components/video-editor/VideoEditor.tsx
@@ -51,7 +51,7 @@ import {
} from "@/lib/exporter";
import { computeFrameStepTime } from "@/lib/frameStep";
import type { CursorCaptureMode, ProjectMedia } from "@/lib/recordingSession";
-import { matchesShortcut } from "@/lib/shortcuts";
+import { isTextEditingTarget, matchesShortcut } from "@/lib/shortcuts";
import {
getExportFolder,
getProjectFolder,
@@ -88,15 +88,18 @@ import {
validateProjectData,
} from "./projectPersistence";
import {
- applyAnnotationAttributes,
- applySpeedAttributes,
- applyZoomAttributes,
buildPastedAnnotation,
+ buildSpeedRegion,
+ buildZoomRegion,
type CopiedRegion,
extractAnnotationAttributes,
extractSpeedAttributes,
extractZoomAttributes,
+ getCopiedRegion,
+ replaceAnnotationAttributes,
+ setCopiedRegion,
} from "./regionClipboard";
+import { findFreeGapAt } from "./regionPlacement";
import { SettingsPanel } from "./SettingsPanel";
import TimelineEditor from "./timeline/TimelineEditor";
import { buildAutoZoomSuggestions } from "./timeline/zoomSuggestionUtils";
@@ -310,9 +313,6 @@ export default function VideoEditor() {
const nextTrimIdRef = useRef(1);
const nextSpeedIdRef = useRef(1);
- // Session clipboard for "copy/paste region attributes" (not undoable, not persisted).
- const regionClipboardRef = useRef<CopiedRegion | null>(null);
-
const { shortcuts, isMac } = useShortcuts();
// Windows recordings include captured cursor assets. macOS hides the system
// cursor in ScreenCaptureKit and renders telemetry samples with OpenScreen's
@@ -326,6 +326,7 @@ export default function VideoEditor() {
const { locale, setLocale, t: rawT } = useI18n();
const t = useScopedT("editor");
const ts = useScopedT("settings");
+ const tt = useScopedT("timeline");
const availableLocales = getAvailableLocales();
const nextAnnotationIdRef = useRef(1);
@@ -1654,29 +1655,28 @@ export default function VideoEditor() {
);
const handleCopySelected = useCallback(() => {
- if (selectedZoomId) {
- const region = zoomRegions.find((r) => r.id === selectedZoomId);
- if (region) {
- regionClipboardRef.current = extractZoomAttributes(region);
- toast.success(t("regionClipboard.copied", { region: t("regionClipboard.kinds.zoom") }));
- }
- return;
- }
- if (selectedSpeedId) {
- const region = speedRegions.find((r) => r.id === selectedSpeedId);
- if (region) {
- regionClipboardRef.current = extractSpeedAttributes(region);
- toast.success(t("regionClipboard.copied", { region: t("regionClipboard.kinds.speed") }));
- }
- return;
- }
- if (selectedAnnotationId) {
- const region = annotationRegions.find((r) => r.id === selectedAnnotationId);
+ // Copy the selected region of any kind into the clipboard. A selected blur is an
+ // annotation (type "blur" lives in annotationRegions), so it copies via that row.
+ const copyTargets = [
+ [selectedZoomId, zoomRegions, extractZoomAttributes, "zoom"],
+ [selectedSpeedId, speedRegions, extractSpeedAttributes, "speed"],
+ [
+ selectedAnnotationId ?? selectedBlurId,
+ annotationRegions,
+ extractAnnotationAttributes,
+ "annotation",
+ ],
+ ] as const;
+
+ for (const [id, regions, extract, kind] of copyTargets) {
+ if (!id) continue;
+ const region = (regions as readonly { id: string }[]).find((r) => r.id === id);
if (region) {
- regionClipboardRef.current = extractAnnotationAttributes(region);
- toast.success(
- t("regionClipboard.copied", { region: t("regionClipboard.kinds.annotation") }),
- );
+ // Each row pairs a region list with its matching extractor, so the cast is sound.
+ setCopiedRegion((extract as (r: never) => CopiedRegion)(region as never));
+ toast.success(t("regionClipboard.copied", { region: t(`regionClipboard.kinds.${kind}`) }), {
+ id: "regionClipboard.copied",
+ });
}
return;
}
@@ -1685,6 +1685,7 @@ export default function VideoEditor() {
selectedZoomId,
selectedSpeedId,
selectedAnnotationId,
+ selectedBlurId,
zoomRegions,
speedRegions,
annotationRegions,
@@ -1692,42 +1693,56 @@ export default function VideoEditor() {
]);
const handlePaste = useCallback(() => {
- const copied = regionClipboardRef.current;
+ const copied = getCopiedRegion();
// If there's nothing in the clipboard, show a message and return early.
if (!copied) {
toast.info(t("regionClipboard.nothingToPaste"));
return;
}
- const regionLabel = t(`regionClipboard.kinds.${copied.kind}`);
- const pastedToast = () => toast.success(t("regionClipboard.pasted", { region: regionLabel }));
-
// Apply onto the selected region of the same kind, keeping its timing.
if (copied.kind === "zoom" && selectedZoomId) {
pushState((prev) => ({
zoomRegions: prev.zoomRegions.map((r) =>
- r.id === selectedZoomId ? applyZoomAttributes(r, copied) : r,
+ r.id === selectedZoomId ? buildZoomRegion(r, copied) : r,
),
}));
- pastedToast();
+ toast.success(
+ t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),
+ {
+ id: "regionClipboard.pasted",
+ },
+ );
return;
}
if (copied.kind === "speed" && selectedSpeedId) {
pushState((prev) => ({
speedRegions: prev.speedRegions.map((r) =>
- r.id === selectedSpeedId ? applySpeedAttributes(r, copied) : r,
+ r.id === selectedSpeedId ? buildSpeedRegion(r, copied) : r,
),
}));
- pastedToast();
+ toast.success(
+ t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),
+ {
+ id: "regionClipboard.pasted",
+ },
+ );
return;
}
- if (copied.kind === "annotation" && selectedAnnotationId) {
+ // Blurs live in annotationRegions (type "blur"), so a selected blur is a valid target too.
+ if (copied.kind === "annotation" && (selectedAnnotationId || selectedBlurId)) {
+ const targetId = selectedAnnotationId ?? selectedBlurId;
pushState((prev) => ({
annotationRegions: prev.annotationRegions.map((r) =>
- r.id === selectedAnnotationId ? applyAnnotationAttributes(r, copied) : r,
+ r.id === targetId ? replaceAnnotationAttributes(r, copied) : r,
),
}));
- pastedToast();
+ toast.success(
+ t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),
+ {
+ id: "regionClipboard.pasted",
+ },
+ );
return;
}
@@ -1738,56 +1753,59 @@ export default function VideoEditor() {
const startPos = Math.max(0, Math.min(Math.round(currentTime * 1000), totalMs));
if (copied.kind === "zoom") {
- const sorted = [...zoomRegions].sort((a, b) => a.startMs - b.startMs);
- const nextRegion = sorted.find((r) => r.startMs > startPos);
- const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;
- const overlapping = sorted.some((r) => startPos >= r.startMs && startPos < r.endMs);
-
- if (overlapping || gapToNext <= 0) {
- toast.error(t("regionClipboard.cannotPlace"));
+ const { ok, gapMs } = findFreeGapAt(zoomRegions, startPos, totalMs);
+ if (!ok) {
+ toast.error(tt("errors.cannotPlaceZoom"), {
+ description: tt("errors.zoomExistsAtLocation"),
+ });
return;
}
const id = `zoom-${nextZoomIdRef.current++}`;
- const region = applyZoomAttributes(
+ const region = buildZoomRegion(
{
id,
startMs: startPos,
- endMs: startPos + Math.min(defaultDuration, gapToNext),
- depth: DEFAULT_ZOOM_DEPTH,
- focus: { cx: 0.5, cy: 0.5 },
+ endMs: startPos + Math.min(defaultDuration, gapMs),
source: "manual",
},
copied,
);
pushState((prev) => ({ zoomRegions: [...prev.zoomRegions, region] }));
handleSelectZoom(id);
- pastedToast();
+ toast.success(
+ t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),
+ {
+ id: "regionClipboard.pasted",
+ },
+ );
return;
}
if (copied.kind === "speed") {
- const sorted = [...speedRegions].sort((a, b) => a.startMs - b.startMs);
- const nextRegion = sorted.find((r) => r.startMs > startPos);
- const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;
- const overlapping = sorted.some((r) => startPos >= r.startMs && startPos < r.endMs);
-
- if (overlapping || gapToNext <= 0) {
- toast.error(t("regionClipboard.cannotPlace"));
+ const { ok, gapMs } = findFreeGapAt(speedRegions, startPos, totalMs);
+ if (!ok) {
+ toast.error(tt("errors.cannotPlaceSpeed"), {
+ description: tt("errors.speedExistsAtLocation"),
+ });
return;
}
const id = `speed-${nextSpeedIdRef.current++}`;
- const region = applySpeedAttributes(
+ const region = buildSpeedRegion(
{
id,
startMs: startPos,
- endMs: startPos + Math.min(defaultDuration, gapToNext),
- speed: DEFAULT_PLAYBACK_SPEED,
+ endMs: startPos + Math.min(defaultDuration, gapMs),
},
copied,
);
pushState((prev) => ({ speedRegions: [...prev.speedRegions, region] }));
handleSelectSpeed(id);
- pastedToast();
+ toast.success(
+ t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),
+ {
+ id: "regionClipboard.pasted",
+ },
+ );
return;
}
@@ -1805,11 +1823,17 @@ export default function VideoEditor() {
);
pushState((prev) => ({ annotationRegions: [...prev.annotationRegions, region] }));
handleSelectAnnotation(id);
- pastedToast();
+ toast.success(
+ t("regionClipboard.pasted", { region: t(`regionClipboard.kinds.${copied.kind}`) }),
+ {
+ id: "regionClipboard.pasted",
+ },
+ );
}, [
selectedZoomId,
selectedSpeedId,
selectedAnnotationId,
+ selectedBlurId,
zoomRegions,
speedRegions,
duration,
@@ -1819,6 +1843,7 @@ export default function VideoEditor() {
handleSelectSpeed,
handleSelectAnnotation,
t,
+ tt,
]);
useEffect(() => {
@@ -1841,10 +1866,7 @@ export default function VideoEditor() {
// Copy/paste region attributes. Skipped while typing in a field so native
// text copy/paste keeps working.
- const editingText =
- e.target instanceof HTMLInputElement ||
- e.target instanceof HTMLTextAreaElement ||
- (e.target instanceof HTMLElement && e.target.isContentEditable);
+ const editingText = isTextEditingTarget(e.target);
if (!editingText) {
if (matchesShortcut(e, shortcuts.copySelected, isMac)) {
e.preventDefault();
diff --git a/src/components/video-editor/regionClipboard.test.ts b/src/components/video-editor/regionClipboard.test.ts
index 5a3fce0d9..f99f17eb2 100644
--- a/src/components/video-editor/regionClipboard.test.ts
+++ b/src/components/video-editor/regionClipboard.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, it } from "vitest";
import {
- applyAnnotationAttributes,
- applySpeedAttributes,
- applyZoomAttributes,
buildPastedAnnotation,
+ buildSpeedRegion,
+ buildZoomRegion,
extractAnnotationAttributes,
extractSpeedAttributes,
extractZoomAttributes,
+ replaceAnnotationAttributes,
} from "./regionClipboard";
import {
type AnnotationRegion,
@@ -56,7 +56,7 @@ describe("zoom attribute copy/paste", () => {
focus: { cx: 0.5, cy: 0.5 },
source: "manual",
};
- const result = applyZoomAttributes(target, attrs);
+ const result = buildZoomRegion(target, attrs);
expect(result.id).toBe("zoom-2");
expect(result.startMs).toBe(9000);
@@ -70,7 +70,7 @@ describe("zoom attribute copy/paste", () => {
it("deep-copies focus so the source and target are decoupled", () => {
const attrs = extractZoomAttributes(zoom);
- const result = applyZoomAttributes({ ...zoom, id: "zoom-2" }, attrs);
+ const result = buildZoomRegion({ ...zoom, id: "zoom-2" }, attrs);
result.focus.cx = 0.99;
expect(zoom.focus.cx).toBe(0.2);
});
@@ -80,7 +80,7 @@ describe("speed attribute copy/paste", () => {
it("copies only the speed value", () => {
const attrs = extractSpeedAttributes(speed);
const target: SpeedRegion = { id: "speed-2", startMs: 4000, endMs: 5000, speed: 1 };
- const result = applySpeedAttributes(target, attrs);
+ const result = buildSpeedRegion(target, attrs);
expect(result).toEqual({ id: "speed-2", startMs: 4000, endMs: 5000, speed: 2 });
});
});
@@ -110,7 +110,7 @@ describe("paste onto an existing annotation applies styling only", () => {
style: { ...DEFAULT_ANNOTATION_STYLE },
zIndex: 9,
};
- const result = applyAnnotationAttributes(target, attrs);
+ const result = replaceAnnotationAttributes(target, attrs);
expect(result.content).toBe("world");
expect(result.position).toEqual(DEFAULT_ANNOTATION_POSITION);
@@ -119,13 +119,14 @@ describe("paste onto an existing annotation applies styling only", () => {
expect(result.style.color).toBe("#ff0000");
expect(result.style.textAnimation).toBe("pop");
expect(result.size).toEqual({ width: 40, height: 25 });
- expect(result.figureData?.color).toBe("#123456");
+ // Target is text, so the copied figure's figureData must NOT attach (F5 guard).
+ expect(result.figureData).toBeUndefined();
});
it("keeps the target's own figure data when the copied region has none", () => {
const textAttrs = extractAnnotationAttributes({ ...annotation, figureData: undefined });
const figureTarget: AnnotationRegion = { ...annotation, id: "annotation-3" };
- const result = applyAnnotationAttributes(figureTarget, textAttrs);
+ const result = replaceAnnotationAttributes(figureTarget, textAttrs);
expect(result.figureData?.color).toBe("#123456");
});
});
@@ -159,3 +160,44 @@ describe("paste as a new annotation clones the full copy", () => {
expect(annotation.position.x).toBe(10);
});
});
+
+describe("zoom paste replaces customScale destructively (F4)", () => {
+ it("clears the target's customScale when the copied zoom is preset-only", () => {
+ const presetOnly = extractZoomAttributes({ ...zoom, customScale: undefined });
+ const target: ZoomRegion = { ...zoom, id: "zoom-3", customScale: 1.5 };
+ const result = buildZoomRegion(target, presetOnly);
+ expect(result.customScale).toBeUndefined();
+ });
+});
+
+describe("figureData guard on paste-onto-existing (F5)", () => {
+ it("does not attach figureData onto a non-figure target", () => {
+ const figureAttrs = extractAnnotationAttributes(annotation);
+ const textTarget: AnnotationRegion = {
+ id: "annotation-6",
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "hi",
+ position: { ...DEFAULT_ANNOTATION_POSITION },
+ size: { ...DEFAULT_ANNOTATION_SIZE },
+ style: { ...DEFAULT_ANNOTATION_STYLE },
+ zIndex: 1,
+ };
+ const result = replaceAnnotationAttributes(textTarget, figureAttrs);
+ expect(result.figureData).toBeUndefined();
+ // Styling still applies regardless of type.
+ expect(result.style.color).toBe("#ff0000");
+ });
+
+ it("applies figureData when the target is itself a figure", () => {
+ const figureAttrs = extractAnnotationAttributes(annotation);
+ const figureTarget: AnnotationRegion = {
+ ...annotation,
+ id: "annotation-7",
+ figureData: { ...DEFAULT_FIGURE_DATA, color: "#000000" },
+ };
+ const result = replaceAnnotationAttributes(figureTarget, figureAttrs);
+ expect(result.figureData?.color).toBe("#123456");
+ });
+});
diff --git a/src/components/video-editor/regionClipboard.ts b/src/components/video-editor/regionClipboard.ts
index fdacafaad..b1dd06c8c 100644
--- a/src/components/video-editor/regionClipboard.ts
+++ b/src/components/video-editor/regionClipboard.ts
@@ -14,28 +14,22 @@ import type {
ZoomRegion,
} from "./types";
-/** Timeline Region kinds whose attributes can be copied. Trim has no attributes */
-export type RegionKind = "zoom" | "speed" | "annotation";
-
-/** ZoomRegion attributes that can be copied */
-export interface ZoomAttributes {
+/** The copyable attributes of each region, tagged with its `kind` so paste can discriminate.
+ * Trim has no attributes, so it isn't copyable. */
+export type CopiedZoom = {
kind: "zoom";
depth: ZoomDepth;
customScale?: number;
focus: ZoomFocus;
focusMode?: ZoomFocusMode;
rotationPreset?: Rotation3DPreset;
-}
+};
-/** SpeedRegion attributes that can be copied */
-export interface SpeedAttributes {
- kind: "speed";
- speed: PlaybackSpeed;
-}
+export type CopiedSpeed = { kind: "speed"; speed: PlaybackSpeed };
-/** AnnotationRegion attributes that can be copied. Copy captures everything; paste then
- * uses only the styling for an existing region, or the full set for a brand-new one. */
-export interface AnnotationAttributes {
+/** Annotation copy captures everything; paste then uses only the styling for an existing
+ * region, or the full set for a brand-new one. */
+export type CopiedAnnotation = {
kind: "annotation";
// Styling — applied both when pasting onto an existing region and onto a new one.
style: AnnotationTextStyle;
@@ -47,11 +41,23 @@ export interface AnnotationAttributes {
textContent?: string;
imageContent?: string;
position: AnnotationPosition;
+};
+
+export type CopiedRegion = CopiedZoom | CopiedSpeed | CopiedAnnotation;
+
+/** Session clipboard for "copy/paste region attributes" (not undoable, not persisted).
+ * Module-level so it's shared regardless of which editor instance copied. */
+let clipboard: CopiedRegion | null = null;
+
+export function getCopiedRegion(): CopiedRegion | null {
+ return clipboard;
}
-export type CopiedRegion = ZoomAttributes | SpeedAttributes | AnnotationAttributes;
+export function setCopiedRegion(region: CopiedRegion): void {
+ clipboard = region;
+}
-export function extractZoomAttributes(region: ZoomRegion): ZoomAttributes {
+export function extractZoomAttributes(region: ZoomRegion): CopiedZoom {
return {
kind: "zoom",
depth: region.depth,
@@ -62,11 +68,11 @@ export function extractZoomAttributes(region: ZoomRegion): ZoomAttributes {
};
}
-export function extractSpeedAttributes(region: SpeedRegion): SpeedAttributes {
+export function extractSpeedAttributes(region: SpeedRegion): CopiedSpeed {
return { kind: "speed", speed: region.speed };
}
-export function extractAnnotationAttributes(region: AnnotationRegion): AnnotationAttributes {
+export function extractAnnotationAttributes(region: AnnotationRegion): CopiedAnnotation {
return {
kind: "annotation",
style: { ...region.style },
@@ -80,35 +86,39 @@ export function extractAnnotationAttributes(region: AnnotationRegion): Annotatio
};
}
-/** Returns a new region with the copied attributes overwriting its own. Identity and
- * timing (id, startMs, endMs) are preserved; nested objects are deep-copied. */
-export function applyZoomAttributes(region: ZoomRegion, attrs: ZoomAttributes): ZoomRegion {
- return {
- ...region,
- depth: attrs.depth,
- customScale: attrs.customScale,
- focus: { ...attrs.focus },
- focusMode: attrs.focusMode,
- rotationPreset: attrs.rotationPreset,
- };
+/** Returns a region carrying the copied attributes. Identity, timing, and source come from
+ * `base` (so a full region keeps its own); every attribute comes from the copy, with nested
+ * objects deep-copied. Passing a stub `base` builds a brand-new region; passing an existing
+ * region overwrites ALL its attributes (e.g. a preset-only copy clears the target's customScale). */
+export function buildZoomRegion(
+ base: Pick<ZoomRegion, "id" | "startMs" | "endMs" | "source">,
+ attrs: CopiedZoom,
+): ZoomRegion {
+ const { kind: _kind, ...zoomAttrs } = attrs;
+ return { ...base, ...zoomAttrs, focus: { ...zoomAttrs.focus } };
}
-export function applySpeedAttributes(region: SpeedRegion, attrs: SpeedAttributes): SpeedRegion {
- return { ...region, speed: attrs.speed };
+export function buildSpeedRegion(
+ base: Pick<SpeedRegion, "id" | "startMs" | "endMs">,
+ attrs: CopiedSpeed,
+): SpeedRegion {
+ return { ...base, speed: attrs.speed };
}
/** Pastes onto an EXISTING annotation: only the styling is overwritten — the target keeps
* its own type, text/image content, position, timing, and stacking order. */
-export function applyAnnotationAttributes(
+export function replaceAnnotationAttributes(
region: AnnotationRegion,
- attrs: AnnotationAttributes,
+ attrs: CopiedAnnotation,
): AnnotationRegion {
return {
...region,
style: { ...attrs.style },
size: { ...attrs.size },
- // Keep the target's own figure data when the copied region has none (e.g. text → figure).
- figureData: attrs.figureData ? { ...attrs.figureData } : region.figureData,
+ // Only carry figure data onto a figure target; never attach it to a non-figure
+ // (e.g. pasting a figure's attributes onto a text annotation keeps the text figure-less).
+ figureData:
+ region.type === "figure" && attrs.figureData ? { ...attrs.figureData } : region.figureData,
};
}
@@ -116,7 +126,7 @@ export function applyAnnotationAttributes(
* figure data, and position. Identity, timing, and stacking order come from `base`. */
export function buildPastedAnnotation(
base: Pick<AnnotationRegion, "id" | "startMs" | "endMs" | "zIndex">,
- attrs: AnnotationAttributes,
+ attrs: CopiedAnnotation,
): AnnotationRegion {
return {
...base,
diff --git a/src/components/video-editor/regionPlacement.test.ts b/src/components/video-editor/regionPlacement.test.ts
new file mode 100644
index 000000000..6268776f9
--- /dev/null
+++ b/src/components/video-editor/regionPlacement.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import { findFreeGapAt } from "./regionPlacement";
+
+const totalMs = 10000;
+
+describe("findFreeGapAt", () => {
+ it("returns the gap to the end when there are no regions", () => {
+ const { ok, gapMs } = findFreeGapAt([], 2000, totalMs);
+ expect(ok).toBe(true);
+ expect(gapMs).toBe(8000);
+ });
+
+ it("rejects a playhead that lands inside an existing region", () => {
+ const regions = [{ startMs: 1000, endMs: 4000 }];
+ const { ok } = findFreeGapAt(regions, 2000, totalMs);
+ expect(ok).toBe(false);
+ });
+
+ it("clamps the gap to the next region's start", () => {
+ const regions = [{ startMs: 5000, endMs: 7000 }];
+ const { ok, gapMs } = findFreeGapAt(regions, 2000, totalMs);
+ expect(ok).toBe(true);
+ expect(gapMs).toBe(3000);
+ });
+
+ it("rejects placement with no room before the end", () => {
+ const { ok, gapMs } = findFreeGapAt([], totalMs, totalMs);
+ expect(ok).toBe(false);
+ expect(gapMs).toBe(0);
+ });
+
+ it("allows placement adjacent to (exactly at the end of) an existing region", () => {
+ const regions = [{ startMs: 0, endMs: 2000 }];
+ const { ok, gapMs } = findFreeGapAt(regions, 2000, totalMs);
+ expect(ok).toBe(true);
+ expect(gapMs).toBe(8000);
+ });
+
+ it("sorts unordered regions before computing the next gap", () => {
+ const regions = [
+ { startMs: 8000, endMs: 9000 },
+ { startMs: 3000, endMs: 4000 },
+ ];
+ const { ok, gapMs } = findFreeGapAt(regions, 1000, totalMs);
+ expect(ok).toBe(true);
+ expect(gapMs).toBe(2000);
+ });
+});
diff --git a/src/components/video-editor/regionPlacement.ts b/src/components/video-editor/regionPlacement.ts
new file mode 100644
index 000000000..7343def0f
--- /dev/null
+++ b/src/components/video-editor/regionPlacement.ts
@@ -0,0 +1,24 @@
+/**
+ * Find the available gap at `startPos` in a list of regions.
+ *
+ * Looks at the span from `startPos` up to the start of the next region
+ * (or up to `totalMs` if there is no later region) and reports its size,
+ * along with whether placement at `startPos` is actually valid.
+ *
+ * Placement is valid as long as `startPos` does not fall inside an
+ * existing region and there is some room before the next one. Landing
+ * exactly on the start of an existing region is fine (adjacency is
+ * allowed); landing strictly between a region's start and end, or
+ * having zero space left before the next region, is not.
+ */
+export function findFreeGapAt(
+ regions: ReadonlyArray<{ startMs: number; endMs: number }>,
+ startPos: number,
+ totalMs: number,
+): { ok: boolean; gapMs: number } {
+ const sorted = [...regions].sort((a, b) => a.startMs - b.startMs);
+ const nextRegion = sorted.find((r) => r.startMs > startPos);
+ const gapMs = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;
+ const overlapping = sorted.some((r) => startPos >= r.startMs && startPos < r.endMs);
+ return { ok: !overlapping && gapMs > 0, gapMs };
+}
diff --git a/src/components/video-editor/timeline/TimelineEditor.tsx b/src/components/video-editor/timeline/TimelineEditor.tsx
index 17894ad1c..96965a012 100644
--- a/src/components/video-editor/timeline/TimelineEditor.tsx
+++ b/src/components/video-editor/timeline/TimelineEditor.tsx
@@ -25,11 +25,12 @@ import {
import { useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { useAudioPeaks } from "@/hooks/useAudioPeaks";
-import { matchesShortcut } from "@/lib/shortcuts";
+import { isTextEditingTarget, matchesShortcut } from "@/lib/shortcuts";
import { cn } from "@/lib/utils";
import { ASPECT_RATIOS, type AspectRatio, getAspectRatioLabel } from "@/utils/aspectRatioUtils";
import { formatShortcut } from "@/utils/platformUtils";
import { BLUR_REGIONS_ENABLED } from "../featureFlags";
+import { findFreeGapAt } from "../regionPlacement";
import type { AnnotationRegion, SpeedRegion, TrimRegion, ZoomRegion } from "../types";
import BackgroundWaveform from "./BackgroundWaveform";
import Item from "./Item";
@@ -1120,21 +1121,15 @@ export default function TimelineEditor({
}
const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));
- const sorted = [...zoomRegions].sort((a, b) => a.startMs - b.startMs);
- const nextRegion = sorted.find((region) => region.startMs > startPos);
- const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;
-
- const isOverlapping = sorted.some(
- (region) => startPos >= region.startMs && startPos < region.endMs,
- );
- if (isOverlapping || gapToNext <= 0) {
+ const { ok, gapMs } = findFreeGapAt(zoomRegions, startPos, totalMs);
+ if (!ok) {
toast.error(t("errors.cannotPlaceZoom"), {
description: t("errors.zoomExistsAtLocation"),
});
return;
}
- const actualDuration = Math.min(defaultRegionDurationMs, gapToNext);
+ const actualDuration = Math.min(defaultRegionDurationMs, gapMs);
onZoomAdded({ start: startPos, end: startPos + actualDuration });
}, [videoDuration, totalMs, currentTimeMs, zoomRegions, onZoomAdded, defaultRegionDurationMs, t]);
@@ -1149,21 +1144,15 @@ export default function TimelineEditor({
}
const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));
- const sorted = [...trimRegions].sort((a, b) => a.startMs - b.startMs);
- const nextRegion = sorted.find((region) => region.startMs > startPos);
- const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;
-
- const isOverlapping = sorted.some(
- (region) => startPos >= region.startMs && startPos < region.endMs,
- );
- if (isOverlapping || gapToNext <= 0) {
+ const { ok, gapMs } = findFreeGapAt(trimRegions, startPos, totalMs);
+ if (!ok) {
toast.error(t("errors.cannotPlaceTrim"), {
description: t("errors.trimExistsAtLocation"),
});
return;
}
- const actualDuration = Math.min(defaultRegionDurationMs, gapToNext);
+ const actualDuration = Math.min(defaultRegionDurationMs, gapMs);
onTrimAdded({ start: startPos, end: startPos + actualDuration });
}, [videoDuration, totalMs, currentTimeMs, trimRegions, onTrimAdded, defaultRegionDurationMs, t]);
@@ -1178,21 +1167,15 @@ export default function TimelineEditor({
}
const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));
- const sorted = [...speedRegions].sort((a, b) => a.startMs - b.startMs);
- const nextRegion = sorted.find((region) => region.startMs > startPos);
- const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;
-
- const isOverlapping = sorted.some(
- (region) => startPos >= region.startMs && startPos < region.endMs,
- );
- if (isOverlapping || gapToNext <= 0) {
+ const { ok, gapMs } = findFreeGapAt(speedRegions, startPos, totalMs);
+ if (!ok) {
toast.error(t("errors.cannotPlaceSpeed"), {
description: t("errors.speedExistsAtLocation"),
});
return;
}
- const actualDuration = Math.min(defaultRegionDurationMs, gapToNext);
+ const actualDuration = Math.min(defaultRegionDurationMs, gapMs);
onSpeedAdded({ start: startPos, end: startPos + actualDuration });
}, [
videoDuration,
@@ -1238,7 +1221,7 @@ export default function TimelineEditor({
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
- if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
+ if (isTextEditingTarget(e.target)) {
return;
}
diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.json
index 3ba6a4eea..e658d08c2 100644
--- a/src/i18n/locales/ar/editor.json
+++ b/src/i18n/locales/ar/editor.json
@@ -83,7 +83,6 @@
"pasted": "تم لصق سمات {{region}}",
"nothingToCopy": "حدد منطقة لنسخ سماتها",
"nothingToPaste": "لم يتم نسخ أي سمات بعد",
- "cannotPlace": "لا يمكن وضع المنطقة هنا: ستتداخل مع منطقة أخرى",
"kinds": {
"zoom": "تكبير",
"speed": "سرعة",
diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.json
index f3d9c1bc6..79b7d7126 100644
--- a/src/i18n/locales/en/editor.json
+++ b/src/i18n/locales/en/editor.json
@@ -83,7 +83,6 @@
"pasted": "{{region}} attributes pasted",
"nothingToCopy": "Select a region to copy its attributes",
"nothingToPaste": "No attributes copied yet",
- "cannotPlace": "Can't place the region here — it would overlap another",
"kinds": {
"zoom": "Zoom",
"speed": "Speed",
diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.json
index bc12b8fd7..b028479a5 100644
--- a/src/i18n/locales/es/editor.json
+++ b/src/i18n/locales/es/editor.json
@@ -83,7 +83,6 @@
"pasted": "Atributos de {{region}} pegados",
"nothingToCopy": "Selecciona una región para copiar sus atributos",
"nothingToPaste": "Aún no se han copiado atributos",
- "cannotPlace": "No se puede colocar la región aquí: se superpondría con otra",
"kinds": {
"zoom": "Zoom",
"speed": "Velocidad",
diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.json
index d3cc39523..e1a8e3e82 100644
--- a/src/i18n/locales/fr/editor.json
+++ b/src/i18n/locales/fr/editor.json
@@ -83,7 +83,6 @@
"pasted": "Attributs de {{region}} collés",
"nothingToCopy": "Sélectionnez une région pour copier ses attributs",
"nothingToPaste": "Aucun attribut copié pour l'instant",
- "cannotPlace": "Impossible de placer la région ici : elle chevaucherait une autre",
"kinds": {
"zoom": "Zoom",
"speed": "Vitesse",
diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.json
index 54edc4787..4cc2fe326 100644
--- a/src/i18n/locales/it/editor.json
+++ b/src/i18n/locales/it/editor.json
@@ -67,7 +67,6 @@
"pasted": "Attributi di {{region}} incollati",
"nothingToCopy": "Seleziona una regione per copiarne gli attributi",
"nothingToPaste": "Nessun attributo copiato",
- "cannotPlace": "Impossibile posizionare la regione qui: si sovrapporrebbe a un'altra",
"kinds": {
"zoom": "Zoom",
"speed": "Velocità",
diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.json
index 0c416c661..9291cdeae 100644
--- a/src/i18n/locales/ja-JP/editor.json
+++ b/src/i18n/locales/ja-JP/editor.json
@@ -83,7 +83,6 @@
"pasted": "{{region}}の属性を貼り付けました",
"nothingToCopy": "属性をコピーする領域を選択してください",
"nothingToPaste": "コピーされた属性がありません",
- "cannotPlace": "ここには領域を配置できません(他の領域と重なります)",
"kinds": {
"zoom": "ズーム",
"speed": "速度",
diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.json
index 2d432941e..ff52a36c9 100644
--- a/src/i18n/locales/ko-KR/editor.json
+++ b/src/i18n/locales/ko-KR/editor.json
@@ -83,7 +83,6 @@
"pasted": "{{region}} 속성을 붙여넣었습니다",
"nothingToCopy": "속성을 복사할 영역을 선택하세요",
"nothingToPaste": "복사된 속성이 없습니다",
- "cannotPlace": "여기에는 영역을 배치할 수 없습니다. 다른 영역과 겹칩니다",
"kinds": {
"zoom": "줌",
"speed": "속도",
diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.json
index c78545713..29e1436cf 100644
--- a/src/i18n/locales/pt-BR/editor.json
+++ b/src/i18n/locales/pt-BR/editor.json
@@ -66,7 +66,6 @@
"pasted": "Atributos de {{region}} colados",
"nothingToCopy": "Selecione uma região para copiar seus atributos",
"nothingToPaste": "Nenhum atributo copiado ainda",
- "cannotPlace": "Não é possível colocar a região aqui: ela se sobreporia a outra",
"kinds": {
"zoom": "Zoom",
"speed": "Velocidade",
diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.json
index c654c14dd..3820315ca 100644
--- a/src/i18n/locales/ru/editor.json
+++ b/src/i18n/locales/ru/editor.json
@@ -83,7 +83,6 @@
"pasted": "Атрибуты «{{region}}» вставлены",
"nothingToCopy": "Выберите регион, чтобы скопировать его атрибуты",
"nothingToPaste": "Атрибуты ещё не скопированы",
- "cannotPlace": "Не удаётся разместить регион здесь: он перекрыл бы другой",
"kinds": {
"zoom": "Масштаб",
"speed": "Скорость",
diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.json
index 7e69e891a..69d7311a8 100644
--- a/src/i18n/locales/tr/editor.json
+++ b/src/i18n/locales/tr/editor.json
@@ -83,7 +83,6 @@
"pasted": "{{region}} öznitelikleri yapıştırıldı",
"nothingToCopy": "Özniteliklerini kopyalamak için bir bölge seçin",
"nothingToPaste": "Henüz öznitelik kopyalanmadı",
- "cannotPlace": "Bölge buraya yerleştirilemiyor: başka bir bölgeyle çakışır",
"kinds": {
"zoom": "Yakınlaştırma",
"speed": "Hız",
diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.json
index f754233dc..49fad41ff 100644
--- a/src/i18n/locales/vi/editor.json
+++ b/src/i18n/locales/vi/editor.json
@@ -83,7 +83,6 @@
"pasted": "Đã dán thuộc tính {{region}}",
"nothingToCopy": "Chọn một vùng để sao chép thuộc tính của nó",
"nothingToPaste": "Chưa sao chép thuộc tính nào",
- "cannotPlace": "Không thể đặt vùng ở đây: nó sẽ chồng lên vùng khác",
"kinds": {
"zoom": "Thu phóng",
"speed": "Tốc độ",
diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.json
index fae1ff2aa..a5335e9cd 100644
--- a/src/i18n/locales/zh-CN/editor.json
+++ b/src/i18n/locales/zh-CN/editor.json
@@ -83,7 +83,6 @@
"pasted": "已粘贴{{region}}属性",
"nothingToCopy": "选择一个区域以复制其属性",
"nothingToPaste": "尚未复制任何属性",
- "cannotPlace": "无法在此放置区域:会与其他区域重叠",
"kinds": {
"zoom": "缩放",
"speed": "速度",
diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.json
index 9038f7e3a..724c7f5a4 100644
--- a/src/i18n/locales/zh-TW/editor.json
+++ b/src/i18n/locales/zh-TW/editor.json
@@ -83,7 +83,6 @@
"pasted": "已貼上{{region}}屬性",
"nothingToCopy": "選擇一個區域以複製其屬性",
"nothingToPaste": "尚未複製任何屬性",
- "cannotPlace": "無法在此放置區域:會與其他區域重疊",
"kinds": {
"zoom": "縮放",
"speed": "速度",
diff --git a/src/lib/shortcuts.ts b/src/lib/shortcuts.ts
index 16129ef4c..2ebdb64c5 100644
--- a/src/lib/shortcuts.ts
+++ b/src/lib/shortcuts.ts
@@ -151,6 +151,15 @@ export function matchesShortcut(
return true;
}
+/** True when the event target is a text-editing surface where shortcuts should not fire. */
+export function isTextEditingTarget(target: EventTarget | null): boolean {
+ return (
+ target instanceof HTMLInputElement ||
+ target instanceof HTMLTextAreaElement ||
+ (target instanceof HTMLElement && target.isContentEditable)
+ );
+}
+
const KEY_LABELS: Record<string, string> = {
" ": "Space",
delete: "Del",