@alpha2-sh/editor 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +60 -3
  2. package/dist/browser/bridge.d.ts +5 -4
  3. package/dist/browser/bridge.js +390 -67
  4. package/dist/browser/extensions-worker.d.ts +4 -3
  5. package/dist/browser/extensions-worker.js +13 -6
  6. package/dist/browser/jobs.d.ts +17 -0
  7. package/dist/browser/jobs.js +40 -0
  8. package/dist/browser/resources.d.ts +9 -4
  9. package/dist/browser/resources.js +17 -5
  10. package/dist/browser/runtime/assets.d.ts +14 -2
  11. package/dist/browser/runtime/assets.js +37 -27
  12. package/dist/browser/runtime/audio.d.ts +12 -2
  13. package/dist/browser/runtime/audio.js +124 -14
  14. package/dist/browser/runtime/engine.js +8 -1
  15. package/dist/browser/runtime/exporter.d.ts +2 -1
  16. package/dist/browser/runtime/exporter.js +15 -4
  17. package/dist/browser/runtime/extension-import.d.ts +30 -10
  18. package/dist/browser/runtime/extension-import.js +52 -9
  19. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  20. package/dist/browser/runtime/preview-utils.js +45 -0
  21. package/dist/browser/runtime/sources.d.ts +2 -2
  22. package/dist/browser/runtime/sources.js +23 -40
  23. package/dist/browser/runtime/wasm.d.ts +5 -5
  24. package/dist/browser/runtime/wasm.js +6 -13
  25. package/dist/browser/types.d.ts +138 -26
  26. package/dist/browser/worker.d.ts +4 -2
  27. package/dist/browser/worker.js +75 -25
  28. package/dist/core/commands.d.ts +46 -3
  29. package/dist/core/commands.js +212 -40
  30. package/dist/core/compositions.d.ts +27 -0
  31. package/dist/core/compositions.js +43 -0
  32. package/dist/core/data.d.ts +34 -0
  33. package/dist/core/data.js +69 -0
  34. package/dist/core/document.d.ts +20 -1
  35. package/dist/core/document.js +138 -8
  36. package/dist/core/keyframes.d.ts +3 -2
  37. package/dist/core/keyframes.js +6 -2
  38. package/dist/core/sameness.d.ts +6 -0
  39. package/dist/core/sameness.js +42 -0
  40. package/dist/core/session.d.ts +85 -7
  41. package/dist/core/session.js +124 -13
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.js +1 -0
  44. package/dist/native-client/index.d.ts +2 -2
  45. package/dist/native-client/index.js +2 -2
  46. package/dist/ports/index.d.ts +5 -4
  47. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import type { InputKey } from "./compositions.js";
2
- import type { Project, Clip, Track, ClipEffect, CaptionCue, Composition, CompositionNode, MediaSource, EffectResource } from "alpha2/project";
2
+ import type { Project, Clip, Track, ClipEffect, CaptionCue, Composition, CompositionNode, MediaSource, EffectResource, DataSet } from "alpha2/project";
3
+ import type { AppliedEdit } from "alpha2/apply-edit";
3
4
  import type { EditorDocument, TrackMetadata, ClipMetadata, AssetDescriptor, Marker, Result, GraphLayout, GraphPosition } from "./document.js";
4
5
  /**
5
6
  * A document while a command applies: its project may hold input as written (a CSS hex color, say)
@@ -234,6 +235,15 @@ export type Command =
234
235
  readonly id: string;
235
236
  readonly ids: readonly string[];
236
237
  }
238
+ /**
239
+ * Gives clip `id` its own copy of its composition tree when another clip, source or group draws
240
+ * part of it, so a graph command on it changes only this clip. Effect commands do this
241
+ * themselves; graph commands name a composition and change every clip that shows it.
242
+ */
243
+ | {
244
+ readonly type: "clip.detachComposition";
245
+ readonly id: string;
246
+ }
237
247
  /** Gives a clip without one a composition that shows its picture. */
238
248
  | {
239
249
  readonly type: "graph.create";
@@ -394,11 +404,32 @@ export type Command =
394
404
  readonly source?: MediaSource;
395
405
  readonly resource?: EffectResource;
396
406
  }
397
- /** Removes a bin asset and its source or effect resource; refused while a clip reads it. */
407
+ /**
408
+ * Removes a bin asset and its source or effect resource; refused while a clip reads it, and
409
+ * (`data_referenced`, with the set ids as `details.dataSets`) while data sets are anchored to it.
410
+ */
398
411
  | {
399
412
  readonly type: "asset.remove";
400
413
  readonly id: string;
401
414
  }
