Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 80 additions & 1 deletion src/core/commands/alias-reference-utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import type { EditDocument } from "@core/edit-document";
import type { Clip, ResolvedEdit } from "@schemas";
import { isAliasReference, parseAliasName } from "@core/timing/types";
import type { Clip, Duck, ResolvedEdit } from "@schemas";

/**
* Stores original alias reference values for a clip.
*/
export interface StoredAliasReference {
start?: string;
length?: string;
/** The clip's original `asset.duck`, before references to removed aliases were pruned. */
duck?: unknown;
}

/**
Expand Down Expand Up @@ -101,6 +104,76 @@ export function convertMultipleAliasReferences(
return combined;
}

function readDuck(asset: unknown): Duck | undefined {
const duck = (asset as { duck?: Duck } | undefined)?.duck;
return typeof duck?.under === "string" || Array.isArray(duck?.under) ? duck : undefined;
}

/**
* `duck` without the alias refs that `drop` names, keeping the shape of `under`.
* Null when no refs remain; undefined when none were dropped.
*/
function trimDuck(duck: Duck, drop: (aliasName: string) => boolean): Duck | null | undefined {
const refs = [duck.under].flat();
const kept = refs.filter(ref => !(isAliasReference(ref) && drop(parseAliasName(ref))));
if (kept.length === refs.length) return undefined;
if (kept.length === 0) return null;
return { ...duck, under: typeof duck.under === "string" ? kept[0] : kept };
}

function withDuck(asset: object, duck: unknown): object {
const next: { duck?: unknown } = { ...asset };
if (duck) next.duck = duck;
else delete next.duck;
return next;
}

/**
* Remove references to deleted aliases from every clip's `asset.duck.under`, dropping
* `duck` when none remain.
*
* @param document - The edit document
* @param removedAliases - Names of the aliases being removed (e.g., "voice" for "alias://voice")
* @param stored - Map to record each pruned clip's original `duck` in, for undo
* @param skipClipIndices - Optional set of "trackIdx:clipIdx" to skip (the clips being deleted)
*/
export function pruneDuckReferences(
document: EditDocument,
removedAliases: Set<string>,
stored: AliasReferenceMap,
skipClipIndices?: Set<string>
): void {
for (let t = 0; t < document.getTrackCount(); t += 1) {
const clips = document.getClipsInTrack(t);
for (let c = 0; c < clips.length; c += 1) {
const clip = clips[c];
const clipId = (clip as { id?: string }).id;
const duck = readDuck(clip.asset);

if (clipId && duck && !skipClipIndices?.has(`${t}:${c}`)) {
const pruned = trimDuck(duck, name => removedAliases.has(name));
if (pruned !== undefined) {
const existing = stored.get(clipId);
stored.set(clipId, { ...existing, duck: structuredClone(duck) });
document.updateClip(t, c, { asset: withDuck(clip.asset, pruned) as Clip["asset"] });
}
}
}
}
}

/**
* Remove references to aliases that `knownAliases` lacks from a pasted clip's
* `asset.duck.under`, dropping `duck` when none remain. Edits `clip` in place.
*/
export function pruneMissingDuckReferences(clip: Clip, knownAliases: Set<string>): void {
const duck = readDuck(clip.asset);
const pruned = duck ? trimDuck(duck, name => !knownAliases.has(name)) : undefined;
if (pruned === undefined) return;

Object.assign(clip, { asset: withDuck(clip.asset, pruned) });
}

/**
* Restore original alias references after undoing deletion.
*
Expand All @@ -114,6 +187,7 @@ export function restoreAliasReferences(document: EditDocument, convertedReferenc
const updates: Partial<Clip> = {};
if (original.start) updates.start = original.start;
if (original.length) updates.length = original.length;
if (original.duck) updates.asset = withDuck(clipInfo.clip.asset, original.duck) as Clip["asset"];
document.updateClip(clipInfo.trackIndex, clipInfo.clipIndex, updates);
}
}
Expand All @@ -135,3 +209,8 @@ export function extractAliasNames(clips: Clip[]): string[] {
}
return aliases;
}

/** Names of every alias defined in the document. */
export function documentAliasNames(document: EditDocument | null): Set<string> {
return new Set(document?.getTracks().flatMap(track => extractAliasNames(track.clips)));
}
3 changes: 2 additions & 1 deletion src/core/commands/delete-clip-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { MergeFieldBinding } from "@core/edit-document";
import { EditEvent } from "@core/events/edit-events";
import type { Clip } from "@schemas";

import { type AliasReferenceMap, convertAliasReferencesToValues, restoreAliasReferences } from "./alias-reference-utils";
import { type AliasReferenceMap, convertAliasReferencesToValues, pruneDuckReferences, restoreAliasReferences } from "./alias-reference-utils";
import { DeleteTrackCommand } from "./delete-track-command";
import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess, CommandNoop } from "./types";

