Skip to content

The VS Code of video editing, built for agents.

TypeScript

Enhance path editing capabilities and introduce new SVG icons

konstantin-paulus555297874724
diff --git a/apps/desktop/src/source.ts b/apps/desktop/src/source.ts
index 5fced69b..99ec8a74 100644
--- a/apps/desktop/src/source.ts
+++ b/apps/desktop/src/source.ts
@@ -29,7 +29,7 @@ const COMPOSITION_COMPONENTS = new Map<string, string>(
// These composition names also exist in SVG. An SVG fragment is DOM content
// only while it has an SVG container in the same JSX tree; elsewhere the tag
// keeps its composition meaning.
-const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "ellipse", "polygon", "text", "image"]);
+const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "ellipse", "polygon", "path", "text", "image"]);
const SVG_CONTAINERS: ReadonlySet<string> = new Set([
"svg", "g", "defs", "symbol", "marker", "mask", "clipPath", "pattern",
"filter", "linearGradient", "radialGradient", "textPath", "tspan", "switch",
diff --git a/apps/web/src/assets/icons/path.trim-end.svg b/apps/web/src/assets/icons/path.trim-end.svg
new file mode 100644
index 00000000..bb5268da
--- /dev/null
+++ b/apps/web/src/assets/icons/path.trim-end.svg
@@ -0,0 +1,4 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.5" d="M6.75 12H12.75" stroke="currentColor" stroke-linecap="round" stroke-dasharray="0.5 2"/>
+<rect x="15.5" y="6.5" width="2" height="11" rx="1" stroke="currentColor"/>
+</svg>
diff --git a/apps/web/src/assets/icons/path.trim-offset.svg b/apps/web/src/assets/icons/path.trim-offset.svg
new file mode 100644
index 00000000..9f3316d3
--- /dev/null
+++ b/apps/web/src/assets/icons/path.trim-offset.svg
@@ -0,0 +1,5 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path opacity="0.5" d="M6.25 12H8.75" stroke="currentColor" stroke-linecap="round" stroke-dasharray="0.5 2"/>
+<rect x="11" y="6.5" width="2" height="11" rx="1" stroke="currentColor"/>
+<path opacity="0.5" d="M15.25 12H17.75" stroke="currentColor" stroke-linecap="round" stroke-dasharray="0.5 2"/>
+</svg>
diff --git a/apps/web/src/assets/icons/path.trim-start.svg b/apps/web/src/assets/icons/path.trim-start.svg
new file mode 100644
index 00000000..c4ab94fc
--- /dev/null
+++ b/apps/web/src/assets/icons/path.trim-start.svg
@@ -0,0 +1,4 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect x="6.5" y="6.5" width="2" height="11" rx="1" stroke="currentColor"/>
+<path opacity="0.5" d="M11.25 12H17.25" stroke="currentColor" stroke-linecap="round" stroke-dasharray="0.5 2"/>
+</svg>
diff --git a/apps/web/src/assets/icons/tool.pen-small.svg b/apps/web/src/assets/icons/tool.pen-small.svg
new file mode 100644
index 00000000..61bd1d83
--- /dev/null
+++ b/apps/web/src/assets/icons/tool.pen-small.svg
@@ -0,0 +1,6 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M7.03 6L15.145 8.61L15.664 13.288L11.324 16.451L7.03 14.524Z" stroke="currentColor" stroke-width="1" stroke-linejoin="round"/>
+<path d="M16.042 13.013L16.97 14.287L11.875 18L10.946 16.726Z" stroke="currentColor" stroke-width="1" stroke-linejoin="round"/>
+<path d="M7.03 6L10.709 11.048" stroke="currentColor" stroke-width="1" stroke-linecap="round"/>
+<circle cx="11.328" cy="11.897" r="1.051" stroke="currentColor" stroke-width="1"/>
+</svg>
diff --git a/apps/web/src/assets/icons/tool.pen.svg b/apps/web/src/assets/icons/tool.pen.svg
new file mode 100644
index 00000000..64ef75e9
--- /dev/null
+++ b/apps/web/src/assets/icons/tool.pen.svg
@@ -0,0 +1,6 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.373 4L16.193 7.48L16.886 13.717L11.099 17.935L5.373 15.365Z" stroke="currentColor" stroke-width="1.125" stroke-linejoin="round"/>
+<path d="M17.389 13.35L18.627 15.049L11.833 20L10.595 18.302Z" stroke="currentColor" stroke-width="1.125" stroke-linejoin="round"/>
+<path d="M5.373 4L10.279 10.731" stroke="currentColor" stroke-width="1.125" stroke-linecap="round"/>
+<circle cx="11.104" cy="11.863" r="1.401" stroke="currentColor" stroke-width="1.125"/>
+</svg>
diff --git a/apps/web/src/components/canvas/toolbar.tsx b/apps/web/src/components/canvas/toolbar.tsx
index 1d248d84..0ee6de6d 100644
--- a/apps/web/src/components/canvas/toolbar.tsx
+++ b/apps/web/src/components/canvas/toolbar.tsx
@@ -48,6 +48,8 @@ export function Toolbar() {
const selectedTool = useTool();
const cursorTool = createMemo(() => CURSOR_TOOLS.find((cursor) => cursor.tool === selectedTool()));
const shapeTool = createMemo(() => SHAPE_TOOLS.find((shape) => shape.tool === selectedTool()));
+ // Editing a path's vertices is the pen's other half, as in Figma.
+ const penTool = () => selectedTool() === ToolType.PEN || selectedTool() === ToolType.PATH_EDIT;
createEffect(() => {
const shape = shapeTool();
@@ -189,6 +191,18 @@ export function Toolbar() {
</DropdownMenuPortal>
</DropdownMenu>
</div>
+ <Tooltip>
+ <TooltipTrigger
+ as={Button}
+ size="icon-square"
+ variant={penTool() ? 'default' : 'ghost'}
+ onClick={() => handleToolChange(ToolType.PEN)}
+ class={penTool() ? 'text-foreground' : 'text-muted-foreground'}
+ >
+ <Icon name="tool.pen" />
+ </TooltipTrigger>
+ <TooltipContent shortcut="P">Pen</TooltipContent>
+ </Tooltip>
<Tooltip>
<TooltipTrigger
as={Button}
diff --git a/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx
index 3d1e3546..0bebd8b2 100644
--- a/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx
+++ b/apps/web/src/components/sidebar-left/project-menu/tool-menu.tsx
@@ -47,6 +47,10 @@ export function ToolMenu() {
<DropdownMenuItem onSelect={() => setTool(ToolType.POLYGON)}>
Polygon
</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setTool(ToolType.PEN)}>
+ Pen
+ <DropdownMenuShortcut>P</DropdownMenuShortcut>
+ </DropdownMenuItem>
<DropdownMenuItem onSelect={() => setTool(ToolType.OBJECT_MASK)}>
Object Mask
<DropdownMenuShortcut>M</DropdownMenuShortcut>
diff --git a/apps/web/src/components/sidebar-right/inspector/appearance.tsx b/apps/web/src/components/sidebar-right/inspector/appearance.tsx
index 4401987b..b4763cf7 100644
--- a/apps/web/src/components/sidebar-right/inspector/appearance.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/appearance.tsx
@@ -346,7 +346,7 @@ export function AppearanceSettings(props: AppearanceSettingsProps) {
</Show>
<Show when={isPolygon(entity())}>
- <ControlRow label="Count" contentClass="grid grid-cols-2 gap-2 min-w-0">
+ <ControlRow label="Points" contentClass="grid grid-cols-2 gap-2 min-w-0">
<ControlledTextField
value={pointCount()}
autoSelect
diff --git a/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx b/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx
index 17aa72d9..1775ccfb 100644
--- a/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/clip-paths.tsx
@@ -24,7 +24,7 @@ type ClipPathsSettingsProps = {
/**
* The clip path children of the selected node (`<rect clipPath>`,
- * `<ellipse clipPath>`, `<polygon clipPath>`): the shapes it is clipped to
+ * `<ellipse clipPath>`, `<polygon clipPath>`, `<path clipPath>`): the shapes it is clipped to
* (several intersect). A clip path is a shape like any other, so it
* has no inspector of its own — a row selects it and the transform, time and
* appearance panels are then its own. The plus picks up the clip path tool,
diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
index d6de4759..7955d0e3 100644
--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
@@ -12,6 +12,7 @@ import {
isCaption,
isGroup,
isClipPath,
+ isPath,
isScene,
isSequence,
isShape,
@@ -25,6 +26,7 @@ import { SceneTemplatePanel } from "./scene-template";
import { AssetInfoPanel } from "./asset-info";
import { TimeSettings } from "./time";
import { AppearanceSettings } from "./appearance";
+import { PathSettings } from "./path";
import { Alignment } from "./alignment";
import { ExportPanel } from "./export";
import { LayoutPanel } from "./layout";
@@ -151,6 +153,10 @@ export function Inspector() {
<TextPanel selection={nodes()} />
</Show>
+ <Show when={nodes().length === 1 && isPath(nodes()[0]!)}>
+ <PathSettings selection={nodes()} />
+ </Show>
+
<Show when={includesTarget("shape", "text", "scene")}>
<FillsSettings selection={nodes()} />
</Show>
diff --git a/apps/web/src/components/sidebar-right/inspector/layout.tsx b/apps/web/src/components/sidebar-right/inspector/layout.tsx
index 1c414793..3202c251 100644
--- a/apps/web/src/components/sidebar-right/inspector/layout.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/layout.tsx
@@ -20,6 +20,7 @@ import { useHas, useWorld } from "@diffusionstudio/koota-solid";
import { ClipsContent, Computed, KeepAspectRatio, isScene } from "@diffusionstudio/runtime";
import { useDerived, useEditor } from "@/engine/hooks";
import { syncKeyframe } from "@/engine/keyframes";
+import { pinViewBox } from "@/engine/path-tool";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -96,6 +97,9 @@ export function LayoutPanel(props: LayoutPanelProps) {
}
}
+ // A path's outline stretches with its box rather than staying put in it.
+ pinViewBox(world, editor, entity());
+
if (width !== undefined) {
width = Math.round(width);
syncKeyframe(world, editor, entity(), "width", width);
diff --git a/apps/web/src/components/sidebar-right/inspector/path.tsx b/apps/web/src/components/sidebar-right/inspector/path.tsx
new file mode 100644
index 00000000..31da7c8c
--- /dev/null
+++ b/apps/web/src/components/sidebar-right/inspector/path.tsx
@@ -0,0 +1,136 @@
+/* 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 { ControlRow } from "@/components/ui/control-group";
+import { Icon } from "@/components/ui/icon";
+import { Keyframe } from "@/components/ui/keyframe";
+import { PanelSection } from "@/components/ui/panel-section";
+import { Select, SelectContent, SelectItem, SelectPortal, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { ControlledTextField } from "@/components/ui/text-field";
+import { useHas, useWorld } from "@diffusionstudio/koota-solid";
+import { Computed, EvenOdd } from "@diffusionstudio/runtime";
+import { useDerived, useEditor } from "@/engine/hooks";
+import { syncKeyframe } from "@/engine/keyframes";
+
+import type { FillRule } from "@diffusionstudio/jsx";
+import type { Entity } from "koota";
+
+type PathSettingsProps = {
+ selection: Entity[];
+};
+
+const FILL_RULES: { value: FillRule; label: string }[] = [
+ { value: "nonzero", label: "Nonzero" },
+ { value: "evenodd", label: "Even-odd" },
+];
+
+type TrimProp = "trimStart" | "trimEnd" | "trimOffset";
+
+/** Each trim prop's default, at which the control unsets it. */
+const TRIM_DEFAULTS: Record<TrimProp, number> = { trimStart: 0, trimEnd: 1, trimOffset: 0 };
+
+const percent = (fraction: number) => Math.round(fraction * 10000) / 100;
+
+/**
+ * What only a `<path>` has: its outline, its fill rule, and the trim that
+ * draws part of its length (`trimStart`/`trimEnd`/`trimOffset`, shown in
+ * percent of the length and keyframable like any prop). The outline has no
+ * value to type — it is edited on the canvas — so its keyframe sits in the
+ * section's header: a `d` keyframe of the outline as it is at the playhead,
+ * which the vertex edits made there then key.
+ */
+export function PathSettings(props: PathSettingsProps) {
+ const world = useWorld();
+ const editor = useEditor();
+ const entity = () => props.selection[0]!;
+
+ const evenOdd = useHas(entity, EvenOdd);
+ const fillRule = (): FillRule => (evenOdd() ? "evenodd" : "nonzero");
+
+ const trimStart = useDerived(() => entity().get(Computed)?.trimStart ?? 0);
+ const trimEnd = useDerived(() => entity().get(Computed)?.trimEnd ?? 1);
+ const trimOffset = useDerived(() => entity().get(Computed)?.trimOffset ?? 0);
+
+ const handleFillRuleChange = (rule: FillRule | null) => {
+ if (rule === null || rule === fillRule()) return;
+ editor.editProperty(entity(), "fillRule", rule === "nonzero" ? false : rule);
+ };
+
+ const handleTrimChange = (name: TrimProp, value: number) => {
+ const fraction = Math.round(value * 100) / 10000;
+ const clamped = name === "trimOffset" ? fraction : Math.min(1, Math.max(0, fraction));
+ editor.editProperty(entity(), name, clamped === TRIM_DEFAULTS[name] ? false : clamped);
+ syncKeyframe(world, editor, entity(), name, clamped);
+ };
+
+ return (
+ <PanelSection
+ title="Path"
+ actions={<Keyframe target={entity()} property="d" class="h-7" />}
+ >
+ <ControlRow label="Fill rule">
+ <Select<FillRule>
+ value={fillRule()}
+ onChange={handleFillRuleChange}
+ options={FILL_RULES.map((rule) => rule.value)}
+ itemComponent={(itemProps) => (
+ <SelectItem item={itemProps.item}>
+ {FILL_RULES.find((rule) => rule.value === itemProps.item.rawValue)?.label}
+ </SelectItem>
+ )}
+ >
+ <SelectTrigger>
+ <SelectValue class="text-xs">{FILL_RULES.find((rule) => rule.value === fillRule())?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectPortal>
+ <SelectContent />
+ </SelectPortal>
+ </Select>
+ </ControlRow>
+
+ <ControlRow label="Trim" contentClass="grid grid-cols-2 gap-2">
+ <ControlledTextField
+ value={percent(trimStart())}
+ onNumber={(value) => handleTrimChange("trimStart", value)}
+ icon={<Icon name="path.trim-start" />}
+ unit="%"
+ step={1}
+ min={0}
+ max={100}
+ autoSelect
+ sliderEnabled
+ limitEvents
+ keyframe={<Keyframe target={entity()} property="trimStart" />}
+ />
+ <ControlledTextField
+ value={percent(trimEnd())}
+ onNumber={(value) => handleTrimChange("trimEnd", value)}
+ icon={<Icon name="path.trim-end" />}
+ unit="%"
+ step={1}
+ min={0}
+ max={100}
+ autoSelect
+ sliderEnabled
+ limitEvents
+ keyframe={<Keyframe target={entity()} property="trimEnd" />}
+ />
+ </ControlRow>
+
+ <ControlRow label="Offset">
+ <ControlledTextField
+ value={percent(trimOffset())}
+ onNumber={(value) => handleTrimChange("trimOffset", value)}
+ icon={<Icon name="path.trim-offset" />}
+ unit="%"
+ step={1}
+ autoSelect
+ sliderEnabled
+ limitEvents
+ keyframe={<Keyframe target={entity()} property="trimOffset" />}
+ />
+ </ControlRow>
+ </PanelSection>
+ );
+}
diff --git a/apps/web/src/components/sidebar-right/inspector/stroke-inspector.tsx b/apps/web/src/components/sidebar-right/inspector/stroke-inspector.tsx
index a89f5dcf..f7c713d9 100644
--- a/apps/web/src/components/sidebar-right/inspector/stroke-inspector.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/stroke-inspector.tsx
@@ -73,7 +73,8 @@ type StrokeInspectorProps = {
* The paint is the stroke's own `color` or a gradient paint child, picked in
* the fill picker without its asset tab; a gradient is placed in the box of
* the stroke's parent, so that is where its handles go. `cap` has no control
- * yet: it only shows on open paths (text glyphs) and there are no icons for it.
+ * yet: it only shows on open paths (text glyphs, open `<path>` subpaths) and
+ * there are no icons for it.
*/
export function StrokeInspector(props: StrokeInspectorProps) {
const world = useWorld();
diff --git a/apps/web/src/components/timeline/layers/keyframe.tsx b/apps/web/src/components/timeline/layers/keyframe.tsx
index aee6e4e1..3318d902 100644
--- a/apps/web/src/components/timeline/layers/keyframe.tsx
+++ b/apps/web/src/components/timeline/layers/keyframe.tsx
@@ -185,6 +185,10 @@ const PROPERTY_NAMES: Partial<Record<PropertyPath, string>> = {
'gradient.ry': 'Radius Y',
'effect.value': 'Value',
'chars': 'Text',
+ 'path': 'Path',
+ 'trim.start': 'Trim Start',
+ 'trim.end': 'Trim End',
+ 'trim.offset': 'Trim Offset',
};
/**
diff --git a/apps/web/src/components/timeline/layers/node.tsx b/apps/web/src/components/timeline/layers/node.tsx
index 5be8127e..542c5394 100644
--- a/apps/web/src/components/timeline/layers/node.tsx
+++ b/apps/web/src/components/timeline/layers/node.tsx
@@ -21,6 +21,7 @@ import {
isGroup,
isClipPath,
isEllipse,
+ isPath,
isPolygon,
isScene,
isSequence,
@@ -362,6 +363,7 @@ function getLayerIcon(world: World, layer: TimelineNode) {
if (isText(entity)) return "text-small";
if (isEllipse(entity)) return "tool.ellipse-small";
if (isPolygon(entity)) return "tool.polygon-small";
+ if (isPath(entity)) return "tool.pen-small";
switch (findGeometryAsset(world, entity)?.type) {
case 'IMAGE':
diff --git a/apps/web/src/engine/clip-path.ts b/apps/web/src/engine/clip-path.ts
index de644ebc..fd268e98 100644
--- a/apps/web/src/engine/clip-path.ts
+++ b/apps/web/src/engine/clip-path.ts
@@ -56,7 +56,7 @@ export function clearClipPathTarget(): void {
/**
* Whether `entity` can become a clip path of `target`: a plain shape (a clip
- * path is a `<rect>`, `<ellipse>` or `<polygon>`, so media, text and
+ * path is a `<rect>`, `<ellipse>`, `<polygon>` or `<path>`, so media, text and
* containers are out), not one
* already, and not the target or something the target sits inside — a node
* cannot be moved into its own subtree.
diff --git a/apps/web/src/engine/create-engine.ts b/apps/web/src/engine/create-engine.ts
index 65df4a22..3a0bafa0 100644
--- a/apps/web/src/engine/create-engine.ts
+++ b/apps/web/src/engine/create-engine.ts
@@ -5,7 +5,7 @@
import { assetSystem, renderSystem, transformSystem, playbackSystem, motionSystem, AudioEngine, createRuntimeWorld, Geometry, Mode, RenderSurface, Time, ChildOf, syncInteractiveState } from '@diffusionstudio/runtime';
import { hudSystem } from './hud';
import { createSignal, type Accessor, type Setter } from 'solid-js';
-import { AssetSelection, DrawTool, GradientTool, Hud, Keys, MODIFIER_KEYS, ObjectMaskTool, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';
+import { AssetSelection, DrawTool, GradientTool, Hud, Keys, MODIFIER_KEYS, ObjectMaskTool, PathEditor, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';
import { inputSystem } from './input/input-system';
import { clearClipFrames, clearClipPeaks, clearMedia, clearPeaks, timelineSystem, TimelineSurface } from './timeline';
import { clearObjectTrackOf, clearObjectTracks } from './object-mask';
@@ -49,7 +49,7 @@ class Engine {
public constructor(projectId: string, options: EngineOptions = {}) {
this.world = createRuntimeWorld(projectId);
- this.world.add(Pointer, Keys, SnapLines, Hud, ObjectMaskTool, GradientTool, DrawTool, PointerEvents, AssetSelection, ProjectConfig, TimelineSurface);
+ this.world.add(Pointer, Keys, SnapLines, Hud, ObjectMaskTool, GradientTool, DrawTool, PathEditor, PointerEvents, AssetSelection, ProjectConfig, TimelineSurface);
this.unsubscribe.push(
this.world.onAdd(ChildOf('*'), () => (this.interactiveDirty = true)),
diff --git a/apps/web/src/engine/hud/hud-system.ts b/apps/web/src/engine/hud/hud-system.ts
index 0ac44051..ebc4b62a 100644
--- a/apps/web/src/engine/hud/hud-system.ts
+++ b/apps/web/src/engine/hud/hud-system.ts
@@ -23,6 +23,7 @@ import { getMountedNameInput } from './name-input';
import { drawObjectMasks } from '../object-mask';
import { drawGradientTool, isGradientTool } from '../gradient-tool';
import { drawDrawTool } from '../draw-tool';
+import { drawPathEditor, drawPenTool, isPathEditing } from '../path-tool';
import type { Entity, World } from 'koota';
import type { Mat2D } from '@diffusionstudio/runtime';
@@ -51,8 +52,9 @@ export function hudSystem(world: World): void {
// The mask is in the way of the thing it is around while that thing is
// being moved, so it steps aside for the gesture; its handles would sit
- // on a gradient's while that is being placed.
- const mask = world.get(Hud)?.mode === 'moving' || isGradientTool(world) ? null : getSelectionMask(world);
+ // on a gradient's while that is being placed, and on a path's vertices
+ // while those are being edited.
+ const mask = world.get(Hud)?.mode === 'moving' || isGradientTool(world) || isPathEditing(world) ? null : getSelectionMask(world);
if (mask) {
drawSelectionMask(world, ctx, mask, resolution);
@@ -63,6 +65,8 @@ export function hudSystem(world: World): void {
drawObjectMasks(world, ctx, resolution);
drawGradientTool(world, ctx, resolution);
drawDrawTool(world, ctx, resolution);
+ drawPenTool(world, ctx, resolution);
+ drawPathEditor(world, ctx, resolution);
}
function drawSnapLines(world: World, ctx: Ctx2D, resolution: number): void {
diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.ts
index c0a4948b..7fb76982 100644
--- a/apps/web/src/engine/index.ts
+++ b/apps/web/src/engine/index.ts
@@ -25,3 +25,4 @@ export * from './keyframes';
export * from './align';
export * from './object-mask';
export * from './clip-path';
+export * from './path-tool';
diff --git a/apps/web/src/engine/input/cursor.ts b/apps/web/src/engine/input/cursor.ts
index 87adce2d..62b7601f 100644
--- a/apps/web/src/engine/input/cursor.ts
+++ b/apps/web/src/engine/input/cursor.ts
@@ -91,6 +91,8 @@ const TOOL_CURSORS: Record<ToolType, { idle: CursorType; pressed?: CursorType }>
[ToolType.RECT]: { idle: 'crosshair' },
[ToolType.ELLIPSE]: { idle: 'crosshair' },
[ToolType.POLYGON]: { idle: 'crosshair' },
+ [ToolType.PEN]: { idle: 'crosshair' },
+ [ToolType.PATH_EDIT]: { idle: 'default' },
[ToolType.TEXT]: { idle: 'crosshair' },
[ToolType.TEXT_EDIT]: { idle: 'text' },
[ToolType.OBJECT_MASK]: { idle: 'crosshair' },
diff --git a/apps/web/src/engine/input/interactions.ts b/apps/web/src/engine/input/interactions.ts
index 025b4a81..1aa37df8 100644
--- a/apps/web/src/engine/input/interactions.ts
+++ b/apps/web/src/engine/input/interactions.ts
@@ -23,7 +23,7 @@ import {
computeGroupBounds, computeLocalMatrix, decompose2D, entityAnchor,
entityOffset, entityQuad, entityWorldMat, enterEntity,
findKeyframeTrackEntity, getParentEntity, getParentNode, getSceneAncestor,
- getSelection, getSelectionMask, identity2D, invert2D, isPointerInEntity,
+ getSelection, getSelectionMask, identity2D, invert2D, isPath, isPointerInEntity,
multiply2D, quadCenter, quadContainsQuad, quadsIntersect, rectToQuad,
rotate2D, scale2D,
store, syncInteractiveState, togglePlayback, transformPoint, transformSystem,
@@ -33,6 +33,7 @@ import { Not, Or } from 'koota';
import { getDocumentEditor } from '../editor';
import { syncKeyframe } from '../keyframes';
+import { beginPathEdit, pinViewBox } from '../path-tool';
import { Hud, Keys, Pointer, SnapLines } from '../traits';
import { getToolCursor, updateCursor, type CursorType } from './cursor';
import { mountNameInput } from '../hud/name-input';
@@ -175,6 +176,13 @@ export function handleGeometryInteraction(world: World, event: DispatchedPointer
handleMaskInteraction(world, event);
}
+ // Double-click on a path edits its vertices.
+ if (event.type === 'dblclick' && event.target.kind === 'entity' && isPath(event.target.id)) {
+ editor.select(event.target.id);
+ beginPathEdit(world, event.target.id);
+ return;
+ }
+
// Double-click drills into a container: its children become the things the
// canvas can hit, and the one under the pointer takes the selection.
if (event.type === 'dblclick' && event.target.kind === 'entity') {
@@ -512,6 +520,8 @@ function resizeNode(world: World, entity: Entity, oldTr: Mat2D, localScale: Mat2
['y', Math.round(decomposed.y - height * anchor.y - offset.y)],
];
if (writeAngles) writes.push(['rotation', Math.round(decomposed.rotation * 100) / 100]);
+ // A path's outline stretches with its box rather than staying put in it.
+ pinViewBox(world, editor, entity);
editTransform(world, editor, entity, writes);
if (writeAngles) {
diff --git a/apps/web/src/engine/input/shortcuts.ts b/apps/web/src/engine/input/shortcuts.ts
index 590164ca..9707e227 100644
--- a/apps/web/src/engine/input/shortcuts.ts
+++ b/apps/web/src/engine/input/shortcuts.ts
@@ -40,6 +40,7 @@ import { groupSelection, ungroupSelection, unwrapSequenceSelection, wrapSelectio
import { getEditHistory } from '../history';
import { withEmptiedTracks } from '../keyframes';
import { cancelObjectMask, getObjectTrack, trackObjectMask, undoMaskStroke } from '../object-mask';
+import { beginPathEdit, deletePickedVertex, endPathEdit, finishPen, isPathEditing, isPenDrawing, selectedPath } from '../path-tool';
import { splitAtPlayhead } from '../split';
import { Keys, MODIFIER_KEYS, ObjectMaskTool, Pointer } from '../traits';
import { editTransform } from './interactions';
@@ -456,10 +457,22 @@ const maskStrokeToUndo = (world: World): boolean => {
const clipPathTool = (world: World): boolean => world.get(Tool)?.value === ToolType.CLIP_PATH;
+/** 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 },
+ // 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 },
+ { keys: ['enter'], action: (world) => finishPen(world, false), active: isPenDrawing },
+ { keys: ['escape'], action: endPathEdit, active: isPathEditing },
+ { keys: ['enter', '!mod'], action: endPathEdit, active: isPathEditing },
+ { keys: ['backspace'], action: deletePickedVertex, active: isPathEditing },
+ { keys: ['delete'], action: deletePickedVertex, active: isPathEditing },
{ keys: ['z', 'mod', '!shift'], action: undoEdit },
{ keys: ['z', 'mod', 'shift'], action: redoEdit },
{ keys: ['backspace'], action: deleteSelection },
@@ -488,6 +501,7 @@ const PRESSED_SHORTCUTS: readonly Shortcut[] = [
{ keys: ['t', '!mod'], action: selectTool(ToolType.TEXT) },
{ keys: ['r', '!mod'], action: selectTool(ToolType.RECT) },
{ keys: ['o', '!mod'], action: selectTool(ToolType.ELLIPSE) },
+ { keys: ['p', '!mod'], action: selectTool(ToolType.PEN), active: (world) => !objectMaskTool(world) },
{ keys: ['m', '!mod'], action: selectTool(ToolType.OBJECT_MASK) },
{ keys: ['a', '!mod'], action: seekFrames(-1) },
{ keys: ['d', '!mod'], action: seekFrames(1) },
@@ -504,6 +518,7 @@ const PRESSED_SHORTCUTS: readonly Shortcut[] = [
{ keys: [']', '!mod'], action: restack('front') },
{ keys: ['[', '!mod'], action: restack('back') },
{ keys: ['\\', '!mod'], action: selectParents },
+ { keys: ['enter', '!mod'], action: editSelectedPath, active: pathToEdit },
{ keys: ['enter', '!mod'], action: selectChildren },
{ keys: ['escape'], action: deselect },
{ keys: ['arrowleft', '!shift'], action: nudge(-NUDGE, 0) },
diff --git a/apps/web/src/engine/keyframes.tsx b/apps/web/src/engine/keyframes.tsx
index 767c6d32..8e93f57e 100644
--- a/apps/web/src/engine/keyframes.tsx
+++ b/apps/web/src/engine/keyframes.tsx
@@ -22,8 +22,10 @@ import {
FrameRate,
colorToHex,
findKeyframeTargetNode,
+ formatPath,
framesToSeconds,
getNodeLocalFrame,
+ getPathGeometry,
getParentEntity,
getPropertyPaths,
Paint,
@@ -59,9 +61,14 @@ export function keyframeFrame(target: Entity): number | null {
/**
* The value of `target`'s `property` as shown right now: the computed one,
* which is what a keyframe added here should hold. Colors come back as the
- * CSS hex a color track's keyframe is spelled with.
+ * CSS hex a color track's keyframe is spelled with, outlines as path data.
*/
function currentValue(world: World, target: Entity, property: AnimatableProperty): number | string | null {
+ // An outline, as the path data a `d` keyframe is spelled with.
+ if (property === "d") {
+ const geometry = getPathGeometry(world, target);
+ return geometry === null ? null : formatPath(geometry);
+ }
const path = trackPropertyPath(target, property);
if (!path) return null;
const value = getPropertyPaths(world)[path]?.computed[target.id()];
diff --git a/apps/web/src/engine/path-tool.tsx b/apps/web/src/engine/path-tool.tsx
new file mode 100644
index 00000000..43b22558
--- /dev/null
+++ b/apps/web/src/engine/path-tool.tsx
@@ -0,0 +1,770 @@
+/* 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/. */
+
+/**
+ * The pen and the path editor, the way Figma has them. The pen (P) draws a
+ * new `<path>` a vertex at a time: a click puts down a corner, a drag pulls
+ * out a smooth vertex's handles, a click on the first vertex closes the path
+ * and Enter or Esc leaves it open. Editing a path (Enter, or a double-click
+ * on it) puts its vertices on the canvas: drag a vertex or a handle, Alt to
+ * break a smooth vertex's handles apart, double-click a vertex to make it a
+ * corner or smooth, click the outline to add a vertex, Delete to take the
+ * picked one out. Leaving the editor fits the box to the outline again.
+ *
+ * Every change is a `d` written through the editor, the way the inspector
+ * writes any prop. A keyframed path keeps its keyframes After Effects'
+ * way: moving a vertex or a handle keys the outline at the playhead, while
+ * adding or deleting a vertex happens in every keyframe at once, so all of
+ * them keep the same vertices and the morph between them stays one.
+ */
+
+import { Path, Stroke } from '@diffusionstudio/reconciler';
+import {
+ Cache, Computed, HitRegions, Keyframe, LocalTransform, Position, RenderSurface, Root, Selected, Source, Tool, ToolType,
+ VectorPath, ViewBox,
+ entityAnchor, entityWorldMat, findSceneAt, formatPath, getNextName, getPathGeometry, getPathTransform,
+ getViewMatrix, identity2D, invert2D, isPath, multiply2D, nearestOnPath, pathBounds, pointInPath,
+ pointOnPath, rectToQuad, removeVertex, screenToWorld, segmentCount, splitSegment, store, transformPath,
+ transformPoint, unionPathBounds, vertexCount, worldToLocal,
+} from '@diffusionstudio/runtime';
+
+import { getDocumentEditor } from './editor';
+import { findKeyframeTrack, syncKeyframe } from './keyframes';
+import { editTransform } from './input/interactions';
+import { DrawTool, Keys, PathEditor, Pointer } from './traits';
+
+import type { Entity, World } from 'koota';
+import type { DispatchedPointerEvent, Mat2D, PathGeometry, Point, Subpath } from '@diffusionstudio/runtime';
+import type { DocumentEditor } from './editor';
+import type { TransformWrite } from './input/interactions';
+
+type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+
+/** A vertex the pen has put down, in document space: its anchor and the control points either side of it. */
+export type PenVertex = { x: number; y: number; inX: number; inY: number; outX: number; outY: number };
+
+/** What of a vertex a press can hold: the vertex itself or one of its handles. */
+export type PathPart = 'anchor' | 'in' | 'out';
+
+const ACCENT = '#008CFF';
+const HALO = 'rgba(0, 0, 0, 0.35)';
+const LINE_WIDTH = 1.5;
+const LINE_HALO = 3.5;
+/** A vertex's dot, CSS px. */
+const VERTEX_RADIUS = 4.5;
+/** The side of the square at a handle's end, CSS px. */
+const HANDLE_SIZE = 5;
+/** The square around a vertex or handle that takes the press, CSS px a side. */
+const HANDLE_HIT = 14;
+/** How near the outline, CSS px, a click adds a vertex. */
+const OUTLINE_HIT = 6;
+/** A pen press that moved less than this, CSS px, is a click: a corner, no handles. */
+const DRAG_THRESHOLD = 3;
+/** How a pen path is stroked when it lands. */
+const PEN_STROKE = { color: '#E0E0E0', width: 4 };
+/** How long a new smooth vertex's handles are, as a share of the way between its neighbors. */
+const SMOOTH_HANDLE = 0.25;
+
+const resolution = (world: World): number => world.get(RenderSurface)?.resolution ?? 1;
+
+/** A point in device pixels, in the document. */
+function toDocument(world: World, x: number, y: number): Point {
+ const res = resolution(world);
+ return screenToWorld(world, x / res, y / res);
+}
+
+function guide(ctx: Ctx2D, res: number): void {
+ ctx.strokeStyle = HALO;
+ ctx.lineWidth = LINE_HALO * res;
+ ctx.stroke();
+ ctx.strokeStyle = ACCENT;
+ ctx.lineWidth = LINE_WIDTH * res;
+ ctx.stroke();
+}
+
+function vertexDot(ctx: Ctx2D, point: Point, res: number, filled: boolean): void {
+ ctx.beginPath();
+ ctx.arc(point.x, point.y, VERTEX_RADIUS * res, 0, Math.PI * 2);
+ ctx.fillStyle = filled ? ACCENT : '#FFFFFF';
+ ctx.fill();
+ ctx.strokeStyle = ACCENT;
+ ctx.lineWidth = LINE_WIDTH * res;
+ ctx.stroke();
+}
+
+/**
+ * A handle: the line from its vertex and, at its end, a small square turned
+ * so that one corner points along the line, which ends in its center.
+ */
+function handleDot(ctx: Ctx2D, anchor: Point, handle: Point, res: number): void {
+ ctx.beginPath();
+ ctx.moveTo(anchor.x, anchor.y);
+ ctx.lineTo(handle.x, handle.y);
+ ctx.strokeStyle = ACCENT;
+ ctx.lineWidth = res;
+ ctx.stroke();
+
+ const size = HANDLE_SIZE * res;
+ ctx.save();
+ ctx.translate(handle.x, handle.y);
+ ctx.rotate(Math.atan2(handle.y - anchor.y, handle.x - anchor.x) + Math.PI / 4);
+ ctx.beginPath();
+ ctx.rect(-size / 2, -size / 2, size, size);
+ ctx.fillStyle = '#FFFFFF';
+ ctx.fill();
+ ctx.lineWidth = res;
+ ctx.stroke();
+ ctx.restore();
+}
+
+function hitQuad(point: Point, res: number) {
+ const half = (HANDLE_HIT * res) / 2;
+ return rectToQuad({ a: 1, b: 0, c: 0, d: 1, e: point.x - half, f: point.y - half }, half * 2, half * 2);
+}
+
+// ── Pen ─────────────────────────────────────────────────────
+
+/**
+ * While the pen is up: the region over the whole stage that takes its
+ * presses, and the path so far with a rubber band from its last vertex to
+ * the pointer. A pen put down for another tool keeps what it drew; the hand
+ * only borrows the stage, so a path survives a space-pan.
+ */
+export function drawPenTool(world: World, ctx: Ctx2D, res: number): void {
+ const tool = world.get(Tool)?.value;
+ const pen = world.get(DrawTool)!;
+ if (tool !== ToolType.PEN) {
+ if (tool !== ToolType.HAND && pen.vertices.length) finishPen(world, false);
+ return;
+ }
+
+ world.get(HitRegions)!.list.push({
+ target: { kind: 'hud', id: 'pen', quad: rectToQuad(identity2D(), ctx.canvas.width, ctx.canvas.height) },
+ callback: handlePenInteraction,
+ });
+
+ const { vertices } = pen;
+ if (!vertices.length) return;
+
+ const view = getViewMatrix(world);
+ const device = (x: number, y: number) => transformPoint(view, x, y);
+ const pointer = world.get(Pointer)!;
+
+ ctx.save();
+ ctx.resetTransform();
+
+ ctx.beginPath();
+ const first = device(vertices[0]!.x, vertices[0]!.y);
+ ctx.moveTo(first.x, first.y);
+ for (let i = 1; i < vertices.length; i++) {
+ const from = vertices[i - 1]!;
+ const to = vertices[i]!;
+ const c1 = device(from.outX, from.outY);
+ const c2 = device(to.inX, to.inY);
+ const end = device(to.x, to.y);
+ ctx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, end.x, end.y);
+ }
+ if (!pen.drawing) {
+ // Where the next click would put the next vertex.
+ const last = vertices[vertices.length - 1]!;
+ const c1 = device(last.outX, last.outY);
+ ctx.bezierCurveTo(c1.x, c1.y, pointer.clientX, pointer.clientY, pointer.clientX, pointer.clientY);
+ }
+ guide(ctx, res);
+
+ const last = vertices[vertices.length - 1]!;
+ const anchor = device(last.x, last.y);
+ if (last.outX !== last.x || last.outY !== last.y) {
+ handleDot(ctx, anchor, device(last.inX, last.inY), res);
+ handleDot(ctx, anchor, device(last.outX, last.outY), res);
+ }
+
+ const closing = !pen.drawing && vertices.length >= 2 && nearFirstVertex(world, pointer.clientX, pointer.clientY);
+ vertices.forEach((vertex, index) => {
+ vertexDot(ctx, device(vertex.x, vertex.y), res, index === 0 ? closing : index === vertices.length - 1);
+ });
+
+ ctx.restore();
+}
+
+function nearFirstVertex(world: World, clientX: number, clientY: number): boolean {
+ const first = world.get(DrawTool)!.vertices[0];
+ if (!first) return false;
+ const point = transformPoint(getViewMatrix(world), first.x, first.y);
+ return Math.hypot(point.x - clientX, point.y - clientY) <= (HANDLE_HIT / 2) * resolution(world);
+}
+
+/**
+ * A press puts down a vertex (or, on the first one, closes the path), and
+ * dragging it out pulls the vertex's handles: the one ahead of it where the
+ * pointer is, the one behind mirrored through the vertex.
+ */
+export function handlePenInteraction(world: World, event: DispatchedPointerEvent): void {
+ const pen = world.get(DrawTool)!;
+
+ if (event.type === 'dragstart') {
+ if (pen.vertices.length >= 2 && nearFirstVertex(world, event.clientX, event.clientY)) {
+ finishPen(world, true);
+ return;
+ }
+ const point = toDocument(world, event.clientX, event.clientY);
+ if (!pen.vertices.length) world.set(DrawTool, { scene: findSceneAt(world, point.x, point.y) });
+ pen.vertices.push({ x: point.x, y: point.y, inX: point.x, inY: point.y, outX: point.x, outY: point.y });
+ world.set(DrawTool, { drawing: true });
+ return;
+ }
+
+ if (event.type === 'drag' && pen.drawing) {
+ const vertex = pen.vertices[pen.vertices.length - 1];
+ if (!vertex) return;
+ const pointer = world.get(Pointer)!;
+ const moved = Math.hypot(event.clientX - pointer.dragStartX, event.clientY - pointer.dragStartY);
+ if (moved < DRAG_THRESHOLD * resolution(world)) {
+ vertex.inX = vertex.outX = vertex.x;
+ vertex.inY = vertex.outY = vertex.y;
+ return;
+ }
+ const point = toDocument(world, event.clientX, event.clientY);
+ vertex.outX = point.x;
+ vertex.outY = point.y;
+ vertex.inX = 2 * vertex.x - point.x;
+ vertex.inY = 2 * vertex.y - point.y;
+ return;
+ }
+
+ if (event.type === 'dragend') {
+ world.set(DrawTool, { drawing: false });
+ }
+}
+
+/**
+ * Puts the pen's path on the stage, open or `closed`, and picks the move
+ * tool back up with it selected. The path lands in the scene its first vertex
+ * was put down in, its box the outline's bounds. Fewer than two vertices are
+ * no path, and are dropped.
+ */
+export function finishPen(world: World, closed: boolean): void {
+ const { vertices, scene } = world.get(DrawTool)!;
+ world.set(DrawTool, { vertices: [], scene: null, drawing: false });
+ if (world.get(Tool)?.value === ToolType.PEN) world.set(Tool, { value: ToolType.MOVE });
+ if (vertices.length < 2) return;
+
+ const parentScene = scene?.isAlive() ? scene : null;
+ const parent = parentScene ?? world.get(Root)!;
+ // Nothing to draw into until a project is mounted.
+ if (!parent.get(Source)?.value) return;
+
+ const local = (x: number, y: number): [number, number] => {
+ if (parentScene === null) return [x, y];
+ const point = worldToLocal(world, parentScene, x, y);
+ return [point.x, point.y];
+ };
+
+ const points = [...local(vertices[0]!.x, vertices[0]!.y)];
+ const segment = (from: PenVertex, to: PenVertex) => {
+ points.push(...local(from.outX, from.outY), ...local(to.inX, to.inY), ...local(to.x, to.y));
+ };
+ for (let i = 1; i < vertices.length; i++) segment(vertices[i - 1]!, vertices[i]!);
+ if (closed) segment(vertices[vertices.length - 1]!, vertices[0]!);
+
+ const geometry: PathGeometry = { subpaths: [{ closed, points }] };
+ const bounds = pathBounds(geometry);
+ if (bounds === null) return;
+
+ // Whole pixels round the outline, as the runtime keeps a box's size.
+ const x = Math.floor(bounds.minX);
+ const y = Math.floor(bounds.minY);
+ const width = Math.max(1, Math.ceil(bounds.maxX - x));
+ const height = Math.max(1, Math.ceil(bounds.maxY - y));
+ const d = formatPath(transformPath(geometry, { sx: 1, sy: 1, tx: -x, ty: -y }));
+ const name = getNextName(world, 'Path');
+
+ const editor = getDocumentEditor(world);
+ const [entity] = editor.insertElement(parent, () => (
+ <Path name={name} x={x} y={y} width={width} height={height} d={d}>
+ <Stroke color={PEN_STROKE.color} width={PEN_STROKE.width} />
+ </Path>
+ ));
+ if (entity) editor.select(entity);
+}
+
+export function isPenDrawing(world: World): boolean {
+ return world.get(Tool)?.value === ToolType.PEN && world.get(DrawTool)!.vertices.length > 0;
+}
+
+// ── Vertex indices ──────────────────────────────────────────
+//
+// Where a vertex's numbers sit in its subpath's `points` (see `Subpath`):
+// its anchor, which a closed subpath's first vertex has twice (it is also the
+// end of the closing segment), the control point after it (the first of the
+// segment it starts) and the one before it (the second of the segment it ends).
+
+function anchorIndices(subpath: Subpath, vertex: number): number[] {
+ const segments = segmentCount(subpath);
+ if (vertex === 0) return subpath.closed && segments > 0 ? [0, 2 + 6 * (segments - 1) + 4] : [0];
+ return [2 + 6 * (vertex - 1) + 4];
+}
+
+function handleIndex(subpath: Subpath, vertex: number, part: 'in' | 'out'): number {
+ const segments = segmentCount(subpath);
+ if (part === 'out') return vertex < segments ? 2 + 6 * vertex : -1;
+ if (vertex > 0) return 2 + 6 * (vertex - 1) + 2;
+ return subpath.closed && segments > 0 ? 2 + 6 * (segments - 1) + 2 : -1;
+}
+
+function at(points: number[], index: number): Point {
+ return { x: points[index]!, y: points[index + 1]! };
+}
+
+/** The vertices either side of `vertex`, wrapping round a closed subpath; -1 where there is none. */
+function neighbors(subpath: Subpath, vertex: number): [number, number] {
+ const count = vertexCount(subpath);
+ if (subpath.closed) return [(vertex - 1 + count) % count, (vertex + 1) % count];
+ return [vertex - 1, vertex + 1 < count ? vertex + 1 : -1];
+}
+
+/** Whether a vertex's handles point straight away from each other, the way a smooth vertex's do. */
+function isSmooth(subpath: Subpath, vertex: number): boolean {
+ const into = handleIndex(subpath, vertex, 'in');
+ const out = handleIndex(subpath, vertex, 'out');
+ if (into === -1 || out === -1) return false;
+ const anchor = at(subpath.points, anchorIndices(subpath, vertex)[0]!);
+ const a = at(subpath.points, into);
+ const b = at(subpath.points, out);
+ const ax = a.x - anchor.x, ay = a.y - anchor.y;
+ const bx = b.x - anchor.x, by = b.y - anchor.y;
+ const la = Math.hypot(ax, ay), lb = Math.hypot(bx, by);
+ if (la < 1e-6 || lb < 1e-6) return false;
+ return Math.abs(ax * by - ay * bx) / (la * lb) < 0.02 && ax * bx + ay * by < 0;
+}
+
+function hasHandles(subpath: Subpath, vertex: number): boolean {
+ const anchor = at(subpath.points, anchorIndices(subpath, vertex)[0]!);
+ return (['in', 'out'] as const).some((part) => {
+ const index = handleIndex(subpath, vertex, part);
+ if (index === -1) return false;
+ const handle = at(subpath.points, index);
+ return handle.x !== anchor.x || handle.y !== anchor.y;
+ });
+}
+
+function cloneGeometry(geometry: PathGeometry): PathGeometry {
+ return { subpaths: geometry.subpaths.map(({ closed, points }) => ({ closed, points: points.slice() })) };
+}
+
+// ── Editing ─────────────────────────────────────────────────
+
+/** The path being edited, while the editor is up and it can still be edited. */
+function editTarget(world: World): Entity | null {
+ const entity = world.get(PathEditor)?.entity ?? null;
+ if (world.get(Tool)?.value !== ToolType.PATH_EDIT) return null;
+ return entity?.isAlive() && entity.has(Selected) ? entity : null;
+}
+
+/** The one path selected, which Enter would edit; null for any other selection. */
+export function selectedPath(world: World): Entity | null {
+ const selected = [...world.query(Selected)];
+ return selected.length === 1 && isPath(selected[0]!) ? selected[0]! : null;
+}
+
+export function isPathEditing(world: World): boolean {
+ return world.get(Tool)?.value === ToolType.PATH_EDIT;
+}
+
+/** Puts the path editor up on `entity`. */
+export function beginPathEdit(world: World, entity: Entity): void {
+ world.set(PathEditor, { entity, subpath: -1, vertex: -1, held: null, start: null });
+ world.set(Tool, { value: ToolType.PATH_EDIT });
+}
+
+/** Puts the editor down, the box fitted to the outline again, and picks the move tool back up. */
+export function endPathEdit(world: World): void {
+ const entity = world.get(PathEditor)?.entity ?? null;
+ world.set(PathEditor, { entity: null, subpath: -1, vertex: -1, held: null, start: null });
+ if (world.get(Tool)?.value === ToolType.PATH_EDIT) world.set(Tool, { value: ToolType.MOVE });
+ if (entity?.isAlive()) fitPathBox(world, getDocumentEditor(world), entity);
+}
+
+/** The `d`'s coordinates of the path in device pixels. */
+function pathMatrix(world: World, entity: Entity): Mat2D {
+ const { sx, sy, tx, ty } = getPathTransform(world, entity);
+ return multiply2D(entityWorldMat(world, entity), { a: sx, b: 0, c: 0, d: sy, e: tx, f: ty });
+}
+
+/**
+ * While the editor is up: a region over the stage for clicks on the
+ * outline or off it, the outline itself, every vertex, and the handles
+ * around the picked one — its own, and the neighbors' that shape the two
+ * segments it joins. The editor goes down by itself when its path is
+ * deleted or deselected, or when another tool is picked (the hand only
+ * borrows the stage).
+ */
+export function drawPathEditor(world: World, ctx: Ctx2D, res: number): void {
+ const state = world.get(PathEditor)!;
+ const tool = world.get(Tool)?.value;
+ if (state.entity !== null && tool !== ToolType.HAND && editTarget(world) === null) {
+ endPathEdit(world);
+ return;
+ }
+ const entity = editTarget(world);
+ if (entity === null) return;
+
+ const regions = world.get(HitRegions)!.list;
+ regions.push({
+ target: { kind: 'hud', id: 'path-edit', entity, quad: rectToQuad(identity2D(), ctx.canvas.width, ctx.canvas.height) },
+ callback: handlePathEditInteraction,
+ });
+
+ const geometry = getPathGeometry(world, entity);
+ if (geometry === null) return;
+
+ const mat = pathMatrix(world, entity);
+ const device = (point: Point) => transformPoint(mat, point.x, point.y);
+
+ ctx.save();
+ ctx.setTransform(mat.a, mat.b, mat.c, mat.d, mat.e, mat.f);
+ ctx.beginPath();
+ for (const { closed, points } of geometry.subpaths) {
+ ctx.moveTo(points[0]!, points[1]!);
+ for (let o = 2; o < points.length; o += 6) {
+ ctx.bezierCurveTo(points[o]!, points[o + 1]!, points[o + 2]!, points[o + 3]!, points[o + 4]!, points[o + 5]!);
+ }
+ if (closed) ctx.closePath();
+ }
+ ctx.resetTransform();
+ guide(ctx, res);
+
+ const push = (id: string, point: Point) => {
+ regions.push({ target: { kind: 'hud', id, entity, quad: hitQuad(point, res) }, callback: handlePathEditInteraction });
+ };
+
+ // The picked vertex's handles, and the neighbors' facing it.
+ const picked = geometry.subpaths[state.subpath];
+ if (picked && state.vertex >= 0 && state.vertex < vertexCount(picked)) {
+ const [previous, next] = neighbors(picked, state.vertex);
+ const shown: [number, 'in' | 'out'][] = [[state.vertex, 'in'], [state.vertex, 'out']];
+ if (previous !== -1) shown.push([previous, 'out']);
+ if (next !== -1) shown.push([next, 'in']);
+ for (const [vertex, part] of shown) {
+ const index = handleIndex(picked, vertex, part);
+ if (index === -1) continue;
+ const anchor = device(at(picked.points, anchorIndices(picked, vertex)[0]!));
+ const handle = device(at(picked.points, index));
+ if (Math.hypot(handle.x - anchor.x, handle.y - anchor.y) < 0.5 * res) continue;
+ handleDot(ctx, anchor, handle, res);
+ push(`${part}:${state.subpath}:${vertex}`, handle);
+ }
+ }
+
+ geometry.subpaths.forEach((subpath, s) => {
+ for (let v = 0; v < vertexCount(subpath); v++) {
+ const point = device(at(subpath.points, anchorIndices(subpath, v)[0]!));
+ vertexDot(ctx, point, res, s === state.subpath && v === state.vertex);
+ push(`anchor:${s}:${v}`, point);
+ }
+ });
+
+ ctx.restore();
+}
+
+/** The pointer in the edited path's `d` coordinates. */
+function pointerInPath(world: World, entity: Entity, clientX: number, clientY: number): Point {
+ return transformPoint(invert2D(pathMatrix(world, entity)), clientX, clientY);
+}
+
+function parsePart(id: string): { part: PathPart; subpath: number; vertex: number } | null {
+ const [part, subpath, vertex] = id.split(':');
+ if (part !== 'anchor' && part !== 'in' && part !== 'out') return null;
+ return { part, subpath: Number(subpath), vertex: Number(vertex) };
+}
+
+/**
+ * Presses in the editor: on a vertex or a handle, picking it up to drag
+ * (double-click a vertex to turn it corner or smooth); on the outline, a
+ * new vertex there; inside the path, nothing picked; anywhere else, the
+ * editor goes down.
+ */
+export function handlePathEditInteraction(world: World, event: DispatchedPointerEvent): void {
+ if (event.target.kind !== 'hud') return;
+ const entity = editTarget(world);
+ if (entity === null) return;
+ const editor = getDocumentEditor(world);
+
+ if (event.target.id === 'path-edit') {
+ if (event.type !== 'click') return;
+ const geometry = getPathGeometry(world, entity);
+ const point = pointerInPath(world, entity, event.clientX, event.clientY);
+ const nearest = geometry && nearestOnPath(geometry, point.x, point.y);
+ if (geometry && nearest) {
+ const on = transformPoint(pathMatrix(world, entity), ...xy(pointOnPath(geometry, nearest.subpath, nearest.segment, nearest.t)));
+ if (Math.hypot(on.x - event.clientX, on.y - event.clientY) <= OUTLINE_HIT * resolution(world)) {
+ insertVertex(world, editor, entity, nearest.subpath, nearest.segment, nearest.t);
+ world.set(PathEditor, { subpath: nearest.subpath, vertex: nearest.segment + 1 });
+ return;
+ }
+ if (pointInPath(geometry, point.x, point.y)) {
+ world.set(PathEditor, { subpath: -1, vertex: -1 });
+ return;
+ }
+ }
+ endPathEdit(world);
+ return;
+ }
+
+ const hit = parsePart(event.target.id);
+ if (hit === null) return;
+
+ if (event.type === 'dragstart') {
+ const geometry = getPathGeometry(world, entity);
+ if (geometry === null) return;
+ const origin = pointerInPath(world, entity, event.clientX, event.clientY);
+ // A vertex pressed is picked; a handle pressed may be a neighbor's,
+ // and the picked vertex stays the one whose handles are showing.
+ world.set(PathEditor, {
+ subpath: hit.subpath,
+ vertex: hit.part === 'anchor' ? hit.vertex : world.get(PathEditor)!.vertex,
+ held: hit.part,
+ heldVertex: hit.vertex,
+ start: cloneGeometry(geometry),
+ originX: origin.x,
+ originY: origin.y,
+ });
+ return;
+ }
+
+ if (event.type === 'drag') {
+ const state = world.get(PathEditor)!;
+ if (state.held === null || state.start === null) return;
+ const point = pointerInPath(world, entity, event.clientX, event.clientY);
+ const independent = world.get(Keys)?.held.has('alt') ?? false;
+ const next = moveVertexPart(state.start, state.subpath, state.heldVertex, state.held, point.x - state.originX, point.y - state.originY, independent);
+ writeOutline(world, editor, entity, next);
+ return;
+ }
+
+ if (event.type === 'dragend') {
+ world.set(PathEditor, { held: null, start: null });
+ return;
+ }
+
+ if (event.type === 'dblclick' && hit.part === 'anchor') {
+ const geometry = getPathGeometry(world, entity);
+ if (geometry === null) return;
+ writeOutline(world, editor, entity, toggleSmooth(geometry, hit.subpath, hit.vertex));
+ }
+}
+
+function xy(point: Point): [number, number] {
+ return [point.x, point.y];
+}
+
+/**
+ * `geometry` with one part of a vertex moved by (dx, dy): the vertex with
+ * both its handles, or one handle. A smooth vertex's other handle turns to
+ * stay opposite, keeping its length, unless `independent` (Alt) breaks them.
+ */
+function moveVertexPart(geometry: PathGeometry, s: number, vertex: number, part: PathPart, dx: number, dy: number, independent: boolean): PathGeometry {
+ const next = cloneGeometry(geometry);
+ const subpath = next.subpaths[s];
+ if (!subpath) return geometry;
+ const { points } = subpath;
+ const original = geometry.subpaths[s]!;
+
+ if (part === 'anchor') {
+ const moved = [...anchorIndices(subpath, vertex), handleIndex(subpath, vertex, 'in'), handleIndex(subpath, vertex, 'out')];
+ for (const index of moved) {
+ if (index === -1) continue;
+ points[index] = original.points[index]! + dx;
+ points[index + 1] = original.points[index + 1]! + dy;
+ }
+ return next;
+ }
+
+ const index = handleIndex(subpath, vertex, part);
+ if (index === -1) return geometry;
+ points[index] = original.points[index]! + dx;
+ points[index + 1] = original.points[index + 1]! + dy;
+
+ const opposite = handleIndex(subpath, vertex, part === 'in' ? 'out' : 'in');
+ if (!independent && opposite !== -1 && isSmooth(original, vertex)) {
+ const anchor = at(points, anchorIndices(subpath, vertex)[0]!);
+ const length = Math.hypot(points[opposite]! - anchor.x, points[opposite + 1]! - anchor.y);
+ const hx = points[index]! - anchor.x;
+ const hy = points[index + 1]! - anchor.y;
+ const handleLength = Math.hypot(hx, hy);
+ if (handleLength > 1e-6) {
+ points[opposite] = anchor.x - (hx / handleLength) * length;
+ points[opposite + 1] = anchor.y - (hy / handleLength) * length;
+ }
+ }
+ return next;
+}
+
+/**
+ * `geometry` with a vertex turned: a vertex with handles loses them (a
+ * corner), one without gets a pair along the line between its neighbors (smooth).
+ */
+function toggleSmooth(geometry: PathGeometry, s: number, vertex: number): PathGeometry {
+ const next = cloneGeometry(geometry);
+ const subpath = next.subpaths[s];
+ if (!subpath) return geometry;
+ const { points } = subpath;
+ const anchor = at(points, anchorIndices(subpath, vertex)[0]!);
+ const into = handleIndex(subpath, vertex, 'in');
+ const out = handleIndex(subpath, vertex, 'out');
+
+ if (hasHandles(subpath, vertex)) {
+ for (const index of [into, out]) {
+ if (index === -1) continue;
+ points[index] = anchor.x;
+ points[index + 1] = anchor.y;
+ }
+ return next;
+ }
+
+ const [previous, following] = neighbors(subpath, vertex);
+ const before = previous === -1 ? anchor : at(points, anchorIndices(subpath, previous)[0]!);
+ const after = following === -1 ? anchor : at(points, anchorIndices(subpath, following)[0]!);
+ const tx = (after.x - before.x) * SMOOTH_HANDLE;
+ const ty = (after.y - before.y) * SMOOTH_HANDLE;
+ if (into !== -1) {
+ points[into] = anchor.x - tx;
+ points[into + 1] = anchor.y - ty;
+ }
+ if (out !== -1) {
+ points[out] = anchor.x + tx;
+ points[out + 1] = anchor.y + ty;
+ }
+ return next;
+}
+
+/**
+ * Writes an outline the editor changed: the `d` and, when the path is
+ * keyframed, the keyframe at the playhead, which the motion system would
+ * otherwise put back on the next frame (see `editTransform`).
+ */
+function writeOutline(world: World, editor: DocumentEditor, entity: Entity, geometry: PathGeometry): void {
+ const d = formatPath(geometry);
+ syncKeyframe(world, editor, entity, 'd', d);
+ editor.editProperty(entity, 'd', d);
+}
+
+/**
+ * Applies a change of vertices to every outline the path has: its `d` and
+ * each of its `d` keyframes, so they all keep the same vertices and still
+ * morph into each other.
+ */
+function editEveryOutline(world: World, editor: DocumentEditor, entity: Entity, change: (geometry: PathGeometry) => PathGeometry): void {
+ const authored = entity.get(VectorPath)?.geometry;
+ if (authored) editor.editProperty(entity, 'd', formatPath(change(authored)));
+
+ const track = findKeyframeTrack(world, entity, 'd');
+ for (const keyframe of track?.get(Cache)?.keyframes ?? []) {
+ const path = keyframe.get(Keyframe)?.path;
+ if (path) editor.editProperty(keyframe, 'value', formatPath(change(path)));
+ }
+}
+
+function changeSubpath(s: number, change: (subpath: Subpath) => Subpath) {
+ return (geometry: PathGeometry): PathGeometry => ({
+ subpaths: geometry.subpaths.map((subpath, index) => (index === s ? change(subpath) : subpath)),
+ });
+}
+
+/** Adds a vertex `t` along a segment, in every outline the path has. */
+function insertVertex(world: World, editor: DocumentEditor, entity: Entity, s: number, segment: number, t: number): void {
+ editEveryOutline(world, editor, entity, changeSubpath(s, (subpath) => splitSegment(subpath, segment, t)));
+}
+
+/** Takes the picked vertex out of every outline the path has; false when none is picked. */
+export function deletePickedVertex(world: World): boolean {
+ const entity = editTarget(world);
+ const { subpath, vertex } = world.get(PathEditor)!;
+ if (entity === null || subpath < 0 || vertex < 0) return false;
+ editEveryOutline(world, getDocumentEditor(world), entity, changeSubpath(subpath, (path) => removeVertex(path, vertex)));
+ world.set(PathEditor, { subpath: -1, vertex: -1 });
+ return true;
+}
+
+// ── Viewbox and box ─────────────────────────────────────────
+
+/** A number as the box props spell it. */
+const round2 = (value: number): number => Math.round(value * 100) / 100;
+
+/**
+ * Pins a path's `d` to the box it has, so the resize about to happen
+ * stretches the outline instead of leaving it where it is: a path without a
+ * `viewBox` is drawn in its box's pixels, and once its box changes size the
+ * viewBox is what says what those pixels were. Nothing to do for a path that
+ * has one, or for anything that is not a path.
+ */
+export function pinViewBox(world: World, editor: DocumentEditor, entity: Entity): void {
+ if (!isPath(entity) || entity.has(ViewBox)) return;
+ const computed = store(world, Computed);
+ const width = computed.width[entity.id()] ?? 0;
+ const height = computed.height[entity.id()] ?? 0;
+ if (width <= 0 || height <= 0) return;
+ editor.editProperty(entity, 'viewBox', `0 0 ${round2(width)} ${round2(height)}`);
+}
+
+/** The transform props whose keyframes a fitted box would have to move as well. */
+const BOX_TRACKS = ['x', 'y', 'width', 'height', 'rotation', 'scale', 'scaleX', 'scaleY'] as const;
+
+/**
+ * Fits the path's box to its outline, as Figma does once a vector's
+ * vertices are edited: the outline of every keyframe at once, in the box's
+ * own pixels, the `viewBox` folded into the `d`s, and the box moved so
+ * nothing moves on the canvas. Left as it is while any of the box's own
+ * props is keyframed, which a move of the box would have to rewrite too.
+ */
+export function fitPathBox(world: World, editor: DocumentEditor, entity: Entity): void {
+ if (!isPath(entity)) return;
+ if (BOX_TRACKS.some((property) => findKeyframeTrack(world, entity, property) !== null)) return;
+
+ const authored = entity.get(VectorPath)?.geometry ?? null;
+ const track = findKeyframeTrack(world, entity, 'd');
+ const keyframes = (track?.get(Cache)?.keyframes ?? []).filter((keyframe) => keyframe.get(Keyframe)?.path);
+ const transform = getPathTransform(world, entity);
+ const inBox = (geometry: PathGeometry) => transformPath(geometry, transform);
+
+ const outlines = [authored, ...keyframes.map((keyframe) => keyframe.get(Keyframe)!.path)].filter((geometry): geometry is PathGeometry => geometry != null);
+ const bounds = unionPathBounds(outlines.map(inBox));
+ if (bounds === null) return;
+
+ const computed = store(world, Computed);
+ const eid = entity.id();
+ const oldWidth = computed.width[eid] ?? 0;
+ const oldHeight = computed.height[eid] ?? 0;
+ // A box's size is whole pixels to the runtime, so the box rounds the outline up.
+ const width = Math.max(1, Math.ceil(bounds.maxX - bounds.minX - 0.005));
+ const height = Math.max(1, Math.ceil(bounds.maxY - bounds.minY - 0.005));
+ const shiftX = bounds.minX;
+ const shiftY = bounds.minY;
+ const tight = !entity.has(ViewBox) && Math.abs(shiftX) < 0.005 && Math.abs(shiftY) < 0.005
+ && Math.abs(width - oldWidth) < 0.005 && Math.abs(height - oldHeight) < 0.005;
+ if (tight) return;
+
+ // The box's position moves by the shift as its linear part takes it, the
+ // pivot (anchor × size) moving with the new size: L(p) = pos + pivot + A(p − pivot).
+ const anchor = entityAnchor(world, entity);
+ const local = store(world, LocalTransform);
+ const a = local.a[eid]!, b = local.b[eid]!, c = local.c[eid]!, d = local.d[eid]!;
+ const pivotX = anchor.x * (width - oldWidth);
+ const pivotY = anchor.y * (height - oldHeight);
+ const vx = shiftX + pivotX;
+ const vy = shiftY + pivotY;
+ const position = entity.get(Position) ?? { x: 0, y: 0 };
+ const x = round2(position.x - pivotX + a * vx + c * vy);
+ const y = round2(position.y - pivotY + b * vx + d * vy);
+
+ const shift = { sx: transform.sx, sy: transform.sy, tx: transform.tx - shiftX, ty: transform.ty - shiftY };
+ editor.editProperty(entity, 'viewBox', false);
+ if (authored) editor.editProperty(entity, 'd', formatPath(transformPath(authored, shift)));
+ for (const keyframe of keyframes) {
+ editor.editProperty(keyframe, 'value', formatPath(transformPath(keyframe.get(Keyframe)!.path!, shift)));
+ }
+
+ const writes: TransformWrite[] = [['width', width], ['height', height], ['x', x], ['y', y]];
+ editTransform(world, editor, entity, writes);
+}
diff --git a/apps/web/src/engine/timeline/style.ts b/apps/web/src/engine/timeline/style.ts
index b8050b29..7addb173 100644
--- a/apps/web/src/engine/timeline/style.ts
+++ b/apps/web/src/engine/timeline/style.ts
@@ -12,6 +12,7 @@ import {
isGroup,
isClipPath,
isEllipse,
+ isPath,
isPolygon,
isRect,
isScene,
@@ -89,6 +90,7 @@ export function getClipFallbackName(world: World, entity: Entity): string {
if (isEllipse(entity)) return 'Ellipse';
if (isPolygon(entity)) return 'Polygon';
+ if (isPath(entity)) return 'Path';
return isRect(entity) ? 'Rectangle' : 'Layer';
}
diff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.ts
index 3a708fa3..3cb606dd 100644
--- a/apps/web/src/engine/traits.ts
+++ b/apps/web/src/engine/traits.ts
@@ -11,9 +11,10 @@
import { trait } from 'koota';
-import type { CanvasPointerEvent, Point } from '@diffusionstudio/runtime';
+import type { CanvasPointerEvent, PathGeometry, Point } from '@diffusionstudio/runtime';
import type { Entity } from 'koota';
import type { GradientHandle } from './gradient-tool';
+import type { PathPart, PenVertex } from './path-tool';
import type { ObjectMaskMode, ObjectMaskOp } from './object-mask/store';
import type { ProjectConfig as ProjectConfigStore } from './project-config';
@@ -102,13 +103,37 @@ export const GradientTool = trait({
});
/**
- * A box being drawn by the rect, scene or text tool: whether a press is
- * drawing one, and the scene it landed in, which the new node goes into.
- * The box itself is the pointer's, from where the press began to where it is.
+ * A node being drawn: whether a press is drawing, and the scene the first
+ * press landed in, which the new node goes into. For the rect, ellipse,
+ * polygon, scene and text tools the press is the whole gesture, and the box
+ * is the pointer's, from where it began to where it is. The pen takes a
+ * press per vertex, so it also keeps the `vertices` put down so far, in
+ * document space; `drawing` is then whether the press that placed the last
+ * one is still down, pulling out its handles.
*/
export const DrawTool = trait({
drawing: false,
scene: null as Entity | null,
+ vertices: () => [] as PenVertex[],
+});
+
+/**
+ * The path whose vertices are being edited, null while none is. `subpath`
+ * and `vertex` are the vertex picked (-1 for none). While a press holds a
+ * vertex or a handle, `held` is which part, `heldVertex` whose (a handle can
+ * be a neighbor's of the picked vertex), `start` the outline as the press
+ * found it and `originX`/`originY` where it went down, in the `d`'s
+ * coordinates.
+ */
+export const PathEditor = trait({
+ entity: null as Entity | null,
+ subpath: -1,
+ vertex: -1,
+ held: null as PathPart | null,
+ heldVertex: -1,
+ start: () => null as PathGeometry | null,
+ originX: 0,
+ originY: 0,
});
/**
diff --git a/docs/reference/jsx/README.md b/docs/reference/jsx/README.md
index 42ee8d22..b4dbd09f 100644
--- a/docs/reference/jsx/README.md
+++ b/docs/reference/jsx/README.md
@@ -33,7 +33,7 @@ export default function Project() {
| [stage.md](./stage.md) | `<stage>`: the root, canvas background and camera, canvas placement |
| [scene.md](./scene.md) | `<scene>`: the clipped, playable frame and the timeline its children sit on |
| [elements.md](./elements.md) | Element-to-node mapping, coordinates and sizing, the shared property table |
-| [group.md](./group.md), [rect.md](./rect.md), [ellipse.md](./ellipse.md), [polygon.md](./polygon.md), [text.md](./text.md), [video.md](./video.md), [image.md](./image.md), [audio.md](./audio.md) | Per-element props |
+| [group.md](./group.md), [rect.md](./rect.md), [ellipse.md](./ellipse.md), [polygon.md](./polygon.md), [path.md](./path.md), [text.md](./text.md), [video.md](./video.md), [image.md](./image.md), [audio.md](./audio.md) | Per-element props |
| [fonts.md](./fonts.md) | Fonts for `<text>` and HTML: local families, the `fonts` tool |
| [paints.md](./paints.md) | `<solidPaint>`, gradients, `<colorStop>`, `<imagePaint>` / `<videoPaint>` |
| [styles.md](./styles.md) | `<stroke>`, `<shadow>`, `<effect>`: outlines, drop shadows and filters |
diff --git a/docs/reference/jsx/elements.md b/docs/reference/jsx/elements.md
index 803c049c..bf0493cd 100644
--- a/docs/reference/jsx/elements.md
+++ b/docs/reference/jsx/elements.md
@@ -18,6 +18,7 @@ camelCase composition elements map 1:1 onto entities. Lowercase DOM vocabulary i
| [`<rect>`](./rect.md) | A rectangle. Takes paints, strokes, shadows and effects. With `clipPath` it clips its parent instead of drawing. |
| [`<ellipse>`](./ellipse.md) | An ellipse inscribed in its box. Takes what a rect takes. |
| [`<polygon>`](./polygon.md) | A regular polygon (`pointCount` corners, a triangle by default) stretched to fill its box. Takes what a rect takes. |
+| [`<path>`](./path.md) | A vector outline from SVG path data (`d`), in its box's pixels or stretched from a `viewBox`; morphs between keyframes and trims. Takes what a rect takes. |
| [`<text>`](./text.md) | Text; its children are the glyphs. Sizes itself to them unless given a box. |
| [`<textRange>`](./text.md#textrange) | A style override over a run of the parent `<text>`'s glyphs, by character index. |
| [`<video>`](./video.md) | A video clip: a rect whose intrinsic paint is the media `src` names. |
@@ -67,7 +68,7 @@ User-defined components are ordinary Solid components; they compose the elements
| ------- | ----------- |
| `<video>`, `<image>`, `<adjustmentLayer>` | 1920 × 1080 |
| `<scene>` | required — the frame's own size |
-| `<rect>`, `<ellipse>`, `<polygon>`, `<html>`, `<surface>` | 100 × 100 |
+| `<rect>`, `<ellipse>`, `<polygon>`, `<path>`, `<html>`, `<surface>` | 100 × 100 |
| `<audio>` | 500 × 150 (the waveform box on the canvas) |
| `<rect clipPath>` | 500 × 500 |
| `<text>` | fits its glyphs |
diff --git a/docs/reference/jsx/keyframes.md b/docs/reference/jsx/keyframes.md
index 03f05bcb..414647b1 100644
--- a/docs/reference/jsx/keyframes.md
+++ b/docs/reference/jsx/keyframes.md
@@ -18,9 +18,9 @@ A `<keyframeTrack>` animates one prop of the element holding it over the node's
| Element | Props | Meaning |
| ------- | ----- | ------- |
| `<keyframeTrack>` | `property` (**required**) | The prop of the holding element it drives, by name. One track per prop. |
-| `<keyframe>` | `time` (**required**), `value` (**required**), `easing` | One keyframe: source-local time in any [time format](./timing.md#time-formats), the value at that time (a number, or any CSS color on a `color` track), and the easing into the next keyframe. |
+| `<keyframe>` | `time` (**required**), `value` (**required**), `easing` | One keyframe: source-local time in any [time format](./timing.md#time-formats), the value at that time (a number, any CSS color on a `color` track, or path data on a `d` track), and the easing into the next keyframe. |
-Animatable props (`property`): `x`, `y`, `offsetX`, `offsetY`, `width`, `height`, `rotation`, `scale`, `scaleX`, `scaleY`, `opacity`, `cornerRadius`, `cornerRadiusTopLeft`, `cornerRadiusTopRight`, `cornerRadiusBottomRight`, `cornerRadiusBottomLeft`, `volume`, `color`, `offset`, `blur`, `value`. Whose prop is the track's holder's: a track under a [paint or color stop](./paints.md) animates the paint (`color`, `opacity`, `offset`), and one under a [`<stroke>`, `<shadow>` or `<effect>`](./styles.md) that style's own — `width` is a stroke's line width, `blur`/`offsetX`/`offsetY` a shadow's, `value` an effect's amount. For preset in/out effects (fade, slides, text reveals, ...) use [`<animation>`](./animations.md) instead.
+Animatable props (`property`): `x`, `y`, `offsetX`, `offsetY`, `width`, `height`, `rotation`, `scale`, `scaleX`, `scaleY`, `opacity`, `cornerRadius`, `cornerRadiusTopLeft`, `cornerRadiusTopRight`, `cornerRadiusBottomRight`, `cornerRadiusBottomLeft`, `volume`, `color`, `offset`, `blur`, `value`, and on a [`<path>`](./path.md) `d`, `trimStart`, `trimEnd`, `trimOffset`. Whose prop is the track's holder's: a track under a [paint or color stop](./paints.md) animates the paint (`color`, `opacity`, `offset`), and one under a [`<stroke>`, `<shadow>` or `<effect>`](./styles.md) that style's own — `width` is a stroke's line width, `blur`/`offsetX`/`offsetY` a shadow's, `value` an effect's amount. A `d` track morphs a path's outline from one keyframe's path data to the next (see [path.md](./path.md#animating-the-outline)). For preset in/out effects (fade, slides, text reveals, ...) use [`<animation>`](./animations.md) instead.
## Semantics
diff --git a/docs/reference/jsx/path.md b/docs/reference/jsx/path.md
new file mode 100644
index 00000000..6027dc25
--- /dev/null
+++ b/docs/reference/jsx/path.md
@@ -0,0 +1,78 @@
+# `<path>`
+
+A vector outline from SVG path data: any number of subpaths, open or closed, of straight and curved segments. Takes the same children as [`<rect>`](./rect.md): [paint children](./paints.md), plus [`<stroke>`, `<shadow>`, `<effect>`](./styles.md), [`<animation>`](./animations.md) and [`<keyframeTrack>`](./keyframes.md).
+
+```tsx
+<path x={420} y={180} width={320} height={240} fill="#FF0055"
+ d="M0 240 C80 0 240 0 320 240 Z">
+ <stroke color="#000000" width={6} join="round" cap="round" />
+</path>
+```
+
+## Props
+
+All [common props](./elements.md#common-props), plus:
+
+| Prop | Type | Default | Meaning |
+| ---- | ---- | ------- | ------- |
+| `d` | `string` | none | SVG path data. Every command is read, absolute and relative: `M` `L` `H` `V` `C` `S` `Q` `T` `A` `Z`. Without it the path draws nothing. |
+| `viewBox` | `string` | `"0 0 width height"` | The rectangle of `d`'s coordinates the box shows, `"x y width height"`, stretched onto the box on each axis. |
+| `fillRule` | `"nonzero" \| "evenodd"` | `"nonzero"` | What counts as inside where the outline crosses itself or one subpath sits inside another. `"evenodd"` always cuts a hole; `"nonzero"` only cuts one drawn the other way round from its outline. |
+| `trimStart`, `trimEnd` | `number` | `0`, `1` | Draw only the part of each subpath between these two fractions of its length (After Effects' Trim Paths). The part that is left is also what is filled and picked up on the canvas. |
+| `trimOffset` | `number` | `0` | Slides the trimmed part along the path, as a fraction of its length. It wraps, so `1` is once round: across the start of a closed subpath, into a second piece on an open one. |
+| `fill` | `string` | none | Any CSS color; alpha is ignored (use `opacity`). Shorthand for a solid paint child, drawn beneath any paint children. |
+| `clipPath` | `boolean` | `false` | Makes the path a clip path of its parent instead of a drawn shape: the parent shows only inside its outline. Works like [`<rect clipPath>`](./rect.md#clip-paths); a keyframed `d` on one is an animated mask. |
+
+A `d` that does not parse draws what came before the error, as SVG does, and the error is logged. Without `width`/`height` a path's box is 100×100. A fill closes open subpaths with a straight line; a [`<stroke>`](./styles.md#stroke) does not, and ends them with its `cap`.
+
+## Coordinates and the box
+
+`d` is in the box's own pixels, `0 0` at its top-left, unless a `viewBox` says otherwise. With a `viewBox`, `d` is drawn from that rectangle and stretched to fill the box on each axis (SVG's `preserveAspectRatio="none"`), so resizing the box resizes the outline without `d` changing, and a `width`/`height` keyframe stretches the path. Strokes are not stretched: a 6 px stroke stays 6 px wide.
+
+The editor keeps the two in step the way Figma does. Resizing a path's box writes a `viewBox` holding the size the box had, and leaves `d` alone. Editing its vertices on the canvas folds the `viewBox` back into `d` once you are done, and fits the box to the outline again (to every keyframe's outline, for a keyframed path). The box is left as it is while one of its own props (`x`, `y`, `width`, `height`, `rotation`, `scale`) is keyframed.
+
+The editor writes `d` back as absolute `M`/`L`/`C`/`Z`, with coordinates rounded to two decimals: arcs and quadratics come back as the cubic curves they are drawn with.
+
+## Animating the outline
+
+A `d` [keyframe track](./keyframes.md) morphs the outline: each keyframe's `value` is path data, and every anchor and control point moves in a straight line from one keyframe to the next, eased like any other track.
+
+```tsx
+<path x={420} y={180} width={320} height={240} fill="#FF0055"
+ d="M0 240 C80 0 240 0 320 240 Z">
+ <keyframeTrack property="d">
+ <keyframe time={0} value="M0 240 C80 0 240 0 320 240 Z" easing="easeInOut" />
+ <keyframe time={1} value="M0 120 C80 240 240 240 320 120 Z" />
+ </keyframeTrack>
+</path>
+```
+
+- Vertices pair up in order, each subpath's `M` with the other keyframe's. To change which vertex goes where, start the subpath at a different vertex.
+- Subpaths with different numbers of vertices still morph: the one with fewer is subdivided, its longest segments split in half until the counts match.
+- A different number of subpaths, or an open subpath against a closed one, does not morph. The outline holds until the next keyframe and then jumps.
+- A spring easing that overshoots carries the outline past the keyframe and back.
+
+In the inspector, the diamond in the Path section's header keys the outline at the playhead, which is how a path's animation is started. Click it again on a keyframe to remove that keyframe. When you edit a keyframed path on the canvas, a moved vertex or handle is keyed at the playhead. A vertex added or deleted is added to or deleted from every keyframe, so the keyframes keep matching.
+
+`trimStart`, `trimEnd` and `trimOffset` take keyframe tracks as numbers do. Keying `trimEnd` from `0` to `1` draws a line on:
+
+```tsx
+<path width={600} height={200} d="M0 100 C150 0 450 200 600 100">
+ <stroke color="#FFFFFF" width={8} cap="round" />
+ <keyframeTrack property="trimEnd">
+ <keyframe time={0} value={0} easing="easeOut" />
+ <keyframe time={1.2} value={1} />
+ </keyframeTrack>
+</path>
+```
+
+## On the canvas
+
+- **Pen (P)** draws a new path one vertex at a time. Click to place a corner; drag to place a smooth vertex and pull out its handles. Click the first vertex to close the path; press Enter or Esc to leave it open. The path lands in the scene its first vertex was placed in, with a stroke and a box fitted to it.
+- **Edit (Enter, or double-click a path)** shows the vertices:
+ - Drag a vertex, or one of the picked vertex's handles. A smooth vertex's other handle turns with it; hold Alt to move one handle on its own.
+ - Double-click a vertex to turn it into a corner or make it smooth.
+ - Click on the outline to add a vertex there.
+ - Delete or Backspace removes the picked vertex.
+ - Enter, Esc or a click away from the path finishes editing.
+- A click picks up a path inside what it fills, or within reach of its outline (its widest stroke, plus a few pixels), so open unfilled paths can be picked up too.
diff --git a/docs/reference/jsx/rect.md b/docs/reference/jsx/rect.md
index 847a558a..63ee3bab 100644
--- a/docs/reference/jsx/rect.md
+++ b/docs/reference/jsx/rect.md
@@ -19,7 +19,7 @@ A rect with neither `fill` nor a paint child draws nothing; it is still a box: i
## Clip paths
-A `<rect clipPath>` clips the element holding it instead of drawing: the parent's fills, strokes, shadows and children show only inside the rect's box. [`<ellipse clipPath>`](./ellipse.md) and [`<polygon clipPath>`](./polygon.md) work the same way and clip to their curve or outline; everything below applies to them too. It is still a rect — same coordinates, `cornerRadius`, transform and timing — so it can be moved, rotated, keyframed and animated independently of what it clips: a clip path whose `width` is keyframed across a text is a wipe, one that starts later than its parent is a reveal.
+A `<rect clipPath>` clips the element holding it instead of drawing: the parent's fills, strokes, shadows and children show only inside the rect's box. [`<ellipse clipPath>`](./ellipse.md), [`<polygon clipPath>`](./polygon.md) and [`<path clipPath>`](./path.md) work the same way and clip to their curve or outline; everything below applies to them too. It is still a rect — same coordinates, `cornerRadius`, transform and timing — so it can be moved, rotated, keyframed and animated independently of what it clips: a clip path whose `width` is keyframed across a text is a wipe, one that starts later than its parent is a reveal.
```tsx
<text fontSize={120} color="#FFFFFF" textAlign="center" textBaseline="middle">
diff --git a/docs/reference/jsx/styles.md b/docs/reference/jsx/styles.md
index 40a82a34..1b5b56a7 100644
--- a/docs/reference/jsx/styles.md
+++ b/docs/reference/jsx/styles.md
@@ -12,14 +12,14 @@ Three sub-entity children a node takes alongside its [paints](./paints.md): an o
## `<stroke>`
-An outline of the parent's shape (its box, or the curve of an `<ellipse>`, the corners of a `<polygon>`) — or of its glyphs, on a `<text>` or a `<textRange>`. `color` is its paint, the rest its line style.
+An outline of the parent's shape (its box, or the curve of an `<ellipse>`, the corners of a `<polygon>`, the outline of a `<path>`) — or of its glyphs, on a `<text>` or a `<textRange>`. `color` is its paint, the rest its line style.
| Prop | Type | Default | Meaning |
| ---- | ---- | ------- | ------- |
| `color` | `string` | none | Any CSS color; alpha is ignored (use `opacity`). Without it the stroke is drawn by its paint children alone. |
| `width` | `number` | `1` | Line width, px. A `width` [keyframe track](./keyframes.md) under a stroke drives this, not a box. |
| `join` | `"miter" \| "round" \| "bevel"` | `"miter"` | How the stroke turns corners. |
-| `cap` | `"butt" \| "round" \| "square"` | `"butt"` | How the stroke ends open paths (text glyphs). |
+| `cap` | `"butt" \| "round" \| "square"` | `"butt"` | How the stroke ends open paths (text glyphs, open subpaths of a [`<path>`](./path.md)). |
| `miterLimit` | `number` | `10` | Miter length limit, as a ratio of the width. |
| `opacity` | `number` | `1` | `0`–`1`, over `color` and every paint child. |
| `blendMode` | `BlendMode` | `"sourceOver"` | How the stroke composites. |
diff --git a/packages/jsx/src/index.ts b/packages/jsx/src/index.ts
index 6d6c940a..f2428b2a 100644
--- a/packages/jsx/src/index.ts
+++ b/packages/jsx/src/index.ts
@@ -43,6 +43,7 @@ export type {
EffectProps,
MaskProps,
EffectType,
+ FillRule,
Fit,
GradientPaintProps,
LinearGradientPaintProps,
@@ -57,6 +58,7 @@ export type {
KeyframeProps,
KeyframeTrackProps,
MediaPaintProps,
+ PathProps,
PolygonProps,
RectProps,
SceneNode,
diff --git a/packages/jsx/src/jsx-runtime.ts b/packages/jsx/src/jsx-runtime.ts
index a1b83cb0..03eb88cc 100644
--- a/packages/jsx/src/jsx-runtime.ts
+++ b/packages/jsx/src/jsx-runtime.ts
@@ -38,6 +38,7 @@ import type {
ImageProps,
KeyframeProps,
KeyframeTrackProps,
+ PathProps,
PolygonProps,
RectProps,
SceneProps,
@@ -68,7 +69,7 @@ type HtmlElementTags = Omit<SolidJSX.HTMLElementTags, "canvas" | "audio" | "vide
type ImgTag = Omit<SolidJSX.HTMLElementTags["img"], "src"> & { src?: string };
// The shared names are re-declared below as unions with the composition props.
-type SvgElementTags = Omit<SolidJSX.SVGElementTags, "rect" | "ellipse" | "polygon" | "text" | "image">;
+type SvgElementTags = Omit<SolidJSX.SVGElementTags, "rect" | "ellipse" | "polygon" | "path" | "text" | "image">;
export declare namespace JSX {
// Solid's Element type keeps Solid's control flow (<For>, <Show>, …) and
@@ -87,6 +88,7 @@ export declare namespace JSX {
rect: (RectProps & SourceProps) | SolidJSX.SVGElementTags["rect"];
ellipse: (EllipseProps & SourceProps) | SolidJSX.SVGElementTags["ellipse"];
polygon: (PolygonProps & SourceProps) | SolidJSX.SVGElementTags["polygon"];
+ path: (PathProps & SourceProps) | SolidJSX.SVGElementTags["path"];
video: VideoProps & SourceProps;
image: (ImageProps & SourceProps) | SolidJSX.SVGElementTags["image"];
audio: AudioProps & SourceProps;
diff --git a/packages/jsx/src/source.ts b/packages/jsx/src/source.ts
index f57c3d4c..7b1be951 100644
--- a/packages/jsx/src/source.ts
+++ b/packages/jsx/src/source.ts
@@ -95,6 +95,7 @@ export const COMPOSITION_TAGS = [
"rect",
"ellipse",
"polygon",
+ "path",
"video",
"image",
"audio",
diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.ts
index 979b41cf..f31cb956 100644
--- a/packages/jsx/src/types.ts
+++ b/packages/jsx/src/types.ts
@@ -20,6 +20,13 @@ export type StrokeJoin = "miter" | "round" | "bevel";
/** How a stroke ends an open path: the canvas `lineCap` values. */
export type StrokeCap = "butt" | "round" | "square";
+/**
+ * What a `<path>` counts as inside where its outline crosses itself or one
+ * subpath sits in another: SVG's `fill-rule`. "nonzero" fills a hole drawn
+ * the same way round as its outline; "evenodd" never does.
+ */
+export type FillRule = "nonzero" | "evenodd";
+
/**
* How an element follows its scene's frame along one axis when that frame is
* resized: pinned to the near edge ("left"/"top", the default), to the far
@@ -96,7 +103,8 @@ export type Easing =
* The props a `<keyframeTrack>` can drive, by name. Whose prop is the
* track's holder's: `x` under a `<rect>` is the rect's, `width` under a
* `<stroke>` the line width, `value` under an `<effect>` its amount,
- * `color`/`opacity` under a paint the paint's.
+ * `color`/`opacity` under a paint the paint's. `d` morphs a `<path>`'s
+ * outline from one keyframe's path data to the next.
*/
export type AnimatableProperty =
| "x"
@@ -127,7 +135,11 @@ export type AnimatableProperty =
| "rx"
| "ry"
| "blur"
- | "value";
+ | "value"
+ | "d"
+ | "trimStart"
+ | "trimEnd"
+ | "trimOffset";
/** Transition styles — the editor's transition inspector options. */
export type TransitionType =
@@ -605,6 +617,58 @@ export type PolygonProps = CommonProps & FillProps & {
children?: SolidJSX.Element;
};
+/**
+ * `<path>` — a vector outline from SVG path data: any number of subpaths,
+ * open or closed, of lines and curves. `d` is drawn in the box's own pixels,
+ * or, with a `viewBox`, stretched from it onto the box, so resizing the box
+ * resizes the outline without the data changing. Takes the same children as
+ * `<rect>`; a stroke ends its open subpaths with its `cap`.
+ */
+export type PathProps = CommonProps & FillProps & {
+ /**
+ * SVG path data: `M`/`L`/`H`/`V`/`C`/`S`/`Q`/`T`/`A`/`Z`, absolute or
+ * relative. The editor writes it back as absolute `M`/`L`/`C`/`Z`. A
+ * malformed `d` draws what came before the error, as in SVG. A `d`
+ * `<keyframeTrack>` morphs it: anchors and control points move in a
+ * straight line from keyframe to keyframe, the first vertex of each
+ * subpath (its `M`) to the first; paths with different vertex counts are
+ * subdivided to match, and ones with a different number of subpaths, or an
+ * open against a closed one, hold until the next keyframe.
+ */
+ d?: string;
+ /**
+ * The rectangle of `d`'s coordinates the box shows, `"x y width height"`,
+ * stretched to the box on each axis (SVG's `preserveAspectRatio="none"`).
+ * Default `"0 0 width height"`: `d` is in the box's pixels.
+ */
+ viewBox?: string;
+ /** Default "nonzero". */
+ fillRule?: FillRule;
+ /**
+ * Trims the outline to part of its length (After Effects' Trim Paths), as
+ * fractions 0–1 of each subpath's length: what lies between `trimStart`
+ * and `trimEnd` is drawn, filled and hit. Default 0 and 1, the whole path.
+ */
+ trimStart?: number;
+ trimEnd?: number;
+ /**
+ * Slides the trimmed stretch along the path, as a fraction of its length;
+ * it wraps, so 1 is once round. Default 0.
+ */
+ trimOffset?: number;
+ /**
+ * Makes the path a clip path of its parent, as `<rect clipPath>` does: the
+ * parent shows only inside its outline. Never rendered or hit.
+ */
+ clipPath?: boolean;
+ /**
+ * Paint children (`<SolidPaint>`, `<LinearGradientPaint>`,
+ * `<RadialGradientPaint>`, `<AngularGradientPaint>`), plus `<Stroke>`, `<Shadow>`, `<Effect>`,
+ * `<Animation>` and `<KeyframeTrack>` children.
+ */
+ children?: SolidJSX.Element;
+};
+
/**
* `<stroke>` — an outline of the parent's box (or glyphs), a sub-entity like a
* paint: `color` is its own solid paint, `width`/`join`/`cap`/`miterLimit` its
@@ -620,7 +684,7 @@ export type StrokeProps = Partial<ColorProps> & PaintProps & {
width?: number;
/** How the stroke turns corners. Default "miter". */
join?: StrokeJoin;
- /** How the stroke ends open paths (text glyphs). Default "butt". */
+ /** How the stroke ends open paths (text glyphs, open `<path>` subpaths). Default "butt". */
cap?: StrokeCap;
/** Miter length limit, as a ratio of the width. Default 10. */
miterLimit?: number;
@@ -729,7 +793,7 @@ export type KeyframeProps = {
* stay pinned to the same content when the clip is moved or trimmed.
*/
time: Time;
- /** The value at `time`: a number, or any CSS color on a `color` track. */
+ /** The value at `time`: a number, any CSS color on a `color` track, or path data on a `d` track. */
value: number | string;
/** Shapes the segment to the next keyframe; ignored on the last. Default "linear". */
easing?: Easing;
diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.ts
index 5af188de..0a8806b4 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, CAPTION_PRESET_FILLS, CAPTION_PRESET_STYLES, CaptionType, Chars, ClipHeight, ClipsContent, Computed, Constraint, ConstraintCache, ConstraintType, CornerRadius, clampPointCount, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, Expanded, FontStyle, FramePromises, FrameRate, getActiveEntity, Loop, LoadRequest, Mask, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsClipPath, isText, ItemIndex, KeepAspectRatio, Keyframe, KeyframeTrack, LINEAR_GRADIENT_DEFAULTS, LinearGradient, MixedCornerRadius, Mode, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, PendingSource, PendingSync, Playback, PlaybackRate, PointCount, Position, ELLIPTICAL_GRADIENT_DEFAULTS, EllipticalGradient, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceFrameRate, setCameraMatrix, setPlayhead, setTimelineView, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SyncRequest, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, 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, CAPTION_PRESET_FILLS, CAPTION_PRESET_STYLES, CaptionType, Chars, ClipHeight, ClipsContent, Computed, Constraint, ConstraintCache, ConstraintType, CornerRadius, clampPointCount, createEntity, DEFAULT_BACKGROUND, Color, ColorStop, Delay, Effect, EffectType, EvenOdd, Expanded, FontStyle, FramePromises, FrameRate, getActiveEntity, Loop, LoadRequest, Mask, Geometry, GeometryType, getEntityTree, getParentEntity, getParentNode, Hidden, Host, IsClipPath, isText, ItemIndex, KeepAspectRatio, Keyframe, KeyframeTrack, LINEAR_GRADIENT_DEFAULTS, LinearGradient, MixedCornerRadius, Mode, Muted, Name, Offset, Opacity, Paint, PaintType, parseColor, parsePath, PathTrim, PendingSource, PendingSync, Playback, PlaybackRate, PointCount, Position, ELLIPTICAL_GRADIENT_DEFAULTS, EllipticalGradient, removeChild, RenderSurface, resizeEntity, Scale, ScaleMode, ScaleModeType, secondsToFrames, getAsset, getEntityChildren, Group, Sequential, Shader, Size, Stage, Root, Rotation, Scene, Selected, Shadow, Source, SourceFrameRate, setCameraMatrix, setPlayhead, setTimelineView, Stroke, StrokeCap, StrokeJoin, StrokeStyle, SyncRequest, TextAlign, TextBaseline, TextCase, TextRange, TextStyle, Transition, TransitionType, Trim, UniformScale, VectorPath, ViewBox, Volume, Workarea } from '@diffusionstudio/runtime';
import { DEFAULT_MASK_SMOOTHING } from '@diffusionstudio/assets';
import { LOOP_ATTR, parseTime, SOURCE_ATTR } from '@diffusionstudio/jsx';
import { createSignal } from 'solid-js';
@@ -207,6 +207,10 @@ const TRACK_PROPERTIES: Record<string, PropertyPath> = {
ry: 'gradient.ry',
blur: 'blur',
value: 'effect.value',
+ d: 'path',
+ trimStart: 'trim.start',
+ trimEnd: 'trim.end',
+ trimOffset: 'trim.offset',
};
/**
@@ -239,6 +243,13 @@ export function trackProperty(path: string): AnimatableProperty | undefined {
return TRACK_PROPERTY_NAMES[path as PropertyPath];
}
+/**
+ * Whether a keyframe's value is path data rather than a color: it opens with
+ * a moveto and a coordinate, which no CSS color does ("magenta" has no digit
+ * after its m).
+ */
+const PATH_DATA = /^\s*[Mm][\s,]*[-+.\d]/;
+
/** The `<rect>` props of the per-corner radii, in the trait's (CSS) order. */
const CORNER_PROPS = ['cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomRight', 'cornerRadiusBottomLeft'] as const;
@@ -543,6 +554,15 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
resizeEntity(this.world, entity, { width: 100, height: 100 });
break;
}
+ case 'path': {
+ entity = createEntity(this.world);
+ entity.add(Geometry);
+ entity.set(Geometry, { value: GeometryType.PATH });
+ entity.add(Position);
+ entity.set(Position, { x: 0, y: 0 });
+ resizeEntity(this.world, entity, { width: 100, height: 100 });
+ break;
+ }
case 'text': {
// No Size: a text without one sizes itself to its glyphs.
entity = createEntity(this.world);
@@ -980,6 +1000,55 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
}
return;
}
+ case 'd': {
+ if (typeof value !== 'string') {
+ entity.remove(VectorPath);
+ return;
+ }
+
+ const { geometry, error } = parsePath(value);
+
+ if (error !== null) {
+ console.warn(`[path] ${error} in d="${value}"`);
+ }
+
+ entity.add(VectorPath);
+ entity.set(VectorPath, { geometry });
+ return;
+ }
+ case 'viewBox': {
+ const numbers = typeof value === 'string' ? value.trim().split(/[\s,]+/).map(Number) : [];
+ const [x, y, width, height] = numbers;
+ if (numbers.length !== 4 || numbers.some((n) => !Number.isFinite(n)) || width! <= 0 || height! <= 0) {
+ entity.remove(ViewBox);
+ return;
+ }
+ entity.add(ViewBox);
+ entity.set(ViewBox, { x: x!, y: y!, width: width!, height: height! });
+ return;
+ }
+ case 'fillRule': {
+ if (value === 'evenodd') {
+ entity.add(EvenOdd);
+ } else {
+ entity.remove(EvenOdd);
+ }
+ return;
+ }
+ case 'trimStart':
+ case 'trimEnd':
+ case 'trimOffset': {
+ const start = toNumber(node.props.trimStart);
+ const end = toNumber(node.props.trimEnd);
+ const offset = toNumber(node.props.trimOffset);
+ if (start === undefined && end === undefined && offset === undefined) {
+ entity.remove(PathTrim);
+ return;
+ }
+ entity.add(PathTrim);
+ entity.set(PathTrim, { start: start ?? 0, end: end ?? 1, offset: offset ?? 0 });
+ return;
+ }
case 'blendMode': {
const mode = typeof value === 'string' ? BLEND_MODES[value] : undefined;
if (mode === undefined || mode === BlendModeType.SOURCE_OVER) {
@@ -1139,8 +1208,10 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
}
case 'value': {
if (entity.has(Keyframe)) {
- // A number, or a color on a color track; either is a number to the trait.
- entity.set(Keyframe, { value: toNumber(value) ?? parseColor(value) ?? 0 });
+ // A number, or a color on a color track; either is a number to the
+ // trait. Path data, on a `d` track, is an outline instead.
+ const path = typeof value === 'string' && PATH_DATA.test(value) ? parsePath(value).geometry : null;
+ entity.set(Keyframe, { value: path ? 0 : toNumber(value) ?? parseColor(value) ?? 0, path });
return;
}
if (!entity.has(Effect)) return;
diff --git a/packages/reconciler/src/elements.ts b/packages/reconciler/src/elements.ts
index fa031cc6..c09a619e 100644
--- a/packages/reconciler/src/elements.ts
+++ b/packages/reconciler/src/elements.ts
@@ -37,6 +37,7 @@ import type {
KeyframeProps,
KeyframeTrackProps,
MediaPaintProps,
+ PathProps,
PolygonProps,
RectProps,
SceneProps,
@@ -96,6 +97,7 @@ export const Group = hostElement<GroupProps>("Group");
export const Rect = hostElement<RectProps>("Rect");
export const Ellipse = hostElement<EllipseProps>("Ellipse");
export const Polygon = hostElement<PolygonProps>("Polygon");
+export const Path = hostElement<PathProps>("Path");
export const Video = hostElement<VideoProps>("Video");
export const Image = hostElement<ImageProps>("Image");
export const Audio = hostElement<AudioProps>("Audio");
diff --git a/packages/runtime/src/constants.ts b/packages/runtime/src/constants.ts
index 7118be10..482bc333 100644
--- a/packages/runtime/src/constants.ts
+++ b/packages/runtime/src/constants.ts
@@ -70,6 +70,7 @@ export enum GeometryType {
TEXT,
ELLIPSE,
POLYGON,
+ PATH,
}
export enum PaintType {
@@ -189,4 +190,6 @@ export enum ToolType {
ANGULAR_GRADIENT,
ELLIPSE,
POLYGON,
+ PEN,
+ PATH_EDIT,
}
diff --git a/packages/runtime/src/math/index.ts b/packages/runtime/src/math/index.ts
index 5259ec30..49867fe8 100644
--- a/packages/runtime/src/math/index.ts
+++ b/packages/runtime/src/math/index.ts
@@ -6,3 +6,4 @@ export * from './common';
export * from './matrix2d';
export * from './aabb';
export * from './shape';
+export * from './path';
diff --git a/packages/runtime/src/math/path.ts b/packages/runtime/src/math/path.ts
new file mode 100644
index 00000000..7a524047
--- /dev/null
+++ b/packages/runtime/src/math/path.ts
@@ -0,0 +1,903 @@
+/* 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/. */
+
+// Vector paths: a `<path>`'s `d` as cubic segments, and what is done with
+// them — reading and writing SVG path data, morphing one path into another
+// (a `d` keyframe track), trimming (`trimStart`/`trimEnd`/`trimOffset`),
+// bounds and hit testing. The renderer, the hit test and the pen tool all
+// read the same numbers.
+
+/**
+ * One subpath with every segment a cubic. `points` holds the start anchor
+ * and then, per segment, its two control points and its end anchor:
+ * `[x0, y0, c1x, c1y, c2x, c2y, x1, y1, ...]`. A straight segment has its
+ * control points on its anchors. A closed subpath's last segment ends back on
+ * its start, so the closing segment is one like the others (it can curve)
+ * and every vertex is an anchor once.
+ */
+export interface Subpath {
+ closed: boolean;
+ points: number[];
+}
+
+export interface PathGeometry {
+ subpaths: Subpath[];
+}
+
+/** A path as read from its `d`: what parsed, and why the rest did not. */
+export interface ParsedPath {
+ geometry: PathGeometry;
+ /** Null when the whole string parsed; otherwise the geometry is what came before the error, as SVG renders it. */
+ error: string | null;
+}
+
+/** Where a `d` is drawn from: SVG's `viewBox`, stretched onto the box. */
+export interface ViewBoxRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** Maps a `d`'s coordinates into the box: `x * sx + tx`, `y * sy + ty`. */
+export interface PathTransform {
+ sx: number;
+ sy: number;
+ tx: number;
+ ty: number;
+}
+
+const EPSILON = 1e-9;
+
+export const EMPTY_PATH: PathGeometry = { subpaths: [] };
+
+export function segmentCount(subpath: Subpath): number {
+ return (subpath.points.length - 2) / 6;
+}
+
+/** How many vertices a subpath has: a closed one's last anchor is its first. */
+export function vertexCount(subpath: Subpath): number {
+ const segments = segmentCount(subpath);
+ return subpath.closed && segments > 0 ? segments : segments + 1;
+}
+
+// ── Parsing ─────────────────────────────────────────────────
+
+const PARAMS: Record<string, number> = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };
+const NUMBER = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y;
+const SEPARATORS = /[\s,]*/y;
+
+/**
+ * Reads SVG path data into cubic subpaths: every command, absolute and
+ * relative, implicit repeats, `H`/`V`, quadratics and arcs (elevated and
+ * approximated to cubics). Like SVG, a malformed string keeps what came
+ * before the error.
+ */
+export function parsePath(d: string): ParsedPath {
+ const subpaths: Subpath[] = [];
+ let current: Subpath | null = null;
+ let x = 0, y = 0; // current point
+ let startX = 0, startY = 0; // current subpath's start
+ let controlX = 0, controlY = 0; // last control point, for S/T
+ let previous = ''; // last command, lowercase
+ let command = '';
+ let i = 0;
+ let error: string | null = null;
+
+ const skip = () => {
+ SEPARATORS.lastIndex = i;
+ SEPARATORS.exec(d);
+ i = SEPARATORS.lastIndex;
+ };
+
+ const number = (): number | null => {
+ skip();
+ NUMBER.lastIndex = i;
+ const match = NUMBER.exec(d);
+ if (!match) return null;
+ i = NUMBER.lastIndex;
+ return Number(match[0]);
+ };
+
+ // Arc flags are a single digit and may run into what follows ("a1 1 0 01 1 1").
+ const flag = (): number | null => {
+ skip();
+ const char = d[i];
+ if (char !== '0' && char !== '1') return null;
+ i++;
+ return char === '1' ? 1 : 0;
+ };
+
+ const moveTo = (px: number, py: number) => {
+ current = { closed: false, points: [px, py] };
+ subpaths.push(current);
+ x = startX = px;
+ y = startY = py;
+ };
+
+ // A drawing command after a close starts a new subpath where the last one began.
+ const open = (): Subpath => {
+ if (current === null) moveTo(x, y);
+ return current!;
+ };
+
+ const curveTo = (c1x: number, c1y: number, c2x: number, c2y: number, px: number, py: number) => {
+ open().points.push(c1x, c1y, c2x, c2y, px, py);
+ x = px;
+ y = py;
+ };
+
+ const lineTo = (px: number, py: number) => curveTo(x, y, px, py, px, py);
+
+ while (true) {
+ skip();
+ if (i >= d.length) break;
+
+ const char = d[i]!;
+ if (char.toLowerCase() in PARAMS) {
+ command = char;
+ i++;
+ } else if (command === '' || command === 'z' || command === 'Z') {
+ error = `Expected a command at ${i}, found "${char}"`;
+ break;
+ }
+
+ const lower = command.toLowerCase();
+ const relative = command !== command.toUpperCase();
+ const args: number[] = [];
+ for (let p = 0; p < PARAMS[lower]!; p++) {
+ const value = lower === 'a' && (p === 3 || p === 4) ? flag() : number();
+ if (value === null) {
+ error = `Expected ${PARAMS[lower]} parameters for "${command}" at ${i}`;
+ break;
+ }
+ args.push(value);
+ }
+ if (error !== null) break;
+
+ const ox = relative ? x : 0;
+ const oy = relative ? y : 0;
+
+ switch (lower) {
+ case 'm':
+ moveTo(args[0]! + ox, args[1]! + oy);
+ // Pairs after a moveto are linetos.
+ command = relative ? 'l' : 'L';
+ break;
+ case 'l':
+ lineTo(args[0]! + ox, args[1]! + oy);
+ break;
+ case 'h':
+ lineTo(args[0]! + ox, y);
+ break;
+ case 'v':
+ lineTo(x, args[0]! + oy);
+ break;
+ case 'c':
+ curveTo(args[0]! + ox, args[1]! + oy, args[2]! + ox, args[3]! + oy, args[4]! + ox, args[5]! + oy);
+ controlX = args[2]! + ox;
+ controlY = args[3]! + oy;
+ break;
+ case 's': {
+ const reflect = previous === 'c' || previous === 's';
+ const c1x = reflect ? 2 * x - controlX : x;
+ const c1y = reflect ? 2 * y - controlY : y;
+ controlX = args[0]! + ox;
+ controlY = args[1]! + oy;
+ curveTo(c1x, c1y, controlX, controlY, args[2]! + ox, args[3]! + oy);
+ break;
+ }
+ case 'q': {
+ const qx = args[0]! + ox;
+ const qy = args[1]! + oy;
+ quadTo(qx, qy, args[2]! + ox, args[3]! + oy);
+ break;
+ }
+ case 't': {
+ const reflect = previous === 'q' || previous === 't';
+ const qx = reflect ? 2 * x - controlX : x;
+ const qy = reflect ? 2 * y - controlY : y;
+ quadTo(qx, qy, args[0]! + ox, args[1]! + oy);
+ break;
+ }
+ case 'a': {
+ const ex = args[5]! + ox;
+ const ey = args[6]! + oy;
+ arcToCubics(x, y, args[0]!, args[1]!, args[2]!, args[3] === 1, args[4] === 1, ex, ey, curveTo);
+ // A degenerate arc draws nothing but still moves the pen.
+ x = ex;
+ y = ey;
+ break;
+ }
+ case 'z':
+ if (current !== null) close(current, startX, startY);
+ current = null;
+ x = startX;
+ y = startY;
+ break;
+ }
+ previous = lower;
+ }
+
+ return { geometry: { subpaths }, error };
+
+ function quadTo(qx: number, qy: number, px: number, py: number) {
+ curveTo(
+ x + (2 / 3) * (qx - x), y + (2 / 3) * (qy - y),
+ px + (2 / 3) * (qx - px), py + (2 / 3) * (qy - py),
+ px, py,
+ );
+ controlX = qx;
+ controlY = qy;
+ }
+}
+
+/**
+ * Closes `subpath` back to its start: with a straight segment, unless its
+ * last segment already ends there, in which case that one is the closing
+ * segment — so `L 0 0 Z` and `Z` alone are the same outline.
+ */
+function close(subpath: Subpath, startX: number, startY: number): void {
+ const { points } = subpath;
+ const n = points.length;
+ const ends = n > 2 && near(points[n - 2]!, startX) && near(points[n - 1]!, startY);
+ if (n > 2 && !ends) {
+ points.push(points[n - 2]!, points[n - 1]!, startX, startY, startX, startY);
+ } else if (ends) {
+ // Exactly on the start, so the seam has no gap to stroke over.
+ points[n - 2] = startX;
+ points[n - 1] = startY;
+ }
+ subpath.closed = true;
+}
+
+function near(a: number, b: number): boolean {
+ return Math.abs(a - b) <= 1e-6;
+}
+
+/**
+ * An SVG elliptical arc from (x1, y1) to (x2, y2) as cubics of at most a
+ * quarter turn each (SVG 1.1 implementation notes, F.6.5–F.6.6).
+ */
+function arcToCubics(
+ x1: number, y1: number,
+ rx: number, ry: number, rotation: number,
+ largeArc: boolean, sweep: boolean,
+ x2: number, y2: number,
+ curveTo: (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) => void,
+): void {
+ if (x1 === x2 && y1 === y2) return;
+ rx = Math.abs(rx);
+ ry = Math.abs(ry);
+ if (rx === 0 || ry === 0) {
+ curveTo(x1, y1, x2, y2, x2, y2);
+ return;
+ }
+
+ const phi = (rotation * Math.PI) / 180;
+ const cos = Math.cos(phi);
+ const sin = Math.sin(phi);
+ const dx = (x1 - x2) / 2;
+ const dy = (y1 - y2) / 2;
+ const x1p = cos * dx + sin * dy;
+ const y1p = -sin * dx + cos * dy;
+
+ // Radii too small for the endpoints grow until they just fit.
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
+ if (lambda > 1) {
+ rx *= Math.sqrt(lambda);
+ ry *= Math.sqrt(lambda);
+ }
+
+ const numerator = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
+ const denominator = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
+ const coefficient = (largeArc !== sweep ? 1 : -1) * Math.sqrt(Math.max(0, numerator / denominator));
+ const cxp = (coefficient * rx * y1p) / ry;
+ const cyp = (-coefficient * ry * x1p) / rx;
+ const cx = cos * cxp - sin * cyp + (x1 + x2) / 2;
+ const cy = sin * cxp + cos * cyp + (y1 + y2) / 2;
+
+ const angle = (ux: number, uy: number, vx: number, vy: number) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
+ const theta = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
+ let delta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
+ if (!sweep && delta > 0) delta -= 2 * Math.PI;
+ if (sweep && delta < 0) delta += 2 * Math.PI;
+
+ const count = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2) - 1e-9));
+ const step = delta / count;
+ const k = (4 / 3) * Math.tan(step / 4);
+ const map = (ux: number, uy: number): [number, number] => [
+ cos * rx * ux - sin * ry * uy + cx,
+ sin * rx * ux + cos * ry * uy + cy,
+ ];
+
+ for (let s = 0; s < count; s++) {
+ const a = theta + s * step;
+ const b = a + step;
+ const [c1x, c1y] = map(Math.cos(a) - k * Math.sin(a), Math.sin(a) + k * Math.cos(a));
+ const [c2x, c2y] = map(Math.cos(b) + k * Math.sin(b), Math.sin(b) - k * Math.cos(b));
+ const [ex, ey] = s === count - 1 ? [x2, y2] : map(Math.cos(b), Math.sin(b));
+ curveTo(c1x, c1y, c2x, c2y, ex, ey);
+ }
+}
+
+// ── Writing ─────────────────────────────────────────────────
+
+/** A number as path data spells it: rounded to `digits` places, no `-0`. */
+function formatNumber(value: number, digits: number): string {
+ const scale = 10 ** digits;
+ const rounded = Math.round(value * scale) / scale;
+ return Object.is(rounded, -0) ? '0' : String(rounded);
+}
+
+/**
+ * The path as SVG path data in absolute `M`/`L`/`C`/`Z`: a segment whose
+ * control points sit on its anchors is a line, and a closed subpath's
+ * straight closing segment is the `Z` alone.
+ */
+export function formatPath(geometry: PathGeometry, digits = 2): string {
+ const f = (value: number) => formatNumber(value, digits);
+ const parts: string[] = [];
+
+ for (const { closed, points } of geometry.subpaths) {
+ parts.push(`M${f(points[0]!)} ${f(points[1]!)}`);
+ const segments = (points.length - 2) / 6;
+ for (let s = 0; s < segments; s++) {
+ const o = 2 + s * 6;
+ const line = isLine(points, o, f);
+ if (closed && s === segments - 1 && line) break;
+ parts.push(line
+ ? `L${f(points[o + 4]!)} ${f(points[o + 5]!)}`
+ : `C${f(points[o]!)} ${f(points[o + 1]!)} ${f(points[o + 2]!)} ${f(points[o + 3]!)} ${f(points[o + 4]!)} ${f(points[o + 5]!)}`);
+ }
+ if (closed) parts.push('Z');
+ }
+
+ return parts.join(' ');
+}
+
+/** Whether the segment at `o` is straight as written: its controls round onto its anchors. */
+function isLine(points: number[], o: number, f: (value: number) => string): boolean {
+ return f(points[o]!) === f(points[o - 2]!) && f(points[o + 1]!) === f(points[o - 1]!)
+ && f(points[o + 2]!) === f(points[o + 4]!) && f(points[o + 3]!) === f(points[o + 5]!);
+}
+
+// ── Mapping ─────────────────────────────────────────────────
+
+/**
+ * How a `d` drawn in `viewBox` lands in a `width` × `height` box: stretched
+ * to fill it on each axis (SVG's `preserveAspectRatio="none"`). Without a
+ * viewBox the coordinates are the box's own.
+ */
+export function viewBoxTransform(viewBox: ViewBoxRect | null, width: number, height: number): PathTransform {
+ if (viewBox === null || viewBox.width <= 0 || viewBox.height <= 0) {
+ return { sx: 1, sy: 1, tx: 0, ty: 0 };
+ }
+ const sx = width / viewBox.width;
+ const sy = height / viewBox.height;
+ return { sx, sy, tx: -viewBox.x * sx, ty: -viewBox.y * sy };
+}
+
+/** The path with every coordinate mapped by `transform`. */
+export function transformPath(geometry: PathGeometry, { sx, sy, tx, ty }: PathTransform): PathGeometry {
+ return {
+ subpaths: geometry.subpaths.map(({ closed, points }) => ({
+ closed,
+ points: points.map((value, index) => (index % 2 === 0 ? value * sx + tx : value * sy + ty)),
+ })),
+ };
+}
+
+/**
+ * Traces the path onto `path` (the caller begins it), its coordinates
+ * mapped by `transform` on the way so a stretched path needs no copy.
+ */
+export function tracePath(path: CanvasPath, geometry: PathGeometry, transform?: PathTransform): void {
+ const { sx, sy, tx, ty } = transform ?? { sx: 1, sy: 1, tx: 0, ty: 0 };
+ for (const { closed, points } of geometry.subpaths) {
+ path.moveTo(points[0]! * sx + tx, points[1]! * sy + ty);
+ for (let o = 2; o < points.length; o += 6) {
+ const straight = points[o] === points[o - 2] && points[o + 1] === points[o - 1]
+ && points[o + 2] === points[o + 4] && points[o + 3] === points[o + 5];
+ if (straight) {
+ path.lineTo(points[o + 4]! * sx + tx, points[o + 5]! * sy + ty);
+ } else {
+ path.bezierCurveTo(
+ points[o]! * sx + tx, points[o + 1]! * sy + ty,
+ points[o + 2]! * sx + tx, points[o + 3]! * sy + ty,
+ points[o + 4]! * sx + tx, points[o + 5]! * sy + ty,
+ );
+ }
+ }
+ if (closed) path.closePath();
+ }
+}
+
+// ── Bounds ──────────────────────────────────────────────────
+
+export interface PathBounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+/** The tight bounds of the path's outline (curve extrema included), or null for an empty path. */
+export function pathBounds(geometry: PathGeometry): PathBounds | null {
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ const include = (x: number, y: number) => {
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ };
+
+ for (const { points } of geometry.subpaths) {
+ include(points[0]!, points[1]!);
+ for (let o = 2; o < points.length; o += 6) {
+ const x0 = points[o - 2]!, y0 = points[o - 1]!;
+ const x3 = points[o + 4]!, y3 = points[o + 5]!;
+ include(x3, y3);
+ for (const t of cubicExtrema(x0, points[o]!, points[o + 2]!, x3)) {
+ include(cubicAt(x0, points[o]!, points[o + 2]!, x3, t), cubicAt(y0, points[o + 1]!, points[o + 3]!, y3, t));
+ }
+ for (const t of cubicExtrema(y0, points[o + 1]!, points[o + 3]!, y3)) {
+ include(cubicAt(x0, points[o]!, points[o + 2]!, x3, t), cubicAt(y0, points[o + 1]!, points[o + 3]!, y3, t));
+ }
+ }
+ }
+
+ return minX === Infinity ? null : { minX, minY, maxX, maxY };
+}
+
+/** The union of several paths' bounds, or null when all are empty. */
+export function unionPathBounds(geometries: Iterable<PathGeometry>): PathBounds | null {
+ let union: PathBounds | null = null;
+ for (const geometry of geometries) {
+ const bounds = pathBounds(geometry);
+ if (bounds === null) continue;
+ union = union === null ? bounds : {
+ minX: Math.min(union.minX, bounds.minX),
+ minY: Math.min(union.minY, bounds.minY),
+ maxX: Math.max(union.maxX, bounds.maxX),
+ maxY: Math.max(union.maxY, bounds.maxY),
+ };
+ }
+ return union;
+}
+
+function cubicAt(p0: number, p1: number, p2: number, p3: number, t: number): number {
+ const u = 1 - t;
+ return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3;
+}
+
+/** The parameters in (0, 1) where one axis of a cubic turns. */
+function cubicExtrema(p0: number, p1: number, p2: number, p3: number): number[] {
+ const a = -p0 + 3 * p1 - 3 * p2 + p3;
+ const b = 2 * (p0 - 2 * p1 + p2);
+ const c = p1 - p0;
+ const roots: number[] = [];
+ if (Math.abs(a) < EPSILON) {
+ if (Math.abs(b) > EPSILON) roots.push(-c / b);
+ } else {
+ const discriminant = b * b - 4 * a * c;
+ if (discriminant >= 0) {
+ const root = Math.sqrt(discriminant);
+ roots.push((-b + root) / (2 * a), (-b - root) / (2 * a));
+ }
+ }
+ return roots.filter((t) => t > 0 && t < 1);
+}
+
+// ── Splitting ───────────────────────────────────────────────
+
+type Cubic = [x0: number, y0: number, c1x: number, c1y: number, c2x: number, c2y: number, x3: number, y3: number];
+
+/** The segment at index `s` of `points`, start anchor included. */
+function cubicOf(points: number[], s: number): Cubic {
+ const o = 2 + s * 6;
+ return [points[o - 2]!, points[o - 1]!, points[o]!, points[o + 1]!, points[o + 2]!, points[o + 3]!, points[o + 4]!, points[o + 5]!];
+}
+
+/**
+ * Whether a segment is straight as stored: its control points on its
+ * anchors. Such a segment is parameterized linearly here (its point at `t` is
+ * `t` of the way along), so it splits, trims and morphs into straight pieces.
+ */
+function isStraight(cubic: Cubic): boolean {
+ return cubic[2] === cubic[0] && cubic[3] === cubic[1] && cubic[4] === cubic[6] && cubic[5] === cubic[7];
+}
+
+/** The point at `t` along a segment. */
+function pointOn(cubic: Cubic, t: number): [number, number] {
+ if (isStraight(cubic)) {
+ return [cubic[0] + (cubic[6] - cubic[0]) * t, cubic[1] + (cubic[7] - cubic[1]) * t];
+ }
+ return [cubicAt(cubic[0], cubic[2], cubic[4], cubic[6], t), cubicAt(cubic[1], cubic[3], cubic[5], cubic[7], t)];
+}
+
+/**
+ * A segment split at `t`: the part before and the part after. A curve
+ * splits by de Casteljau, a straight segment into two straight ones.
+ */
+export function splitCubic(cubic: Cubic, t: number): [Cubic, Cubic] {
+ if (isStraight(cubic)) {
+ const [mx, my] = pointOn(cubic, t);
+ return [
+ [cubic[0], cubic[1], cubic[0], cubic[1], mx, my, mx, my],
+ [mx, my, mx, my, cubic[6], cubic[7], cubic[6], cubic[7]],
+ ];
+ }
+ const [x0, y0, x1, y1, x2, y2, x3, y3] = cubic;
+ const lerp = (a: number, b: number) => a + (b - a) * t;
+ const ax = lerp(x0, x1), ay = lerp(y0, y1);
+ const bx = lerp(x1, x2), by = lerp(y1, y2);
+ const cx = lerp(x2, x3), cy = lerp(y2, y3);
+ const dx = lerp(ax, bx), dy = lerp(ay, by);
+ const ex = lerp(bx, cx), ey = lerp(by, cy);
+ const fx = lerp(dx, ex), fy = lerp(dy, ey);
+ return [[x0, y0, ax, ay, dx, dy, fx, fy], [fx, fy, ex, ey, cx, cy, x3, y3]];
+}
+
+/** The part of a cubic between `t0` and `t1`. */
+function sliceCubic(cubic: Cubic, t0: number, t1: number): Cubic {
+ const [head] = t1 >= 1 ? [cubic] : splitCubic(cubic, t1);
+ if (t0 <= 0) return head;
+ return splitCubic(head, t1 <= 0 ? 0 : t0 / t1)[1];
+}
+
+/** Rough length of a segment, enough to rank segments by: its control polygon. */
+function hullLength(cubic: Cubic): number {
+ const [x0, y0, x1, y1, x2, y2, x3, y3] = cubic;
+ return Math.hypot(x1 - x0, y1 - y0) + Math.hypot(x2 - x1, y2 - y1) + Math.hypot(x3 - x2, y3 - y2);
+}
+
+/**
+ * The subpath with segment `s` split in two at `t`: a vertex inserted on the
+ * outline without changing it. Its vertices after the split are one further on.
+ */
+export function splitSegment(subpath: Subpath, s: number, t: number): Subpath {
+ if (s < 0 || s >= segmentCount(subpath)) return subpath;
+ const [head, tail] = splitCubic(cubicOf(subpath.points, s), t);
+ const points = subpath.points.slice();
+ const o = 2 + s * 6;
+ points.splice(o, 6, ...head.slice(2), ...tail.slice(2));
+ return { closed: subpath.closed, points };
+}
+
+/**
+ * The subpath with vertex `v` taken out: an end vertex takes its one segment
+ * with it, any other merges its two segments into one that keeps their outer
+ * control points. Unchanged if it would leave no segment at all.
+ */
+export function removeVertex(subpath: Subpath, v: number): Subpath {
+ const segments = segmentCount(subpath);
+ const vertices = vertexCount(subpath);
+ if (v < 0 || v >= vertices || vertices <= 2) return subpath;
+ const { points } = subpath;
+
+ if (!subpath.closed) {
+ if (v === 0) return { closed: false, points: points.slice(6) };
+ if (v === vertices - 1) return { closed: false, points: points.slice(0, -6) };
+ // Segment v-1 runs into the vertex, segment v out of it.
+ const into = 2 + (v - 1) * 6;
+ const merged = [points[into]!, points[into + 1]!, points[into + 8]!, points[into + 9]!, points[into + 10]!, points[into + 11]!];
+ const next = points.slice();
+ next.splice(into, 12, ...merged);
+ return { closed: false, points: next };
+ }
+
+ // Closed: the segment into v and the one out of it, wrapping round.
+ const into = (v - 1 + segments) % segments;
+ const out = v;
+ const a = cubicOf(points, into);
+ const b = cubicOf(points, out);
+ const merged: Cubic = [a[0], a[1], a[2], a[3], b[4], b[5], b[6], b[7]];
+ const cubics: Cubic[] = [];
+ for (let s = 0; s < segments; s++) {
+ if (s === out) continue;
+ cubics.push(s === into ? merged : cubicOf(points, s));
+ }
+ // Taking out the first vertex leaves the merged segment last, so the next
+ // vertex is first.
+ return fromCubics(cubics, true);
+}
+
+function fromCubics(cubics: Cubic[], closed: boolean): Subpath {
+ const points = [cubics[0]![0], cubics[0]![1]];
+ for (const cubic of cubics) points.push(...cubic.slice(2));
+ return { closed, points };
+}
+
+// ── Morphing ────────────────────────────────────────────────
+
+/**
+ * `subpath` with as many segments as `count`: the longest segment is split in
+ * half, again and again, so the outline is the same and the new vertices
+ * land where there is the most room. A subpath with no segment at all (a
+ * lone point) grows segments of no length.
+ */
+function subdivide(subpath: Subpath, count: number): Subpath {
+ let segments = segmentCount(subpath);
+ if (segments >= count) return subpath;
+ if (segments === 0) {
+ const [x, y] = subpath.points as [number, number];
+ const points = [x, y];
+ for (let s = 0; s < count; s++) points.push(x, y, x, y, x, y);
+ return { closed: subpath.closed, points };
+ }
+
+ const cubics: Cubic[] = [];
+ for (let s = 0; s < segments; s++) cubics.push(cubicOf(subpath.points, s));
+ const lengths = cubics.map(hullLength);
+ while (segments < count) {
+ let longest = 0;
+ for (let s = 1; s < lengths.length; s++) if (lengths[s]! > lengths[longest]!) longest = s;
+ const halves = splitCubic(cubics[longest]!, 0.5);
+ cubics.splice(longest, 1, ...halves);
+ lengths.splice(longest, 1, hullLength(halves[0]), hullLength(halves[1]));
+ segments++;
+ }
+ return fromCubics(cubics, subpath.closed);
+}
+
+/** Two paths made the same shape of data, so they lerp number for number; null when they cannot be. */
+type MatchedPair = [PathGeometry, PathGeometry];
+
+const matches = new WeakMap<PathGeometry, WeakMap<PathGeometry, MatchedPair | null>>();
+
+/**
+ * `from` and `to` with the same subpaths, the same open/closed flags and the
+ * same number of segments in each, the shorter of each pair subdivided to the
+ * longer. Null when they differ in subpath count or in which are closed:
+ * those hold instead of morphing. Paths are parsed once and never changed,
+ * so a pair is matched once and kept.
+ */
+function matchPaths(from: PathGeometry, to: PathGeometry): MatchedPair | null {
+ let byTarget = matches.get(from);
+ if (byTarget === undefined) {
+ byTarget = new WeakMap();
+ matches.set(from, byTarget);
+ }
+ const cached = byTarget.get(to);
+ if (cached !== undefined) return cached;
+
+ let pair: MatchedPair | null = null;
+ if (from.subpaths.length === to.subpaths.length
+ && from.subpaths.every((subpath, index) => subpath.closed === to.subpaths[index]!.closed)) {
+ const a: Subpath[] = [];
+ const b: Subpath[] = [];
+ from.subpaths.forEach((subpath, index) => {
+ const other = to.subpaths[index]!;
+ const count = Math.max(segmentCount(subpath), segmentCount(other));
+ a.push(subdivide(subpath, count));
+ b.push(subdivide(other, count));
+ });
+ pair = [{ subpaths: a }, { subpaths: b }];
+ }
+ byTarget.set(to, pair);
+ return pair;
+}
+
+/**
+ * The path `progress` of the way from `from` to `to`, each anchor and
+ * control point on a straight line (After Effects' path keyframes). Vertex
+ * counts that differ are evened out by subdividing; a different number of
+ * subpaths, or an open one against a closed one, holds `from` until the
+ * next keyframe instead.
+ */
+export function interpolatePath(from: PathGeometry, to: PathGeometry, progress: number): PathGeometry {
+ if (progress === 0 || from === to) return from;
+ if (progress === 1) return to;
+
+ // An easing that overshoots (a spring) carries the morph past either end.
+ const pair = matchPaths(from, to);
+ if (pair === null) return progress < 1 ? from : to;
+
+ const [a, b] = pair;
+ return {
+ subpaths: a.subpaths.map((subpath, index) => {
+ const target = b.subpaths[index]!.points;
+ return {
+ closed: subpath.closed,
+ points: subpath.points.map((value, p) => value + (target[p]! - value) * progress),
+ };
+ }),
+ };
+}
+
+// ── Trimming ────────────────────────────────────────────────
+
+/** Samples per segment when measuring and flattening. */
+const SAMPLES = 16;
+
+/** Cumulative arc length along a segment at `SAMPLES + 1` evenly spaced parameters. */
+function measure(cubic: Cubic): number[] {
+ const lengths = [0];
+ let px = cubic[0], py = cubic[1];
+ for (let i = 1; i <= SAMPLES; i++) {
+ const [x, y] = pointOn(cubic, i / SAMPLES);
+ lengths.push(lengths[i - 1]! + Math.hypot(x - px, y - py));
+ px = x;
+ py = y;
+ }
+ return lengths;
+}
+
+/** The parameter at arc length `length` along a segment measured by `measure`. */
+function parameterAt(lengths: number[], length: number): number {
+ const total = lengths[SAMPLES]!;
+ if (length <= 0 || total <= 0) return 0;
+ if (length >= total) return 1;
+ let i = 1;
+ while (lengths[i]! < length) i++;
+ const before = lengths[i - 1]!;
+ const span = lengths[i]! - before;
+ return (i - 1 + (span > 0 ? (length - before) / span : 0)) / SAMPLES;
+}
+
+/** The stretch of a subpath between arc lengths `from` and `to`, as cubics. */
+function slice(cubics: Cubic[], measures: number[][], from: number, to: number): Cubic[] {
+ const out: Cubic[] = [];
+ let start = 0;
+ for (let s = 0; s < cubics.length; s++) {
+ const length = measures[s]![SAMPLES]!;
+ const end = start + length;
+ if (end > from && start < to && length > 0) {
+ const t0 = parameterAt(measures[s]!, from - start);
+ const t1 = parameterAt(measures[s]!, to - start);
+ out.push(sliceCubic(cubics[s]!, t0, t1));
+ }
+ start = end;
+ }
+ return out;
+}
+
+/**
+ * The path trimmed to the stretch from `start` to `end` of each subpath, as
+ * fractions of its length (After Effects' Trim Paths, trimming every subpath
+ * at once). `offset` slides that stretch along the path and wraps: on a
+ * closed subpath across its start, on an open one into a second piece.
+ * `start` above `end` trims the same as the two the other way round; a
+ * stretch of the whole length or more leaves the path as it is.
+ */
+export function trimPath(geometry: PathGeometry, start: number, end: number, offset: number): PathGeometry {
+ const from = Math.min(1, Math.max(0, Math.min(start, end)));
+ const to = Math.min(1, Math.max(0, Math.max(start, end)));
+ const span = to - from;
+ if (span >= 1) return geometry;
+ if (span <= 0) return EMPTY_PATH;
+
+ const shift = from + offset;
+ const head = shift - Math.floor(shift);
+ const subpaths: Subpath[] = [];
+
+ for (const subpath of geometry.subpaths) {
+ const segments = segmentCount(subpath);
+ if (segments === 0) continue;
+ const cubics: Cubic[] = [];
+ for (let s = 0; s < segments; s++) cubics.push(cubicOf(subpath.points, s));
+ const measures = cubics.map(measure);
+ const total = measures.reduce((sum, lengths) => sum + lengths[SAMPLES]!, 0);
+ if (total <= 0) continue;
+
+ const a = head * total;
+ const b = (head + span) * total;
+ if (b <= total) {
+ const piece = slice(cubics, measures, a, b);
+ if (piece.length) subpaths.push(fromCubics(piece, false));
+ continue;
+ }
+
+ const first = slice(cubics, measures, a, total);
+ const second = slice(cubics, measures, 0, b - total);
+ if (subpath.closed) {
+ // Through the start, which is where the outline continues.
+ const joined = [...first, ...second];
+ if (joined.length) subpaths.push(fromCubics(joined, false));
+ } else {
+ if (first.length) subpaths.push(fromCubics(first, false));
+ if (second.length) subpaths.push(fromCubics(second, false));
+ }
+ }
+
+ return { subpaths };
+}
+
+// ── Hit testing ─────────────────────────────────────────────
+
+/** A subpath as a polyline, `[x0, y0, x1, y1, ...]`. */
+function flatten(subpath: Subpath): number[] {
+ const { points } = subpath;
+ const out = [points[0]!, points[1]!];
+ for (let s = 0; s < segmentCount(subpath); s++) {
+ const cubic = cubicOf(points, s);
+ const steps = isStraight(cubic) ? 1 : SAMPLES;
+ for (let i = 1; i <= steps; i++) out.push(...pointOn(cubic, i / steps));
+ }
+ return out;
+}
+
+/**
+ * Whether (x, y) is inside the area the path fills, every subpath closed the
+ * way a fill closes it, by the nonzero or the even-odd rule.
+ */
+export function pointInPath(geometry: PathGeometry, x: number, y: number, evenOdd = false): boolean {
+ let winding = 0;
+ for (const subpath of geometry.subpaths) {
+ const line = flatten(subpath);
+ const n = line.length / 2;
+ for (let i = 0; i < n; i++) {
+ const ax = line[i * 2]!, ay = line[i * 2 + 1]!;
+ const j = (i + 1) % n;
+ const bx = line[j * 2]!, by = line[j * 2 + 1]!;
+ if (ay <= y) {
+ if (by > y && (bx - ax) * (y - ay) - (x - ax) * (by - ay) > 0) winding++;
+ } else if (by <= y && (bx - ax) * (y - ay) - (x - ax) * (by - ay) < 0) {
+ winding--;
+ }
+ }
+ }
+ return evenOdd ? winding % 2 !== 0 : winding !== 0;
+}
+
+/** The shortest distance from (x, y) to the path's outline (not its area). */
+export function distanceToPath(geometry: PathGeometry, x: number, y: number): number {
+ let best = Infinity;
+ for (const subpath of geometry.subpaths) {
+ const line = flatten(subpath);
+ if (line.length === 2) best = Math.min(best, Math.hypot(x - line[0]!, y - line[1]!));
+ for (let i = 2; i < line.length; i += 2) {
+ best = Math.min(best, distanceToSegment(x, y, line[i - 2]!, line[i - 1]!, line[i]!, line[i + 1]!));
+ }
+ }
+ return best;
+}
+
+function distanceToSegment(x: number, y: number, ax: number, ay: number, bx: number, by: number): number {
+ const dx = bx - ax;
+ const dy = by - ay;
+ const lengthSquared = dx * dx + dy * dy;
+ const t = lengthSquared > 0 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / lengthSquared)) : 0;
+ return Math.hypot(x - (ax + t * dx), y - (ay + t * dy));
+}
+
+/** The point `t` along segment `segment` of subpath `subpath`. */
+export function pointOnPath(geometry: PathGeometry, subpath: number, segment: number, t: number): { x: number; y: number } {
+ const [x, y] = pointOn(cubicOf(geometry.subpaths[subpath]!.points, segment), t);
+ return { x, y };
+}
+
+/**
+ * The point on the path's outline closest to (x, y): which subpath, which
+ * segment, the parameter along it, and how far away it is. Null for an empty
+ * path. What an editor inserts a vertex at.
+ */
+export function nearestOnPath(geometry: PathGeometry, x: number, y: number): { subpath: number; segment: number; t: number; distance: number } | null {
+ let best: { subpath: number; segment: number; t: number; distance: number } | null = null;
+ geometry.subpaths.forEach((subpath, index) => {
+ for (let s = 0; s < segmentCount(subpath); s++) {
+ const cubic = cubicOf(subpath.points, s);
+ // Coarse samples, then a finer look around the closest one.
+ let bestT = 0;
+ let bestDistance = Infinity;
+ const probe = (t: number) => {
+ const [px, py] = pointOn(cubic, t);
+ const distance = Math.hypot(px - x, py - y);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestT = t;
+ }
+ };
+ for (let i = 0; i <= SAMPLES * 2; i++) probe(i / (SAMPLES * 2));
+ const around = bestT;
+ const step = 1 / (SAMPLES * 2);
+ for (let i = -10; i <= 10; i++) probe(Math.min(1, Math.max(0, around + (i / 10) * step)));
+ if (best === null || bestDistance < best.distance) {
+ best = { subpath: index, segment: s, t: bestT, distance: bestDistance };
+ }
+ }
+ });
+ return best;
+}
diff --git a/packages/runtime/src/queries/index.ts b/packages/runtime/src/queries/index.ts
index c40a0c16..0525c795 100644
--- a/packages/runtime/src/queries/index.ts
+++ b/packages/runtime/src/queries/index.ts
@@ -5,3 +5,4 @@ export * from './timeline-index';
export * from './timeline-view';
export * from './hit-test';
export * from './interaction';
+export * from './path';
diff --git a/packages/runtime/src/queries/interaction.ts b/packages/runtime/src/queries/interaction.ts
index 409adf0f..c2fa8275 100644
--- a/packages/runtime/src/queries/interaction.ts
+++ b/packages/runtime/src/queries/interaction.ts
@@ -13,15 +13,16 @@
import { Not, Or } from 'koota';
import {
- Anchor, Computed, Geometry, Group, LocalTransform, Offset, PointCount, Selected,
+ Anchor, Cache, Computed, EvenOdd, Geometry, Group, LocalTransform, Offset, PointCount, Selected,
Sequential, WorldBounds, WorldTransform,
} from '../traits';
import { GeometryType } from '../constants';
import { store } from '../world/store';
import { isStage } from './predicates';
+import { getDrawnPath, getPathTransform } from './path';
import { getViewMatrix } from './camera';
import {
- decompose2D, identity2D, invert2D, multiply2D, pointInShape, rectToQuad, rotate2D,
+ decompose2D, distanceToPath, identity2D, invert2D, multiply2D, pointInPath, pointInShape, rectToQuad, rotate2D,
scale2D, skew2D, transformPoint, translate2D,
} from '../math';
@@ -106,6 +107,9 @@ export function isPointerInEntity(world: World, entity: Entity, point: Point): b
const height = computed.height[eid] ?? 0;
const type = entity.has(Geometry) ? store(world, Geometry).value[eid] : undefined;
+ if (type === GeometryType.PATH) {
+ return isPointerInPath(world, entity, local.x - originX, local.y - originY);
+ }
if (type === GeometryType.ELLIPSE || type === GeometryType.POLYGON) {
const pointCount = entity.has(PointCount) ? store(world, PointCount).value[eid]! : 3;
return pointInShape(type, local.x - originX, local.y - originY, width, height, pointCount);
@@ -115,6 +119,34 @@ export function isPointerInEntity(world: World, entity: Entity, point: Point): b
&& local.y >= originY && local.y <= originY + height;
}
+/** How near the outline of a path, in its own px, still hits it (on top of half its widest stroke). */
+const PATH_HIT_SLOP = 4;
+
+/**
+ * Whether a point in a path's box (px from its top-left) hits it: inside
+ * what it fills, or on its outline, as far out as its widest stroke reaches
+ * — what an open, unfilled path is picked up by. Measured in the `d`'s own
+ * coordinates, the tolerance taken back through the viewBox's stretch.
+ */
+function isPointerInPath(world: World, entity: Entity, x: number, y: number): boolean {
+ const geometry = getDrawnPath(world, entity);
+ if (geometry === null) return false;
+
+ const { sx, sy, tx, ty } = getPathTransform(world, entity);
+ if (sx === 0 || sy === 0) return false;
+ const px = (x - tx) / sx;
+ const py = (y - ty) / sy;
+ if (pointInPath(geometry, px, py, entity.has(EvenOdd))) return true;
+
+ const computed = store(world, Computed);
+ let reach = 0;
+ for (const stroke of store(world, Cache).strokes[entity.id()] ?? []) {
+ reach = Math.max(reach, (computed.strokeWidth[stroke.id()] ?? 0) / 2);
+ }
+ const scale = Math.min(Math.abs(sx), Math.abs(sy));
+ return distanceToPath(geometry, px, py) * scale <= reach + PATH_HIT_SLOP;
+}
+
/** The entities a selection mask spans: sequences are not spatial, so they never do. */
export function getMaskSelection(world: World): Entity[] {
return [...world.query(Selected, Or(Geometry, Group), Not(Sequential))];
diff --git a/packages/runtime/src/queries/path.ts b/packages/runtime/src/queries/path.ts
new file mode 100644
index 00000000..3f4c4562
--- /dev/null
+++ b/packages/runtime/src/queries/path.ts
@@ -0,0 +1,51 @@
+/* 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/. */
+
+// A `<path>`'s outline as it stands this frame, for whatever draws, hits or
+// edits it: the authored `d` or what its keyframe track made of it, how its
+// viewBox lands in its box, and the part its trim leaves.
+
+import { Computed, VectorPath, ViewBox } from '../traits';
+import { store } from '../world/store';
+import { trimPath, viewBoxTransform } from '../math/path';
+
+import type { Entity, World } from 'koota';
+import type { PathGeometry, PathTransform, ViewBoxRect } from '../math/path';
+
+/**
+ * The path's outline this frame, untrimmed, in its `d`'s coordinates: what
+ * a `d` keyframe track has it at, or the authored `d`. Null for none.
+ */
+export function getPathGeometry(world: World, entity: Entity): PathGeometry | null {
+ const eid = entity.id();
+ const animated = store(world, Computed).path[eid];
+ if (animated !== undefined) return animated;
+ return entity.has(VectorPath) ? store(world, VectorPath).geometry[eid] ?? null : null;
+}
+
+/** The authored viewBox, or null for the box's own coordinates. */
+export function getViewBox(entity: Entity): ViewBoxRect | null {
+ return entity.get(ViewBox) ?? null;
+}
+
+/** How the path's `d` coordinates land in its box this frame (see `viewBoxTransform`). */
+export function getPathTransform(world: World, entity: Entity): PathTransform {
+ const computed = store(world, Computed);
+ const eid = entity.id();
+ return viewBoxTransform(getViewBox(entity), computed.width[eid] ?? 0, computed.height[eid] ?? 0);
+}
+
+/**
+ * The outline as drawn this frame, in its `d`'s coordinates: the path's
+ * geometry with its trim applied. Null for none.
+ */
+export function getDrawnPath(world: World, entity: Entity): PathGeometry | null {
+ const geometry = getPathGeometry(world, entity);
+ if (geometry === null) return null;
+
+ // The whole length comes back as the same geometry, untouched.
+ const computed = store(world, Computed);
+ const eid = entity.id();
+ return trimPath(geometry, computed.trimStart[eid] ?? 0, computed.trimEnd[eid] ?? 1, computed.trimOffset[eid] ?? 0);
+}
diff --git a/packages/runtime/src/queries/predicates.ts b/packages/runtime/src/queries/predicates.ts
index 72aa581b..5ff4221d 100644
--- a/packages/runtime/src/queries/predicates.ts
+++ b/packages/runtime/src/queries/predicates.ts
@@ -58,14 +58,19 @@ export function isPolygon(entity: Entity): boolean {
return entity.get(Geometry)?.value === GeometryType.POLYGON;
}
+export function isPath(entity: Entity): boolean {
+ return entity.get(Geometry)?.value === GeometryType.PATH;
+}
+
/** Whether a geometry draws a filled and stroked outline: everything but text. */
export function isShapeGeometry(type: GeometryType | undefined): boolean {
return type === GeometryType.RECT
|| type === GeometryType.ELLIPSE
- || type === GeometryType.POLYGON;
+ || type === GeometryType.POLYGON
+ || type === GeometryType.PATH;
}
-/** A vanilla shape (rect, ellipse or polygon) — not a container
+/** A vanilla shape (rect, ellipse, polygon or path) — not a container
* (group/scene/sequence) or audio clip. (Captions live on TEXT geometry, so
* they're naturally excluded.) */
export function isShape(entity: Entity): boolean {
diff --git a/packages/runtime/src/systems/gradients.ts b/packages/runtime/src/systems/gradients.ts
index 853374d1..ad691a91 100644
--- a/packages/runtime/src/systems/gradients.ts
+++ b/packages/runtime/src/systems/gradients.ts
@@ -73,10 +73,10 @@ export function createLinearGradient(
return gradient;
}
-/** Fill the current path with a linear gradient paint. */
-export function fillLinearGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {
+/** Fill the current path with a linear gradient paint, by `fillRule`. */
+export function fillLinearGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number, fillRule: CanvasFillRule = 'nonzero'): void {
ctx.fillStyle = createLinearGradient(world, paint, ctx, w, h);
- ctx.fill();
+ ctx.fill(fillRule);
}
/** Stroke the current path with a linear gradient paint, in the stroke style already set on `ctx`. */
@@ -195,12 +195,12 @@ const unitAngularGradient: UnitGradient = (world, paint, ctx) => {
* ellipse comes from the matrix, which bends only the paint: the path was
* placed when it was built.
*/
-function fillThroughEllipse(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number, unit: UnitGradient): void {
+function fillThroughEllipse(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number, unit: UnitGradient, fillRule: CanvasFillRule): void {
const { a, b, c, d, e, f } = getGradientEllipseMatrix(world, paint, w, h);
ctx.save();
ctx.transform(a, b, c, d, e, f);
ctx.fillStyle = unit(world, paint, ctx);
- ctx.fill();
+ ctx.fill(fillRule);
ctx.restore();
}
@@ -253,9 +253,9 @@ function createPatternThroughEllipse(
return pattern;
}
-/** Fill the current path with a radial gradient paint. */
-export function fillRadialGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {
- fillThroughEllipse(world, paint, ctx, w, h, unitRadialGradient);
+/** Fill the current path with a radial gradient paint, by `fillRule`. */
+export function fillRadialGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number, fillRule: CanvasFillRule = 'nonzero'): void {
+ fillThroughEllipse(world, paint, ctx, w, h, unitRadialGradient, fillRule);
}
/**
@@ -273,9 +273,9 @@ export function strokeRadialGradient(world: World, paint: Entity, ctx: Ctx2D, w:
ctx.stroke();
}
-/** Fill the current path with an angular gradient paint. */
-export function fillAngularGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number): void {
- fillThroughEllipse(world, paint, ctx, w, h, unitAngularGradient);
+/** Fill the current path with an angular gradient paint, by `fillRule`. */
+export function fillAngularGradient(world: World, paint: Entity, ctx: Ctx2D, w: number, h: number, fillRule: CanvasFillRule = 'nonzero'): void {
+ fillThroughEllipse(world, paint, ctx, w, h, unitAngularGradient, fillRule);
}
/**
diff --git a/packages/runtime/src/systems/motion.ts b/packages/runtime/src/systems/motion.ts
index b157226b..e0bd8126 100644
--- a/packages/runtime/src/systems/motion.ts
+++ b/packages/runtime/src/systems/motion.ts
@@ -11,13 +11,15 @@ import {
Computed, Cache, Animation, KeyframeTrack, Keyframe, Chars,
UniformScale, Position, Offset, Rotation, Scale, Skew, Size, Opacity,
Color, Blur, Volume, Effect, StrokeStyle, CornerRadius, MixedCornerRadius,
- ColorStop, LinearGradient, EllipticalGradient,
+ ColorStop, LinearGradient, EllipticalGradient, PathTrim, VectorPath,
} from '../traits';
import { AnimationType, AnimationPhase, LINEAR_GRADIENT_DEFAULTS, ELLIPTICAL_GRADIENT_DEFAULTS } from '../constants';
import { revealChars, revealWords, scrambleChars } from '../utils/text-motion';
import { getLocalWindow } from '../utils/time';
+import { interpolatePath } from '../math/path';
import type { Entity, Trait, TraitRecord, World } from 'koota';
+import type { PathGeometry } from '../math/path';
/**
* Reset an entity's Computed values back to its authored trait values.
@@ -63,6 +65,9 @@ export function resetAnimatedValues(world: World, entity: Entity | null, ignore?
computed.gradientCY[eid] = read(EllipticalGradient, 'cy', ELLIPTICAL_GRADIENT_DEFAULTS.cy);
computed.gradientRX[eid] = read(EllipticalGradient, 'rx', ELLIPTICAL_GRADIENT_DEFAULTS.rx);
computed.gradientRY[eid] = read(EllipticalGradient, 'ry', ELLIPTICAL_GRADIENT_DEFAULTS.ry);
+ computed.trimStart[eid] = read(PathTrim, 'start', 0);
+ computed.trimEnd[eid] = read(PathTrim, 'end', 1);
+ computed.trimOffset[eid] = read(PathTrim, 'offset', 0);
if (entity.has(UniformScale) && ignore !== UniformScale) {
computed.scaleX[eid] = read(UniformScale, 'value', 1);
@@ -76,6 +81,8 @@ export function resetAnimatedValues(world: World, entity: Entity | null, ignore?
// Chars straight to the store, so a copy would pin the text a static
// node shows. Unset, the renderer reads Chars; text motion overrides it.
computed.chars[eid] = undefined;
+ // The same for a path's outline: unset, the renderer reads VectorPath.
+ computed.path[eid] = undefined;
}
/**
@@ -251,6 +258,11 @@ export function motionSystem(world: World): void {
const property = keyframeTrack.property[tid] as PropertyPath;
const target = keyframeTrack.target[tid];
const keyframes = cache.keyframes[tid] ?? [];
+ if (property === 'path') {
+ const path = samplePathTrack(world, keyframes, localFrame);
+ if (path !== null && target != null) computed.path[target.id()] = path;
+ continue;
+ }
const result = sampleTrack(world, keyframes, localFrame, property);
if (result === null || target == null) continue;
worldProps[property].computed[target.id()] = result;
@@ -405,6 +417,22 @@ export function getPropertyPaths(world: World) {
computed: computed.chars,
authored: store(world, Chars).value,
},
+ 'path': {
+ computed: computed.path,
+ authored: store(world, VectorPath).geometry,
+ },
+ 'trim.start': {
+ computed: computed.trimStart,
+ authored: store(world, PathTrim).start,
+ },
+ 'trim.end': {
+ computed: computed.trimEnd,
+ authored: store(world, PathTrim).end,
+ },
+ 'trim.offset': {
+ computed: computed.trimOffset,
+ authored: store(world, PathTrim).offset,
+ },
};
}
@@ -523,6 +551,37 @@ function sampleTrack(
return lastValue;
}
+/**
+ * Sample a presorted `d` track at a local frame: the outline between the two
+ * keyframes around it (see `interpolatePath`), or the first/last one outside
+ * them. Returns null if no keyframe holds an outline.
+ */
+function samplePathTrack(world: World, keyframes: Entity[], frame: number): PathGeometry | null {
+ const keyframe = store(world, Keyframe);
+ const keyed = keyframes.filter((entity) => keyframe.path[entity.id()] != null);
+ if (keyed.length === 0) return null;
+
+ const first = keyed[0]!.id();
+ const last = keyed[keyed.length - 1]!.id();
+ if (keyed.length === 1 || frame <= keyframe.time[first]!) return keyframe.path[first]!;
+ if (frame >= keyframe.time[last]!) return keyframe.path[last]!;
+
+ for (let i = 0; i < keyed.length - 1; i++) {
+ const from = keyed[i]!.id();
+ const to = keyed[i + 1]!.id();
+ const start = keyframe.time[from]!;
+ const end = keyframe.time[to]!;
+ if (frame < start || frame > end || end - start <= 0) continue;
+
+ let progress = Math.max(0, Math.min(1, (frame - start) / (end - start)));
+ const easingFn = resolveEasing(keyframe.easing[from]);
+ if (easingFn) progress = easingFn(progress);
+ return interpolatePath(keyframe.path[from]!, keyframe.path[to]!, progress);
+ }
+
+ return keyframe.path[last]!;
+}
+
/**
* Channel-wise linear interpolation between two packed 0xRRGGBB colors.
* Linear interpolation on the packed integer bleeds bits between channels
diff --git a/packages/runtime/src/systems/render.ts b/packages/runtime/src/systems/render.ts
index 5b77e8be..d80b2fd0 100644
--- a/packages/runtime/src/systems/render.ts
+++ b/packages/runtime/src/systems/render.ts
@@ -19,7 +19,7 @@ import {
import {
ChildOf, Hidden, Culled, Interactive, IsClipPath, AssetId,
ClipsContent, Geometry, Group, Paint, Color, Caption, ScaleMode, Shader,
- BlendMode, Effect, Mask, Transition, MixedCornerRadius, PointCount,
+ BlendMode, Effect, Mask, Transition, MixedCornerRadius, PointCount, EvenOdd,
LocalTransform, WorldTransform, Computed, Cache,
Host, Scene, Shimmering,
Mode, FrameRate, Camera, Background, RenderSurface,
@@ -28,7 +28,8 @@ import {
} from '../traits';
import { getParentNode } from '../queries/hierarchy';
import { isShapeGeometry } from '../queries/predicates';
-import { traceShape } from '../math';
+import { tracePath, traceShape } from '../math';
+import { getDrawnPath, getPathTransform } from '../queries/path';
import { getViewMatrix } from '../queries/camera';
import { colorToHex } from '../utils/color';
import { FAILED_COLOR, getSourceFailure } from '../utils/source-failure';
@@ -62,11 +63,16 @@ function getCtx(world: World): Ctx2D {
return getSurfaceContext(world)!;
}
+// The rule the shape path fills and clips by. A canvas takes it with each
+// fill or clip rather than with the path, so `drawShapePath` leaves it here
+// for the calls that fill or clip by the outline it traced.
+let shapeFillRule: CanvasFillRule = 'nonzero';
+
/**
* Begins the current path with the outline of `entity` in its own box: a
- * rect with its corner radii, or the ellipse, line or polygon its geometry
- * names. Everything that fills, strokes or clips by the node's shape reads it
- * from here.
+ * rect with its corner radii, the ellipse or polygon its geometry names, or
+ * a path's outline (with its fill rule left in `shapeFillRule`). Everything
+ * that fills, strokes or clips by the node's shape reads it from here.
*/
export function drawShapePath(world: World, entity: Entity): void {
const ctx = getCtx(world);
@@ -76,6 +82,14 @@ export function drawShapePath(world: World, entity: Entity): void {
const h = computed.height[eid]!;
const type = entity.has(Geometry) ? store(world, Geometry).value[eid]! : GeometryType.RECT;
+ shapeFillRule = 'nonzero';
+ if (type === GeometryType.PATH) {
+ ctx.beginPath();
+ const geometry = getDrawnPath(world, entity);
+ if (geometry !== null) tracePath(ctx, geometry, getPathTransform(world, entity));
+ if (entity.has(EvenOdd)) shapeFillRule = 'evenodd';
+ return;
+ }
if (type !== GeometryType.RECT && isShapeGeometry(type)) {
const pointCount = entity.has(PointCount) ? store(world, PointCount).value[eid]! : 3;
ctx.beginPath();
@@ -241,7 +255,7 @@ export function renderIntrinsicFill(world: World, entity: Entity): void {
const computed = store(world, Computed);
const eid = entity.id();
ctx.fillStyle = colorToHex(computed.color[eid] ?? 0);
- ctx.fill();
+ ctx.fill(shapeFillRule);
}
const intrinsic = getIntrinsicPaint(entity);
@@ -252,7 +266,7 @@ export function renderIntrinsicFill(world: World, entity: Entity): void {
const computed = store(world, Computed);
const eid = entity.id();
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
ctx.drawImage(canvas, 0, 0, computed.width[eid]!, computed.height[eid]!);
ctx.restore();
}
@@ -309,7 +323,7 @@ function renderHtmlFill(world: World, entity: Entity, source: Entity): void {
const eid = entity.id();
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
const width = computed.width[eid]!;
const height = computed.height[eid]!;
@@ -354,7 +368,7 @@ function renderMedia(world: World, entity: Entity, source: Entity, kind: MediaKi
if (frame) {
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
const mode = store(world, ScaleMode).value[source.id()] ?? 0;
const [dx, dy, sw, sh] = getScaledImageProps(mode, frame.width, frame.height, w, h);
@@ -363,7 +377,7 @@ function renderMedia(world: World, entity: Entity, source: Entity, kind: MediaKi
ctx.restore();
} else if (failed) {
ctx.fillStyle = MISSING_ASSET_COLOR;
- ctx.fill();
+ ctx.fill(shapeFillRule);
}
}
@@ -400,25 +414,25 @@ export function renderFills(world: World, entity: Entity): void {
const canvas = fill.get(Host)?.element;
if (canvas instanceof HTMLCanvasElement) {
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
ctx.drawImage(canvas, 0, 0, computed.width[eid]!, computed.height[eid]!);
ctx.restore();
}
} else if (paint === PaintType.SOLID) {
ctx.fillStyle = colorToHex(computed.color[fid]!);
- ctx.fill();
+ ctx.fill(shapeFillRule);
} else if (paint === PaintType.LINEAR_GRADIENT) {
const w = computed.width[eid]!;
const h = computed.height[eid]!;
- fillLinearGradient(world, fill, ctx, w, h);
+ fillLinearGradient(world, fill, ctx, w, h, shapeFillRule);
} else if (paint === PaintType.RADIAL_GRADIENT) {
const w = computed.width[eid]!;
const h = computed.height[eid]!;
- fillRadialGradient(world, fill, ctx, w, h);
+ fillRadialGradient(world, fill, ctx, w, h, shapeFillRule);
} else if (paint === PaintType.ANGULAR_GRADIENT) {
const w = computed.width[eid]!;
const h = computed.height[eid]!;
- fillAngularGradient(world, fill, ctx, w, h);
+ fillAngularGradient(world, fill, ctx, w, h, shapeFillRule);
} else if (paint === PaintType.WAVEFORM) {
renderWaveform(world, entity, fill);
} else if (paint === PaintType.SHADER) {
@@ -541,7 +555,7 @@ function renderShaderFill(world: World, entity: Entity, fills: Entity[], index:
const time = (computed.localTime[eid] ?? 0) / fps;
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
host.draw(ctx, w, h, input?.source ?? null, input?.width ?? 1, input?.height ?? 1, fit, time, store(world, Shader).uniforms[fills[index]!.id()] ?? null);
ctx.restore();
}
@@ -573,7 +587,7 @@ function renderShadows(world: World, entity: Entity): void {
ctx.shadowBlur = computed.blur[sid]! * shadowScale;
ctx.shadowOffsetX = computed.offsetX[sid]! * shadowScale;
ctx.shadowOffsetY = computed.offsetY[sid]! * shadowScale;
- ctx.fill();
+ ctx.fill(shapeFillRule);
}
ctx.restore();
@@ -660,7 +674,7 @@ function renderPendingFill(world: World, entity: Entity): void {
const ctx = getCtx(world);
ctx.fillStyle = generating ? getGeneratingColor(world) : FAILED_COLOR;
- ctx.fill();
+ ctx.fill(shapeFillRule);
}
const SHIMMER_PERIOD = 2400; // ms per turn of the highlights
@@ -785,7 +799,7 @@ function renderWaveform(world: World, entity: Entity, fill: Entity): void {
const h = computed.height[entity.id()]!;
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
// Background
ctx.fillStyle = WAVEFORM_BG_COLOR;
@@ -991,7 +1005,7 @@ function clipTo(world: World, clipPath: Entity): void {
setWorldTransform(world, ctx, clipPath);
drawShapePath(world, clipPath);
ctx.restore();
- ctx.clip();
+ ctx.clip(shapeFillRule);
}
function setWorldTransform(world: World, ctx: Ctx2D, entity: Entity): void {
@@ -1032,7 +1046,7 @@ function renderContent(world: World, entity: Entity, effects: string | null): vo
if (children.length) {
if (entity.has(ClipsContent)) {
ctx.save();
- ctx.clip();
+ ctx.clip(shapeFillRule);
}
for (const child of children) {
@@ -1219,7 +1233,7 @@ function applyMaskedEffect(world: World, entity: Entity, pass: Extract<EffectPas
resetLayer(coverage, local);
drawOnto(coverage.ctx, () => drawShapePath(world, entity));
coverage.ctx.fillStyle = '#000000';
- coverage.ctx.fill();
+ coverage.ctx.fill(shapeFillRule);
for (const mask of pass.masks) {
const strength = Math.min(1, Math.max(0, opacities[mask.id()] ?? 1));
if (strength <= EPSILON || !drawMaskRemoval(world, entity, mask, scratch, local)) continue;
@@ -1273,9 +1287,9 @@ function drawMaskRemoval(world: World, entity: Entity, mask: Entity, layer: Laye
drawOnto(ctx, () => drawShapePath(world, entity));
if (!inverted) {
ctx.fillStyle = '#000000';
- ctx.fill();
+ ctx.fill(shapeFillRule);
}
- ctx.clip();
+ ctx.clip(shapeFillRule);
ctx.globalCompositeOperation = inverted ? 'source-over' : 'destination-out';
if (feather > EPSILON) ctx.filter = `blur(${feather}px)`;
if (outline) {
diff --git a/packages/runtime/src/traits/derived.ts b/packages/runtime/src/traits/derived.ts
index 1832c541..3c38c000 100644
--- a/packages/runtime/src/traits/derived.ts
+++ b/packages/runtime/src/traits/derived.ts
@@ -6,6 +6,8 @@ import { trait, type Entity } from 'koota';
import { LINEAR_GRADIENT_DEFAULTS, ELLIPTICAL_GRADIENT_DEFAULTS } from '../constants';
+import type { PathGeometry } from '../math/path';
+
// Fully resolved per-frame values (base state + constraints + animations +
// keyframes). Written by the motion and transform systems, read by render and
// UI code. Never serialized.
@@ -43,9 +45,15 @@ export const Computed = trait({
gradientCY: ELLIPTICAL_GRADIENT_DEFAULTS.cy,
gradientRX: ELLIPTICAL_GRADIENT_DEFAULTS.rx,
gradientRY: ELLIPTICAL_GRADIENT_DEFAULTS.ry,
+ trimStart: 0,
+ trimEnd: 1,
+ trimOffset: 0,
width: 0,
height: 0,
chars: undefined as string | undefined,
+ // A path's outline as its `d` track has it this frame. Unset, the
+ // renderer reads VectorPath.
+ path: () => undefined as PathGeometry | undefined,
localTimeInSeconds: 0, // playhead position in seconds
localTime: 0, // playhead position in frames (mirrors localTimeInSeconds)
duration: 0, // end - start
diff --git a/packages/runtime/src/traits/motion.ts b/packages/runtime/src/traits/motion.ts
index 4916ce1a..6ac89a80 100644
--- a/packages/runtime/src/traits/motion.ts
+++ b/packages/runtime/src/traits/motion.ts
@@ -6,6 +6,8 @@ import { trait, type Entity } from 'koota';
import { AnimationType, AnimationPhase } from '../constants';
+import type { PathGeometry } from '../math/path';
+
// KeyframeTrack entity: one per (target, property) pair. ChildOf its target
// (geometry, paint, color stop, ...) and owns the Keyframe entities as
// children. `target` is denormalised: ChildOf is authoritative, but the keyed
@@ -17,8 +19,10 @@ export const KeyframeTrack = trait({
});
// Keyframe entity: ChildOf its KeyframeTrack. Easing applies to the segment
-// from this keyframe to the next-in-time on the same track.
-export const Keyframe = trait({ time: 0, value: 0, easing: 'linear' });
+// from this keyframe to the next-in-time on the same track. A keyframe on a
+// `d` track holds its outline in `path` (parsed from its value) rather than
+// in `value`.
+export const Keyframe = trait({ time: 0, value: 0, easing: 'linear', path: () => null as PathGeometry | null });
// Animation entity: one preset in/out animation, ChildOf its target.
export const Animation = trait({
diff --git a/packages/runtime/src/traits/node.ts b/packages/runtime/src/traits/node.ts
index 23dde3e5..fd8ba781 100644
--- a/packages/runtime/src/traits/node.ts
+++ b/packages/runtime/src/traits/node.ts
@@ -7,7 +7,7 @@ import { trait } from 'koota';
import { GeometryType, PaintType, CaptionType, CaptionAlign } from '../constants';
-// Geometric primitive: RECT, ELLIPSE, POLYGON or TEXT (see GeometryType). Other node-like roles
+// Geometric primitive: RECT, ELLIPSE, POLYGON, PATH or TEXT (see GeometryType). Other node-like roles
// (group, audio, scene, caption) are layered on top via tag traits.
export const Geometry = trait({ value: GeometryType.RECT as GeometryType });
diff --git a/packages/runtime/src/traits/style.ts b/packages/runtime/src/traits/style.ts
index f01ca7fc..c44b16f8 100644
--- a/packages/runtime/src/traits/style.ts
+++ b/packages/runtime/src/traits/style.ts
@@ -5,6 +5,8 @@
import { DEFAULT_MASK_SMOOTHING } from '@diffusionstudio/assets';
import { trait } from 'koota';
+import type { PathGeometry } from '../math/path';
+
import { BlendModeType, EffectType, ScaleModeType, StrokeJoin, StrokeCap, LINEAR_GRADIENT_DEFAULTS, ELLIPTICAL_GRADIENT_DEFAULTS } from '../constants';
// Opacity of whatever the entity is: a node, a paint, a stroke, a shadow, a
@@ -30,6 +32,22 @@ export const MixedCornerRadius = trait({
// A polygon's corner count, at least 3 (see `clampPointCount`). Absent means 3.
export const PointCount = trait({ value: 3 });
+// A path's outline: its `d`, parsed (see `parsePath`), in the coordinates
+// of its ViewBox. Absent or null draws nothing; a `d` keyframe track
+// overrides it through Computed.path.
+export const VectorPath = trait({ geometry: () => null as PathGeometry | null });
+
+// A path filled by the even-odd rule rather than nonzero (`fillRule`).
+export const EvenOdd = trait();
+
+// Where a path's `d` is drawn from, stretched onto its box on each axis.
+// Absent means the box's own coordinates ("0 0 width height").
+export const ViewBox = trait({ x: 0, y: 0, width: 0, height: 0 });
+
+// A path trimmed to part of its length, as fractions of each subpath's
+// length (see `trimPath`). Absent means the whole path.
+export const PathTrim = trait({ start: 0, end: 1, offset: 0 });
+
export const Blur = trait({ value: 0 });
// Scale mode for image fills and any other scaled asset display.
diff --git a/packages/runtime/src/world/observers.ts b/packages/runtime/src/world/observers.ts
index a0d4351d..65ddd056 100644
--- a/packages/runtime/src/world/observers.ts
+++ b/packages/runtime/src/world/observers.ts
@@ -9,7 +9,7 @@ import {
Delay, Trim, PlaybackRate, SourceFrameRate, Keyframe, ItemIndex,
Position, Offset, Rotation, Scale, UniformScale, Skew, Anchor, Flip,
Opacity, Color, Blur, Volume, Effect, CornerRadius, MixedCornerRadius,
- ColorStop, LinearGradient, EllipticalGradient, StrokeStyle, Size, Computed, Active, Stage, IsClipPath,
+ ColorStop, LinearGradient, EllipticalGradient, PathTrim, StrokeStyle, Size, Computed, Active, Stage, IsClipPath,
ImageDecoderHandle, VideoDecoderHandle,
AudioDecoderHandle, CaptionDecoderHandle, WaveformHandle,
ShaderHostHandle, AudioBusHandle, TextStyle, TextRange,
@@ -289,6 +289,14 @@ export function observeWorld(world: World): () => void {
computed.gradientRY[entity.id()] = ry;
});
+ mirror(PathTrim, (entity) => {
+ const computed = store(world, Computed);
+ const { start, end, offset } = entity.get(PathTrim)!;
+ computed.trimStart[entity.id()] = start;
+ computed.trimEnd[entity.id()] = end;
+ computed.trimOffset[entity.id()] = offset;
+ });
+
mirror(StrokeStyle, (entity) => {
store(world, Computed).strokeWidth[entity.id()] = entity.get(StrokeStyle)!.width;
});