Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor aspect ratio handling in layout and resizing logic

konstantin-paulus5bd5076cf032
diff --git a/apps/web/src/components/sidebar-right/inspector/layout.tsx b/apps/web/src/components/sidebar-right/inspector/layout.tsx
index cfb4c6fd..935597cf 100644
--- a/apps/web/src/components/sidebar-right/inspector/layout.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/layout.tsx
@@ -71,22 +71,27 @@ export function LayoutPanel(props: LayoutPanelProps) {
return currentWidth > currentHeight ? "horizontal" : "vertical";
});
- /** Pins the lock to `width`×`height`, the ratio later edits keep. */
- const lockAspectRatio = (width: number, height: number) => {
- if (width <= 0 || height <= 0) return;
- entity().add(KeepAspectRatio);
- entity().set(KeepAspectRatio, { width, height });
+ /**
+ * The ratio the lock keeps: the pinned authored box, or — when the pin is
+ * empty because neither bound is authored — the box as currently shown.
+ */
+ const lockedRatio = () => {
+ const aspect = entity().get(KeepAspectRatio);
+ if (!aspect) return undefined;
+ if (aspect.width > 0 && aspect.height > 0) return aspect.width / aspect.height;
+ return width() > 0 && height() > 0 ? width() / height() : undefined;
};
const resize = (params: { width?: number; height?: number }) => {
let { width, height } = params;
- const aspect = entity().get(KeepAspectRatio);
- if (aspect && aspect.width > 0 && aspect.height > 0) {
- const ratio = aspect.width / aspect.height;
- if (width !== undefined) {
+ // One bound given, the lock drives the other; both given is a size
+ // chosen outright (a preset, an orientation swap) the lock follows.
+ const ratio = lockedRatio();
+ if (ratio !== undefined) {
+ if (width !== undefined && height === undefined) {
height = Math.round(width / ratio);
- } else if (height !== undefined) {
+ } else if (height !== undefined && width === undefined) {
width = Math.round(height * ratio);
}
}
@@ -112,13 +117,7 @@ export function LayoutPanel(props: LayoutPanelProps) {
};
const toggleAspectRatio = () => {
- if (keepAspectRatio()) {
- entity().remove(KeepAspectRatio);
- return;
- }
-
- // Lock: snapshot current absolute dimensions
- lockAspectRatio(width(), height());
+ editor.editProperty(entity(), "keepAspectRatio", !keepAspectRatio());
};
const aspectIcon = () => {
@@ -145,11 +144,12 @@ export function LayoutPanel(props: LayoutPanelProps) {
return "Square";
};
- /** A size chosen outright (orientation swap, preset): the lock follows it rather than fighting it. */
+ /**
+ * A size chosen outright (orientation swap, preset): the lock follows it
+ * rather than fighting it — both bounds are written, and the reconciler
+ * re-pins the lock to the authored box on each.
+ */
const setSize = (width: number, height: number) => {
- if (keepAspectRatio()) {
- lockAspectRatio(width, height);
- }
resize({ width, height });
};
diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.ts
index e275667f..9cff2dfd 100644
--- a/packages/jsx/src/types.ts
+++ b/packages/jsx/src/types.ts
@@ -211,6 +211,13 @@ type SizeProps = {
/** Box size, px. Defaults to the parent's size. */
width?: number;
height?: number;
+ /**
+ * Locks the box to its authored proportions: a resize of one bound drives
+ * the other, so the editor's handles and layout rows keep the ratio
+ * `width`:`height` has (or, with neither authored, the ratio the box
+ * currently has — a media element locked at its natural size).
+ */
+ keepAspectRatio?: boolean;
};
type TransformProps = PositionProps & OffsetProps & SizeProps & {
@@ -445,7 +452,7 @@ export type StageProps = {
* `camera` does: the source is the document, so a scene dragged or clicked on
* the canvas has nowhere else to be written back to.
*/
-export type SceneProps = IdentityProps & PositionProps & Required<SizeProps> & FillProps & {
+export type SceneProps = IdentityProps & PositionProps & Required<Pick<SizeProps, "width" | "height">> & Pick<SizeProps, "keepAspectRatio"> & FillProps & {
/**
* Whether this element is the one the playhead, timeline, and capture
* operate on. Editor state carried by the source like `selected`, with two
diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.ts
index 0100b760..bd84d842 100644
--- a/packages/reconciler/src/document.ts
+++ b/packages/reconciler/src/document.ts
@@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-import { Active, AdjustmentLayer, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, bindAsset, BlendMode, BlendModeType, Blur, Caption, CaptionAlign, CaptionType, Chars, ClipHeight, ClipsContent, Computed, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, Expanded, FontStyle, FramePromises, FrameRate, Generating, GenerationRequest, getActiveEntity, Loop, LoadRequest, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsMask, isText, ItemIndex, Keyframe, KeyframeTrack, MixedCornerRadius, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, PendingSync, Playback, PlaybackRate, Position, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceError, SourceFrameRate, SourceModifiers, hasModifier, setCameraMatrix, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SyncRequest, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, TranscriptionRequest, Transition, TransitionType, Trim, UniformScale, Volume, Workarea } from '@diffusionstudio/runtime';
+import { Active, AdjustmentLayer, Animation, AnimationPhase, AnimationType, appendChild, AssetId, Audio, Background, bindAsset, BlendMode, BlendModeType, Blur, Caption, CaptionAlign, CaptionType, Chars, ClipHeight, ClipsContent, Computed, CornerRadius, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, Expanded, FontStyle, FramePromises, FrameRate, Generating, GenerationRequest, getActiveEntity, Loop, LoadRequest, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsMask, isText, ItemIndex, KeepAspectRatio, Keyframe, KeyframeTrack, MixedCornerRadius, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, PendingSync, Playback, PlaybackRate, Position, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceError, SourceFrameRate, SourceModifiers, hasModifier, setCameraMatrix, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SyncRequest, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, TranscriptionRequest, Transition, TransitionType, Trim, UniformScale, Volume, Workarea } from '@diffusionstudio/runtime';
import { LOOP_ATTR, parseTime, SOURCE_ATTR } from '@diffusionstudio/jsx';
import { createSignal } from 'solid-js';
import { SVGElements } from 'solid-js/web';
@@ -890,6 +890,21 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
}
return;
}
+ case 'keepAspectRatio': {
+ const { entity, props } = node;
+ if (props.keepAspectRatio !== true) {
+ entity.remove(KeepAspectRatio);
+ return;
+ }
+
+ const size = entity.get(Size);
+ entity.add(KeepAspectRatio);
+ entity.set(KeepAspectRatio, {
+ width: toNumber(props.width) ?? size?.width ?? 0,
+ height: toNumber(props.height) ?? size?.height ?? 0,
+ });
+ return;
+ }
case 'hidden': {
if (value === true && entity !== this.stage.entity) {
entity.add(Hidden);
diff --git a/packages/runtime/src/actions/resize.ts b/packages/runtime/src/actions/resize.ts
index a78e1972..037b5317 100644
--- a/packages/runtime/src/actions/resize.ts
+++ b/packages/runtime/src/actions/resize.ts
@@ -17,6 +17,23 @@ import type { Entity, World } from 'koota';
type ResizeParams = { width?: number; height?: number };
+/**
+ * The ratio a locked entity's resize keeps: the pinned dimensions, or — when
+ * the pin is empty because neither bound was authored (see the reconciler's
+ * `syncAspectLock`) — the ratio the box currently has. Undefined without a
+ * lock, or before the box has dimensions to keep.
+ */
+function lockedRatio(entity: Entity): number | undefined {
+ const aspect = entity.get(KeepAspectRatio);
+ if (!aspect) return undefined;
+ if (aspect.width > 0 && aspect.height > 0) return aspect.width / aspect.height;
+
+ const computed = entity.get(Computed);
+ return computed && computed.width > 0 && computed.height > 0
+ ? computed.width / computed.height
+ : undefined;
+}
+
/**
* Resize an entity. Enforces aspect ratio, writes the final Size, propagates
* Computed size down the subtree and reapplies sibling constraints.
@@ -40,10 +57,8 @@ export function resizeEntity(world: World, entity: Entity, params: ResizeParams)
let { width, height } = params;
// Enforce aspect ratio
- const aspect = entity.get(KeepAspectRatio);
- if (aspect && aspect.width > 0 && aspect.height > 0) {
- const ratio = aspect.width / aspect.height;
-
+ const ratio = lockedRatio(entity);
+ if (ratio !== undefined) {
if (width !== undefined && height === undefined) {
height = Math.round(width / ratio);
} else if (height !== undefined && width === undefined) {
@@ -198,12 +213,8 @@ function resolveConstraintOffsetsAgainst(world: World, entity: Entity, dims: Ent
// When the child's aspect ratio is locked, drive the other dimension from
// whichever axis resized so the proportion is preserved. Width wins when
// both axes resize, mirroring resizeEntity's precedence.
- const aspect = child.get(KeepAspectRatio);
- if (
- aspect && aspect.width > 0 && aspect.height > 0 &&
- (newChildW !== undefined || newChildH !== undefined)
- ) {
- const ratio = aspect.width / aspect.height;
+ const ratio = lockedRatio(child);
+ if (ratio !== undefined && (newChildW !== undefined || newChildH !== undefined)) {
if (newChildW !== undefined) {
newChildH = Math.round(newChildW / ratio);
} else if (newChildH !== undefined) {
diff --git a/reference/jsx/elements.md b/reference/jsx/elements.md
index 9f2b38de..66309a4d 100644
--- a/reference/jsx/elements.md
+++ b/reference/jsx/elements.md
@@ -87,6 +87,7 @@ Every node accepts:
| `x`, `y` | `number` | `0` | Position relative to the parent, px. |
| `offsetX`, `offsetY` | `number` | `0` | Render-time translation on top of `x`/`y`, px; moves the drawn content without changing the layout box (the channel the slide animations drive). Subpixel values are kept. |
| `width`, `height` | `number` | per element | Box size, px — see the table above. |
+| `keepAspectRatio` | `boolean` | absent | Locks the box to its authored proportions: resizing one bound (an editor handle, a layout row) drives the other so the ratio `width`:`height` has is kept — or, with neither authored, the ratio the box currently has. |
| `rotation` | `number` | `0` | Rotation in degrees. |
| `scale` | `number` | `1` | Uniform scale about the box origin. Overrides `scaleX`/`scaleY` while set. |
| `scaleX`, `scaleY` | `number` | `1` | Per-axis scale. |
diff --git a/reference/jsx/scene.md b/reference/jsx/scene.md
index cbf5bd51..abd9a2f1 100644
--- a/reference/jsx/scene.md
+++ b/reference/jsx/scene.md
@@ -13,6 +13,7 @@ A scene is the **clipped, playable frame** a composition is made in, and the onl
| Prop | Type | Default | Meaning |
| ---- | ---- | ------- | ------- |
| `width`, `height` | `number` | **required** | Composition size in pixels — the frame that is rendered and exported. Required by the type; a scene that somehow reaches the runtime without them is 1920×1080. |
+| `keepAspectRatio` | `boolean` | absent | Locks the frame to its authored proportions: resizing one bound in the editor drives the other. |
| `x`, `y` | `number` | `0` | Where the frame sits on the infinite canvas. Scenes without one all sit at the origin. |
| `fill` | `string` | none | Background fill, any CSS color; alpha is ignored. A scene without one is transparent, and exports with alpha. |
| `name` | `string` | none | Human-readable node name; what labels the scene in the editor. Recommended. |