OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: implement playback locking and effect application handling in timeline and UI stores
Augustus Otu8db4b8b44ae2
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsxindex 7bb7a03d..44cea494 100644--- a/apps/web/src/components/editor/InspectorPanel.tsx+++ b/apps/web/src/components/editor/InspectorPanel.tsx@@ -1,6 +1,7 @@import React, { useCallback, useEffect, useMemo, useState } from "react";import { ChevronDown, Zap, Captions, Loader2, Sparkles, Trash2 } from "lucide-react";import { useProjectStore } from "../../stores/project-store";+import { useTimelineStore } from "../../stores/timeline-store";import { useUIStore } from "../../stores/ui-store";import { useEngineStore } from "../../stores/engine-store";import type { Transform, FitMode, Clip, EditingTemplatePrimitive } from "@openreel/core";@@ -203,7 +204,19 @@ export const InspectorPanel: React.FC = () => {const project = useProjectStore((state) => state.project);const { getSelectedClipIds } = useUIStore();const selectedItems = useUIStore((state) => state.selectedItems);+ const effectApplicationClipId = useUIStore(+ (state) => state.effectApplicationClipId,+ );+ const startEffectApplication = useUIStore(+ (state) => state.startEffectApplication,+ );+ const finishEffectApplication = useUIStore(+ (state) => state.finishEffectApplication,+ );const selectedClipIds = getSelectedClipIds();+ const pausePlayback = useTimelineStore((state) => state.pause);+ const lockPlayback = useTimelineStore((state) => state.lockPlayback);+ const unlockPlayback = useTimelineStore((state) => state.unlockPlayback);const getTitleEngine = useEngineStore((state) => state.getTitleEngine);const getGraphicsEngine = useEngineStore((state) => state.getGraphicsEngine);@@ -412,58 +425,112 @@ export const InspectorPanel: React.FC = () => {toggleAudioEffect,} = useProjectStore();- const handleRemoveBackground = useCallback(() => {- if (!selectedClip) return;- chromaKeyEngine.enableChromaKey(selectedClip.id);- chromaKeyEngine.setKeyColor(selectedClip.id, { r: 0, g: 1, b: 0 });- chromaKeyEngine.setTolerance(selectedClip.id, 0.35);- forceUpdate();- }, [selectedClip]);-const [isEnhancingAudio, setIsEnhancingAudio] = useState(false);const [audioEnhanced, setAudioEnhanced] = useState(false);+ const isApplyingSelectedClipEffect =+ effectApplicationClipId !== null && effectApplicationClipId === selectedClip?.id;++ const waitForEffectApplicationPaint = useCallback(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => {+ requestAnimationFrame(() => resolve());+ });+ }),+ [],+ );++ const applyClipEffectWithPlaybackLock = useCallback(+ async (+ clipId: string,+ label: string,+ apply: () => void | Promise<void>,+ ) => {+ pausePlayback();+ lockPlayback(label);+ startEffectApplication(clipId, label);++ try {+ await waitForEffectApplicationPaint();+ await apply();+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));+ await waitForEffectApplicationPaint();+ } finally {+ finishEffectApplication();+ unlockPlayback();+ }+ },+ [+ finishEffectApplication,+ lockPlayback,+ pausePlayback,+ startEffectApplication,+ unlockPlayback,+ waitForEffectApplicationPaint,+ ],+ );++ const handleRemoveBackground = useCallback(() => {+ if (!selectedClip) return;+ void applyClipEffectWithPlaybackLock(+ selectedClip.id,+ "Applying background removal",+ () => {+ chromaKeyEngine.enableChromaKey(selectedClip.id);+ chromaKeyEngine.setKeyColor(selectedClip.id, { r: 0, g: 1, b: 0 });+ chromaKeyEngine.setTolerance(selectedClip.id, 0.35);+ forceUpdate();+ },+ );+ }, [applyClipEffectWithPlaybackLock, forceUpdate, selectedClip]);const handleEnhanceAudio = useCallback(async () => {if (!selectedClip) return;setIsEnhancingAudio(true);try {- await initializeAudioBridgeEffects();- const bridge = getAudioBridgeEffects();- const noiseCleanupConfig = {- ...DEFAULT_NOISE_REDUCTION,- ...getNoiseReductionPreset("speech").config,- };-- const existingNoiseReduction = getAudioEffects(selectedClip.id).find(- (effect) => effect.type === "noiseReduction",- );-- if (existingNoiseReduction) {- updateAudioEffect(- selectedClip.id,- existingNoiseReduction.id,- noiseCleanupConfig as unknown as Record<string, unknown>,- );- toggleAudioEffect(selectedClip.id, existingNoiseReduction.id, true);- } else {- const result = bridge.applyNoiseReduction(- selectedClip.id,- noiseCleanupConfig,- );-- if (!result.success) {- throw new Error(result.error ?? "Failed to apply noise cleanup");- }- }-- setAudioEnhanced(true);- setTimeout(() => setAudioEnhanced(false), 2000);- toast.success(- "Noise cleanup applied",- "Fine-tune or switch presets in Background Noise Removal.",+ await applyClipEffectWithPlaybackLock(+ selectedClip.id,+ "Applying audio cleanup",+ async () => {+ await initializeAudioBridgeEffects();+ const bridge = getAudioBridgeEffects();+ const noiseCleanupConfig = {+ ...DEFAULT_NOISE_REDUCTION,+ ...getNoiseReductionPreset("speech").config,+ };++ const existingNoiseReduction = getAudioEffects(selectedClip.id).find(+ (effect) => effect.type === "noiseReduction",+ );++ if (existingNoiseReduction) {+ updateAudioEffect(+ selectedClip.id,+ existingNoiseReduction.id,+ noiseCleanupConfig as unknown as Record<string, unknown>,+ );+ toggleAudioEffect(selectedClip.id, existingNoiseReduction.id, true);+ } else {+ const result = bridge.applyNoiseReduction(+ selectedClip.id,+ noiseCleanupConfig,+ );++ if (!result.success) {+ throw new Error(result.error ?? "Failed to apply noise cleanup");+ }+ }++ setAudioEnhanced(true);+ setTimeout(() => setAudioEnhanced(false), 2000);+ toast.success(+ "Noise cleanup applied",+ "Fine-tune or switch presets in Background Noise Removal.",+ );++ forceUpdate();+ },);-- forceUpdate();} catch (error) {console.error("Failed to enhance audio:", error);toast.error(@@ -476,6 +543,7 @@ export const InspectorPanel: React.FC = () => {setIsEnhancingAudio(false);}}, [+ applyClipEffectWithPlaybackLock,selectedClip,forceUpdate,getAudioEffects,@@ -483,22 +551,36 @@ export const InspectorPanel: React.FC = () => {updateAudioEffect,]);- const handleAutoColor = useCallback(() => {+ const handleAutoColor = useCallback(async () => {if (!selectedClip) return;- addVideoEffect(selectedClip.id, "saturation");- addVideoEffect(selectedClip.id, "contrast");- addVideoEffect(selectedClip.id, "brightness");- const effects = useProjectStore.getState().getVideoEffects(selectedClip.id);- const satEffect = effects.find((e) => e.type === "saturation");- const contEffect = effects.find((e) => e.type === "contrast");- const brightEffect = effects.find((e) => e.type === "brightness");- if (satEffect)- updateVideoEffect(selectedClip.id, satEffect.id, { value: 1.15 });- if (contEffect)- updateVideoEffect(selectedClip.id, contEffect.id, { value: 1.1 });- if (brightEffect)- updateVideoEffect(selectedClip.id, brightEffect.id, { value: 5 });- }, [selectedClip, addVideoEffect, updateVideoEffect]);+ await applyClipEffectWithPlaybackLock(+ selectedClip.id,+ "Applying auto color",+ () => {+ addVideoEffect(selectedClip.id, "saturation");+ addVideoEffect(selectedClip.id, "contrast");+ addVideoEffect(selectedClip.id, "brightness");+ const effects = useProjectStore.getState().getVideoEffects(selectedClip.id);+ const satEffect = effects.find((e) => e.type === "saturation");+ const contEffect = effects.find((e) => e.type === "contrast");+ const brightEffect = effects.find((e) => e.type === "brightness");+ if (satEffect) {+ updateVideoEffect(selectedClip.id, satEffect.id, { value: 1.15 });+ }+ if (contEffect) {+ updateVideoEffect(selectedClip.id, contEffect.id, { value: 1.1 });+ }+ if (brightEffect) {+ updateVideoEffect(selectedClip.id, brightEffect.id, { value: 5 });+ }+ },+ );+ }, [+ addVideoEffect,+ applyClipEffectWithPlaybackLock,+ selectedClip,+ updateVideoEffect,+ ]);const handleGenerateSubtitles = useCallback(async () => {if (!selectedClip || isTranscribing) return;@@ -1570,7 +1652,12 @@ export const InspectorPanel: React.FC = () => {{showVideoControls && (<buttononClick={handleRemoveBackground}- className="w-full py-2 bg-background-tertiary hover:bg-primary hover:text-white border border-border hover:border-primary rounded-lg text-[10px] transition-all"+ disabled={isApplyingSelectedClipEffect}+ className={`w-full py-2 border rounded-lg text-[10px] transition-all ${+ isApplyingSelectedClipEffect+ ? "bg-background-tertiary border-border text-text-muted cursor-not-allowed"+ : "bg-background-tertiary hover:bg-primary hover:text-white border-border hover:border-primary"+ }`}>Remove Background</button>@@ -1578,11 +1665,11 @@ export const InspectorPanel: React.FC = () => {{showAudioEffects && (<buttononClick={handleEnhanceAudio}- disabled={isEnhancingAudio}+ disabled={isEnhancingAudio || isApplyingSelectedClipEffect}className={`w-full py-2 border rounded-lg text-[10px] transition-all flex items-center justify-center gap-1.5 ${audioEnhanced? "bg-green-500/20 border-green-500 text-green-400"- : isEnhancingAudio+ : isEnhancingAudio || isApplyingSelectedClipEffect? "bg-background-tertiary border-border text-text-muted cursor-not-allowed": "bg-background-tertiary hover:bg-primary hover:text-white border-border hover:border-primary"}`}@@ -1602,9 +1689,14 @@ export const InspectorPanel: React.FC = () => {{showVideoEffects && (<buttononClick={handleAutoColor}- className="w-full py-2 bg-background-tertiary hover:bg-primary hover:text-white border border-border hover:border-primary rounded-lg text-[10px] transition-all"+ disabled={isApplyingSelectedClipEffect}+ className={`w-full py-2 border rounded-lg text-[10px] transition-all ${+ isApplyingSelectedClipEffect+ ? "bg-background-tertiary border-border text-text-muted cursor-not-allowed"+ : "bg-background-tertiary hover:bg-primary hover:text-white border-border hover:border-primary"+ }`}>- Auto-Color+ {isApplyingSelectedClipEffect ? "Applying..." : "Auto-Color"}</button>)}</div>diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex afca063f..4737c096 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -702,6 +702,7 @@ export const Preview: React.FC = () => {const {playheadPosition,playbackState,+ playbackLockedReason,playbackRate,isScrubbing,pause,@@ -2286,7 +2287,7 @@ export const Preview: React.FC = () => {if (mediaItem?.blob && mediaItem.type === "video") {const clipSpeed = speedEngine.getClipSpeed(clip.id);const isReverse = speedEngine.isReverse(clip.id);- if (clipSpeed !== 1 || isReverse) {+ if (clipSpeed !== 1 || isReverse || clipNeedsFrameProcessing(clip.id)) {return { canUse: false, clips: [] };}allVideoClips.push({ clip, mediaItem });@@ -5949,10 +5950,18 @@ export const Preview: React.FC = () => {onClick={() => {togglePlayback();}}- className="w-10 h-10 rounded-full bg-primary hover:bg-primary-hover active:bg-primary-active flex items-center justify-center text-white transition-all shadow-[0_0_15px_rgba(34,197,94,0.4)] hover:shadow-[0_0_25px_rgba(34,197,94,0.6)] transform hover:scale-105"+ disabled={Boolean(playbackLockedReason)}+ title={playbackLockedReason ?? (isPlaying ? "Pause" : "Play")}+ className={`w-10 h-10 rounded-full flex items-center justify-center text-white transition-all ${+ playbackLockedReason+ ? "bg-background-tertiary text-text-muted cursor-not-allowed shadow-none"+ : "bg-primary hover:bg-primary-hover active:bg-primary-active shadow-[0_0_15px_rgba(34,197,94,0.4)] hover:shadow-[0_0_25px_rgba(34,197,94,0.6)] transform hover:scale-105"+ }`}>{isPlaying ? (<Pause size={18} fill="currentColor" />+ ) : playbackLockedReason ? (+ <Loader2 size={18} className="animate-spin" />) : (<Play size={18} fill="currentColor" className="ml-0.5" />)}diff --git a/apps/web/src/components/editor/timeline/ClipComponent.tsx b/apps/web/src/components/editor/timeline/ClipComponent.tsxindex a6f0859b..70d5a7c7 100644--- a/apps/web/src/components/editor/timeline/ClipComponent.tsx+++ b/apps/web/src/components/editor/timeline/ClipComponent.tsx@@ -49,6 +49,12 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({}) => {const { getMediaItem } = useProjectStore();const { snapSettings } = useUIStore();+ const effectApplicationClipId = useUIStore(+ (state) => state.effectApplicationClipId,+ );+ const effectApplicationLabel = useUIStore(+ (state) => state.effectApplicationLabel,+ );const { playheadPosition } = useTimelineStore();const mediaItem = getMediaItem(clip.mediaId);const [isDragging, setIsDragging] = useState(false);@@ -339,6 +345,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({const clipName = mediaItem?.name || clip.mediaId.slice(0, 8);const isInteracting = isDragging || isTrimming;+ const isApplyingEffect = effectApplicationClipId === clip.id;return (<ContextMenu>@@ -353,7 +360,9 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({: "cursor-grab"} ${isSelected && !isDragging- ? "ring-2 ring-primary border-primary z-10"+ ? isApplyingEffect+ ? "ring-2 ring-amber-400 border-amber-300 z-10"+ : "ring-2 ring-primary border-primary z-10": !isDragging ? "border-opacity-30 hover:border-opacity-60 hover:brightness-110" : ""} ${clipStyle.bg} border ${clipStyle.border} ${track.locked ? "cursor-not-allowed opacity-60" : ""@@ -368,6 +377,16 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({pointerEvents: isDragging ? 'none' : 'auto',}}>+ {isApplyingEffect && (+ <>+ <div className="absolute -inset-px rounded-lg border border-amber-300/80 shadow-[0_0_18px_rgba(251,191,36,0.55)] pointer-events-none animate-pulse" />+ <div className="absolute inset-0 bg-[linear-gradient(110deg,transparent_0%,rgba(255,255,255,0.08)_28%,rgba(251,191,36,0.28)_50%,rgba(255,255,255,0.08)_72%,transparent_100%)] pointer-events-none animate-pulse" />+ <div className="absolute top-1 right-1 rounded-full bg-black/70 px-2 py-0.5 text-[9px] font-medium uppercase tracking-[0.12em] text-amber-200 pointer-events-none">+ {effectApplicationLabel ?? "Applying effect"}+ </div>+ </>+ )}+{isVideo &&(mediaItem?.filmstripThumbnails?.length || mediaItem?.thumbnailUrl) && (<div className="absolute inset-0 flex pointer-events-none">diff --git a/apps/web/src/stores/timeline-store.test.ts b/apps/web/src/stores/timeline-store.test.tsnew file mode 100644index 00000000..3caadc6a--- /dev/null+++ b/apps/web/src/stores/timeline-store.test.ts@@ -0,0 +1,52 @@+import { beforeEach, describe, expect, it } from "vitest";+import { useTimelineStore, ZOOM_PRESETS } from "./timeline-store";++describe("TimelineStore playback locking", () => {+ beforeEach(() => {+ useTimelineStore.setState({+ playheadPosition: 0,+ playbackState: "stopped",+ playbackLockedReason: null,+ playbackRate: 1,+ pixelsPerSecond: ZOOM_PRESETS.DEFAULT,+ scrollX: 0,+ scrollY: 0,+ viewportWidth: 800,+ viewportHeight: 400,+ trackHeight: 80,+ trackHeights: {},+ loopEnabled: false,+ loopStart: 0,+ loopEnd: 0,+ isScrubbing: false,+ scrubPosition: null,+ expandedTracks: new Set<string>(),+ expandedClipKeyframes: new Set<string>(),+ keyframeEditMode: false,+ });+ });++ it("blocks play and toggle while locked", () => {+ const store = useTimelineStore.getState();++ store.lockPlayback("Applying auto color");+ store.play();+ store.togglePlayback();++ const state = useTimelineStore.getState();+ expect(state.playbackState).toBe("stopped");+ expect(state.playbackLockedReason).toBe("Applying auto color");+ });++ it("allows playback again after unlocking", () => {+ const store = useTimelineStore.getState();++ store.lockPlayback("Applying auto color");+ store.unlockPlayback();+ store.togglePlayback();++ const state = useTimelineStore.getState();+ expect(state.playbackLockedReason).toBeNull();+ expect(state.playbackState).toBe("playing");+ });+});\ No newline at end of filediff --git a/apps/web/src/stores/timeline-store.ts b/apps/web/src/stores/timeline-store.tsindex c80f78f5..d86251d4 100644--- a/apps/web/src/stores/timeline-store.ts+++ b/apps/web/src/stores/timeline-store.ts@@ -12,6 +12,7 @@ export type PlaybackState = "stopped" | "playing" | "paused";export interface TimelineState {playheadPosition: number;playbackState: PlaybackState;+ playbackLockedReason: string | null;playbackRate: number;pixelsPerSecond: number;scrollX: number;@@ -32,6 +33,8 @@ export interface TimelineState {pause: () => void;stop: () => void;togglePlayback: () => void;+ lockPlayback: (reason?: string) => void;+ unlockPlayback: () => void;setPlaybackRate: (rate: number) => void;setPlayheadPosition: (position: number) => void;seekTo: (position: number) => void;@@ -72,6 +75,7 @@ export const useTimelineStore = create<TimelineState>()(subscribeWithSelector((set, get) => ({playheadPosition: 0,playbackState: "stopped",+ playbackLockedReason: null,playbackRate: 1.0,pixelsPerSecond: ZOOM_PRESETS.DEFAULT,@@ -95,6 +99,9 @@ export const useTimelineStore = create<TimelineState>()(keyframeEditMode: false,play: () => {+ if (get().playbackLockedReason) {+ return;+ }set({ playbackState: "playing" });},@@ -107,7 +114,10 @@ export const useTimelineStore = create<TimelineState>()(},togglePlayback: () => {- const { playbackState } = get();+ const { playbackLockedReason, playbackState } = get();+ if (playbackLockedReason) {+ return;+ }if (playbackState === "playing") {set({ playbackState: "paused" });} else {@@ -115,6 +125,14 @@ export const useTimelineStore = create<TimelineState>()(}},+ lockPlayback: (reason?: string) => {+ set({ playbackLockedReason: reason ?? "Applying effect" });+ },++ unlockPlayback: () => {+ set({ playbackLockedReason: null });+ },+setPlaybackRate: (rate: number) => {set({ playbackRate: Math.max(0.1, Math.min(4.0, rate)) });},diff --git a/apps/web/src/stores/ui-store.ts b/apps/web/src/stores/ui-store.tsindex b6e962f5..0dd7e824 100644--- a/apps/web/src/stores/ui-store.ts+++ b/apps/web/src/stores/ui-store.ts@@ -60,6 +60,8 @@ export interface KeyboardShortcuts {export interface UIState {selectedItems: SelectionItem[];lastSelectedItem: SelectionItem | null;+ effectApplicationClipId: string | null;+ effectApplicationLabel: string | null;snapSettings: SnapSettings;panels: Record<PanelId, PanelState>;shortcuts: KeyboardShortcuts;@@ -137,6 +139,8 @@ export interface UIState {progress: number;phase: string;}) => void;+ startEffectApplication: (clipId: string, label?: string) => void;+ finishEffectApplication: () => void;}export interface ContextMenuItem {@@ -190,6 +194,8 @@ export const useUIStore = create<UIState>()((set, get) => ({selectedItems: [],lastSelectedItem: null,+ effectApplicationClipId: null,+ effectApplicationLabel: null,snapSettings: DEFAULT_SNAP_SETTINGS,@@ -231,6 +237,20 @@ export const useUIStore = create<UIState>()(setExportState: (state) => set({ exportState: state }),+ startEffectApplication: (clipId: string, label?: string) => {+ set({+ effectApplicationClipId: clipId,+ effectApplicationLabel: label ?? null,+ });+ },++ finishEffectApplication: () => {+ set({+ effectApplicationClipId: null,+ effectApplicationLabel: null,+ });+ },+select: (item: SelectionItem, addToSelection = false) => {const { selectedItems } = get();if (addToSelection) {