The VS Code of video editing, built for agents.
TypeScript
feat: implement mask tool and replace clip path functionality with masks
konstantin-paulus075732f23741
diff --git a/apps/web/src/components/canvas/clip-path-bar.tsx b/apps/web/src/components/canvas/mask-bar.tsxsimilarity index 68%rename from apps/web/src/components/canvas/clip-path-bar.tsxrename to apps/web/src/components/canvas/mask-bar.tsxindex 6d1e1add..361b3178 100644--- a/apps/web/src/components/canvas/clip-path-bar.tsx+++ b/apps/web/src/components/canvas/mask-bar.tsx@@ -10,25 +10,24 @@ import { Separator } from "@/components/ui/separator";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useDerived } from "@/engine/hooks";import { ActionBar } from "./action-bar";-import { applyClipPaths, cancelClipPath, getClipPathPicks, getClipPathTarget } from "@/engine/clip-path";+import { applyMasks, cancelMask, getMaskPicks, getMaskTarget } from "@/engine/mask";import type { Entity } from "koota";/**- * The clip path tool's action bar, over the canvas while the tool is up: how- * many of the selected shapes would clip the target, and the way out —- * Cancel leaves the document as it was, Confirm makes them clip paths of the- * target.+ * The mask tool's action bar, over the canvas while the tool is up: how many+ * of the selected layers would mask the target, and the way out — Cancel+ * leaves the document as it was, Confirm makes them a mask of the target.*/-export function ClipPathBar() {+export function MaskBar() {const world = useWorld();- const target = useDerived(getClipPathTarget);- const picks = useDerived(() => getClipPathPicks(world), sameEntities);+ const target = useDerived(getMaskTarget);+ const picks = useDerived(() => getMaskPicks(world), sameEntities);// Nothing to aim at (the target was deleted, or undone away): the tool has no work left.createEffect(() => {- if (!target()) cancelClipPath(world);+ if (!target()) cancelMask(world);});return (@@ -37,21 +36,21 @@ export function ClipPathBar() {<ActionBar><span class="px-2 text-xs text-muted-foreground whitespace-nowrap">{picks().length === 0- ? "Pick a shape to use as the clipping source"- : `${picks().length} ${picks().length === 1 ? "shape" : "shapes"} selected`}+ ? "Pick a layer to use as the mask"+ : `${picks().length} ${picks().length === 1 ? "layer" : "layers"} selected`}</span><Separator orientation="vertical" class="min-h-5" /><Tooltip>- <TooltipTrigger as={Button} variant="ghost" class="text-muted-foreground" onClick={() => cancelClipPath(world)}>+ <TooltipTrigger as={Button} variant="ghost" class="text-muted-foreground" onClick={() => cancelMask(world)}>Cancel</TooltipTrigger><TooltipContent shortcut="Esc">Cancel</TooltipContent></Tooltip><Tooltip>- <TooltipTrigger as={Button} disabled={picks().length === 0} onClick={() => applyClipPaths(world)}>+ <TooltipTrigger as={Button} disabled={picks().length === 0} onClick={() => applyMasks(world)}>Confirm</TooltipTrigger>- <TooltipContent shortcut="⌘↵">Clip <TargetName target={node()} /></TooltipContent>+ <TooltipContent shortcut="⌘↵">Mask <TargetName target={node()} /></TooltipContent></Tooltip></ActionBar>)}diff --git a/apps/web/src/components/canvas/toolbar.tsx b/apps/web/src/components/canvas/toolbar.tsxindex 6c8af0eb..3e02a0fe 100644--- a/apps/web/src/components/canvas/toolbar.tsx+++ b/apps/web/src/components/canvas/toolbar.tsx@@ -17,11 +17,11 @@ import {import { PromptInput } from "../genai/prompt-input";import { CommandBar } from "../commands";import { ObjectMaskBar } from "./object-mask-bar";-import { ClipPathBar } from "./clip-path-bar";+import { MaskBar } from "./mask-bar";import { For, Match, Show, Switch, createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js";import { Tool, ToolType } from "@diffusionstudio/runtime";import { useWorld } from "@diffusionstudio/koota-solid";-import { cancelClipPath, cancelObjectMask, clearClipPathTarget, useTool } from "@/engine";+import { cancelMask, cancelObjectMask, clearMaskTarget, useTool } from "@/engine";import { usePromptInput } from "@/context/prompt-input";import { useCommands } from "@/context/commands";import { TOOLBAR_SLOTS, useLayout } from "@/context/layout";@@ -69,8 +69,8 @@ export function Toolbar() {});createEffect(() => {- if (selectedTool() !== ToolType.CLIP_PATH) {- clearClipPathTarget();+ if (selectedTool() !== ToolType.MASK) {+ clearMaskTarget();}});@@ -81,11 +81,11 @@ export function Toolbar() {if (!command) return;setPromptInputOpen(false);if (selectedTool() === ToolType.OBJECT_MASK) cancelObjectMask(world);- if (selectedTool() === ToolType.CLIP_PATH) cancelClipPath(world);+ if (selectedTool() === ToolType.MASK) cancelMask(world);}));createEffect(on([promptInputOpen, selectedTool], ([open, tool]) => {- if (open || tool === ToolType.OBJECT_MASK || tool === ToolType.CLIP_PATH) commands.close();+ if (open || tool === ToolType.OBJECT_MASK || tool === ToolType.MASK) commands.close();}));const handleToolChange = (tool: ToolType) => {@@ -182,8 +182,8 @@ export function Toolbar() {<Match when={selectedTool() === ToolType.OBJECT_MASK}><ObjectMaskBar /></Match>- <Match when={selectedTool() === ToolType.CLIP_PATH}>- <ClipPathBar />+ <Match when={selectedTool() === ToolType.MASK}>+ <MaskBar /></Match></Switch></Show>diff --git a/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx b/apps/web/src/components/sidebar-right/inspector/clip-paths.tsxindex 6e95771f..50de46cf 100644--- a/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx+++ b/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx@@ -2,16 +2,11 @@* 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/. */-import { For } from "solid-js";-import { Button } from "@/components/ui/button";-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { Icon } from "@/components/ui/icon";-import { ItemRow } from "@/components/ui/item-row";+import { For, Show } from "solid-js";import { PanelSection } from "@/components/ui/panel-section";-import { useTrait, useWorld } from "@diffusionstudio/koota-solid";-import { Cache, Name } from "@diffusionstudio/runtime";-import { beginClipPathFor } from "@/engine/clip-path";+import { Cache } from "@diffusionstudio/runtime";import { useDerived, useEditor } from "@/engine/hooks";+import { ContainerRow } from "./masks";import type { Entity } from "koota";@@ -23,14 +18,12 @@ type ClipPathsSettingsProps = {};/**- * The `<clipPath>`s of the selected node, one row each (several intersect).- * A clip path is the shapes under it and has no inspector of its own: a row- * selects its shapes, whose transform, time and appearance panels are then- * the ones shown. The plus picks up the clip path tool, whose bar over the- * canvas puts the shapes selected there into a new clip path of this node.+ * The `<clipPath>`s the selected node was given in its JSX, one row each.+ * Clip paths are on their way out of the UI in favour of masks: nothing here+ * adds or edits one, a row only removes it, and a node without any shows no+ * section at all.*/export function ClipPathsSettings(props: ClipPathsSettingsProps) {- const world = useWorld();const editor = useEditor();const entity = () => props.selection[0]!;@@ -38,65 +31,18 @@ export function ClipPathsSettings(props: ClipPathsSettingsProps) {const clipPaths = useDerived(() => entity().get(Cache)?.clipPaths ?? NO_CLIP_PATHS);return (- <PanelSection- title="Clip Paths"- actions={- <Tooltip>- <TooltipTrigger- as={Button}- size="icon"- variant="ghost"- class="text-muted-foreground"- onClick={() => beginClipPathFor(world, entity())}- >- <Icon name="plus-add" />- </TooltipTrigger>- <TooltipContent>Add clip path</TooltipContent>- </Tooltip>- }- >- <For each={clipPaths()}>- {(clipPath) => (- <ClipPathRow- clipPath={clipPath}- onSelect={() => editor.select(clipPath.get(Cache)?.children ?? [])}- onRemove={() => editor.remove(clipPath)}- />- )}- </For>- </PanelSection>- );-}--type ClipPathRowProps = {- clipPath: Entity;- onSelect(): void;- onRemove(): void;-};--function ClipPathRow(props: ClipPathRowProps) {- const name = useTrait(() => props.clipPath, Name);-- return (- <ItemRow- label="Clip Path"- value={name()?.value || "Clip Path"}- icon={<Icon name="mask-small" />}- class="text-foreground"- onClick={props.onSelect}- >- <Tooltip>- <TooltipTrigger- as={Button}- size="icon"- variant="ghost"- class="text-muted-foreground"- onClick={props.onRemove}- >- <Icon name="close-remove-small" />- </TooltipTrigger>- <TooltipContent>Remove clip path</TooltipContent>- </Tooltip>- </ItemRow>+ <Show when={clipPaths().length > 0}>+ <PanelSection title="Clip Path">+ <For each={clipPaths()}>+ {(clipPath) => (+ <ContainerRow+ container={clipPath}+ label="Shape"+ onRemove={() => editor.remove(clipPath)}+ />+ )}+ </For>+ </PanelSection>+ </Show>);}diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsxindex c63eb83d..e7d694c2 100644--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx@@ -39,6 +39,7 @@ import { ShadowsSettings } from "./shadows";import { EffectsSettings } from "./effects";import { AnimationsSettings } from "./animations";import { TransitionSettings } from "./transition";+import { MasksSettings } from "./masks";import { ClipPathsSettings } from "./clip-paths";import { AudioSettings } from "./audio";import { InterpolationSettings } from "./interpolation";@@ -182,6 +183,7 @@ export function Inspector() {</Show><Show when={includesTarget("shape", "text", "caption", "group")}>+ <MasksSettings selection={nodes()} /><ClipPathsSettings selection={nodes()} /></Show>diff --git a/apps/web/src/components/sidebar-right/inspector/masks.tsx b/apps/web/src/components/sidebar-right/inspector/masks.tsxnew file mode 100644index 00000000..39338f4f--- /dev/null+++ b/apps/web/src/components/sidebar-right/inspector/masks.tsx@@ -0,0 +1,110 @@+/* 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/. */++import { For } from "solid-js";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { Icon } from "@/components/ui/icon";+import { ItemRow } from "@/components/ui/item-row";+import { PanelSection } from "@/components/ui/panel-section";+import { useTrait, useWorld } from "@diffusionstudio/koota-solid";+import { Cache, Name } from "@diffusionstudio/runtime";+import { beginMaskFor } from "@/engine/mask";+import { useDerived, useEditor } from "@/engine/hooks";++import type { Entity } from "koota";++// Stable identity, so a node without masks does not resample every tick.+const NO_MASKS: Entity[] = [];++type MasksSettingsProps = {+ selection: Entity[];+};++/**+ * The `<mask>`s of the selected node, one row each (several intersect). A+ * mask is the layers under it and has no inspector of its own: a row selects+ * its layers, whose transform, time and appearance panels are then the ones+ * shown. The plus picks up the mask tool, whose bar over the canvas puts the+ * layers selected there into a new mask of this node.+ */+export function MasksSettings(props: MasksSettingsProps) {+ const world = useWorld();+ const editor = useEditor();+ const entity = () => props.selection[0]!;++ // Cache is derived state, written without change events.+ const masks = useDerived(() => entity().get(Cache)?.masks ?? NO_MASKS);++ return (+ <PanelSection+ title="Masks"+ actions={+ <Tooltip>+ <TooltipTrigger+ as={Button}+ size="icon"+ variant="ghost"+ class="text-muted-foreground"+ onClick={() => beginMaskFor(world, entity())}+ >+ <Icon name="plus-add" />+ </TooltipTrigger>+ <TooltipContent>Add mask</TooltipContent>+ </Tooltip>+ }+ >+ <For each={masks()}>+ {(mask) => (+ <ContainerRow+ container={mask}+ label="Mask"+ onSelect={() => {+ // A mask drawn from a file has no layers to select.+ const children = mask.get(Cache)?.children ?? [];+ if (children.length) editor.select(children);+ }}+ onRemove={() => editor.remove(mask)}+ />+ )}+ </For>+ </PanelSection>+ );+}++type ContainerRowProps = {+ /** The `<mask>` or `<clipPath>`. */+ container: Entity;+ label: string;+ onSelect?(): void;+ onRemove(): void;+};++/** One mask or clip path of a node: its name selects its layers (when it can), the × removes it with them. */+export function ContainerRow(props: ContainerRowProps) {+ const name = useTrait(() => props.container, Name);++ return (+ <ItemRow+ label={props.label}+ value={name()?.value || props.label}+ icon={<Icon name="mask-small" />}+ class="text-foreground"+ onClick={props.onSelect}+ >+ <Tooltip>+ <TooltipTrigger+ as={Button}+ size="icon"+ variant="ghost"+ class="text-muted-foreground"+ onClick={props.onRemove}+ >+ <Icon name="close-remove-small" />+ </TooltipTrigger>+ <TooltipContent>Remove {props.label.toLowerCase()}</TooltipContent>+ </Tooltip>+ </ItemRow>+ );+}diff --git a/apps/web/src/engine/clip-path.tsx b/apps/web/src/engine/clip-path.tsxdeleted file mode 100644index a9fdfd5b..00000000--- a/apps/web/src/engine/clip-path.tsx+++ /dev/null@@ -1,161 +0,0 @@-/* 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/. */--import { ClipPath as ClipPathElement } from '@diffusionstudio/reconciler';-import {- Computed,- Flip,- Source,- Tool,- ToolType,- decompose2D,- entityPivot,- entityOffset,- entityWorldMat,- getEntityTree,- getIntrinsicPaint,- getParentEntity,- getSelection,- invert2D,- isMaskContainer,- isShape,- multiply2D,- store,- translate2D,-} from '@diffusionstudio/runtime';-import { createSignal } from 'solid-js';--import { getDocumentEditor } from './editor';-import { editTransform } from './input/interactions';--import type { Entity, World } from 'koota';-import type { TransformWrite } from './input/interactions';--const round2 = (value: number): number => Math.round(value * 100) / 100;--// The node the tool is aimed at, reactive so the bar follows it.-const [clipPathTarget, setClipPathTarget] = createSignal<Entity | null>(null);--/** The node the picked shapes will clip, reactive; null while the tool is down. */-export { clipPathTarget };--export function getClipPathTarget(): Entity | null {- const target = clipPathTarget();- return target?.isAlive() ? target : null;-}--/** Picks the tool to add clip paths to `target`. The selection stays on it until a shape is picked. */-export function beginClipPathFor(world: World, target: Entity): void {- setClipPathTarget(target);- world.set(Tool, { value: ToolType.CLIP_PATH });-}--/** Forgets the target: the tool is down. */-export function clearClipPathTarget(): void {- setClipPathTarget(null);-}--/**- * Whether `entity` can clip `target`: a plain shape (what a `<clipPath>`- * clips by is `<rect>`, `<ellipse>`, `<polygon>` or `<path>`, so media, text- * and containers are out), not cutting something already, and not the target- * or something the target sits inside — a node cannot be moved into its own- * subtree.- */-export function canClipWith(world: World, target: Entity, entity: Entity): boolean {- if (entity === target || !entity.isAlive() || !entity.get(Source)?.value) return false;- if (!isShape(entity) || getIntrinsicPaint(entity) !== undefined) return false;- const parent = getParentEntity(entity);- if (parent && isMaskContainer(parent)) return false;- return !getEntityTree(world, entity).includes(target);-}--/** The selected shapes Confirm would apply to the target, in selection order. */-export function getClipPathPicks(world: World): Entity[] {- const target = getClipPathTarget();- if (!target) return [];- return getSelection(world).filter((entity) => canClipWith(world, target, entity));-}--/**- * Gives the target a new `<clipPath>` holding the picked shapes, one undo- * step, and puts the tool down with the target selected: the target then- * shows only inside their outlines together, and within any clip path it had- * before. Each shape keeps its place on the canvas: its matrix is carried- * from the parent it had into the target's space (the clip path's) and- * written back as `x`, `y` and `rotation`, with whatever scale the move adds- * (a target drawn at half size, say) folded into its `width` and `height`- * rather than its own scale.- */-export function applyClipPaths(world: World): void {- const target = getClipPathTarget();- const picks = getClipPathPicks(world);- if (!target || picks.length === 0) return;-- const editor = getDocumentEditor(world);- const computed = store(world, Computed);- const flip = store(world, Flip);- const targetInverse = invert2D(entityWorldMat(world, target));-- const [clipPath] = editor.insertElement(target, () => <ClipPathElement />);- if (!clipPath) {- leaveClipPathTool(world, target);- return;- }-- let moved = 0;- for (const shape of picks) {- const eid = shape.id();- const width = computed.width[eid] ?? 0;- const height = computed.height[eid] ?? 0;- const pivot = entityPivot(world, shape);-- // Where it is drawn now, pivot folded in (see `bakeContainerInto`),- // taken into the target's space (which the clip path shares) before- // the move changes its parent.- const placed = decompose2D(multiply2D(- targetInverse,- multiply2D(entityWorldMat(world, shape), translate2D(pivot.x, pivot.y)),- ));-- if (!editor.reparent(shape, clipPath)) continue;- moved++;-- // The scale the shape carries of its own stays its own; the rest is the move's.- const ownX = (computed.scaleX[eid] ?? 1) * (flip.x[eid] ?? 1);- const ownY = (computed.scaleY[eid] ?? 1) * (flip.y[eid] ?? 1);- const nextWidth = ownX === 0 ? width : Math.round(width * Math.abs(placed.scaleX / ownX));- const nextHeight = ownY === 0 ? height : Math.round(height * Math.abs(placed.scaleY / ownY));-- const offset = entityOffset(world, shape);- const nextPivot = entityPivot(world, shape, nextWidth, nextHeight);- const x = Math.round(placed.x - nextPivot.x - offset.x);- const y = Math.round(placed.y - nextPivot.y - offset.y);- const rotation = round2(placed.rotation);-- const writes: TransformWrite[] = [];- if (x !== Math.round(computed.positionX[eid] ?? 0)) writes.push(['x', x]);- if (y !== Math.round(computed.positionY[eid] ?? 0)) writes.push(['y', y]);- if (rotation !== round2(computed.rotation[eid] ?? 0)) writes.push(['rotation', rotation]);- if (nextWidth !== Math.round(width)) writes.push(['width', nextWidth]);- if (nextHeight !== Math.round(height)) writes.push(['height', nextHeight]);- if (writes.length) editTransform(world, editor, shape, writes);- }-- // An empty clip path would clip nothing; it is not worth the file.- if (moved === 0) editor.remove(clipPath);-- leaveClipPathTool(world, target);-}--/** Puts the tool down without applying anything; the selection goes back to the target. */-export function cancelClipPath(world: World): void {- leaveClipPathTool(world, getClipPathTarget());-}--function leaveClipPathTool(world: World, target: Entity | null): void {- clearClipPathTarget();- if (target) getDocumentEditor(world).select(target);- if (world.get(Tool)?.value === ToolType.CLIP_PATH) world.set(Tool, { value: ToolType.MOVE });-}diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.tsindex 7fb76982..6100f508 100644--- a/apps/web/src/engine/index.ts+++ b/apps/web/src/engine/index.ts@@ -24,5 +24,5 @@ export * from './asset-actions';export * from './keyframes';export * from './align';export * from './object-mask';-export * from './clip-path';+export * from './mask';export * from './path-tool';diff --git a/apps/web/src/engine/input/cursor.ts b/apps/web/src/engine/input/cursor.tsindex 62b7601f..f3044299 100644--- a/apps/web/src/engine/input/cursor.ts+++ b/apps/web/src/engine/input/cursor.ts@@ -96,7 +96,7 @@ const TOOL_CURSORS: Record<ToolType, { idle: CursorType; pressed?: CursorType }>[ToolType.TEXT]: { idle: 'crosshair' },[ToolType.TEXT_EDIT]: { idle: 'text' },[ToolType.OBJECT_MASK]: { idle: 'crosshair' },- [ToolType.CLIP_PATH]: { idle: 'default' },+ [ToolType.MASK]: { idle: 'default' },[ToolType.LINEAR_GRADIENT]: { idle: 'default' },[ToolType.RADIAL_GRADIENT]: { idle: 'default' },[ToolType.ANGULAR_GRADIENT]: { idle: 'default' },diff --git a/apps/web/src/engine/input/shortcuts.ts b/apps/web/src/engine/input/shortcuts.tsindex ec35581f..d6c8894a 100644--- a/apps/web/src/engine/input/shortcuts.ts+++ b/apps/web/src/engine/input/shortcuts.ts@@ -39,7 +39,7 @@ import { Not, Or } from 'koota';import { claimClipboard, hasMedia, readClipboardMedia } from '@/lib/clipboard';import { pasteClipboardMedia } from '../asset-actions';import { zoomBy, zoomTo, zoomToFit, zoomToSelection } from '../camera';-import { applyClipPaths, cancelClipPath } from '../clip-path';+import { applyMasks, cancelMask } from '../mask';import { getDocumentEditor } from '../editor';import { groupSelection, ungroupSelection, unwrapSequenceSelection, wrapSelectionInScene, wrapSelectionInSequence } from '../group';import { getEditHistory } from '../history';@@ -511,16 +511,16 @@ const maskStrokeToUndo = (world: World): boolean => {return objectMaskTool(world) && track?.status === 'seeded' && track.strokes.length > 0;};-const clipPathTool = (world: World): boolean => world.get(Tool)?.value === ToolType.CLIP_PATH;+const maskTool = (world: World): boolean => world.get(Tool)?.value === ToolType.MASK;/** Enter on a lone selected path edits its vertices, where it would otherwise step into children. */const pathToEdit = (world: World) => world.get(Tool)?.value === ToolType.MOVE && selectedPath(world) !== null;const editSelectedPath = (world: World) => beginPathEdit(world, selectedPath(world)!);const PRESSED_SHORTCUTS: readonly Shortcut[] = [- // Clip path tool shortcuts, ahead of the Esc and ⌘↵ the rest of the editor answers to.- { keys: ['escape'], action: cancelClipPath, active: clipPathTool },- { keys: ['enter', 'mod', '!shift', '!alt'], action: applyClipPaths, active: clipPathTool },+ // Mask tool shortcuts, ahead of the Esc and ⌘↵ the rest of the editor answers to.+ { keys: ['escape'], action: cancelMask, active: maskTool },+ { keys: ['enter', 'mod', '!shift', '!alt'], action: applyMasks, active: maskTool },// The pen ends its path on Esc or Enter, the path editor goes down on// either, and Delete takes out its picked vertex rather than the path.{ keys: ['escape'], action: (world) => finishPen(world, false), active: isPenDrawing },diff --git a/apps/web/src/engine/mask.tsx b/apps/web/src/engine/mask.tsxnew file mode 100644index 00000000..00269b94--- /dev/null+++ b/apps/web/src/engine/mask.tsx@@ -0,0 +1,160 @@+/* 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/. */++import { Mask as MaskElement } from '@diffusionstudio/reconciler';+import {+ Computed,+ Flip,+ Source,+ Tool,+ ToolType,+ decompose2D,+ entityPivot,+ entityOffset,+ entityWorldMat,+ getEntityTree,+ getParentEntity,+ getSelection,+ invert2D,+ isMaskContainer,+ isShape,+ isText,+ multiply2D,+ store,+ translate2D,+} from '@diffusionstudio/runtime';+import { createSignal } from 'solid-js';++import { getDocumentEditor } from './editor';+import { editTransform } from './input/interactions';++import type { Entity, World } from 'koota';+import type { TransformWrite } from './input/interactions';++const round2 = (value: number): number => Math.round(value * 100) / 100;++// The node the tool is aimed at, reactive so the bar follows it.+const [maskTarget, setMaskTarget] = createSignal<Entity | null>(null);++/** The node the picked layers will mask, reactive; null while the tool is down. */+export { maskTarget };++export function getMaskTarget(): Entity | null {+ const target = maskTarget();+ return target?.isAlive() ? target : null;+}++/** Picks the tool to add masks to `target`. The selection stays on it until a layer is picked. */+export function beginMaskFor(world: World, target: Entity): void {+ setMaskTarget(target);+ world.set(Tool, { value: ToolType.MASK });+}++/** Forgets the target: the tool is down. */+export function clearMaskTarget(): void {+ setMaskTarget(null);+}++/**+ * Whether `entity` can mask `target`: a shape, media or text (a `<mask>`+ * shows the target where their pixels are; groups and the like are out), not+ * cutting something already, and not the target or something the target sits+ * inside — a node cannot be moved into its own subtree.+ */+export function canMaskWith(world: World, target: Entity, entity: Entity): boolean {+ if (entity === target || !entity.isAlive() || !entity.get(Source)?.value) return false;+ if (!isShape(entity) && !isText(entity)) return false;+ const parent = getParentEntity(entity);+ if (parent && isMaskContainer(parent)) return false;+ return !getEntityTree(world, entity).includes(target);+}++/** The selected layers Confirm would apply to the target, in selection order. */+export function getMaskPicks(world: World): Entity[] {+ const target = getMaskTarget();+ if (!target) return [];+ return getSelection(world).filter((entity) => canMaskWith(world, target, entity));+}++/**+ * Gives the target a new `<mask>` holding the picked layers, one undo step,+ * and puts the tool down with the target selected: the target then shows+ * only where their pixels are together, and within any mask it had before.+ * Each layer keeps its place on the canvas: its matrix is carried from the+ * parent it had into the target's space (the mask's) and written back as+ * `x`, `y` and `rotation`, with whatever scale the move adds (a target drawn+ * at half size, say) folded into its `width` and `height` rather than its+ * own scale.+ */+export function applyMasks(world: World): void {+ const target = getMaskTarget();+ const picks = getMaskPicks(world);+ if (!target || picks.length === 0) return;++ const editor = getDocumentEditor(world);+ const computed = store(world, Computed);+ const flip = store(world, Flip);+ const targetInverse = invert2D(entityWorldMat(world, target));++ const [mask] = editor.insertElement(target, () => <MaskElement />);+ if (!mask) {+ leaveMaskTool(world, target);+ return;+ }++ let moved = 0;+ for (const layer of picks) {+ const eid = layer.id();+ const width = computed.width[eid] ?? 0;+ const height = computed.height[eid] ?? 0;+ const pivot = entityPivot(world, layer);++ // Where it is drawn now, pivot folded in (see `bakeContainerInto`),+ // taken into the target's space (which the mask shares) before+ // the move changes its parent.+ const placed = decompose2D(multiply2D(+ targetInverse,+ multiply2D(entityWorldMat(world, layer), translate2D(pivot.x, pivot.y)),+ ));++ if (!editor.reparent(layer, mask)) continue;+ moved++;++ // The scale the layer carries of its own stays its own; the rest is the move's.+ const ownX = (computed.scaleX[eid] ?? 1) * (flip.x[eid] ?? 1);+ const ownY = (computed.scaleY[eid] ?? 1) * (flip.y[eid] ?? 1);+ const nextWidth = ownX === 0 ? width : Math.round(width * Math.abs(placed.scaleX / ownX));+ const nextHeight = ownY === 0 ? height : Math.round(height * Math.abs(placed.scaleY / ownY));++ const offset = entityOffset(world, layer);+ const nextPivot = entityPivot(world, layer, nextWidth, nextHeight);+ const x = Math.round(placed.x - nextPivot.x - offset.x);+ const y = Math.round(placed.y - nextPivot.y - offset.y);+ const rotation = round2(placed.rotation);++ const writes: TransformWrite[] = [];+ if (x !== Math.round(computed.positionX[eid] ?? 0)) writes.push(['x', x]);+ if (y !== Math.round(computed.positionY[eid] ?? 0)) writes.push(['y', y]);+ if (rotation !== round2(computed.rotation[eid] ?? 0)) writes.push(['rotation', rotation]);+ if (nextWidth !== Math.round(width)) writes.push(['width', nextWidth]);+ if (nextHeight !== Math.round(height)) writes.push(['height', nextHeight]);+ if (writes.length) editTransform(world, editor, layer, writes);+ }++ // An empty mask would show nothing of the target; it is not worth the file.+ if (moved === 0) editor.remove(mask);++ leaveMaskTool(world, target);+}++/** Puts the tool down without applying anything; the selection goes back to the target. */+export function cancelMask(world: World): void {+ leaveMaskTool(world, getMaskTarget());+}++function leaveMaskTool(world: World, target: Entity | null): void {+ clearMaskTarget();+ if (target) getDocumentEditor(world).select(target);+ if (world.get(Tool)?.value === ToolType.MASK) world.set(Tool, { value: ToolType.MOVE });+}diff --git a/packages/runtime/src/constants.ts b/packages/runtime/src/constants.tsindex 482bc333..01683f3b 100644--- a/packages/runtime/src/constants.ts+++ b/packages/runtime/src/constants.ts@@ -184,7 +184,7 @@ export enum ToolType {TEXT,TEXT_EDIT,OBJECT_MASK,- CLIP_PATH,+ MASK,LINEAR_GRADIENT,RADIAL_GRADIENT,ANGULAR_GRADIENT,