Create polished demo videos without editing skills. Mac/Windows/Linux
fix: file seperation, some logic doesn't need to be made in react, but instead in typescript
Alan Trebugeais06ae2d8ac18b
diff --git a/src/components/video-editor/timeline/hooks/timelineAudioPlacement.test.ts b/src/components/video-editor/timeline/hooks/timelineAudioPlacement.test.tsnew file mode 100644index 00000000..d549bb6c--- /dev/null+++ b/src/components/video-editor/timeline/hooks/timelineAudioPlacement.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";+import { resolveAudioPlacement } from "./timelineAudioPlacement";++describe("timelineAudioPlacement", () => {+ it("uses first available track when no preferred track is provided", () => {+ const placement = resolveAudioPlacement({+ audioRegions: [{ id: "a1", startMs: 0, endMs: 500, trackIndex: 0 }],+ startPos: 500,+ totalMs: 2000,+ audioDurationMs: 500,+ });+ expect(placement).toEqual({ trackIndex: 0, durationMs: 500 });+ });++ it("falls back to next track when preferred track is blocked", () => {+ const placement = resolveAudioPlacement({+ audioRegions: [{ id: "a1", startMs: 0, endMs: 1500, trackIndex: 0 }],+ startPos: 1000,+ totalMs: 3000,+ audioDurationMs: 800,+ });+ expect(placement).toEqual({ trackIndex: 1, durationMs: 800 });+ });++ it("returns null when no slot is available", () => {+ const placement = resolveAudioPlacement({+ audioRegions: [{ id: "a1", startMs: 0, endMs: 2000, trackIndex: 0 }],+ startPos: 1500,+ totalMs: 2000,+ audioDurationMs: 800,+ preferredTrackIndex: 0,+ });+ expect(placement).toBeNull();+ });+});diff --git a/src/components/video-editor/timeline/hooks/timelineAudioPlacement.ts b/src/components/video-editor/timeline/hooks/timelineAudioPlacement.tsnew file mode 100644index 00000000..a7316698--- /dev/null+++ b/src/components/video-editor/timeline/hooks/timelineAudioPlacement.ts@@ -0,0 +1,90 @@+import { spansOverlap } from "../core/spans";+import type { AudioRegionLite } from "./timelineHookTypes";++interface ResolveAudioPlacementParams {+ audioRegions: AudioRegionLite[];+ startPos: number;+ totalMs: number;+ audioDurationMs: number;+ preferredTrackIndex?: number;+}++interface AudioPlacement {+ trackIndex: number;+ durationMs: number;+}++export function resolveAudioPlacement({+ audioRegions,+ startPos,+ totalMs,+ audioDurationMs,+ preferredTrackIndex,+}: ResolveAudioPlacementParams): AudioPlacement | null {+ const maxRemainingDuration = totalMs - startPos;+ if (audioDurationMs <= 0 || maxRemainingDuration <= 0) {+ return null;+ }++ const desiredDuration = Math.min(audioDurationMs, maxRemainingDuration);+ const normalizedPreferredTrackIndex = Number.isFinite(preferredTrackIndex)+ ? Math.max(0, Math.floor(preferredTrackIndex ?? 0))+ : null;+ const maxTrackIndex = audioRegions.reduce((max, region) => Math.max(max, region.trackIndex ?? 0), -1);+ const candidateTrackIndexes =+ normalizedPreferredTrackIndex === null+ ? Array.from({ length: maxTrackIndex + 2 }, (_, index) => index)+ : [normalizedPreferredTrackIndex];++ const getGapForTrack = (trackIndex: number) => {+ const trackRegions = audioRegions+ .filter((region) => (region.trackIndex ?? 0) === trackIndex)+ .sort((left, right) => left.startMs - right.startMs);+ const desiredSpan = {+ start: startPos,+ end: startPos + desiredDuration,+ };++ const overlappingRegion = trackRegions.find((region) =>+ spansOverlap(desiredSpan, { start: region.startMs, end: region.endMs }),+ );+ if (overlappingRegion) {+ return 0;+ }++ const nextRegion = trackRegions.find((region) => region.startMs > startPos);+ return nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;+ };++ let selectedTrackIndex: number | null = null;+ let availableGap = 0;++ for (const trackIndex of candidateTrackIndexes) {+ const gap = getGapForTrack(trackIndex);+ if (gap >= desiredDuration) {+ selectedTrackIndex = trackIndex;+ availableGap = gap;+ break;+ }+ }++ if (selectedTrackIndex === null && normalizedPreferredTrackIndex === null) {+ for (const trackIndex of candidateTrackIndexes) {+ const gap = getGapForTrack(trackIndex);+ if (gap > 0) {+ selectedTrackIndex = trackIndex;+ availableGap = gap;+ break;+ }+ }+ }++ if (selectedTrackIndex === null || availableGap <= 0) {+ return null;+ }++ return {+ trackIndex: selectedTrackIndex,+ durationMs: Math.min(audioDurationMs, availableGap, totalMs - startPos),+ };+}diff --git a/src/components/video-editor/timeline/hooks/timelineHookTypes.ts b/src/components/video-editor/timeline/hooks/timelineHookTypes.tsnew file mode 100644index 00000000..596a0be1--- /dev/null+++ b/src/components/video-editor/timeline/hooks/timelineHookTypes.ts@@ -0,0 +1,9 @@+export interface RegionIdLite {+ id: string;+ startMs: number;+ endMs: number;+}++export interface AudioRegionLite extends RegionIdLite {+ trackIndex?: number;+}diff --git a/src/components/video-editor/timeline/hooks/timelineNotifications.ts b/src/components/video-editor/timeline/hooks/timelineNotifications.tsnew file mode 100644index 00000000..37b85820--- /dev/null+++ b/src/components/video-editor/timeline/hooks/timelineNotifications.ts@@ -0,0 +1,13 @@+import { toast } from "sonner";++export interface TimelineNotifications {+ error: (title: string, description?: string) => void;+ info: (title: string, description?: string) => void;+ success: (title: string, description?: string) => void;+}++export const timelineNotifications: TimelineNotifications = {+ error: (title, description) => toast.error(title, description ? { description } : undefined),+ info: (title, description) => toast.info(title, description ? { description } : undefined),+ success: (title, description) => toast.success(title, description ? { description } : undefined),+};diff --git a/src/components/video-editor/timeline/hooks/timelineSelectionUtils.test.ts b/src/components/video-editor/timeline/hooks/timelineSelectionUtils.test.tsnew file mode 100644index 00000000..3a93afde--- /dev/null+++ b/src/components/video-editor/timeline/hooks/timelineSelectionUtils.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";+import { resolveDeleteSelectionTarget } from "./timelineSelectionUtils";++describe("timelineSelectionUtils", () => {+ it("prioritizes select-all over any individual selection", () => {+ expect(+ resolveDeleteSelectionTarget({+ selectAllBlocksActive: true,+ selectedKeyframeId: "kf-1",+ selectedZoomId: "z-1",+ selectedClipId: "c-1",+ selectedAnnotationId: "a-1",+ selectedAudioId: "au-1",+ }),+ ).toBe("all");+ });++ it("follows selection priority order", () => {+ expect(+ resolveDeleteSelectionTarget({+ selectAllBlocksActive: false,+ selectedKeyframeId: "kf-1",+ selectedZoomId: "z-1",+ }),+ ).toBe("keyframe");+ expect(+ resolveDeleteSelectionTarget({+ selectAllBlocksActive: false,+ selectedKeyframeId: null,+ selectedZoomId: "z-1",+ selectedClipId: "c-1",+ }),+ ).toBe("zoom");+ expect(+ resolveDeleteSelectionTarget({+ selectAllBlocksActive: false,+ selectedKeyframeId: null,+ selectedZoomId: null,+ selectedClipId: "c-1",+ selectedAnnotationId: "a-1",+ }),+ ).toBe("clip");+ });++ it("returns none when nothing is selected", () => {+ expect(+ resolveDeleteSelectionTarget({+ selectAllBlocksActive: false,+ selectedKeyframeId: null,+ selectedZoomId: null,+ }),+ ).toBe("none");+ });+});diff --git a/src/components/video-editor/timeline/hooks/timelineSelectionUtils.ts b/src/components/video-editor/timeline/hooks/timelineSelectionUtils.tsnew file mode 100644index 00000000..ac2b1299--- /dev/null+++ b/src/components/video-editor/timeline/hooks/timelineSelectionUtils.ts@@ -0,0 +1,34 @@+export type DeleteSelectionTarget =+ | "all"+ | "keyframe"+ | "zoom"+ | "clip"+ | "annotation"+ | "audio"+ | "none";++interface ResolveDeleteSelectionTargetParams {+ selectAllBlocksActive: boolean;+ selectedKeyframeId: string | null;+ selectedZoomId: string | null;+ selectedClipId?: string | null;+ selectedAnnotationId?: string | null;+ selectedAudioId?: string | null;+}++export function resolveDeleteSelectionTarget({+ selectAllBlocksActive,+ selectedKeyframeId,+ selectedZoomId,+ selectedClipId,+ selectedAnnotationId,+ selectedAudioId,+}: ResolveDeleteSelectionTargetParams): DeleteSelectionTarget {+ if (selectAllBlocksActive) return "all";+ if (selectedKeyframeId) return "keyframe";+ if (selectedZoomId) return "zoom";+ if (selectedClipId) return "clip";+ if (selectedAnnotationId) return "annotation";+ if (selectedAudioId) return "audio";+ return "none";+}diff --git a/src/components/video-editor/timeline/hooks/useTimelineAudioActions.ts b/src/components/video-editor/timeline/hooks/useTimelineAudioActions.tsindex 0ba71057..374ae4fb 100644--- a/src/components/video-editor/timeline/hooks/useTimelineAudioActions.ts+++ b/src/components/video-editor/timeline/hooks/useTimelineAudioActions.ts@@ -1,14 +1,8 @@import { useCallback, useMemo } from "react";-import { toast } from "sonner";import { resolveMediaElementSource } from "@/lib/exporter/localMediaSource";-import { spansOverlap } from "../core/spans";--interface AudioRegionLite {- id: string;- startMs: number;- endMs: number;- trackIndex?: number;-}+import { resolveAudioPlacement } from "./timelineAudioPlacement";+import type { AudioRegionLite } from "./timelineHookTypes";+import { timelineNotifications } from "./timelineNotifications";interface AudioFilePickerResult {success: boolean;@@ -22,10 +16,14 @@ interface TimelineAudioActionsDeps {}interface UseTimelineAudioActionsParams {- videoDuration: number;- totalMs: number;- currentTimeMs: number;- audioRegions: AudioRegionLite[];+ timeline: {+ videoDuration: number;+ totalMs: number;+ currentTimeMs: number;+ };+ regions: {+ audio: AudioRegionLite[];+ };onAudioAdded?: (span: { start: number; end: number }, audioPath: string, trackIndex?: number) => void;deps?: Partial<TimelineAudioActionsDeps>;}@@ -64,28 +62,24 @@ async function defaultProbeAudioDurationMs(audioPath: string): Promise<number> {});}-function defaultReportError(title: string, description: string) {- toast.error(title, { description });-}-function buildTimelineAudioActionsDeps(overrides?: Partial<TimelineAudioActionsDeps>,): TimelineAudioActionsDeps {return {openFilePicker: overrides?.openFilePicker ?? defaultOpenFilePicker,probeAudioDurationMs: overrides?.probeAudioDurationMs ?? defaultProbeAudioDurationMs,- reportError: overrides?.reportError ?? defaultReportError,+ reportError: overrides?.reportError ?? timelineNotifications.error,};}export function useTimelineAudioActions({- videoDuration,- totalMs,- currentTimeMs,- audioRegions,+ timeline,+ regions,onAudioAdded,deps: depsOverrides,}: UseTimelineAudioActionsParams) {+ const { videoDuration, totalMs, currentTimeMs } = timeline;+ const { audio: audioRegions } = regions;const deps = useMemo(() => buildTimelineAudioActionsDeps(depsOverrides), [depsOverrides]);const handleAddAudio = useCallback(@@ -110,8 +104,7 @@ export function useTimelineAudioActions({}const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));- const maxRemainingDuration = totalMs - startPos;- if (maxRemainingDuration <= 0) {+ if (totalMs - startPos <= 0) {deps.reportError("Cannot place audio here","There is no remaining space at the current playhead position.",@@ -119,63 +112,14 @@ export function useTimelineAudioActions({return;}- const desiredDuration = Math.min(audioDurationMs, maxRemainingDuration);- const normalizedPreferredTrackIndex = Number.isFinite(preferredTrackIndex)- ? Math.max(0, Math.floor(preferredTrackIndex ?? 0))- : null;- const maxTrackIndex = audioRegions.reduce(- (max, region) => Math.max(max, region.trackIndex ?? 0),- -1,- );- const candidateTrackIndexes =- normalizedPreferredTrackIndex === null- ? Array.from({ length: maxTrackIndex + 2 }, (_, index) => index)- : [normalizedPreferredTrackIndex];-- const getGapForTrack = (trackIndex: number) => {- const trackRegions = audioRegions- .filter((region) => (region.trackIndex ?? 0) === trackIndex)- .sort((left, right) => left.startMs - right.startMs);- const desiredSpan = {- start: startPos,- end: startPos + desiredDuration,- };-- const overlappingRegion = trackRegions.find((region) =>- spansOverlap(desiredSpan, { start: region.startMs, end: region.endMs }),- );- if (overlappingRegion) {- return 0;- }-- const nextRegion = trackRegions.find((region) => region.startMs > startPos);- return nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- };-- let selectedTrackIndex: number | null = null;- let availableGap = 0;-- for (const trackIndex of candidateTrackIndexes) {- const gap = getGapForTrack(trackIndex);- if (gap >= desiredDuration) {- selectedTrackIndex = trackIndex;- availableGap = gap;- break;- }- }-- if (selectedTrackIndex === null && normalizedPreferredTrackIndex === null) {- for (const trackIndex of candidateTrackIndexes) {- const gap = getGapForTrack(trackIndex);- if (gap > 0) {- selectedTrackIndex = trackIndex;- availableGap = gap;- break;- }- }- }-- if (selectedTrackIndex === null || availableGap <= 0) {+ const placement = resolveAudioPlacement({+ audioRegions,+ startPos,+ totalMs,+ audioDurationMs,+ preferredTrackIndex,+ });+ if (!placement) {deps.reportError("Cannot place audio here","Audio region already exists at this location or not enough space available.",@@ -183,8 +127,11 @@ export function useTimelineAudioActions({return;}- const actualDuration = Math.min(audioDurationMs, availableGap, totalMs - startPos);- onAudioAdded({ start: startPos, end: startPos + actualDuration }, audioPath, selectedTrackIndex);+ onAudioAdded(+ { start: startPos, end: startPos + placement.durationMs },+ audioPath,+ placement.trackIndex,+ );},[videoDuration, totalMs, onAudioAdded, deps, currentTimeMs, audioRegions],);diff --git a/src/components/video-editor/timeline/hooks/useTimelineZoomActions.ts b/src/components/video-editor/timeline/hooks/useTimelineZoomActions.tsindex 4e07bf68..156b747c 100644--- a/src/components/video-editor/timeline/hooks/useTimelineZoomActions.ts+++ b/src/components/video-editor/timeline/hooks/useTimelineZoomActions.ts@@ -1,17 +1,23 @@import type { Span } from "dnd-timeline";import { useCallback, useEffect, useMemo } from "react";-import { toast } from "sonner";import type { CursorTelemetryPoint, ZoomFocus, ZoomRegion } from "../../types";import { buildInteractionZoomSuggestions } from "../zoomSuggestionUtils";+import { timelineNotifications } from "./timelineNotifications";interface UseTimelineZoomActionsParams {- videoDuration: number;- totalMs: number;- currentTimeMs: number;- zoomRegions: ZoomRegion[];- clipRegions: { startMs: number; endMs: number }[];+ timeline: {+ videoDuration: number;+ totalMs: number;+ currentTimeMs: number;+ };+ regions: {+ zoom: ZoomRegion[];+ clip: { startMs: number; endMs: number }[];+ };cursorTelemetry: CursorTelemetryPoint[];- disableSuggestedZooms: boolean;+ options: {+ disableSuggestedZooms: boolean;+ };autoSuggestZoomsTrigger: number;onAutoSuggestZoomsConsumed?: () => void;onZoomAdded: (span: Span) => void;@@ -19,18 +25,18 @@ interface UseTimelineZoomActionsParams {}export function useTimelineZoomActions({- videoDuration,- totalMs,- currentTimeMs,- zoomRegions,- clipRegions,+ timeline,+ regions,cursorTelemetry,- disableSuggestedZooms,+ options,autoSuggestZoomsTrigger,onAutoSuggestZoomsConsumed,onZoomAdded,onZoomSuggested,}: UseTimelineZoomActionsParams) {+ const { videoDuration, totalMs, currentTimeMs } = timeline;+ const { zoom: zoomRegions, clip: clipRegions } = regions;+ const { disableSuggestedZooms } = options;const defaultRegionDurationMs = useMemo(() => Math.min(1000, totalMs), [totalMs]);const canPlaceZoomAtMs = useCallback(@@ -81,10 +87,10 @@ export function useTimelineZoomActions({const startPos = Math.max(0, Math.min(startMs, totalMs));if (!canPlaceZoomAtMs(startPos)) {- toast.error("Cannot place zoom here", {- description:- "Zoom already exists here or there is not enough room before the next zoom or clip end.",- });+ timelineNotifications.error(+ "Cannot place zoom here",+ "Zoom already exists here or there is not enough room before the next zoom or clip end.",+ );return;}@@ -107,19 +113,20 @@ export function useTimelineZoomActions({}if (disableSuggestedZooms) {- toast.info("Suggested zooms are unavailable while cursor looping is enabled.");+ timelineNotifications.info("Suggested zooms are unavailable while cursor looping is enabled.");return;}if (!onZoomSuggested) {- toast.error("Zoom suggestion handler unavailable");+ timelineNotifications.error("Zoom suggestion handler unavailable");return;}if (cursorTelemetry.length < 2) {- toast.info("No cursor telemetry available", {- description: "Record a screencast first to generate cursor-based suggestions.",- });+ timelineNotifications.info(+ "No cursor telemetry available",+ "Record a screencast first to generate cursor-based suggestions.",+ );return;}@@ -138,23 +145,26 @@ export function useTimelineZoomActions({});if (result.status === "no-telemetry") {- toast.info("No usable cursor telemetry", {- description: "The recording does not include enough cursor movement data.",- });+ timelineNotifications.info(+ "No usable cursor telemetry",+ "The recording does not include enough cursor movement data.",+ );return;}if (result.status === "no-interactions") {- toast.info("No clear interaction moments found", {- description: "Try a recording with pauses or clicks around important actions.",- });+ timelineNotifications.info(+ "No clear interaction moments found",+ "Try a recording with pauses or clicks around important actions.",+ );return;}if (result.status === "no-slots" || result.suggestions.length === 0) {- toast.info("No auto-zoom slots available", {- description: "Detected dwell points overlap existing zoom regions.",- });+ timelineNotifications.info(+ "No auto-zoom slots available",+ "Detected dwell points overlap existing zoom regions.",+ );return;}@@ -162,7 +172,7 @@ export function useTimelineZoomActions({onZoomSuggested({ start: region.start, end: region.end }, region.focus);}- toast.success(+ timelineNotifications.success(`Added ${result.suggestions.length} interaction-based zoom suggestion${result.suggestions.length === 1 ? "" : "s"}`,);}, [