Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript
31.8 KB
Raw Blame
import type {
  Action,
  TimelineAction,
  TrackAction,
  ClipAction,
  EffectAction,
  TransformAction,
  KeyframeAction,
  TransitionAction,
  AudioAction,
  SubtitleAction,
  MediaAction,
  ProjectAction,
  MarkerAction,
} from "../types/actions";
import type { Project, MediaItem } from "../types/project";
import type { Track, Clip, Transition } from "../types/timeline";
import type { TextClip } from "../text/types";
import type { ShapeClip, StickerClip, SVGClip } from "../graphics/types";
import type { AdjustmentLayer } from "../video/adjustment-layer-engine";
import type { MotionCompositionInstance } from "../motion/types";
import { getActionHandler } from "./registry";
import { invertTimelineToolEdits, type TimelineToolItemEdit } from "../editing/timeline-tool-edit";
import { prepareClipSplit } from "../editing/clip-fragments";

type TrackOwnedProjectItem =
  | TextClip
  | ShapeClip
  | SVGClip
  | StickerClip
  | AdjustmentLayer
  | MotionCompositionInstance;

export class InverseActionGenerator {
  generate(action: Action, projectBefore: Project): Action | null {
    const type = (action as TimelineAction).type;

    const handler = getActionHandler(type);
    if (handler) {
      return handler.invert(action, projectBefore);
    }

    if (type.startsWith("project/")) {
      return this.generateProjectInverse(
        action as ProjectAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("media/")) {
      return this.generateMediaInverse(
        action as MediaAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("track/")) {
      return this.generateTrackInverse(
        action as TrackAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("clip/")) {
      return this.generateClipInverse(
        action as ClipAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("effect/")) {
      return this.generateEffectInverse(
        action as EffectAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("transform/")) {
      return this.generateTransformInverse(
        action as TransformAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("keyframe/")) {
      return this.generateKeyframeInverse(
        action as KeyframeAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("transition/")) {
      return this.generateTransitionInverse(
        action as TransitionAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("audio/")) {
      return this.generateAudioInverse(
        action as AudioAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("subtitle/")) {
      return this.generateSubtitleInverse(
        action as SubtitleAction & Action,
        projectBefore,
      );
    } else if (type.startsWith("marker/")) {
      return this.generateMarkerInverse(
        action as MarkerAction & Action,
        projectBefore,
      );
    }

    return null;
  }

  private generateMarkerInverse(
    action: MarkerAction & Action,
    projectBefore: Project,
  ): Action | null {
    const timeline = projectBefore.timeline;

    switch (action.type) {
      case "marker/add":
        return this.createInverseAction(action, "marker/remove", {
          markerId: "__LAST_ADDED__",
        });

      case "marker/remove": {
        const position = timeline.markers.findIndex(
          (m) => m.id === action.params.markerId,
        );
        if (position === -1) return null;
        const marker = timeline.markers[position];

        return this.createInverseAction(action, "marker/restore", {
          marker: { ...marker },
          position,
        });
      }

      case "marker/update": {
        const marker = timeline.markers.find(
          (m) => m.id === action.params.markerId,
        );
        if (!marker) return null;

        return this.createInverseAction(action, "marker/update", {
          markerId: action.params.markerId,
          updates: {
            time: marker.time,
            label: marker.label,
            color: marker.color,
            duration: marker.duration,
            comment: marker.comment,
            kind: marker.kind,
            author: marker.author,
            status: marker.status,
            replies: marker.replies,
            createdAt: marker.createdAt,
          },
        });
      }
    }
  }

  private createInverseAction(
    originalAction: Action,
    type: string,
    params: Record<string, unknown>,
  ): Action {
    return {
      type,
      id: `inverse-${originalAction.id}`,
      timestamp: Date.now(),
      params,
    };
  }

  private generateProjectInverse(
    action: ProjectAction & Action,
    projectBefore: Project,
  ): Action | null {
    switch (action.type) {
      case "project/rename":
        return this.createInverseAction(action, "project/rename", {
          name: projectBefore.name,
        });

      case "project/updateSettings":
        return this.createInverseAction(action, "project/updateSettings", {
          ...projectBefore.settings,
          // Optional settings must be named so undo can clear a value the project did not have before.
          workingColorSpace: projectBefore.settings.workingColorSpace,
          colorManagement: projectBefore.settings.colorManagement,
          acesOutput: projectBefore.settings.acesOutput,
          ocio: projectBefore.settings.ocio,
          graphicsWhiteNits: projectBefore.settings.graphicsWhiteNits,
          channelLayout: projectBefore.settings.channelLayout,
          startTimecode: projectBefore.settings.startTimecode,
          pixelAspectRatio: projectBefore.settings.pixelAspectRatio,
          fieldOrder: projectBefore.settings.fieldOrder,
          vr: projectBefore.settings.vr,
        });

      case "project/setCanvasBackground":
        return this.createInverseAction(action, "project/setCanvasBackground", {
          backgroundFillMode: projectBefore.timeline.backgroundFillMode,
          layoutBackgroundColor: projectBefore.timeline.layoutBackgroundColor,
        });

      case "project/create":
        // Cannot undo project creation in a meaningful way
        return null;

      case "project/registerGeneratedShader":
        return this.createInverseAction(
          action,
          "project/removeGeneratedShader",
          { shaderId: action.params.def.id },
        );

      case "project/removeGeneratedShader": {
        const removed = (projectBefore.generatedShaders ?? []).find(
          (def) => def.id === action.params.shaderId,
        );
        if (!removed) return null;
        return this.createInverseAction(
          action,
          "project/registerGeneratedShader",
          { def: removed },
        );
      }
    }
  }

  private generateMediaInverse(
    action: MediaAction & Action,
    projectBefore: Project,
  ): Action | null {
    switch (action.type) {
      case "media/import":
        // To undo import, delete the media that was added. The executor resolves
        // "__LAST_ADDED__" to the id recorded in lastAddedIds for the "media"
        // category when the import was applied.
        return this.createInverseAction(action, "media/delete", {
          mediaId: "__LAST_ADDED__",
        });

      case "media/delete": {
        const deletedMedia = projectBefore.mediaLibrary.items.find(
          (item) => item.id === action.params.mediaId,
        );
        if (!deletedMedia) return null;
        return this.createInverseAction(action, "media/restore", {
          mediaItem: this.cloneMediaItem(deletedMedia),
        });
      }

      case "media/rename": {
        const media = projectBefore.mediaLibrary.items.find(
          (item) => item.id === action.params.mediaId,
        );
        if (!media) return null;

        return this.createInverseAction(action, "media/rename", {
          mediaId: action.params.mediaId,
          name: media.name,
        });
      }
    }
  }

  private generateTrackInverse(
    action: TrackAction & Action,
    projectBefore: Project,
  ): Action | null {
    const timeline = projectBefore.timeline;

    switch (action.type) {
      case "track/add":
        // To undo add, we need to remove the track that was added
        return this.createInverseAction(action, "track/remove", {
          trackId: "__LAST_ADDED__", // Special marker to be resolved
        });

      case "track/duplicate":
        return this.createInverseAction(action, "track/remove", {
          trackId: "__LAST_ADDED__",
        });

      case "track/remove": {
        const removedTrack = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!removedTrack) return null;

        const position = timeline.tracks.findIndex(
          (t) => t.id === action.params.trackId,
        );

        return this.createInverseAction(action, "track/restore", {
          track: this.cloneTrack(removedTrack),
          position,
          items: {
            textClips: this.cloneTrackItems(projectBefore.textClips, action.params.trackId),
            shapeClips: this.cloneTrackItems(
              projectBefore.shapeClips,
              action.params.trackId,
            ),
            svgClips: this.cloneTrackItems(projectBefore.svgClips, action.params.trackId),
            stickerClips: this.cloneTrackItems(
              projectBefore.stickerClips,
              action.params.trackId,
            ),
            adjustmentLayers: this.cloneTrackItems(
              projectBefore.adjustmentLayers,
              action.params.trackId,
            ),
            motionInstances: this.cloneTrackItems(
              projectBefore.motionInstances,
              action.params.trackId,
            ),
          },
        });
      }

      case "track/rename": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/rename", {
          trackId: action.params.trackId,
          name: track.name,
        });
      }

      case "track/reorder": {
        const currentPosition = timeline.tracks.findIndex(
          (t) => t.id === action.params.trackId,
        );
        if (currentPosition === -1) return null;

        return this.createInverseAction(action, "track/reorder", {
          trackId: action.params.trackId,
          newPosition: currentPosition,
        });
      }

      case "track/lock": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/lock", {
          trackId: action.params.trackId,
          locked: track.locked,
        });
      }

      case "track/setSyncLock": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/setSyncLock", {
          trackId: action.params.trackId,
          syncLock: track.syncLock !== false,
        });
      }

      case "track/hide": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/hide", {
          trackId: action.params.trackId,
          hidden: track.hidden,
        });
      }

      case "track/mute": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/mute", {
          trackId: action.params.trackId,
          muted: track.muted,
        });
      }

      case "track/setSoloSafe": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/setSoloSafe", {
          trackId: action.params.trackId,
          soloSafe: track.soloSafe === true,
        });
      }

      case "track/solo": {
        const track = timeline.tracks.find(
          (t) => t.id === action.params.trackId,
        );
        if (!track) return null;

        return this.createInverseAction(action, "track/solo", {
          trackId: action.params.trackId,
          solo: track.solo,
        });
      }

      case "track/consolidate" as TrackAction["type"]: {
        const trackId = (action.params as { trackId: string }).trackId;
        const track = timeline.tracks.find((t) => t.id === trackId);
        if (!track) return null;
        const positions = track.clips.map((c) => ({
          clipId: c.id,
          startTime: c.startTime,
        }));
        return this.createInverseAction(action, "track/restorePositions", {
          trackId,
          positions,
        });
      }
    }
    return null;
  }

  private generateClipInverse(
    action: ClipAction & Action,
    projectBefore: Project,
  ): Action | null {
    const timeline = projectBefore.timeline;

    switch (action.type) {
      case "clip/add":
        return this.createInverseAction(action, "clip/remove", {
          clipId: "__LAST_ADDED__",
        });

      case "clip/remove": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/restore", {
          clip: this.cloneClip(clip),
        });
      }

      case "clip/addBatch":
        return this.createInverseAction(action, "clip/removeBatch", {
          clipIds: action.params.clips.map((entry) => entry.clipId),
        });

      case "clip/removeBatch": {
        const doomed = new Set(action.params.clipIds);
        const entries: Array<{ clip: Record<string, unknown>; index: number }> = [];
        for (const track of timeline.tracks) {
          track.clips.forEach((clip, index) => {
            if (doomed.has(clip.id)) entries.push({ clip: this.cloneClip(clip), index });
          });
        }
        return entries.length ? this.createInverseAction(action, "clip/restoreBatch", { entries }) : null;
      }

      case "clip/restoreBatch":
        return this.createInverseAction(action, "clip/removeBatch", {
          clipIds: action.params.entries.map((entry) => entry.clip.id),
        });

      case "clip/restore":
        return this.createInverseAction(action, "clip/remove", {
          clipId: action.params.clip.id,
        });

      case "clip/move": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/move", {
          clipId: action.params.clipId,
          startTime: clip.startTime,
          trackId: clip.trackId,
        });
      }

      case "clip/moveBatch": {
        const byId = new Map<string, { startTime: number; trackId: string }>();
        for (const track of timeline.tracks) {
          for (const clip of track.clips) byId.set(clip.id, { startTime: clip.startTime, trackId: clip.trackId });
        }
        const moves = action.params.moves.flatMap((move) => {
          const before = byId.get(move.clipId);
          return before ? [{ clipId: move.clipId, startTime: before.startTime, trackId: before.trackId }] : [];
        });
        return this.createInverseAction(action, "clip/moveBatch", { moves });
      }

      case "clip/trim": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/trim", {
          clipId: action.params.clipId,
          inPoint: clip.inPoint,
          outPoint: clip.outPoint,
        });
      }

      case "clip/trimToPlayhead": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;
        return this.createInverseAction(action, "clip/restoreTiming", {
          clipId: clip.id,
          startTime: clip.startTime,
          duration: clip.duration,
          inPoint: clip.inPoint,
          outPoint: clip.outPoint,
        });
      }

      case "clip/split": {
        try {
          const edits = Array.isArray(action.params.splitEdits) ? action.params.splitEdits as TimelineToolItemEdit[]
            : prepareClipSplit(projectBefore, action.params.clipId, action.params.time, action.id).edits;
          return this.createInverseAction(action, "timeline/toolEdit", { edits: invertTimelineToolEdits(edits), label: "Undo split clip" });
        } catch { return null; }
      }

      case "clip/rippleDelete": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;
        const track = timeline.tracks.find((t) => t.id === clip.trackId);
        const affectedClips =
          track?.clips
            .filter((c) => c.startTime > clip.startTime)
            .map((c) => ({ id: c.id, originalStartTime: c.startTime })) || [];

        return this.createInverseAction(action, "clip/rippleRestore", {
          clip: this.cloneClip(clip),
          affectedClips,
        });
      }

      case "clip/setBlendMode": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/setBlendMode", {
          clipId: action.params.clipId,
          blendMode: clip.blendMode ?? "normal",
        });
      }

      case "clip/setBlendOpacity": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/setBlendOpacity", {
          clipId: action.params.clipId,
          opacity: clip.blendOpacity ?? 100,
        });
      }

      case "clip/setEmphasisAnimation": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/setEmphasisAnimation", {
          clipId: action.params.clipId,
          emphasisAnimation: clip.emphasisAnimation
            ? { ...clip.emphasisAnimation }
            : undefined,
        });
      }

      case "clip/setColorGrading": {
        const clip = this.findClip(timeline, action.params.clipId);
        if (!clip) return null;

        return this.createInverseAction(action, "clip/setColorGrading", {
          clipId: action.params.clipId,
          colorGrading: clip.colorGrading
            ? structuredClone(clip.colorGrading)
            : undefined,
        });
      }

      case "clip/closeGapBefore" as ClipAction["type"]: {
        const params = action.params as { clipId: string };
        const clip = this.findClip(timeline, params.clipId);
        if (!clip) return null;
        const track = timeline.tracks.find((t) => t.id === clip.trackId);
        if (!track) return null;
        const positions = track.clips
          .filter((c) => c.startTime >= clip.startTime)
          .map((c) => ({ clipId: c.id, startTime: c.startTime }));
        return this.createInverseAction(action, "track/restorePositions", {
          trackId: track.id,
          positions,
        });
      }
    }
    return null;
  }

  private generateEffectInverse(
    action: EffectAction & Action,
    projectBefore: Project,
  ): Action | null {
    const timeline = projectBefore.timeline;
    const clip = this.findClip(timeline, action.params.clipId);
    if (!clip) return null;

    switch (action.type) {
      case "effect/add":
        return this.createInverseAction(action, "effect/remove", {
          clipId: action.params.clipId,
          effectId: action.params.effectId ?? "__LAST_ADDED__",
        });

      case "effect/remove": {
        const effect = clip.effects.find(
          (e) => e.id === action.params.effectId,
        );
        if (!effect) return null;

        const index = clip.effects.findIndex(
          (e) => e.id === action.params.effectId,
        );

        return this.createInverseAction(action, "effect/restore", {
          clipId: action.params.clipId,
          effect: { ...effect },
          index,
        });
      }

      case "effect/update": {
        const effect = clip.effects.find(
          (e) => e.id === action.params.effectId,
        );
        if (!effect) return null;

        return this.createInverseAction(action, "effect/update", {
          clipId: action.params.clipId,
          effectId: action.params.effectId,
          params: { ...effect.params },
        });
      }

      case "effect/toggle": {
        const effect = clip.effects.find(
          (e) => e.id === action.params.effectId,
        );
        if (!effect) return null;

        return this.createInverseAction(action, "effect/toggle", {
          clipId: action.params.clipId,
          effectId: action.params.effectId,
          enabled: effect.enabled,
        });
      }

      case "effect/reorder": {
        const currentIndex = clip.effects.findIndex(
          (e) => e.id === action.params.effectId,
        );
        if (currentIndex === -1) return null;

        return this.createInverseAction(action, "effect/reorder", {
          clipId: action.params.clipId,
          effectId: action.params.effectId,
          newIndex: currentIndex,
        });
      }
    }

    return null;
  }

  private generateTransformInverse(
    action: TransformAction & Action,
    projectBefore: Project,
  ): Action | null {
    const clip = this.findClip(projectBefore.timeline, action.params.clipId);
    if (!clip) return null;

    return this.createInverseAction(action, "transform/update", {
      clipId: action.params.clipId,
      transform: structuredClone(clip.transform),
      replace: true,
    });
  }

  private generateKeyframeInverse(
    action: KeyframeAction & Action,
    projectBefore: Project,
  ): Action | null {
    const clip = this.findClip(projectBefore.timeline, action.params.clipId);
    if (!clip) return null;

    switch (action.type) {
      case "keyframe/add":
        return this.createInverseAction(action, "keyframe/remove", {
          clipId: action.params.clipId,
          property: action.params.property,
          time: action.params.time,
        });

      case "keyframe/remove": {
        const keyframe = clip.keyframes.find(
          (kf) =>
            kf.property === action.params.property &&
            kf.time === action.params.time,
        );
        if (!keyframe) return null;

        return this.createInverseAction(action, "keyframe/add", {
          clipId: action.params.clipId,
          property: keyframe.property,
          time: keyframe.time,
          value: keyframe.value,
        });
      }

      case "keyframe/update": {
        const keyframe = clip.keyframes.find(
          (kf) =>
            kf.property === action.params.property &&
            kf.time === action.params.time,
        );
        if (!keyframe) return null;

        return this.createInverseAction(action, "keyframe/update", {
          clipId: action.params.clipId,
          property: keyframe.property,
          time: keyframe.time,
          value: keyframe.value,
          easing: keyframe.easing,
        });
      }
    }

    return null;
  }

  private generateTransitionInverse(
    action: TransitionAction & Action,
    projectBefore: Project,
  ): Action | null {
    const timeline = projectBefore.timeline;

    switch (action.type) {
      case "transition/add":
        return this.createInverseAction(action, "transition/remove", {
          transitionId: "__LAST_ADDED__",
        });

      case "transition/set": {
        const clipA = this.findClip(
          timeline,
          action.params.transition.clipAId,
        );
        if (!clipA) return null;
        const track = timeline.tracks.find((t) => t.id === clipA.trackId);
        if (!track) return null;

        return this.createInverseAction(action, "transition/restoreTrack", {
          trackId: track.id,
          transitions: (track.transitions || []).map((t) => ({ ...t })),
        });
      }

      case "transition/remove": {
        const transition = this.findTransition(
          timeline,
          action.params.transitionId,
        );
        if (!transition) return null;

        return this.createInverseAction(action, "transition/restore", {
          transition: { ...transition },
        });
      }

      case "transition/update": {
        const transition = this.findTransition(
          timeline,
          action.params.transitionId,
        );
        if (!transition) return null;

        // A merging update cannot remove keys introduced by the forward edit.
        return this.createInverseAction(action, "transition/restore", {
          transition: { ...transition, params: { ...transition.params } },
        });
      }
    }
  }

  private generateAudioInverse(
    action: AudioAction & Action,
    projectBefore: Project,
  ): Action | null {
    const clip = this.findClip(projectBefore.timeline, action.params.clipId);
    if (!clip) return null;

    switch (action.type) {
      case "audio/setVolume":
        return this.createInverseAction(action, "audio/setVolume", {
          clipId: action.params.clipId,
          volume: clip.volume,
        });

      case "audio/setFade":
      case "audio/restoreFade":
        return this.createInverseAction(action, "audio/restoreFade", {
          clipId: action.params.clipId,
          fade: clip.fade ? structuredClone(clip.fade) : null,
        });

      case "audio/addAutomation":
        return this.createInverseAction(action, "audio/addAutomation", {
          clipId: action.params.clipId,
          points: clip.automation?.volume?.map((point) => ({ ...point })) ?? null,
        });

      case "audio/addEffect": {
        const effect = action.params.effect;
        return this.createInverseAction(action, "audio/removeEffect", {
          clipId: action.params.clipId,
          effectId: effect.id,
        });
      }

      case "audio/removeEffect": {
        const index = clip.audioEffects.findIndex(
          (e) => e.id === action.params.effectId,
        );
        if (index === -1) return null;
        const effect = clip.audioEffects[index];

        return this.createInverseAction(action, "audio/restoreEffect", {
          clipId: action.params.clipId,
          effect: { ...effect, params: { ...effect.params } },
          index,
        });
      }

      case "audio/replaceEffect": {
        const effect = (clip.audioEffects ?? []).find((item) => item.id === action.params.effectId);
        if (!effect) return null;
        return this.createInverseAction(action, "audio/replaceEffect", {
          clipId: action.params.clipId, effectId: effect.id, effect: structuredClone(effect),
        });
      }

      case "audio/updateEffect": {
        const effect = clip.audioEffects.find(
          (e) => e.id === action.params.effectId,
        );
        if (!effect) return null;

        return this.createInverseAction(action, "audio/replaceEffect", {
          clipId: action.params.clipId,
          effectId: action.params.effectId,
          effect: structuredClone(effect),
        });
      }

      case "audio/toggleEffect": {
        const effect = clip.audioEffects.find(
          (e) => e.id === action.params.effectId,
        );
        if (!effect) return null;

        return this.createInverseAction(action, "audio/toggleEffect", {
          clipId: action.params.clipId,
          effectId: action.params.effectId,
          enabled: effect.enabled,
        });
      }

      case "audio/setLiveDucking":
        return this.createInverseAction(action, "audio/setLiveDucking", {
          clipId: action.params.clipId,
          config: clip.metadata?.liveDucking ? structuredClone(clip.metadata.liveDucking) : null,
        });

      case "audio/setEssentialSound":
        return this.createInverseAction(action, "audio/setEssentialSound", {
          clipId: action.params.clipId,
          audioType: clip.audioType ?? null,
          state: clip.metadata?.essentialSound
            ? structuredClone(clip.metadata.essentialSound)
            : null,
        });
    }
  }

  private generateSubtitleInverse(
    action: SubtitleAction & Action,
    projectBefore: Project,
  ): Action | null {
    const timeline = projectBefore.timeline;

    switch (action.type) {
      case "subtitle/import":
        return this.createInverseAction(action, "subtitle/restoreAll", {
          subtitles: timeline.subtitles.map((s) => ({ ...s })),
        });

      case "subtitle/add":
        return this.createInverseAction(action, "subtitle/remove", {
          subtitleId: "__LAST_ADDED__",
        });

      case "subtitle/remove": {
        const subtitle = timeline.subtitles.find(
          (s) => s.id === action.params.subtitleId,
        );
        if (!subtitle) return null;

        return this.createInverseAction(action, "subtitle/restore", {
          subtitle: { ...subtitle },
        });
      }

      case "subtitle/update": {
        const subtitle = timeline.subtitles.find(
          (s) => s.id === action.params.subtitleId,
        );
        if (!subtitle) return null;

        return this.createInverseAction(action, "subtitle/update", {
          subtitleId: action.params.subtitleId,
          text: subtitle.text,
          startTime: subtitle.startTime,
          endTime: subtitle.endTime,
        });
      }

      case "subtitle/setStyle": {
        const firstSubtitle = timeline.subtitles[0];
        return this.createInverseAction(action, "subtitle/setStyle", {
          style: firstSubtitle?.style ?? null,
        });
      }
    }

    return null;
  }

  private findClip(timeline: { tracks: Track[] }, clipId: string): Clip | null {
    for (const track of timeline.tracks) {
      const clip = track.clips.find((c) => c.id === clipId);
      if (clip) return clip;
    }
    return null;
  }

  private findTransition(
    timeline: { tracks: Track[] },
    transitionId: string,
  ): Transition | null {
    for (const track of timeline.tracks) {
      const transition = track.transitions?.find((t) => t.id === transitionId);
      if (transition) return transition;
    }
    return null;
  }

  private cloneMediaItem(item: MediaItem): Record<string, unknown> {
    return {
      id: item.id,
      name: item.name,
      type: item.type,
      fileHandle: item.fileHandle,
      blob: item.blob,
      metadata: { ...item.metadata },
      thumbnailUrl: item.thumbnailUrl,
      waveformData: item.waveformData
        ? new Float32Array(item.waveformData)
        : null,
    };
  }

  private cloneTrackItems<T extends TrackOwnedProjectItem>(
    items: readonly T[] | undefined,
    trackId: string,
  ): T[] {
    return (items ?? [])
      .filter((item) => item.trackId === trackId)
      .map((item) => structuredClone(item));
  }

  private cloneTrack(track: Track): Record<string, unknown> {
    return {
      ...(track as unknown as Record<string, unknown>),
      clips: track.clips.map((c) => this.cloneClip(c)),
      transitions: track.transitions?.map((t) => ({ ...t })) ?? [],
    };
  }

  private cloneClip(clip: Clip): Record<string, unknown> {
    // Spread every field first so nothing is silently dropped (blendMode,
    // blendOpacity, emphasisAnimation, speed, reversed, stabilization,
    // audioTrackIndex, metadata, ...), then deep-clone the mutable nested
    // structures so the restored clip does not share references.
    return {
      ...(clip as unknown as Record<string, unknown>),
      effects: clip.effects.map((e) => ({ ...e, params: { ...e.params } })),
      audioEffects: clip.audioEffects.map((e) => ({
        ...e,
        params: { ...e.params },
      })),
      transform: { ...clip.transform },
      fade: clip.fade ? { ...clip.fade } : undefined,
      automation: clip.automation
        ? {
            volume: clip.automation.volume?.map((p) => ({ ...p })),
            pan: clip.automation.pan?.map((p) => ({ ...p })),
          }
        : undefined,
      keyframes: clip.keyframes.map((kf) => ({ ...kf })),
      emphasisAnimation: clip.emphasisAnimation
        ? { ...clip.emphasisAnimation }
        : undefined,
      metadata: clip.metadata ? { ...clip.metadata } : undefined,
    };
  }
}