Skip to content

🎥 Make videos programmatically with React

Cache effect preparation and skip static frame subscriptions

JonnyBurger4ae6b0363050
diff --git a/packages/core/src/effects/use-memoized-effects.ts b/packages/core/src/effects/use-memoized-effects.ts
index b4a8077776..bca93b56ca 100644
--- a/packages/core/src/effects/use-memoized-effects.ts
+++ b/packages/core/src/effects/use-memoized-effects.ts
@@ -1,10 +1,11 @@
-import React, {useContext, useLayoutEffect, useRef} from 'react';
+import React, {useContext, useLayoutEffect, useMemo, useRef} from 'react';
import {evaluateSourcePropStatuses} from '../evaluate-source-expressions.js';
import {
getFrameInKeyframedStatusClock,
resolveDragOverrideValue,
} from '../get-effective-visual-mode-value.js';
import {interpolateKeyframedStatus} from '../interpolate-keyframed-status.js';
+import {areRegistryEntriesEqual} from '../registry-store.js';
import {createRuntimeValueStore} from '../runtime-value-store.js';
import type {RuntimeValueStore} from '../runtime-value-store.js';
import {SequenceActivityDormantContext} from '../sequence-activity-context.js';
@@ -19,7 +20,7 @@ import {
VisualModePropStatusesContext,
type SequencePropsSubscriptionKey,
} from '../SequenceManager.js';
-import {useCurrentFrame} from '../use-current-frame.js';
+import {useCurrentFrameWithOptionalSubscription} from '../use-current-frame.js';
import {
type CanUpdateSequencePropStatus,
type DragOverrideValue,
@@ -35,6 +36,25 @@ import type {
const emptyDragOverrides: Record<string, DragOverrideValue> = {};
const useCacheCommitEffect = React.useInsertionEffect ?? useLayoutEffect;
+const areEffectParamsEqual = (previous: unknown, next: unknown): boolean => {
+ if (Object.is(previous, next)) {
+ return true;
+ }
+
+ if (
+ previous === null ||
+ next === null ||
+ typeof previous !== 'object' ||
+ typeof next !== 'object' ||
+ Object.getPrototypeOf(previous) !== Object.prototype ||
+ Object.getPrototypeOf(next) !== Object.prototype
+ ) {
+ return false;
+ }
+
+ return areRegistryEntriesEqual(previous, next);
+};
+
const mergeOverrides = ({
descriptor,
propStatusOverrides,
@@ -126,14 +146,12 @@ export const useMemoizedEffectDefinitions = (
readonly controllers: ReturnType<typeof createRuntimeValueStore>[];
} | null>(null);
- const definitions = effects.map((descriptor) => descriptor.definition);
-
const previous = previousRef.current;
const isSame =
previous !== null &&
- previous.definitions.length === definitions.length &&
+ previous.definitions.length === effects.length &&
previous.definitions.every(
- (definition, i) => definition === definitions[i],
+ (definition, i) => definition === effects[i].definition,
);
const controllers = isSame
? previous.controllers
@@ -142,9 +160,12 @@ export const useMemoizedEffectDefinitions = (
);
const stableDefinitions = isSame
? previous.definitions
- : Object.assign(definitions, {
- runtimeValues: controllers.map((controller) => controller.store),
- });
+ : Object.assign(
+ effects.map((descriptor) => descriptor.definition),
+ {
+ runtimeValues: controllers.map((controller) => controller.store),
+ },
+ );
useCacheCommitEffect(() => {
// Insertion effects also run for hidden Activity commits. Store listeners
@@ -154,6 +175,17 @@ export const useMemoizedEffectDefinitions = (
return;
}
+ if (
+ controllers.every((controller, index) =>
+ areEffectParamsEqual(
+ controller.store.getSnapshot(),
+ effects[index]?.params,
+ ),
+ )
+ ) {
+ return;
+ }
+
let cancelled = false;
queueMicrotask(() => {
if (cancelled) {
@@ -163,29 +195,10 @@ export const useMemoizedEffectDefinitions = (
controllers.forEach((controller, index) => {
const snapshot = effects[index]?.params as Record<string, unknown>;
const currentSnapshot = controller.store.getSnapshot();
- if (Object.is(snapshot, currentSnapshot)) {
- return;
- }
-
// Equivalent inline params should not notify inspector subscribers on
// every dormant render. Preserve changes to keys and leaf references.
- if (
- snapshot !== null &&
- currentSnapshot !== null &&
- typeof snapshot === 'object' &&
- typeof currentSnapshot === 'object'
- ) {
- const keys = Object.keys(snapshot);
- if (
- keys.length === Object.keys(currentSnapshot).length &&
- keys.every(
- (key) =>
- Object.prototype.hasOwnProperty.call(currentSnapshot, key) &&
- Object.is(snapshot[key], currentSnapshot[key]),
- )
- ) {
- return;
- }
+ if (areEffectParamsEqual(snapshot, currentSnapshot)) {
+ return;
}
controller.setSnapshot(snapshot);
@@ -201,7 +214,11 @@ export const useMemoizedEffectDefinitions = (
// array, so frame-dependent parameters don't re-register the Sequence.
stableDefinitions.forEach((_definition, index) => {
const snapshot = effects[index]?.params as Record<string, unknown>;
- controllers[index].setSnapshot(snapshot);
+ if (
+ !areEffectParamsEqual(controllers[index].store.getSnapshot(), snapshot)
+ ) {
+ controllers[index].setSnapshot(snapshot);
+ }
});
}, [controllers, effects, stableDefinitions]);
@@ -273,6 +290,16 @@ export const getPropStatusesCtx = (
export type GetPropStatusesType = typeof getPropStatusesCtx;
+type PreparedEffect = {
+ readonly definition: EffectDefinition<unknown>;
+ readonly sourceKey: string;
+ readonly params: unknown;
+ readonly propStatus: Record<string, CanUpdateSequencePropStatus> | null;
+ readonly dragOverrides: Record<string, DragOverrideValue> | null;
+ readonly frame: number | null;
+ readonly value: EffectDefinitionAndStack<unknown>;
+};
+
export const useMemoizedEffects = ({
effects,
overrideId,
@@ -282,10 +309,12 @@ export const useMemoizedEffects = ({
readonly overrideId: string | null;
videoConfigValues: VideoConfigValues | null;
}): EffectDefinitionAndStack<unknown>[] => {
- const previousRef = useRef<EffectDefinitionAndStack<unknown>[] | null>(null);
+ const previousRef = useRef<{
+ readonly prepared: PreparedEffect[];
+ readonly effects: EffectDefinitionAndStack<unknown>[];
+ } | null>(null);
const {propStatuses} = useContext(VisualModePropStatusesContext);
- const frame = useCurrentFrame();
const {overrideIdToNodePathMappings} = useContext(
OverrideIdsToNodePathsGettersContext,
@@ -298,27 +327,64 @@ export const useMemoizedEffects = ({
: null;
const effectDragOverrides = useEffectDragOverridesForNodePath(nodePath);
- const resolved = effects.map((descriptor, index) => {
- if (nodePath === null) {
- return {
- descriptor,
- params: descriptor.params,
- effectKey: descriptor.effectKey,
- };
- }
+ const effectPropStatuses = useMemo(
+ () =>
+ Array.from({length: effects.length}, (_, effectIndex) => {
+ if (nodePath === null) {
+ return null;
+ }
- const effectStatus = getEffectPropStatusesCtx({
- propStatuses,
- nodePath: {...nodePath, videoConfigValues},
- effectIndex: index,
- });
- const propStatusOverrides =
- effectStatus.type === 'can-update-effect'
- ? resolvePropStatusOverrides(effectStatus.props, frame)
- : null;
+ const status = getEffectPropStatusesCtx({
+ propStatuses,
+ nodePath: {...nodePath, videoConfigValues},
+ effectIndex,
+ });
+ return status.type === 'can-update-effect' ? status.props : null;
+ }),
+ [effects.length, nodePath, propStatuses, videoConfigValues],
+ );
+ const animatedEffects = useMemo(
+ () =>
+ effectPropStatuses.map(
+ (status, index) =>
+ Object.values(status ?? {}).some(
+ (prop) => prop.status === 'keyframed',
+ ) ||
+ Object.values(effectDragOverrides[index] ?? emptyDragOverrides).some(
+ (override) => override.type === 'keyframed',
+ ),
+ ),
+ [effectDragOverrides, effectPropStatuses],
+ );
+ // Runtime animations arrive through props. Only source/drag keyframes need
+ // their own clock, and an animated effect must not invalidate static siblings.
+ const frame = useCurrentFrameWithOptionalSubscription(
+ animatedEffects.some(Boolean),
+ );
+
+ const prepared = effects.map((descriptor, index): PreparedEffect => {
+ const propStatus = effectPropStatuses[index];
const dragOverridesMap = effectDragOverrides[index] ?? emptyDragOverrides;
const dragOverrides =
Object.keys(dragOverridesMap).length === 0 ? null : dragOverridesMap;
+ const effectFrame = animatedEffects[index] ? frame : null;
+ const cached = previous?.prepared[index];
+ if (
+ cached &&
+ cached.definition === descriptor.definition &&
+ cached.sourceKey === descriptor.effectKey &&
+ areEffectParamsEqual(cached.params, descriptor.params) &&
+ cached.propStatus === propStatus &&
+ cached.dragOverrides === dragOverrides &&
+ cached.frame === effectFrame
+ ) {
+ return cached;
+ }
+
+ const propStatusOverrides = resolvePropStatusOverrides(
+ propStatus ?? undefined,
+ frame,
+ );
const {params, effectKey} = mergeOverrides({
descriptor,
@@ -327,28 +393,42 @@ export const useMemoizedEffects = ({
frame,
});
- return {descriptor, params, effectKey};
+ return {
+ definition: descriptor.definition,
+ sourceKey: descriptor.effectKey,
+ // Snapshot plain params so shallow comparisons see in-place field edits.
+ params:
+ descriptor.params !== null &&
+ typeof descriptor.params === 'object' &&
+ Object.getPrototypeOf(descriptor.params) === Object.prototype
+ ? {...descriptor.params}
+ : descriptor.params,
+ propStatus,
+ dragOverrides,
+ frame: effectFrame,
+ value:
+ cached?.value.definition === descriptor.definition &&
+ cached.value.effectKey === effectKey
+ ? cached.value
+ : {
+ definition: descriptor.definition,
+ effectKey,
+ params,
+ memoized: true,
+ },
+ };
});
const isSame =
previous !== null &&
- previous.length === resolved.length &&
- previous.every(
- (p, i) =>
- p.definition === resolved[i].descriptor.definition &&
- p.effectKey === resolved[i].effectKey,
- );
+ previous.effects.length === prepared.length &&
+ previous.effects.every((effect, i) => effect === prepared[i].value);
const next: EffectDefinitionAndStack<unknown>[] = isSame
- ? previous
- : resolved.map(({descriptor, params, effectKey}) => ({
- definition: descriptor.definition,
- effectKey,
- params,
- memoized: true,
- }));
+ ? previous.effects
+ : prepared.map((effect) => effect.value);
useCacheCommitEffect(() => {
- previousRef.current = next;
- }, [next]);
+ previousRef.current = {prepared, effects: next};
+ }, [next, prepared]);
return next;
};