Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor Alignment component and integrate world context

konstantin-paulus838517c1918e
diff --git a/apps/web/src/components/sidebar-right/inspector/alignment.tsx b/apps/web/src/components/sidebar-right/inspector/alignment.tsx
index 26b5fc02..b8eb443a 100644
--- a/apps/web/src/components/sidebar-right/inspector/alignment.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/alignment.tsx
@@ -5,14 +5,10 @@
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { For } from "solid-js";
+import { useWorld } from "@diffusionstudio/koota-solid";
import { Icon } from "@/components/ui/icon";
-import { useEngine } from "@/context/engine";
-import { isScene, setComponent } from "@/components/engine";
-import { getParentEntity } from "@/components/engine/api";
-import { invert2D, transformPoint } from "@/components/engine/math/aabb";
-import { Or, query } from "bitecs";
-
+import { alignSelection, distributeSelection } from "@/engine/align";
const ALIGNMENT_ACTIONS = [
/** Horizontal alignment */
@@ -63,203 +59,22 @@ const ALIGNMENT_ACTIONS = [
export type AlignmentAction = (typeof ALIGNMENT_ACTIONS)[number]["id"];
-type Axis = "x" | "y";
-
-type SelectionMask = {
- minX: number;
- minY: number;
- maxX: number;
- maxY: number;
- width: number;
- height: number;
- centerX: number;
- centerY: number;
-};
-
+/** The align/distribute toolbar shown for a multi-selection; the moves are `x`/`y` edits (see `engine/align.ts`). */
export function Alignment() {
- const { world } = useEngine();
- const c = world.components;
-
- /**
- * Return selected entities that live directly inside a scene, plus top-level
- * entities (scenes themselves) which are parented to nothing / the root.
- */
- const getSelectedEids = () =>
- [...query(world, [c.Selected, Or(c.Geometry, c.Group)])].filter(
- (eid) => {
- const parentEid = getParentEntity(world, eid);
- return parentEid === null || isScene(world, parentEid);
- }
- );
-
- const getSelectionMask = (): SelectionMask | null => {
- const eids = getSelectedEids();
- if (eids.length === 0) return null;
-
- const minX = Math.min(...eids.map((eid) => c.WorldBounds.minX[eid]));
- const minY = Math.min(...eids.map((eid) => c.WorldBounds.minY[eid]));
- const maxX = Math.max(...eids.map((eid) => c.WorldBounds.maxX[eid]));
- const maxY = Math.max(...eids.map((eid) => c.WorldBounds.maxY[eid]));
-
- return {
- minX,
- minY,
- maxX,
- maxY,
- width: maxX - minX,
- height: maxY - minY,
- centerX: (minX + maxX) / 2,
- centerY: (minY + maxY) / 2,
- };
- };
-
- /** Convert a world-space delta into the parent's local space for the given entity. */
- const worldDeltaToParentLocal = (eid: number, dx: number, dy: number) => {
- const parentEid = getParentEntity(world, eid);
-
- const parentMat =
- parentEid !== null
- ? {
- a: c.WorldTransform.a[parentEid],
- b: c.WorldTransform.b[parentEid],
- c: c.WorldTransform.c[parentEid],
- d: c.WorldTransform.d[parentEid],
- e: c.WorldTransform.e[parentEid],
- f: c.WorldTransform.f[parentEid],
- }
- : {
- a: world.camera.a * world.resolution,
- b: world.camera.b * world.resolution,
- c: world.camera.c * world.resolution,
- d: world.camera.d * world.resolution,
- e: world.camera.e * world.resolution,
- f: world.camera.f * world.resolution,
- };
-
- const inv = invert2D(parentMat);
- const localOrigin = transformPoint(inv, 0, 0);
- const localDelta = transformPoint(inv, dx, dy);
-
- return {
- x: localDelta.x - localOrigin.x,
- y: localDelta.y - localOrigin.y,
- };
- };
-
- const moveNodeByWorldDelta = (eid: number, dx: number, dy: number) => {
- if (dx === 0 && dy === 0) return;
-
- const localDelta = worldDeltaToParentLocal(eid, dx, dy);
- if (!localDelta) return;
-
- setComponent(world, eid, c.Position, {
- x: c.Position.x[eid] + localDelta.x,
- y: c.Position.y[eid] + localDelta.y,
- });
- };
-
- /**
- * Align every selected item relative to the selection's bounding box.
- * A single selected item is a no-op (the selection bounds equal the item).
- */
- const alignSelection = (action: AlignmentAction) => {
- const eids = getSelectedEids();
- if (eids.length < 2) return;
-
- const mask = getSelectionMask();
- if (!mask) return;
-
- world.history.transaction("Align selection", () => {
- for (const eid of eids) {
- const boundsWidth = c.WorldBounds.maxX[eid] - c.WorldBounds.minX[eid];
- const boundsHeight = c.WorldBounds.maxY[eid] - c.WorldBounds.minY[eid];
-
- let targetMinX = c.WorldBounds.minX[eid];
- let targetMinY = c.WorldBounds.minY[eid];
-
- if (action === "align-left") {
- targetMinX = mask.minX;
- }
- if (action === "align-center-horizontal") {
- targetMinX = mask.centerX - boundsWidth / 2;
- }
- if (action === "align-right") {
- targetMinX = mask.maxX - boundsWidth;
- }
- if (action === "align-top") {
- targetMinY = mask.minY;
- }
- if (action === "align-center-vertical") {
- targetMinY = mask.centerY - boundsHeight / 2;
- }
- if (action === "align-bottom") {
- targetMinY = mask.maxY - boundsHeight;
- }
-
- moveNodeByWorldDelta(eid, targetMinX - c.WorldBounds.minX[eid], targetMinY - c.WorldBounds.minY[eid]);
- }
- });
- };
-
- const distributeSelection = (axis: Axis) => {
- const eids = getSelectedEids();
- if (eids.length < 3) return;
-
- const mask = getSelectionMask();
- if (!mask) return;
-
- const isHorizontal = axis === "x";
- const sorted = [...eids].sort((a, b) =>
- isHorizontal
- ? c.WorldBounds.minX[a] - c.WorldBounds.minX[b]
- : c.WorldBounds.minY[a] - c.WorldBounds.minY[b]
- );
-
- const totalSize = sorted.reduce(
- (sum, eid) =>
- sum +
- (isHorizontal
- ? c.WorldBounds.maxX[eid] - c.WorldBounds.minX[eid]
- : c.WorldBounds.maxY[eid] - c.WorldBounds.minY[eid]),
- 0
- );
- const maskSize = isHorizontal ? mask.width : mask.height;
- const gap = (maskSize - totalSize) / (sorted.length - 1);
-
- let cursor = isHorizontal ? mask.minX : mask.minY;
-
- world.history.transaction("Distribute entities", () => {
- for (const eid of sorted) {
- const currentMin = isHorizontal ? c.WorldBounds.minX[eid] : c.WorldBounds.minY[eid];
- const size = isHorizontal
- ? c.WorldBounds.maxX[eid] - c.WorldBounds.minX[eid]
- : c.WorldBounds.maxY[eid] - c.WorldBounds.minY[eid];
- const delta = cursor - currentMin;
-
- if (isHorizontal) {
- moveNodeByWorldDelta(eid, delta, 0);
- } else {
- moveNodeByWorldDelta(eid, 0, delta);
- }
-
- cursor += size + gap;
- }
- }
- );
- };
+ const world = useWorld();
const handleAction = (action: AlignmentAction) => {
if (action === "distribute-horizontal") {
- distributeSelection("x");
+ distributeSelection(world, "x");
return;
}
if (action === "distribute-vertical") {
- distributeSelection("y");
+ distributeSelection(world, "y");
return;
}
- alignSelection(action);
+ alignSelection(world, action);
};
return (
diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
index db740345..48f40cfe 100644
--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
@@ -24,7 +24,7 @@ import { SceneTemplatePanel } from "./scene-template";
import { AssetInfoPanel } from "./asset-info";
import { TimeSettings } from "./time";
import { AppearanceSettings } from "./appearance";
-// import { Alignment } from "./alignment";
+import { Alignment } from "./alignment";
// import { ExportPanel } from "./export";
// import { TransformSettings } from "./transform";
// import { LayoutPanel } from "./layout";
@@ -113,9 +113,9 @@ export function Inspector() {
<SceneTemplatePanel />
</Show>
- {/* <Show when={nodes().length > 1}>
+ <Show when={nodes().length > 1}>
<Alignment />
- </Show> */}
+ </Show>
{/* <Show when={includesTarget("scene") && !isNested()}>
<ExportPanel selection={nodes()} />
diff --git a/apps/web/src/engine/align.ts b/apps/web/src/engine/align.ts
new file mode 100644
index 00000000..b112f565
--- /dev/null
+++ b/apps/web/src/engine/align.ts
@@ -0,0 +1,161 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Align and distribute the selection: the nodes are moved in device space
+ * against the upright box of them all (`WorldBounds`, which the transform
+ * system writes), and each move becomes the `x`/`y` a drag would write, in
+ * the node's own parent's space. Only nodes directly inside a scene (or
+ * top-level ones) take part, as before: a nested node aligns to siblings in
+ * its group, which has no box of its own to align against here.
+ */
+
+import {
+ Geometry,
+ Group,
+ Position,
+ Selected,
+ WorldBounds,
+ entityWorldMat,
+ getParentEntity,
+ getParentNode,
+ invert2D,
+ isScene,
+ store,
+ transformPoint,
+} from "@diffusionstudio/runtime";
+import { Or } from "koota";
+import { getDocumentEditor } from "./editor";
+import { syncKeyframe } from "./keyframes";
+
+import type { Entity, World } from "koota";
+
+export type AlignAction =
+ | "align-left"
+ | "align-center-horizontal"
+ | "align-right"
+ | "align-top"
+ | "align-center-vertical"
+ | "align-bottom";
+
+export type Axis = "x" | "y";
+
+type Box = { minX: number; minY: number; maxX: number; maxY: number };
+
+/** The selected nodes alignment moves: top-level ones and direct children of scenes. */
+export function getAlignableSelection(world: World): Entity[] {
+ return [...world.query(Selected, Or(Geometry, Group))].filter((entity) => {
+ const parent = getParentNode(entity);
+ return parent === null || isScene(parent);
+ });
+}
+
+function boundsOf(world: World, entity: Entity): Box {
+ const bounds = store(world, WorldBounds);
+ const eid = entity.id();
+ return {
+ minX: bounds.minX[eid] ?? 0,
+ minY: bounds.minY[eid] ?? 0,
+ maxX: bounds.maxX[eid] ?? 0,
+ maxY: bounds.maxY[eid] ?? 0,
+ };
+}
+
+function union(boxes: Box[]): Box {
+ return {
+ minX: Math.min(...boxes.map((box) => box.minX)),
+ minY: Math.min(...boxes.map((box) => box.minY)),
+ maxX: Math.max(...boxes.map((box) => box.maxX)),
+ maxY: Math.max(...boxes.map((box) => box.maxY)),
+ };
+}
+
+/**
+ * Moves `entity` by a device-space delta: the delta in its parent's space
+ * (the stage's is the view) added to its `x`/`y`, rounded like a drag's, and
+ * kept in step with any position track.
+ */
+function moveByWorldDelta(world: World, entity: Entity, dx: number, dy: number): void {
+ if (dx === 0 && dy === 0) return;
+ const position = entity.get(Position);
+ if (!position) return;
+
+ const inverse = invert2D(entityWorldMat(world, getParentEntity(entity)));
+ const origin = transformPoint(inverse, 0, 0);
+ const delta = transformPoint(inverse, dx, dy);
+ const editor = getDocumentEditor(world);
+
+ if (dx !== 0) {
+ const x = Math.round(position.x + delta.x - origin.x);
+ editor.editProperty(entity, "x", x);
+ syncKeyframe(world, editor, entity, "x", x);
+ }
+ if (dy !== 0) {
+ const y = Math.round(position.y + delta.y - origin.y);
+ editor.editProperty(entity, "y", y);
+ syncKeyframe(world, editor, entity, "y", y);
+ }
+}
+
+/**
+ * Aligns every selected node to the edge or center of the selection's box.
+ * One node is a no-op: the box is the node.
+ */
+export function alignSelection(world: World, action: AlignAction): void {
+ const entities = getAlignableSelection(world);
+ if (entities.length < 2) return;
+
+ const boxes = entities.map((entity) => boundsOf(world, entity));
+ const mask = union(boxes);
+ const centerX = (mask.minX + mask.maxX) / 2;
+ const centerY = (mask.minY + mask.maxY) / 2;
+
+ entities.forEach((entity, index) => {
+ const box = boxes[index]!;
+ const width = box.maxX - box.minX;
+ const height = box.maxY - box.minY;
+
+ let targetMinX = box.minX;
+ let targetMinY = box.minY;
+
+ switch (action) {
+ case "align-left": targetMinX = mask.minX; break;
+ case "align-center-horizontal": targetMinX = centerX - width / 2; break;
+ case "align-right": targetMinX = mask.maxX - width; break;
+ case "align-top": targetMinY = mask.minY; break;
+ case "align-center-vertical": targetMinY = centerY - height / 2; break;
+ case "align-bottom": targetMinY = mask.maxY - height; break;
+ }
+
+ moveByWorldDelta(world, entity, targetMinX - box.minX, targetMinY - box.minY);
+ });
+}
+
+/**
+ * Spaces the selected nodes evenly along `axis` between the two outermost,
+ * in their current order. Needs three: two have nothing between them.
+ */
+export function distributeSelection(world: World, axis: Axis): void {
+ const entities = getAlignableSelection(world);
+ if (entities.length < 3) return;
+
+ const horizontal = axis === "x";
+ const min = (box: Box) => (horizontal ? box.minX : box.minY);
+ const size = (box: Box) => (horizontal ? box.maxX - box.minX : box.maxY - box.minY);
+
+ const sorted = entities
+ .map((entity) => ({ entity, box: boundsOf(world, entity) }))
+ .sort((a, b) => min(a.box) - min(b.box));
+ const mask = union(sorted.map((item) => item.box));
+
+ const total = sorted.reduce((sum, item) => sum + size(item.box), 0);
+ const gap = (size(mask) - total) / (sorted.length - 1);
+
+ let cursor = min(mask);
+ for (const { entity, box } of sorted) {
+ const delta = cursor - min(box);
+ moveByWorldDelta(world, entity, horizontal ? delta : 0, horizontal ? 0 : delta);
+ cursor += size(box) + gap;
+ }
+}
diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.ts
index d38587d0..53656795 100644
--- a/apps/web/src/engine/index.ts
+++ b/apps/web/src/engine/index.ts
@@ -14,3 +14,4 @@ export * from './hud';
export * from './library';
export * from './asset-actions';
export * from './keyframes';
+export * from './align';