415
+ /**
416
+ * Adds a data set, or replaces the set with its id in place. Undo history keeps a replaced set
417
+ * whole, about its JSON size, so one put of a set near `MAX_DATA_VALUES` (tens of MB) can evict
418
+ * most or all earlier steps under the default `historyByteLimit`.
419
+ */
420
+ | {
421
+ readonly type: "data.put";
422
+ readonly dataSet: DataSet;
423
+ }
424
+ /**
425
+ * Removes a data set. Refused (`data_referenced`, with the places as `details.references`) while
426
+ * a binding, correction or caption track reads it. To keep what they show, apply a `bake` with
427
+ * this command in its `then` (`EditorSession.applyEdit`).
428
+ */
429
+ | {
430
+ readonly type: "data.remove";
431
+ readonly id: string;
432
+ }
402
433
  /** Replaces the document metadata fields the patch has. */
403
434
  | {
404
435
  readonly type: "metadata.update";
@@ -408,13 +439,25 @@ export type Command =
408
439
  export declare function graphNames(document: DraftDocument): Readonly<Record<string, string>>;
409
440
  /** The node editor positions a document stores. */
410
441
  export declare function graphLayout(document: DraftDocument): GraphLayout;
442
+ /**
443
+ * Puts an engine edit result (`alpha2/apply-edit` `AppliedEdit`, computed from `document`'s
444
+ * project) in `document`, then runs `then` on it as one transaction. Clips the edit created get the
445
+ * editor metadata of the clip each was cut from (`report.created[].from`); removed clips lose
446
+ * theirs. Every part the edit left equal to `document`'s keeps `document`'s object, so a locked
447
+ * track the edit did not touch passes the lock check; the rest is the engine's project as written.
448
+ *
449
+ * Never throws. A refusal is `{ ok: false }` with an `EditorError`, `locked` for a change to a
450
+ * locked track, `invalid_result` for a result that does not validate (an engine defect), or the
451
+ * refusal of a `then` command. `document` is not modified, and the result is deep-frozen.
452
+ */
453
+ export declare function executeEditResult(document: EditorDocument, applied: Pick<AppliedEdit, "projectJson" | "report">, then?: readonly Command[]): Result<EditorDocument>;
411
454
  /**
412
455
  * Applies `command` to `document` and validates the result. `gesture` checks only what a pointer
413
456
  * move can change (see `validateDocumentShape`); the gesture validates in full when it commits.
414
457
  *
415
458
  * Never throws: a refusal is `{ ok: false }` with an `EditorError` (`invalid_command`, `locked`, a
416
459
  * validation code, or an edit code from `alpha2/edit`). `document` and `command` are not modified;
417
- * compositions the edit leaves undrawn are removed from the result.
460
+ * compositions the edit leaves undrawn are removed from the result, which is deep-frozen.
418
461
  */
419
462
  export declare function executeCommand(document: EditorDocument, command: Command, { gesture }?: {
420
463
  gesture?: boolean;
@@ -1,9 +1,11 @@
1
1
  import { addTransition, resizeTransition, removeTransition, } from "./transitions.js";
2
2
  import { splitCue, trimCue } from "alpha2/captions";
3
3
  import * as edit from "alpha2/edit";
4
- import { drawnEffectResources, effectStack, findComposition, freeCompositionId, freeNodeId, groupNodes, ungroupNode, acceptsInput, correspondingCompositions, ownComposition, withEffectStack, withoutUndrawn, withInput, withoutNodes, shownSources, } from "./compositions.js";
4
+ import { drawnEffectResources, effectStack, findComposition, freeCompositionId, freeNodeId, groupNodes, ungroupNode, acceptsInput, correspondingCompositions, ownComposition, detachComposition, withEffectStack, withoutUndrawn, withInput, withoutNodes, shownSources, } from "./compositions.js";
5
+ import { dataReferences, shareUnchangedParts } from "alpha2/project";
6
+ import { assertClipsUnread, assertDataUnread, assertSourceUnanchored, changedDataSets, } from "./data.js";
5
7
  import { rememberValid, withValidated } from "./validated.js";
6
- import { EditorError, validateDocument, validateDocumentShape, canonicalDocument, assertProjection, indexDocument, transitionInstanceId, withInstanceIds, } from "./document.js";
8
+ import { EditorError, freeze, validateDocument, validateDocumentShape, canonicalDocument, assertProjection, indexDocument, transitionInstanceId, withInstanceIds, } from "./document.js";
7
9
  const NO_NAMES = Object.freeze({});
8
10
  /** The names the node editor shows for group compositions, by composition id. */
9
11
  export function graphNames(document) {
@@ -127,6 +129,20 @@ function shiftMarkers(document, pivot, delta) {
127
129
  fail("The edit would move a marker before the timeline start");
128
130
  return { ...document, metadata: { ...document.metadata, markers } };
129
131
  }
132
+ /**
133
+ * `document` with its markers moved as `result`'s ripple moved time. Like timeline-anchored data,
134
+ * markers move only when the ripple reached every track.
135
+ */
136
+ function followTimeline(document, result) {
137
+ const change = result.ok ? result.timeline : undefined;
138
+ if (!change?.everyTrack)
139
+ return document;
140
+ if (change.removed)
141
+ return shiftMarkers(document, change.removed.end, change.removed.start - change.removed.end);
142
+ return change.opened
143
+ ? shiftMarkers(document, change.opened.at, change.opened.length)
144
+ : document;
145
+ }
130
146
  /** The metadata right part `newId` of split clip `leftId` inherits. */
131
147
  function afterSplit(document, newId, leftId) {
132
148
  if (!indexDocument(document).clips.has(newId))
@@ -308,6 +324,7 @@ function reduce(document, command) {
308
324
  return withCopiedGraphs({ ...document, project: next }, copies);
309
325
  }
310
326
  case "track.remove":
327
+ assertClipsUnread(project, new Set((track.clips ?? []).map((c) => c.id)), command.type);
311
328
  return {
312
329
  ...document,
313
330
  project: {
@@ -413,8 +430,7 @@ function reduce(document, command) {
413
430
  if (cut)
414
431
  next = afterSplit(next, command.splitId, cut.id);
415
432
  }
416
- if (command.mode === "insert" && syncTracks.length)
417
- next = shiftMarkers(next, command.at, command.clip.timeline_range.end - command.clip.timeline_range.start);
433
+ next = followTimeline(next, result);
418
434
  return withCopiedGraphs(next, owned.copies);
419
435
  }
420
436
  case "clip.slip":
@@ -438,12 +454,7 @@ function reduce(document, command) {
438
454
  ...(command.keyframes ? { keyframes: command.keyframes } : {}),
439
455
  });
440
456
  const made = edited(result, command, command.id);
441
- const next = { ...document, project: made };
442
- // Timeline markers move with a ripple that reaches other tracks.
443
- const before = found.clip.timeline_range;
444
- return syncTracks.length
445
- ? shiftMarkers(next, before.end, before.start + command.duration - before.end)
446
- : next;
457
+ return followTimeline({ ...document, project: made }, result);
447
458
  }
448
459
  case "marker.add":
449
460
  if (document.metadata.markers.some((m) => m.id === command.marker.id))
@@ -485,6 +496,8 @@ function reduce(document, command) {
485
496
  case "clip.delete": {
486
497
  let result;
487
498
  const found = indexDocument(document).clips.get(command.id);
499
+ if (command.type === "clip.delete")
500
+ assertClipsUnread(project, new Set([command.id]), command.type);
488
501
  const syncTracks = "ripple" in command && command.ripple && found
489
502
  ? syncTrackIds(document, found.trackId)
490
503
  : [];
@@ -519,21 +532,7 @@ function reduce(document, command) {
519
532
  const made = command.type === "clip.delete" && !command.ripple && result.ok
520
533
  ? result.project
521
534
  : edited(result, command, command.id);
522
- let next = { ...document, project: made };
523
- // Timeline markers move with a ripple that reaches other tracks.
524
- if (syncTracks.length && found) {
525
- const before = found.clip.timeline_range;
526
- if (command.type === "clip.trim") {
527
- const delta = command.edge === "end"
528
- ? command.at - before.end
529
- : before.start - command.at;
530
- next = shiftMarkers(next, before.end, delta);
531
- }
532
- else if (command.type === "clip.delete") {
533
- const gap = edit.rippleDeleteSpan(project, command.id);
534
- next = shiftMarkers(next, gap.end, gap.start - gap.end);
535
- }
536
- }
535
+ let next = followTimeline({ ...document, project: made }, result);
537
536
  if (command.type === "clip.split")
538
537
  next = afterSplit(next, command.newId, command.id);
539
538
  return next;
@@ -553,7 +552,9 @@ function reduce(document, command) {
553
552
  const found = indexDocument(document).clips.get(command.id);
554
553
  if (!found)
555
554
  fail("Unknown clip", command.id);
556
- const current = effectStack(project, found.clip);
555
+ // Another clip may show the same composition; the edit is this clip's alone.
556
+ const detached = detachComposition(project, command.id);
557
+ const current = effectStack(detached.project, found.clip);
557
558
  if (!current)
558
559
  fail("The clip's composition is a graph, not an effect stack; edit it as a graph", command.id);
559
560
  const order = current.map((entry) => entry.id);
@@ -585,10 +586,16 @@ function reduce(document, command) {
585
586
  bypass: command.bypass ?? stack[i].bypass,
586
587
  };
587
588
  }
588
- return {
589
+ return withCopiedGraphs({
589
590
  ...document,
590
- project: withEffectStack(project, command.id, stack),
591
- };
591
+ project: withEffectStack(detached.project, command.id, stack),
592
+ }, detached.copies);
593
+ }
594
+ case "clip.detachComposition": {
595
+ if (!indexDocument(document).clips.has(command.id))
596
+ fail("Unknown clip", command.id);
597
+ const detached = detachComposition(project, command.id);
598
+ return withCopiedGraphs({ ...document, project: detached.project }, detached.copies);
592
599
  }
593
600
  case "graph.create": {
594
601
  const found = indexDocument(document).clips.get(command.clipId);
@@ -900,7 +907,7 @@ function reduce(document, command) {
900
907
  fail("Not a caption track", command.trackId);
901
908
  const key = `${track.id}/cues`;
902
909
  const nextIds = [...(document.metadata.instanceIds[key] ?? [])];
903
- const cues = [...track.captions.cues];
910
+ const cues = [...(track.captions.cues ?? [])];
904
911
  // Cues stay in start order; overlaps are for validation to report.
905
912
  const place = (instanceId, cue) => {
906
913
  const at = cues.findIndex((c) => c.timeline_range.start > cue.timeline_range.start);
@@ -939,6 +946,32 @@ function reduce(document, command) {
939
946
  }),
940
947
  }, key, nextIds);
941
948
  }
949
+ case "data.put": {
950
+ const sets = project.data ?? [];
951
+ const at = sets.findIndex((set) => set.id === command.dataSet.id);
952
+ return {
953
+ ...document,
954
+ project: {
955
+ ...project,
956
+ data: at < 0
957
+ ? [...sets, command.dataSet]
958
+ : sets.map((set, index) => index === at ? command.dataSet : set),
959
+ },
960
+ };
961
+ }
962
+ case "data.remove": {
963
+ const sets = project.data ?? [];
964
+ if (!sets.some((set) => set.id === command.id))
965
+ fail("Unknown data set", command.id);
966
+ assertDataUnread(project, command.id, command.type);
967
+ const data = sets.filter((set) => set.id !== command.id);
968
+ // The engine writes no data list when it is empty.
969
+ const { data: _removed, ...rest } = project;
970
+ return {
971
+ ...document,
972
+ project: data.length ? { ...rest, data } : rest,
973
+ };
974
+ }
942
975
  case "asset.put": {
943
976
  const previous = document.assets[command.asset.id];
944
977
  if (previous && command.asset.contentRevision < previous.contentRevision)
@@ -966,6 +999,7 @@ function reduce(document, command) {
966
999
  };
967
1000
  }
968
1001
  case "asset.remove": {
1002
+ assertSourceUnanchored(project, command.id, command.type);
969
1003
  const assets = { ...document.assets };
970
1004
  delete assets[command.id];
971
1005
  return {
@@ -1041,6 +1075,8 @@ function assertLocksKept(document, next, command) {
1041
1075
  const sourcesSame = assetsSame && after.sources === before.sources;
1042
1076
  const resourcesSame = assetsSame && after.effect_resources === before.effect_resources;
1043
1077
  const compositionsSame = after.compositions === before.compositions;
1078
+ const dataChanged = changedDataSets(before, after);
1079
+ let references = null;
1044
1080
  const tracksAfter = after.timeline.tracks === before.timeline.tracks
1045
1081
  ? null
1046
1082
  : new Map(after.timeline.tracks.map((t) => [t.id, t]));
@@ -1068,6 +1104,30 @@ function assertLocksKept(document, next, command) {
1068
1104
  if ([...shownSources(before, [track])].some((id) => is.get(id) !== was.get(id) || assetChanged(id)))
1069
1105
  return true;
1070
1106
  }
1107
+ if (dataChanged.size) {
1108
+ references ??= dataReferences(before);
1109
+ const clips = new Set((track.clips ?? []).map((c) => c.id));
1110
+ const compositions = reachedCompositions(before, track.clips ?? []);
1111
+ const sources = shownSources(before, [track]);
1112
+ const reads = (r) => {
1113
+ const owner = r.owner;
1114
+ switch (owner.kind) {
1115
+ case "clip":
1116
+ return clips.has(owner.clip);
1117
+ case "track":
1118
+ case "transition":
1119
+ return owner.track === track.id;
1120
+ case "node":
1121
+ return compositions.has(owner.composition);
1122
+ case "source":
1123
+ return sources.has(owner.source);
1124
+ case "master":
1125
+ return false;
1126
+ }
1127
+ };
1128
+ if (references.some((r) => dataChanged.has(r.data) && reads(r)))
1129
+ return true;
1130
+ }
1071
1131
  if (!resourcesSame) {
1072
1132
  resources ??= [
1073
1133
  byId(before.effect_resources ?? []),
@@ -1083,24 +1143,141 @@ function assertLocksKept(document, next, command) {
1083
1143
  throw new EditorError("locked", "Track is locked", command.type, track.id);
1084
1144
  }
1085
1145
  }
1146
+ /**
1147
+ * `next` without the editor metadata (entries and instance id lists) of the clips and tracks
1148
+ * `before` has and `next` lost. A clip that moved keeps its id and its metadata. Only tracks that
1149
+ * are not the same objects in both are walked.
1150
+ */
1151
+ function withoutRemovedMetadata(before, next) {
1152
+ const old = before.project.timeline.tracks;
1153
+ const now = next.project.timeline.tracks;
1154
+ if (old === now)
1155
+ return next;
1156
+ const kept = new Set(now);
1157
+ const changed = old.filter((track) => !kept.has(track));
1158
+ if (!changed.length)
1159
+ return next;
1160
+ const unchanged = new Set(old);
1161
+ const added = now.filter((track) => !unchanged.has(track));
1162
+ const byId = new Map(added.map((track) => [track.id, track]));
1163
+ // A track whose clips keep their ids in place (a move or trim) loses no clip.
1164
+ const sameIds = (before) => {
1165
+ const track = byId.get(before.id);
1166
+ const after = track?.clips ?? [];
1167
+ const clips = before.clips ?? [];
1168
+ return (track !== undefined &&
1169
+ clips.length === after.length &&
1170
+ clips.every((clip, index) => clip.id === after[index].id));
1171
+ };
1172
+ const losing = changed.filter((track) => !sameIds(track));
1173
+ if (!losing.length)
1174
+ return next;
1175
+ const present = new Set();
1176
+ for (const track of added)
1177
+ for (const clip of track.clips ?? [])
1178
+ present.add(clip.id);
1179
+ const trackIds = new Set(now.map((track) => track.id));
1180
+ const clips = losing
1181
+ .flatMap((track) => (track.clips ?? []).map((clip) => clip.id))
1182
+ .filter((id) => !present.has(id));
1183
+ const tracks = losing
1184
+ .map((track) => track.id)
1185
+ .filter((id) => !trackIds.has(id));
1186
+ const { metadata } = next;
1187
+ const stale = [
1188
+ ...clips.map((id) => `${id}/masks`),
1189
+ ...tracks.flatMap((id) => [`${id}/cues`, `${id}/transitions`]),
1190
+ ].filter((key) => key in metadata.instanceIds);
1191
+ const named = clips.filter((id) => id in metadata.clips);
1192
+ const flagged = tracks.filter((id) => id in metadata.tracks);
1193
+ if (!stale.length && !named.length && !flagged.length)
1194
+ return next;
1195
+ const instanceIds = { ...metadata.instanceIds };
1196
+ for (const key of stale)
1197
+ delete instanceIds[key];
1198
+ const clipMetadata = { ...metadata.clips };
1199
+ for (const id of named)
1200
+ delete clipMetadata[id];
1201
+ const trackMetadata = { ...metadata.tracks };
1202
+ for (const id of flagged)
1203
+ delete trackMetadata[id];
1204
+ return {
1205
+ ...next,
1206
+ metadata: {
1207
+ ...metadata,
1208
+ instanceIds,
1209
+ clips: clipMetadata,
1210
+ tracks: trackMetadata,
1211
+ },
1212
+ };
1213
+ }
1214
+ /**
1215
+ * Puts an engine edit result (`alpha2/apply-edit` `AppliedEdit`, computed from `document`'s
1216
+ * project) in `document`, then runs `then` on it as one transaction. Clips the edit created get the
1217
+ * editor metadata of the clip each was cut from (`report.created[].from`); removed clips lose
1218
+ * theirs. Every part the edit left equal to `document`'s keeps `document`'s object, so a locked
1219
+ * track the edit did not touch passes the lock check; the rest is the engine's project as written.
1220
+ *
1221
+ * Never throws. A refusal is `{ ok: false }` with an `EditorError`, `locked` for a change to a
1222
+ * locked track, `invalid_result` for a result that does not validate (an engine defect), or the
1223
+ * refusal of a `then` command. `document` is not modified, and the result is deep-frozen.
1224
+ */
1225
+ export function executeEditResult(document, applied, then = []) {
1226
+ let edited;
1227
+ try {
1228
+ edited = withValidated(() => {
1229
+ let next = withoutRemovedMetadata(document, {
1230
+ ...document,
1231
+ project: shareUnchangedParts(document.project, JSON.parse(applied.projectJson)),
1232
+ });
1233
+ for (const created of applied.report.created)
1234
+ next = afterSplit(next, created.id, created.from);
1235
+ // What the edit stopped drawing goes, with its graph layout and names.
1236
+ const undrawn = withoutUndrawn(document.project, next.project);
1237
+ if (undrawn.removed.size)
1238
+ next = withoutGraphs({ ...next, project: undrawn.project }, undrawn.removed);
1239
+ assertLocksKept(document, next, { type: "edit" });
1240
+ const result = freeze(withInstanceIds(canonicalDocument(next)));
1241
+ try {
1242
+ validateDocument(result);
1243
+ }
1244
+ catch (cause) {
1245
+ throw new EditorError("invalid_result", `The engine's edit result does not validate: ${cause instanceof Error ? cause.message : String(cause)}`, "edit", undefined, true, { cause });
1246
+ }
1247
+ return result;
1248
+ });
1249
+ }
1250
+ catch (cause) {
1251
+ return { ok: false, error: asEditorError(cause) };
1252
+ }
1253
+ return then.length
1254
+ ? executeCommand(edited, { type: "transaction", commands: then })
1255
+ : { ok: true, value: edited };
1256
+ }
1257
+ function asEditorError(cause) {
1258
+ return cause instanceof EditorError
1259
+ ? cause
1260
+ : new EditorError("invalid_command", String(cause), "dispatch", undefined, true, { cause });
1261
+ }
1086
1262
  /**
1087
1263
  * Applies `command` to `document` and validates the result. `gesture` checks only what a pointer
1088
1264
  * move can change (see `validateDocumentShape`); the gesture validates in full when it commits.
1089
1265
  *
1090
1266
  * Never throws: a refusal is `{ ok: false }` with an `EditorError` (`invalid_command`, `locked`, a
1091
1267
  * validation code, or an edit code from `alpha2/edit`). `document` and `command` are not modified;
1092
- * compositions the edit leaves undrawn are removed from the result.
1268
+ * compositions the edit leaves undrawn are removed from the result, which is deep-frozen.
1093
1269
  */
1094
1270
  export function executeCommand(document, command, { gesture = false } = {}) {
1095
1271
  try {
1096
1272
  return withValidated(() => {
1097
- const reduced = apply(document, structuredClone(command));
1273
+ const reduced = withoutRemovedMetadata(document, apply(document, structuredClone(command)));
1098
1274
  // A clip owns the composition it shows: what the command stopped drawing goes.
1099
1275
  const undrawn = withoutUndrawn(document.project, reduced.project);
1100
1276
  // Canonicalize what the command brought in.
1101
- const next = withInstanceIds(canonicalDocument(withoutGraphs(undrawn.removed.size
1277
+ // Frozen before validation, so validation caches its walk of new parts for later commands.
1278
+ const next = freeze(withInstanceIds(canonicalDocument(withoutGraphs(undrawn.removed.size
1102
1279
  ? { ...reduced, project: undrawn.project }
1103
- : reduced, undrawn.removed)));
1280
+ : reduced, undrawn.removed))));
1104
1281
  if (gesture) {
1105
1282
  validateDocumentShape(next);
1106
1283
  assertProjection(next);
@@ -1111,11 +1288,6 @@ export function executeCommand(document, command, { gesture = false } = {}) {
1111
1288
  });
1112
1289
  }
1113
1290
  catch (cause) {
1114
- return {
1115
- ok: false,
1116
- error: cause instanceof EditorError
1117
- ? cause
1118
- : new EditorError("invalid_command", String(cause), "dispatch", undefined, true, { cause }),
1119
- };
1291
+ return { ok: false, error: asEditorError(cause) };
1120
1292
  }
1121
1293
  }
@@ -64,6 +64,33 @@ export declare function ownComposition<P extends Project>(project: P, clip: Clip
64
64
  readonly clip: ClipOf<P>;
65
65
  readonly copies: ReadonlyMap<string, string>;
66
66
  };
67
+ /** What draws composition `id` directly: clips that show it, sources, and group nodes. */
68
+ export interface CompositionUsers {
69
+ /** Ids of clips that show it. */
70
+ readonly clips: readonly string[];
71
+ /** Ids of composition sources (Library items) that show it. */
72
+ readonly sources: readonly string[];
73
+ /** Group nodes that draw it, by composition and node id. */
74
+ readonly groups: readonly {
75
+ readonly composition: string;
76
+ readonly node: string;
77
+ }[];
78
+ }
79
+ /**
80
+ * What draws composition `id` directly. Clips may share a composition (an engine edit gives every
81
+ * part of a cut clip the clip's own), and a graph command changes every clip that shows it; a view
82
+ * can use this to say so, and `clip.detachComposition` gives one clip its own copy.
83
+ */
84
+ export declare function compositionUsers(project: Project, id: string): CompositionUsers;
85
+ /**
86
+ * `project` with clip `clipId` showing its own copy of its composition tree when anything else
87
+ * draws a member of it, which is copy on write for a clip-addressed edit. Returns the copies' ids
88
+ * by their originals' (empty when the clip already owns its tree).
89
+ */
90
+ export declare function detachComposition<P extends Project>(project: P, clipId: string): {
91
+ readonly project: P;
92
+ readonly copies: ReadonlyMap<string, string>;
93
+ };
67
94
  /**
68
95
  * The compositions `copy` draws for those `original` draws, by id: the two roots and, recursively,
69
96
  * the definitions of same-id group nodes. Compositions copied for a split or paste correspond this
@@ -226,6 +226,49 @@ export function ownComposition(project, clip, compositions) {
226
226
  copies: copy.copies,
227
227
  };
228
228
  }
229
+ /**
230
+ * What draws composition `id` directly. Clips may share a composition (an engine edit gives every
231
+ * part of a cut clip the clip's own), and a graph command changes every clip that shows it; a view
232
+ * can use this to say so, and `clip.detachComposition` gives one clip its own copy.
233
+ */
234
+ export function compositionUsers(project, id) {
235
+ const clips = [];
236
+ for (const track of project.timeline.tracks)
237
+ for (const clip of track.clips ?? [])
238
+ if (clip.composition?.id === id)
239
+ clips.push(clip.id);
240
+ const sources = project.sources
241
+ .filter((source) => source.composition === id)
242
+ .map((source) => source.id);
243
+ const groups = [];
244
+ for (const composition of project.compositions ?? [])
245
+ for (const node of composition.nodes ?? [])
246
+ if (node.op.type === "group" && node.op.composition === id)
247
+ groups.push({ composition: composition.id, node: node.id });
248
+ return { clips, sources, groups };
249
+ }
250
+ /**
251
+ * `project` with clip `clipId` showing its own copy of its composition tree when anything else
252
+ * draws a member of it, which is copy on write for a clip-addressed edit. Returns the copies' ids
253
+ * by their originals' (empty when the clip already owns its tree).
254
+ */
255
+ export function detachComposition(project, clipId) {
256
+ const unchanged = { project, copies: new Map() };
257
+ let clip;
258
+ for (const track of project.timeline.tracks)
259
+ clip ??= (track.clips ?? []).find((c) => c.id === clipId);
260
+ if (clip?.composition == null)
261
+ return unchanged;
262
+ // Drops this clip's own use, so `ownComposition` sees only the other users.
263
+ const without = setClipComposition(project, clipId, undefined);
264
+ const owned = ownComposition(without, clip);
265
+ if (!owned.copies.size)
266
+ return unchanged;
267
+ return {
268
+ project: setClipComposition(owned.project, clipId, owned.clip.composition ?? undefined),
269
+ copies: owned.copies,
270
+ };
271
+ }
229
272
  /**
230
273
  * The compositions `copy` draws for those `original` draws, by id: the two roots and, recursively,
231
274
  * the definitions of same-id group nodes. Compositions copied for a split or paste correspond this
@@ -0,0 +1,34 @@
1
+ import type { Animated, DataRemap, DataSpace, DataVia, Project } from "alpha2/project";
2
+ /** A value that follows a data channel at render time instead of holding its own. */
3
+ export type DataBoundValue = Extract<Animated<unknown>, {
4
+ mode: "data";
5
+ }>;
6
+ /** What {@link dataValue} binds to. */
7
+ export interface DataValueOptions {
8
+ readonly data: string;
9
+ readonly channel: string;
10
+ /** The clip or media node whose time map reads a source-anchored set; omit for the timeline. */
11
+ readonly via?: DataVia;
12
+ /** Whether a point read through `via` lands in the clip's `picture` or on the `canvas`. */
13
+ readonly space?: DataSpace;
14
+ /** `[x, y]` added to a point after the space mapping. */
15
+ readonly offset?: readonly [number, number];
16
+ /** A linear map of a scalar. */
17
+ readonly remap?: DataRemap;
18
+ }
19
+ /**
20
+ * A value bound to a data channel, for a `clip.update`, `track.update` or `graph.node.update`
21
+ * patch. Only the given options are written; validation of the command checks them against the
22
+ * set (kind, channel, `via`, `space`).
23
+ */
24
+ export declare function dataValue(options: DataValueOptions): DataBoundValue;
25
+ /** Whether `value` follows a data channel (`mode: "data"`). */
26
+ export declare function isDataBound(value: unknown): value is DataBoundValue;
27
+ /** Refuses removing data set `id` while a place of `project` reads it. */
28
+ export declare function assertDataUnread(project: Project, id: string, operation: string): void;
29
+ /** Refuses removing source `id` while a data set is anchored to it. */
30
+ export declare function assertSourceUnanchored(project: Project, id: string, operation: string): void;
31
+ /** Refuses removing the clips `removed` while a binding of a staying clip reads through one. */
32
+ export declare function assertClipsUnread(project: Project, removed: ReadonlySet<string>, operation: string): void;
33
+ /** Ids of the data sets whose object differs between `before` and `after`, or that only one has. */
34
+ export declare function changedDataSets(before: Project, after: Project): ReadonlySet<string>;
@@ -0,0 +1,69 @@
1
+ import { dataReferences, describeDataReference } from "alpha2/project";
2
+ import { EditorError } from "./document.js";
3
+ /**
4
+ * A value bound to a data channel, for a `clip.update`, `track.update` or `graph.node.update`
5
+ * patch. Only the given options are written; validation of the command checks them against the
6
+ * set (kind, channel, `via`, `space`).
7
+ */
8
+ export function dataValue(options) {
9
+ return {
10
+ mode: "data",
11
+ data: options.data,
12
+ channel: options.channel,
13
+ ...(options.via === undefined ? {} : { via: options.via }),
14
+ ...(options.space === undefined ? {} : { space: options.space }),
15
+ ...(options.offset === undefined ? {} : { offset: options.offset }),
16
+ ...(options.remap === undefined ? {} : { remap: options.remap }),
17
+ };
18
+ }
19
+ /** Whether `value` follows a data channel (`mode: "data"`). */
20
+ export function isDataBound(value) {
21
+ return (typeof value === "object" &&
22
+ value !== null &&
23
+ value.mode === "data");
24
+ }
25
+ function listed(references) {
26
+ return references.map(describeDataReference).join(", ");
27
+ }
28
+ /** Refuses removing data set `id` while a place of `project` reads it. */
29
+ export function assertDataUnread(project, id, operation) {
30
+ const references = dataReferences(project).filter((r) => r.data === id);
31
+ if (references.length)
32
+ throw new EditorError("data_referenced", `Data set ${id} is read by ${listed(references)}`, operation, id, true, { details: { references } });
33
+ }
34
+ /** Refuses removing source `id` while a data set is anchored to it. */
35
+ export function assertSourceUnanchored(project, id, operation) {
36
+ const dataSets = (project.data ?? [])
37
+ .filter((set) => set.anchor.type === "source" && set.anchor.source_id === id)
38
+ .map((set) => set.id);
39
+ if (dataSets.length)
40
+ throw new EditorError("data_referenced", `Data sets ${dataSets.join(", ")} are anchored to source ${id}`, operation, id, true, { details: { dataSets } });
41
+ }
42
+ /** Refuses removing the clips `removed` while a binding of a staying clip reads through one. */
43
+ export function assertClipsUnread(project, removed, operation) {
44
+ if (!removed.size || !project.data?.length)
45
+ return;
46
+ const references = dataReferences(project).filter((r) => r.via !== undefined &&
47
+ "clip" in r.via &&
48
+ removed.has(r.via.clip) &&
49
+ !(r.owner.kind === "clip" && removed.has(r.owner.clip)));
50
+ if (references.length) {
51
+ const via = references[0].via;
52
+ throw new EditorError("data_referenced", `Clip ${via.clip} is read through by ${listed(references)}`, operation, via.clip, true, { details: { references } });
53
+ }
54
+ }
55
+ /** Ids of the data sets whose object differs between `before` and `after`, or that only one has. */
56
+ export function changedDataSets(before, after) {
57
+ const changed = new Set();
58
+ if (before.data === after.data)
59
+ return changed;
60
+ const was = new Map((before.data ?? []).map((set) => [set.id, set]));
61
+ const is = new Map((after.data ?? []).map((set) => [set.id, set]));
62
+ for (const [id, set] of was)
63
+ if (is.get(id) !== set)
64
+ changed.add(id);
65
+ for (const id of is.keys())
66
+ if (!was.has(id))
67
+ changed.add(id);
68
+ return changed;
69
+ }