Expand Down Expand Up @@ -55,6 +55,7 @@ export class DeleteClipCommand implements EditCommand {
if (clipAlias) {
const skipIndices = new Set([`${this.trackIdx}:${this.clipIdx}`]);
this.convertedReferences = convertAliasReferencesToValues(document, context.getEditState(), clipAlias, skipIndices);
pruneDuckReferences(document, new Set([clipAlias]), this.convertedReferences, skipIndices);
}

// Clear any error associated with this clip before deletion
Expand Down
9 changes: 8 additions & 1 deletion src/core/commands/delete-track-command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { EditEvent } from "@core/events/edit-events";
import type { Clip } from "@schemas";

import { type AliasReferenceMap, convertMultipleAliasReferences, extractAliasNames, restoreAliasReferences } from "./alias-reference-utils";
import {
type AliasReferenceMap,
convertMultipleAliasReferences,
extractAliasNames,
pruneDuckReferences,
restoreAliasReferences
} from "./alias-reference-utils";
import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess, CommandNoop } from "./types";

/**
Expand Down Expand Up @@ -39,6 +45,7 @@ export class DeleteTrackCommand implements EditCommand {
skipIndices.add(`${this.trackIdx}:${c}`);
}
this.convertedReferences = convertMultipleAliasReferences(document, context.getEditState(), aliasNames, skipIndices);
pruneDuckReferences(document, new Set(aliasNames), this.convertedReferences, skipIndices);
}

// Document mutation - remove track (and all its clips)
Expand Down
4 changes: 4 additions & 0 deletions src/core/edit-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { parseSvgIntrinsicSize, sanitiseSvg } from "@core/clipboard/svg-clipboar
import { AddClipCommand } from "@core/commands/add-clip-command";
import { AddTrackCommand } from "@core/commands/add-track-command";
import { AddTracksCommand } from "@core/commands/add-tracks-command";
import { documentAliasNames, pruneMissingDuckReferences } from "@core/commands/alias-reference-utils";
import { DeleteClipCommand } from "@core/commands/delete-clip-command";
import { DeleteTrackCommand } from "@core/commands/delete-track-command";
import { MoveClipCommand } from "@core/commands/move-clip-command";
Expand Down Expand Up @@ -870,6 +871,7 @@ export class Edit {
}

remintPastedClipIdentity(parsed as { id?: string; alias?: string });
pruneMissingDuckReferences(parsed, documentAliasNames(this.document));

const asset = parsed.asset as { type?: string; src?: string } | undefined;
if (asset?.type === "svg" && typeof asset.src === "string") {
Expand Down Expand Up @@ -910,11 +912,13 @@ export class Edit {
const anchor = (opts.start ?? this.playbackTime) as number;
const offset = anchor - minStart;

const knownAliases = documentAliasNames(this.document);
const prepared: Track[] = tracks.map(track => ({
...track,
clips: track.clips.map(clip => {
const cloned = structuredClone(clip) as Clip;
remintPastedClipIdentity(cloned as { id?: string; alias?: string });
pruneMissingDuckReferences(cloned, knownAliases);
const asset = cloned.asset as { type?: string; src?: string } | undefined;
if (asset?.type === "svg" && typeof asset.src === "string") {
asset.src = sanitiseSvg(asset.src);
Expand Down
1 change: 1 addition & 0 deletions src/core/schemas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export type Font = components["schemas"]["Font"];
// Asset types
export type VideoAsset = components["schemas"]["VideoAsset"];
export type AudioAsset = components["schemas"]["AudioAsset"];
export type Duck = components["schemas"]["Duck"];
export type ImageAsset = components["schemas"]["ImageAsset"];
export type TextAsset = components["schemas"]["TextAsset"];
export type RichTextAsset = components["schemas"]["RichTextAsset"];
Expand Down
2 changes: 2 additions & 0 deletions src/core/selection-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { clipToJsonString } from "@core/clipboard/clip-json";
import { insertClipWithOverlapPolicy } from "@core/clipboard/paste-dispatcher";
import { remintPastedClipIdentity } from "@core/clipboard/remint-pasted-alias";
import { writeSystemClipboardText } from "@core/clipboard/system-clipboard";
import { documentAliasNames, pruneMissingDuckReferences } from "@core/commands/alias-reference-utils";
import { EditEvent } from "@core/events/edit-events";
import type { ResolvedClip, Clip } from "@core/schemas";
import { stripInternalProperties } from "@core/shared/clip-utils";
Expand Down Expand Up @@ -153,6 +154,7 @@ export class SelectionManager {
pastedClip.start = this.edit.playbackTime as Seconds;

remintPastedClipIdentity(pastedClip as { id?: string; alias?: string });
pruneMissingDuckReferences(pastedClip, documentAliasNames(this.edit.getDocument()));

return insertClipWithOverlapPolicy(this.edit, this.copiedClip.trackIndex, pastedClip);
}
Expand Down
Loading
Loading