Skip to content

Open source CapCut alternative.

TypeScript

feat(site): twelve overlay loops, four of them per letter [rebuild]

David Le1d7da61e0e1c
diff --git a/site/packages/effects-kit/src/anim.ts b/site/packages/effects-kit/src/anim.ts
index b4422649..476af22e 100644
--- a/site/packages/effects-kit/src/anim.ts
+++ b/site/packages/effects-kit/src/anim.ts
@@ -13,9 +13,49 @@ export type OverlayAnimStyle =
| "slideright"
| "slideup"
| "slidedown"
- | "typewriter"; // text only; other kinds render it as a fade
+ | "typewriter" // text only; other kinds render it as a fade
+ | "wipe"
+ // Per-glyph styles: on text each character runs the ramp on its own delay
+ // (see glyphAnimAt); on every other kind the whole element runs it once.
+ | "rise"
+ | "drop"
+ | "grow"
+ | "flip"
+ | "swivel"
+ | "bounce"
+ | "wave"
+ | "converge"
+ | "streak"
+ | "tumble"
+ | "scatter";
-export type OverlayLoopStyle = "pulse" | "wiggle" | "spin" | "float";
+export type OverlayLoopStyle =
+ | "pulse"
+ | "heartbeat"
+ | "float"
+ | "sway"
+ | "spin"
+ | "wiggle"
+ | "shake"
+ | "flicker"
+ // Per-glyph loops: on text each character runs the cycle on its own delay
+ // (see glyphLoopAt), so the motion travels along the line; on every other
+ // kind the whole element runs it as one piece.
+ | "wave"
+ | "bounce"
+ | "flip"
+ | "flutter";
+
+/** The loops that move each character on its own delay. */
+export type GlyphLoopStyle = "wave" | "bounce" | "flip" | "flutter";
+
+export const GLYPH_LOOP_STYLE_IDS: GlyphLoopStyle[] = ["wave", "bounce", "flip", "flutter"];
+
+const GLYPH_LOOPS: Set<string> = new Set(GLYPH_LOOP_STYLE_IDS);
+
+export function isGlyphLoopStyle(style: OverlayLoopStyle): style is GlyphLoopStyle {
+ return GLYPH_LOOPS.has(style);
+}
export interface OverlayAnim {
in?: { style: OverlayAnimStyle; seconds: number };
@@ -34,9 +74,79 @@ export const OVERLAY_ANIM_STYLE_IDS: OverlayAnimStyle[] = [
"slideup",
"slidedown",
"typewriter",
+ "wipe",
+ "rise",
+ "drop",
+ "grow",
+ "flip",
+ "swivel",
+ "bounce",
+ "wave",
+ "converge",
+ "streak",
+ "tumble",
+ "scatter",
];
-export const OVERLAY_LOOP_STYLE_IDS: OverlayLoopStyle[] = ["pulse", "wiggle", "spin", "float"];
+/** The styles that move each character on its own delay. Text plays them glyph
+ * by glyph; anything else plays the same motion as one piece. */
+export type GlyphAnimStyle =
+ | "rise"
+ | "drop"
+ | "grow"
+ | "flip"
+ | "swivel"
+ | "bounce"
+ | "wave"
+ | "converge"
+ | "streak"
+ | "tumble"
+ | "scatter";
+
+export const GLYPH_ANIM_STYLE_IDS: GlyphAnimStyle[] = [
+ "rise",
+ "drop",
+ "grow",
+ "flip",
+ "swivel",
+ "bounce",
+ "wave",
+ "converge",
+ "streak",
+ "tumble",
+ "scatter",
+];
+
+const GLYPH_STYLES: Set<string> = new Set(GLYPH_ANIM_STYLE_IDS);
+
+export function isGlyphAnimStyle(style: OverlayAnimStyle): style is GlyphAnimStyle {
+ return GLYPH_STYLES.has(style);
+}
+
+/**
+ * Whether a style changes the element's pixels rather than moving them as one
+ * picture. A cached bitmap under a transform can't express these, so both
+ * renderers bake them frame by frame.
+ */
+export function bakesPixels(style: OverlayAnimStyle, isText: boolean): boolean {
+ if (style === "wipe") return true;
+ return isText && (style === "typewriter" || isGlyphAnimStyle(style));
+}
+
+export const OVERLAY_LOOP_STYLE_IDS: OverlayLoopStyle[] = [
+ "pulse",
+ "heartbeat",
+ "float",
+ "sway",
+ "spin",
+ "wiggle",
+ "shake",
+ "flicker",
+ "wave",
+ "bounce",
+ "flip",
+ "flutter",
+];
export const OVERLAY_ANIM_STYLE_LABELS: Record<OverlayAnimStyle, string> = {
fade: "Fade",
@@ -47,13 +157,33 @@ export const OVERLAY_ANIM_STYLE_LABELS: Record<OverlayAnimStyle, string> = {
slideup: "Slide up",
slidedown: "Slide down",
typewriter: "Typewriter",
+ wipe: "Wipe",
+ rise: "Rise",
+ drop: "Drop",
+ grow: "Grow",
+ flip: "Flip",
+ swivel: "Swivel",
+ bounce: "Bounce",
+ wave: "Wave",
+ converge: "Converge",
+ streak: "Streak",
+ tumble: "Tumble",
+ scatter: "Scatter",
};
export const OVERLAY_LOOP_STYLE_LABELS: Record<OverlayLoopStyle, string> = {
pulse: "Pulse",
- wiggle: "Wiggle",
- spin: "Spin",
+ heartbeat: "Heartbeat",
float: "Float",
+ sway: "Sway",
+ spin: "Spin",
+ wiggle: "Wiggle",
+ shake: "Shake",
+ flicker: "Flicker",
+ wave: "Wave",
+ bounce: "Bounce",
+ flip: "Flip",
+ flutter: "Flutter",
};
/** Ramp length bounds, seconds (mirrors clip animations). */
@@ -65,17 +195,90 @@ export const OVERLAY_ANIM_DEFAULT_SECONDS = 0.5;
export const SLIDE_TRAVEL = 120;
/** Float bob amplitude, design px. */
export const FLOAT_TRAVEL = 12;
+/** Loop amplitudes, design px. */
+const SWAY_TRAVEL = 18;
+const SHAKE_TRAVEL = 7;
+const WAVE_LOOP_TRAVEL = 16;
+const BOUNCE_LOOP_TRAVEL = 24;
+const FLUTTER_TRAVEL = 5;
+/** Per-glyph travel distances, design px. */
+const RISE_TRAVEL = 46;
+const WAVE_TRAVEL = 26;
+const STREAK_TRAVEL = 110;
+const CONVERGE_SPREAD = 90;
+const SCATTER_TRAVEL = 70;
+/** The farthest a glyph ever strays from its resting spot — what the frame
+ * sampler pads its crop region by. */
+export const GLYPH_TRAVEL_MAX = 120;
/** Base loop periods in seconds at speed 1. */
export const LOOP_PERIODS: Record<OverlayLoopStyle, number> = {
pulse: 1.2,
- wiggle: 0.9,
- spin: 4,
+ heartbeat: 1.5,
float: 2.4,
+ sway: 2.8,
+ spin: 4,
+ wiggle: 0.9,
+ shake: 0.5,
+ flicker: 1.8,
+ wave: 1.6,
+ bounce: 1.6,
+ flip: 3.2,
+ flutter: 1.4,
};
+/**
+ * How far a loop strays from rest, in design px, and whether it turns. The
+ * frame sampler crops an element to the box it lives in, so a loop that
+ * travels has to say so or the sampler clips the motion off.
+ */
+export function loopExtent(style: OverlayLoopStyle | undefined): {
+ travel: number;
+ rotates: boolean;
+} {
+ switch (style) {
+ case "float":
+ return { travel: FLOAT_TRAVEL, rotates: false };
+ case "sway":
+ return { travel: SWAY_TRAVEL, rotates: true };
+ case "shake":
+ return { travel: SHAKE_TRAVEL, rotates: false };
+ case "wave":
+ return { travel: WAVE_LOOP_TRAVEL, rotates: false };
+ case "bounce":
+ return { travel: BOUNCE_LOOP_TRAVEL, rotates: false };
+ case "flutter":
+ return { travel: FLUTTER_TRAVEL, rotates: true };
+ case "spin":
+ case "wiggle":
+ return { travel: 0, rotates: true };
+ default:
+ return { travel: 0, rotates: false };
+ }
+}
+
+/** Where a per-glyph ramp stands. Renderers walk the element's characters and
+ * ask `glyphAnimAt` where each one sits. */
+export interface GlyphPhase {
+ style: OverlayAnimStyle;
+ /** 0 at the far end of the ramp, 1 at rest. */
+ p: number;
+ exiting: boolean;
+}
+
+/** Where a per-glyph loop stands: one number, 0 to 1 around the cycle. Each
+ * character reads it at its own delay. */
+export interface GlyphLoopPhase {
+ style: GlyphLoopStyle;
+ phase: number;
+}
+
/** The transform an animation contributes at one moment. dx/dy are design px
* (1080 short side); rotate is degrees; alpha multiplies the element opacity;
- * textProgress (0..1, typewriter only) is the share of characters shown. */
+ * textProgress (0..1, typewriter only) is the share of characters shown;
+ * reveal (0..1, wipe) is the share of the box uncovered from its left edge;
+ * glyphs and glyphLoop replace the whole-element transform with a
+ * per-character one, and both apply at once (a title can fly its letters in
+ * and then keep them waving). */
export interface OverlayAnimState {
dx: number;
dy: number;
@@ -83,9 +286,24 @@ export interface OverlayAnimState {
rotate: number;
alpha: number;
textProgress?: number;
+ reveal?: number;
+ glyphs?: GlyphPhase;
+ glyphLoop?: GlyphLoopPhase;
+}
+
+/** How one character sits at a moment: offsets in design px, a scale per axis
+ * (a flip runs its axis through zero), degrees, and its own opacity. */
+export interface GlyphAnimState {
+ dx: number;
+ dy: number;
+ sx: number;
+ sy: number;
+ rotate: number;
+ alpha: number;
}
const IDLE: OverlayAnimState = { dx: 0, dy: 0, scale: 1, rotate: 0, alpha: 1 };
+const GLYPH_IDLE: GlyphAnimState = { dx: 0, dy: 0, sx: 1, sy: 1, rotate: 0, alpha: 1 };
const easeOutCubic = (p: number) => 1 - Math.pow(1 - p, 3);
const easeInCubic = (p: number) => p * p * p;
@@ -95,11 +313,317 @@ const easeOutBack = (p: number) => {
return 1 + c3 * Math.pow(p - 1, 3) + c1 * Math.pow(p - 1, 2);
};
+const easeOutBounce = (p: number) => {
+ const n1 = 7.5625;
+ const d1 = 2.75;
+ if (p < 1 / d1) return n1 * p * p;
+ if (p < 2 / d1) return n1 * (p -= 1.5 / d1) * p + 0.75;
+ if (p < 2.5 / d1) return n1 * (p -= 2.25 / d1) * p + 0.9375;
+ return n1 * (p -= 2.625 / d1) * p + 0.984375;
+};
+
+const clamp01 = (p: number) => Math.min(1, Math.max(0, p));
+
+/**
+ * One glyph's motion at its own progress `q` (0 = the far end of the ramp,
+ * 1 = at rest). `index`/`count` place it in the run, which is what a spread or
+ * a scatter needs; a whole element playing the same style is glyph 0 of 1.
+ */
+function glyphMotion(
+ style: OverlayAnimStyle,
+ q: number,
+ exiting: boolean,
+ index: number,
+ count: number
+): GlyphAnimState {
+ const away = 1 - easeOutCubic(q);
+ const dir = exiting ? -1 : 1;
+ const fade = (mult: number) => Math.min(1, q * mult);
+ switch (style) {
+ case "rise":
+ return { ...GLYPH_IDLE, dy: away * RISE_TRAVEL * dir, alpha: q };
+ case "drop":
+ return { ...GLYPH_IDLE, dy: -away * RISE_TRAVEL * dir, alpha: q };
+ case "grow": {
+ const s = easeOutBack(q);
+ return { ...GLYPH_IDLE, sx: s, sy: s, alpha: fade(2) };
+ }
+ case "flip":
+ return { ...GLYPH_IDLE, sy: Math.cos((1 - q) * Math.PI), alpha: fade(4) };
+ case "swivel":
+ return { ...GLYPH_IDLE, sx: Math.cos((1 - q) * Math.PI), alpha: fade(4) };
+ case "bounce":
+ return {
+ ...GLYPH_IDLE,
+ dy: -(1 - easeOutBounce(q)) * RISE_TRAVEL * dir,
+ alpha: fade(4),
+ };
+ case "wave":
+ // Up from below with an arch past the resting line; run one after the
+ // other, the arch is what reads as the wave.
+ return {
+ ...GLYPH_IDLE,
+ dy: (away - Math.sin(q * Math.PI) * 0.6) * WAVE_TRAVEL,
+ alpha: fade(2.5),
+ };
+ case "converge": {
+ // Spread across the run, then pulled together into place.
+ const frac = count > 1 ? (index / (count - 1)) * 2 - 1 : 0;
+ return { ...GLYPH_IDLE, dx: frac * CONVERGE_SPREAD * away, alpha: fade(2) };
+ }
+ case "streak":
+ return {
+ ...GLYPH_IDLE,
+ dx: -away * STREAK_TRAVEL * dir,
+ sx: 1 + away * 0.5,
+ alpha: fade(2),
+ };
+ case "tumble":
+ return {
+ ...GLYPH_IDLE,
+ dy: -away * RISE_TRAVEL * 1.4 * dir,
+ rotate: -away * 35 * dir,
+ alpha: fade(2),
+ };
+ case "scatter": {
+ // The golden angle spreads the directions evenly however many glyphs
+ // there are, and the same index always flies the same way.
+ const a = index * 2.399963;
+ const reach = SCATTER_TRAVEL * (0.7 + 0.3 * (((index * 7919) % 13) / 13));
+ return {
+ ...GLYPH_IDLE,
+ dx: Math.cos(a) * reach * away,
+ dy: Math.sin(a) * reach * away,
+ rotate: away * 25 * (index % 2 ? -1 : 1),
+ alpha: q,
+ };
+ }
+ default:
+ return GLYPH_IDLE;
+ }
+}
+
+/** Share of the ramp spent handing the motion from the first glyph to the
+ * last; what's left is how long any one glyph takes. */
+const GLYPH_STAGGER = 0.6;
+const GLYPH_STAGGER_BY_STYLE: Partial<Record<OverlayAnimStyle, number>> = {
+ converge: 0.25,
+ wave: 0.75,
+ flip: 0.7,
+ swivel: 0.7,
+};
+
+/**
+ * Where character `index` of `count` sits when its element's ramp stands at
+ * `p`. Glyphs start in order and overlap, so the motion sweeps the line; an
+ * exit sweeps out the way it came in.
+ */
+export function glyphAnimAt(
+ style: OverlayAnimStyle,
+ p: number,
+ index: number,
+ count: number,
+ exiting: boolean
+): GlyphAnimState {
+ const n = Math.max(1, count);
+ const i = exiting ? n - 1 - index : index;
+ const stagger = GLYPH_STAGGER_BY_STYLE[style] ?? GLYPH_STAGGER;
+ const from = n > 1 ? (i / (n - 1)) * stagger : 0;
+ return glyphMotion(style, clamp01((clamp01(p) - from) / (1 - stagger)), exiting, index, n);
+}
+
+/** The whole-element stand-in for a per-glyph ramp: the same motion run once
+ * over the box, for renderers that only have one cached picture to move. */
+export function glyphFallback(phase: GlyphPhase): GlyphAnimState {
+ return glyphMotion(phase.style, clamp01(phase.p), phase.exiting, 0, 1);
+}
+
+const TAU = Math.PI * 2;
+const wrap01 = (v: number) => v - Math.floor(v);
+/** Distance between two points on a cycle, either way round. */
+const cyclicGap = (a: number, b: number) => {
+ const d = Math.abs(wrap01(a) - wrap01(b));
+ return Math.min(d, 1 - d);
+};
+
+/**
+ * One glyph's place in a loop at cycle position `phase`. Every loop is exactly
+ * periodic in `phase` — built from whole harmonics and wrapped offsets — which
+ * is what lets the frame sampler render one cycle of pictures and repeat them
+ * for as long as the element runs.
+ *
+ * `index`/`count` stagger the run: most of these hand the motion down the line
+ * one character at a time, and a whole element playing the same loop is glyph
+ * 0 of 1.
+ */
+function glyphLoopMotion(
+ style: GlyphLoopStyle,
+ phase: number,
+ index: number,
+ count: number
+): GlyphAnimState {
+ const n = Math.max(1, count);
+ // Each character starts its turn a little later than the one before it, so
+ // one cycle sweeps the whole line exactly once.
+ const u = wrap01(phase - index / n);
+ switch (style) {
+ case "wave":
+ return { ...GLYPH_IDLE, dy: -Math.sin(u * TAU) * WAVE_LOOP_TRAVEL };
+ case "bounce": {
+ // Up over the first half of the turn, a beat on the ground for the
+ // second. The character stretches as it rises and squashes as it sits,
+ // so the weight of the hop reads even at caption size.
+ const hop = Math.max(0, Math.sin(u * TAU));
+ const ground = Math.max(0, -Math.sin(u * TAU));
+ return {
+ ...GLYPH_IDLE,
+ dy: -hop * BOUNCE_LOOP_TRAVEL,
+ sx: 1 - 0.05 * hop + 0.08 * ground,
+ sy: 1 + 0.07 * hop - 0.1 * ground,
+ };
+ }
+ case "flip": {
+ // A split-flap turn: one full revolution inside the character's window,
+ // and it sits still for the rest of the cycle.
+ const window = 0.4;
+ return { ...GLYPH_IDLE, sy: Math.cos(TAU * Math.min(1, u / window)) };
+ }
+ case "flutter": {
+ // No hand-off here: the golden angle gives every character its own place
+ // in the cycle, so the line shimmers instead of sweeping.
+ const a = index * 2.399963;
+ return {
+ ...GLYPH_IDLE,
+ dx: Math.sin(TAU * phase + a) * FLUTTER_TRAVEL,
+ dy: Math.sin(TAU * phase + a * 1.7) * FLUTTER_TRAVEL,
+ rotate: Math.sin(2 * TAU * phase + a) * 5,
+ };
+ }
+ }
+}
+
+/** Where character `index` of `count` sits with everything applied — the edge
+ * ramp it is playing and the loop it is running, folded into one transform.
+ * Every renderer that draws a title letter by letter calls this. */
+export function glyphStateAt(
+ state: { glyphs?: GlyphPhase; glyphLoop?: GlyphLoopPhase },
+ index: number,
+ count: number
+): GlyphAnimState {
+ const ramp = state.glyphs
+ ? glyphAnimAt(state.glyphs.style, state.glyphs.p, index, count, state.glyphs.exiting)
+ : GLYPH_IDLE;
+ if (!state.glyphLoop) return ramp;
+ const loop = glyphLoopMotion(state.glyphLoop.style, state.glyphLoop.phase, index, count);
+ return {
+ dx: ramp.dx + loop.dx,
+ dy: ramp.dy + loop.dy,
+ sx: ramp.sx * loop.sx,
+ sy: ramp.sy * loop.sy,
+ rotate: ramp.rotate + loop.rotate,
+ alpha: ramp.alpha * loop.alpha,
+ };
+}
+
+/** Whether this moment draws the element letter by letter. */
+export function hasGlyphMotion(state: {
+ glyphs?: GlyphPhase;
+ glyphLoop?: GlyphLoopPhase;
+}): boolean {
+ return !!state.glyphs || !!state.glyphLoop;
+}
+
+/** The loop's contribution at `phase`, written onto the state the edge ramps
+ * left. A per-glyph loop hands the characters their own cycle; on any other
+ * kind it folds back into the one transform the element has. */
+function applyLoop(
+ state: OverlayAnimState,
+ style: OverlayLoopStyle,
+ phase: number,
+ isText: boolean
+): void {
+ if (isGlyphLoopStyle(style)) {
+ if (isText) {
+ state.glyphLoop = { style, phase };
+ return;
+ }
+ const g = glyphLoopMotion(style, phase, 0, 1);
+ state.dx += g.dx;
+ state.dy += g.dy;
+ state.rotate += g.rotate;
+ state.scale *= (g.sx + g.sy) / 2;
+ state.alpha *= g.alpha;
+ return;
+ }
+ const wave = Math.sin(phase * TAU);
+ switch (style) {
+ case "pulse":
+ state.scale *= 1 + 0.06 * wave;
+ break;
+ case "heartbeat": {
+ // Two thumps close together, then the rest of the cycle at rest — the
+ // gap is what separates it from a pulse.
+ const thump = (at: number, width: number) =>
+ Math.exp(-Math.pow(cyclicGap(phase, at) / width, 2));
+ state.scale *= 1 + 0.14 * thump(0.06, 0.045) + 0.09 * thump(0.2, 0.05);
+ break;
+ }
+ case "float":
+ state.dy += FLOAT_TRAVEL * wave;
+ break;
+ case "sway":
+ // The tilt follows the glide, so the element leans into the turn.
+ state.dx += SWAY_TRAVEL * wave;
+ state.rotate += 3 * wave;
+ break;
+ case "spin":
+ state.rotate += phase * 360;
+ break;
+ case "wiggle":
+ state.rotate += 4 * wave;
+ break;
+ case "shake":
+ // Stacked harmonics: erratic to watch, and still exactly periodic.
+ state.dx += SHAKE_TRAVEL * (wave * 0.65 + Math.sin(3 * phase * TAU) * 0.35);
+ state.dy +=
+ SHAKE_TRAVEL *
+ 0.7 *
+ (Math.sin(2 * phase * TAU) * 0.7 + Math.sin(5 * phase * TAU) * 0.3);
+ break;
+ case "flicker": {
+ // Lit most of the way round, with one stuttering dip.
+ const dip = Math.max(0, wave) * (0.6 + 0.4 * Math.sin(5 * phase * TAU));
+ state.alpha *= 1 - 0.55 * Math.max(0, dip);
+ break;
+ }
+ }
+}
+
/** One edge ramp. `p` runs 0→1 over the window in play direction for "in";
- * for "out" the caller feeds remaining-share so the motion mirrors. */
-function edgeState(style: OverlayAnimStyle, p: number, exiting: boolean): OverlayAnimState {
+ * for "out" the caller feeds remaining-share so the motion mirrors. Text hands
+ * the per-glyph styles to the renderer as a phase; every other kind plays the
+ * same motion as one piece. */
+function edgeState(
+ style: OverlayAnimStyle,
+ p: number,
+ exiting: boolean,
+ isText: boolean
+): OverlayAnimState {
const clamped = Math.min(1, Math.max(0, p));
+ if (isGlyphAnimStyle(style)) {
+ if (isText) return { ...IDLE, glyphs: { style, p: clamped, exiting } };
+ const g = glyphFallback({ style, p: clamped, exiting });
+ return {
+ dx: g.dx,
+ dy: g.dy,
+ scale: (g.sx + g.sy) / 2,
+ rotate: g.rotate,
+ alpha: g.alpha,
+ };
+ }
switch (style) {
+ case "wipe":
+ return { ...IDLE, reveal: clamped };
case "fade":
return { ...IDLE, alpha: clamped };
case "pop":
@@ -135,7 +659,8 @@ function edgeState(style: OverlayAnimStyle, p: number, exiting: boolean): Overla
export function evalOverlayAnim(
anim: OverlayAnim | undefined,
tLocal: number,
- dur: number
+ dur: number,
+ isText = false
): OverlayAnimState {
if (!anim) return IDLE;
let state = { ...IDLE };
@@ -144,30 +669,15 @@ export function evalOverlayAnim(
const outSecs = anim.out ? Math.min(anim.out.seconds, Math.max(0, dur - inSecs)) : 0;
if (anim.in && tLocal < inSecs) {
- state = edgeState(anim.in.style, tLocal / inSecs, false);
+ state = edgeState(anim.in.style, tLocal / inSecs, false, isText);
} else if (anim.out && tLocal > dur - outSecs) {
- state = edgeState(anim.out.style, (dur - tLocal) / outSecs, true);
+ state = edgeState(anim.out.style, (dur - tLocal) / outSecs, true, isText);
}
if (anim.loop) {
const speed = anim.loop.speed > 0 ? anim.loop.speed : 1;
const period = LOOP_PERIODS[anim.loop.style] / speed;
- const phase = (tLocal % period) / period;
- const wave = Math.sin(phase * Math.PI * 2);
- switch (anim.loop.style) {
- case "pulse":
- state.scale *= 1 + 0.06 * wave;
- break;
- case "wiggle":
- state.rotate += 4 * wave;
- break;
- case "spin":
- state.rotate += phase * 360;
- break;
- case "float":
- state.dy += FLOAT_TRAVEL * wave;
- break;
- }
+ applyLoop(state, anim.loop.style, wrap01(tLocal / period), isText);
}
return state;
}
diff --git a/site/packages/effects-kit/src/keys.ts b/site/packages/effects-kit/src/keys.ts
index ccacdb64..521a3816 100644
--- a/site/packages/effects-kit/src/keys.ts
+++ b/site/packages/effects-kit/src/keys.ts
@@ -15,7 +15,13 @@
* the frame sampler that feeds ffmpeg.
*/
-import { evalOverlayAnim, hasOverlayAnim, type OverlayAnim } from "./anim";
+import {
+ evalOverlayAnim,
+ hasOverlayAnim,
+ type GlyphLoopPhase,
+ type GlyphPhase,
+ type OverlayAnim,
+} from "./anim";
/** A pose captured at `t` seconds into the element. Values are absolute, in
* the same units as the element's own fields — `scale` multiplies the
@@ -46,6 +52,9 @@ interface Posable {
end: number;
x: number;
y: number;
+ /** Absent means text — the union's own default. Only the per-glyph styles
+ * read it, to decide whether there are glyphs to move. */
+ kind?: string;
rotation?: number;
opacity?: number;
anim?: OverlayAnim;
@@ -176,12 +185,19 @@ export interface OverlayFrameState extends OverlayPose {
dy: number;
/** 0..1 share of the text shown (typewriter); absent when not typing. */
textProgress?: number;
+ /** 0..1 share of the box uncovered from its left edge (wipe). */
+ reveal?: number;
+ /** Where a per-glyph ramp stands; the element's own transform stays neutral
+ * and each character carries the motion. */
+ glyphs?: GlyphPhase;
+ /** Where a per-glyph loop stands, on the same terms. */
+ glyphLoop?: GlyphLoopPhase;
}
export function evalOverlayFrame(o: Posable, tLocal: number): OverlayFrameState {
const dur = Math.max(0.1, o.end - o.start);
const pose = poseAt(o, tLocal);
- const ev = evalOverlayAnim(o.anim, tLocal, dur);
+ const ev = evalOverlayAnim(o.anim, tLocal, dur, (o.kind ?? "text") === "text");
return {
x: pose.x,
y: pose.y,
@@ -191,6 +207,9 @@ export function evalOverlayFrame(o: Posable, tLocal: number): OverlayFrameState
rotation: pose.rotation + ev.rotate,
opacity: pose.opacity * ev.alpha,
...(ev.textProgress !== undefined ? { textProgress: ev.textProgress } : {}),
+ ...(ev.reveal !== undefined ? { reveal: ev.reveal } : {}),
+ ...(ev.glyphs ? { glyphs: ev.glyphs } : {}),
+ ...(ev.glyphLoop ? { glyphLoop: ev.glyphLoop } : {}),
};
}
diff --git a/site/packages/effects-kit/src/render.ts b/site/packages/effects-kit/src/render.ts
index 82faef84..e69ff941 100644
--- a/site/packages/effects-kit/src/render.ts
+++ b/site/packages/effects-kit/src/render.ts
@@ -6,9 +6,16 @@
*/
import {
- FLOAT_TRAVEL,
+ bakesPixels,
+ glyphStateAt,
+ GLYPH_TRAVEL_MAX,
+ hasGlyphMotion,
+ isGlyphAnimStyle,
+ loopExtent,
loopPeriod,
SLIDE_TRAVEL,
+ type GlyphLoopPhase,
+ type GlyphPhase,
type OverlayAnim,
type OverlayAnimStyle,
} from "./anim";
@@ -16,6 +23,7 @@ import { evalOverlayFrame, hasOverlayKeys, poseAt, poseExtent, sortedKeys } from
import { applyMaskToCanvas, isMaskAnimated } from "./mask";
import type { LottieHandle } from "./lottie";
import { elementPlugin } from "./registry";
+import { kitCanvas } from "./surface";
import {
lineLikeShape,
type Overlay,
@@ -108,6 +116,18 @@ export interface PaintFrame {
height: number;
scale: number;
t?: number;
+ /** Pixel-level animation baked into this picture; absent = the element at
+ * rest. */
+ phase?: PaintPhase;
+}
+
+/** What a pixel-changing animation contributes to one picture: how much of the
+ * element is uncovered, and where its characters sit. The transform styles
+ * never come through here — they ride the drawn picture instead. */
+export interface PaintPhase {
+ reveal?: number;
+ glyphs?: GlyphPhase;
+ glyphLoop?: GlyphLoopPhase;
}
/**
@@ -379,6 +399,42 @@ async function paintText(
? cx - maxW / 2 + widthsOf[i] / 2
: cx + maxW / 2 - widthsOf[i] / 2;
+ const phase = frame.phase;
+ if (phase && hasGlyphMotion(phase)) {
+ // A per-glyph ramp or loop draws character by character, each at its own
+ // place in the motion. The index counts through the whole element, line
+ // breaks included, which is exactly what the DOM preview counts.
+ const total = Math.max(1, [...overlay.text].length);
+ const alpha0 = ctx.globalAlpha;
+ let gi = 0;
+ lines.forEach((line, i) => {
+ const y = cy - totalH / 2 + lineH * (i + 0.5);
+ // Characters drawn one by one lose the kerning between them, so the run
+ // is centered on what it actually measures — the DOM's inline boxes
+ // land in the same place.
+ const chars = [...line];
+ const widths = chars.map((ch) => ctx.measureText(ch).width);
+ let x = lineX(i) - widths.reduce((a, b) => a + b, 0) / 2;
+ chars.forEach((ch, ci) => {
+ const w = widths[ci];
+ const g = glyphStateAt(phase, gi, total);
+ gi++;
+ if (ch !== " " && g.alpha > 0.001) {
+ ctx.save();
+ ctx.globalAlpha = alpha0 * Math.min(1, Math.max(0, g.alpha));
+ ctx.translate(x + w / 2 + g.dx * scale, y + g.dy * scale);
+ if (g.rotate) ctx.rotate((g.rotate * Math.PI) / 180);
+ ctx.scale(g.sx, g.sy);
+ drawText(ch, 0, 0);
+ ctx.restore();
+ }
+ x += w;
+ });
+ gi++; // the line break takes a turn too
+ });
+ return;
+ }
+
// Karaoke: draw word by word so the spoken word gets the accent color and an
// underline; the word index counts across all lines.
let k = 0;
@@ -434,6 +490,20 @@ export async function paintElement(
): Promise<void> {
const kind = overlay.kind ?? "text";
if (kind === "effect") return; // effects filter the video; nothing to paint
+ const reveal = frame.phase?.reveal;
+ if (reveal !== undefined && reveal < 1) {
+ // A wipe uncovers the element from its left edge: clip to the uncovered
+ // share of its box and paint the whole thing behind it.
+ if (reveal <= 0) return;
+ const b = await measureElementBounds(overlay, frame, env);
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(b.cx - b.w / 2, b.cy - b.h / 2, b.w * reveal, b.h);
+ ctx.clip();
+ await paintElement(ctx, overlay, { ...frame, phase: { ...frame.phase, reveal: undefined } }, env);
+ ctx.restore();
+ return;
+ }
const plugin = elementPlugin(kind);
if (plugin) {
await plugin.paint(ctx, overlay, frame, env);
@@ -458,10 +528,7 @@ function pngBlob(canvas: HTMLCanvasElement, env: RenderEnv): Promise<Blob> {
function newCanvas(env: RenderEnv, w: number, h: number): HTMLCanvasElement {
if (env.createCanvas) return env.createCanvas(Math.max(1, w), Math.max(1, h));
- const c = document.createElement("canvas");
- c.width = Math.max(1, w);
- c.height = Math.max(1, h);
- return c;
+ return kitCanvas(w, h);
}
/**
@@ -473,14 +540,15 @@ export async function renderElementPng(
overlay: Overlay,
width: number,
height: number,
- env: RenderEnv
+ env: RenderEnv,
+ phase?: PaintPhase
): Promise<Blob> {
// Element sizes are design pixels with a 1080 short side, so scaling by the
// short side keeps them the same visual size in any aspect and resolution.
const scale = Math.min(width, height) / 1080;
const canvas = newCanvas(env, width, height);
const ctx = canvas.getContext("2d")!;
- const frame: PaintFrame = { width, height, scale };
+ const frame: PaintFrame = { width, height, scale, phase };
ctx.globalAlpha = overlay.opacity ?? 1;
if (overlay.rotation) {
@@ -576,33 +644,46 @@ export interface AnimatedLayer {
overlay: Overlay;
start: number; // timeline seconds
end: number;
+ /** The pixel-level animation this window's picture is drawn at (a wipe's
+ * uncovered share, a per-glyph ramp's position); absent = at rest. */
+ phase?: PaintPhase;
/** The slots still in play for this window (a typed-out one has spent its
* ramp, so that slot is gone). */
anim: OverlayAnim;
}
-/** Typewriter slices per second: one per output frame, matching the rate the
- * frame sequences sample at. */
+/** Baked slices per second: one per output frame, matching the rate the frame
+ * sequences sample at. */
const TYPE_SLICE_FPS = 30;
/**
* Split an animated element into the windows a canvas renderer draws.
*
* Continuous transforms — slides, fades, loops, a keyframed pose — stay one
- * window whose picture is drawn under a per-frame transform. A typewriter
- * changes the pixels themselves, so its ramp becomes one window per revealed
- * slice. This is the canvas-side twin of `renderOverlayFrames`: same split,
- * one baked into pictures, the other handed to a compositor.
+ * window whose picture is drawn under a per-frame transform. A style that
+ * changes the pixels themselves (typing, a wipe, per-glyph motion) can't ride
+ * one cached picture, so its ramp becomes one window per slice. This is the
+ * canvas-side twin of `renderOverlayFrames`: same split, one baked into
+ * pictures, the other handed to a compositor.
*/
export function planAnimatedLayers(o: Overlay, end: number): AnimatedLayer[] {
const anim: OverlayAnim = o.anim ?? {};
const dur = Math.max(0.1, o.end - o.start);
- const isTw = (slot: "in" | "out") =>
- anim[slot]?.style === "typewriter" && (o.kind ?? "text") === "text";
+ const isText = (o.kind ?? "text") === "text";
+ const baked = (slot: "in" | "out") => {
+ const style = anim[slot]?.style;
+ return !!style && bakesPixels(style, isText);
+ };
const inS = anim.in ? Math.min(anim.in.seconds, dur) : 0;
const outS = anim.out ? Math.min(anim.out.seconds, Math.max(0, dur - inS)) : 0;
const out: AnimatedLayer[] = [];
- const push = (overlay: Overlay, from: number, to: number, animPart: OverlayAnim) => {
+ const push = (
+ overlay: Overlay,
+ from: number,
+ to: number,
+ animPart: OverlayAnim,
+ phase?: PaintPhase
+ ) => {
const start = Math.max(o.start, from);
const stop = Math.min(end, to);
if (stop - start < 1e-3) return;
@@ -611,29 +692,40 @@ export function planAnimatedLayers(o: Overlay, end: number): AnimatedLayer[] {
start,
end: stop,
anim: animPart,
+ phase,
});
};
- const typeSlices = (from: number, secs: number, reverse: boolean) => {
- const text = (o as TextOverlay).text;
- const n = Math.max(1, Math.min(text.length, Math.ceil(secs * TYPE_SLICE_FPS)));
- for (let i = 1; i <= n; i++) {
- const chars = Math.ceil((text.length * (reverse ? n - i + 1 : i)) / n);
- push(
- { ...o, text: text.slice(0, chars) } as Overlay,
- from + ((i - 1) / n) * secs,
- from + (i / n) * secs,
- { ...anim, [reverse ? "out" : "in"]: undefined }
- );
+ /** One window per slice, each drawn at the ramp's position mid-window. The
+ * slot leaves the window's anim: its motion is in the picture already. */
+ const slices = (from: number, secs: number, slot: "in" | "out") => {
+ const style = anim[slot]!.style;
+ const text = isText ? (o as TextOverlay).text : "";
+ const cap = style === "typewriter" ? Math.max(1, text.length) : Infinity;
+ const n = Math.max(1, Math.min(cap, Math.ceil(secs * TYPE_SLICE_FPS)));
+ const rest: OverlayAnim = { ...anim, [slot]: undefined };
+ for (let i = 0; i < n; i++) {
+ const mid = (i + 0.5) / n;
+ const p = slot === "out" ? 1 - mid : mid;
+ const at = from + (i / n) * secs;
+ const to = from + ((i + 1) / n) * secs;
+ if (style === "typewriter") {
+ const chars = Math.max(1, Math.ceil(p * text.length));
+ push({ ...o, text: text.slice(0, chars) } as Overlay, at, to, rest);
+ } else if (isGlyphAnimStyle(style)) {
+ push(o, at, to, rest, { glyphs: { style, p, exiting: slot === "out" } });
+ } else {
+ push(o, at, to, rest, { reveal: p });
+ }
}
};
if (inS > 1e-3) {
- if (isTw("in")) typeSlices(o.start, inS, false);
+ if (baked("in")) slices(o.start, inS, "in");
else push(o, o.start, o.start + inS, anim);
}
push(o, o.start + inS, o.start + dur - outS, anim);
if (outS > 1e-3) {
- if (isTw("out")) typeSlices(o.start + dur - outS, outS, true);
+ if (baked("out")) slices(o.start + dur - outS, outS, "out");
else push(o, o.start + dur - outS, o.start + dur, anim);
}
return out;
@@ -690,8 +782,14 @@ export async function renderOverlayFrames(
(s): s is OverlayAnimStyle => !!s
);
const slides = styles.some((s) => s.startsWith("slide"));
+ // Glyphs stray from the resting box on their own; pad by the farthest any
+ // of them travels.
+ const glyphs = styles.some(isGlyphAnimStyle);
+ const loop = loopExtent(anim?.loop?.style);
const travel =
- (slides ? SLIDE_TRAVEL : 0) * scale + (anim?.loop?.style === "float" ? FLOAT_TRAVEL * scale : 0);
+ (slides ? SLIDE_TRAVEL : 0) * scale +
+ (glyphs ? GLYPH_TRAVEL_MAX : 0) * scale +
+ loop.travel * scale;
// A keyframed element carries its own travel and its own zoom: the region
// spans every pose the track visits, at the largest scale it reaches.
const keyed = hasOverlayKeys(overlay);
@@ -699,8 +797,7 @@ export async function renderOverlayFrames(
const maxScale = 1.15 * extent.scale;
const rotates =
!!overlay.rotation ||
- anim?.loop?.style === "spin" ||
- anim?.loop?.style === "wiggle" ||
+ loop.rotates ||
(keyed && sortedKeys(overlay.kf!).some((k) => !!k.rotation));
let halfW = (base.w * maxScale) / 2 + travel + 4;
let halfH = (base.h * maxScale) / 2 + travel + 4;
@@ -742,8 +839,16 @@ export async function renderOverlayFrames(
// Typing reveals characters; it must not also fade them.
ctx.globalAlpha = poseAt(overlay, tLocal).opacity;
}
+ const phase: PaintPhase | undefined =
+ ev.glyphs || ev.glyphLoop || ev.reveal !== undefined
+ ? {
+ ...(ev.glyphs ? { glyphs: ev.glyphs } : {}),
+ ...(ev.glyphLoop ? { glyphLoop: ev.glyphLoop } : {}),
+ ...(ev.reveal !== undefined ? { reveal: ev.reveal } : {}),
+ }
+ : undefined;
const maskTransform = ctx.getTransform();
- await paintElement(ctx, el, { ...frame, t: tLocal }, env);
+ await paintElement(ctx, el, { ...frame, t: tLocal, phase }, env);
if (overlay.mask && maskScratch) {
// Painted under the frame's element transform, so the mask rides the
// pose; its own keys evaluate at this frame's time.
diff --git a/site/src/cut/components/AnimationTiles.tools.ts b/site/src/cut/components/AnimationTiles.tools.ts
index d6754177..693fd63c 100644
--- a/site/src/cut/components/AnimationTiles.tools.ts
+++ b/site/src/cut/components/AnimationTiles.tools.ts
@@ -12,6 +12,8 @@ import {
OVERLAY_ANIM_DEFAULT_SECONDS,
OVERLAY_ANIM_MAX_SECONDS,
OVERLAY_ANIM_MIN_SECONDS,
+ GLYPH_ANIM_STYLE_IDS,
+ GLYPH_LOOP_STYLE_IDS,
OVERLAY_ANIM_STYLE_IDS,
OVERLAY_LOOP_STYLE_IDS,
} from "@donkeycut/effects-kit";
@@ -23,7 +25,7 @@ export const OVERLAY_ANIMATION_TOOLS = [
{
name: "set_overlay_animation",
description:
- `Animate an overlay element (title, shape, or sticker): preset In/Out ramps plus a Loop that runs its whole duration. Omitted slots keep their setting; pass "none" to clear one. In/Out styles: ${OVERLAY_ANIM_STYLE_IDS.join(", ")} — slide names are the motion direction, typewriter animates titles only. Loop styles: ${OVERLAY_LOOP_STYLE_IDS.join(", ")}.`,
+ `Animate an overlay element (title, shape, or sticker): preset In/Out ramps plus a Loop that runs its whole duration. Omitted slots keep their setting; pass "none" to clear one. In/Out styles: ${OVERLAY_ANIM_STYLE_IDS.join(", ")} — slide names are the motion direction; typewriter animates titles only; ${GLYPH_ANIM_STYLE_IDS.join(", ")} move a title's letters one at a time, and move any other kind as one piece. Loop styles: ${OVERLAY_LOOP_STYLE_IDS.join(", ")} — ${GLYPH_LOOP_STYLE_IDS.join(", ")} carry a title's letters on their own delays, and carry any other kind as one piece.`,
inputSchema: obj({
id: str("Overlay element id"),
in_style: {
diff --git a/site/src/cut/components/AnimationTiles.tsx b/site/src/cut/components/AnimationTiles.tsx
index 6d648891..58439b9a 100644
--- a/site/src/cut/components/AnimationTiles.tsx
+++ b/site/src/cut/components/AnimationTiles.tsx
@@ -1,9 +1,13 @@
"use client";
-import { useEffect, useRef, useState } from "react";
-import { Ban, Image as ImageIcon } from "lucide-react";
+import { useEffect, useRef, useState, type CSSProperties } from "react";
+import { X } from "lucide-react";
import {
evalOverlayAnim,
+ glyphStateAt,
+ hasGlyphMotion,
+ isGlyphAnimStyle,
+ isGlyphLoopStyle,
OVERLAY_ANIM_STYLE_IDS,
OVERLAY_ANIM_STYLE_LABELS,
OVERLAY_LOOP_STYLE_IDS,
@@ -14,152 +18,416 @@ import {
import { Tile } from "@/cut/components/PanelTile";
/**
- * The animation picker: a grid of tiles that play their animation on a
- * stand-in shape, so the motion is chosen by watching rather than by reading a
- * name. Only the tile under the pointer moves — a dozen shapes all cycling at
- * once is noise, and it makes the one you are actually looking at harder to
- * read.
+ * The animation picker: a grid of tiles, each playing its style on the style's
+ * own name, in the element's own text — the grid reads as what every motion
+ * does without asking the reader to hunt for it. A card outside the picker
+ * holds its name still until the pointer reaches it.
*
- * Every tile samples `evalOverlayAnim` — the same function the preview, the
- * in-tab export and the frame sampler use. A tile therefore cannot promise
- * motion the export will not deliver, and a new style animates here the moment
- * the evaluator learns it.
+ * Playback samples `evalOverlayAnim` — the same function the preview, the
+ * in-tab export and the frame sampler use — so a tile can't promise motion the
+ * export won't play. A new style draws itself here the moment the evaluator
+ * learns it.
*/
-/** Demo timing: a ramp, then a beat of rest, then round again. */
-const DEMO_RAMP = 0.6;
-const DEMO_HOLD = 0.55;
-const DEMO_CYCLE = DEMO_RAMP + DEMO_HOLD;
+/** Rest beat between demo ramps. An exit clears the stage for its whole ramp,
+ * and a per-glyph ramp leaves a couple of letters scattered for most of it, so
+ * the demo rests for a multiple of the ramp it just played: the tile shows the
+ * name it is offering roughly three quarters of the time. */
+const DEMO_HOLD = 1.4;
+const HOLD_RATIO = 2.6;
+
+const demoCycle = (ramp: number) => ramp + Math.max(DEMO_HOLD, ramp * HOLD_RATIO);
+
+/** How far apart in its cycle each tile starts from the one before it. The
+ * golden ratio spreads any run of tiles evenly around the cycle, so the few
+ * that are mid-motion at a given moment are scattered through the grid. */
+const PHASE_STEP = 0.618;
+/** The cycle a loop tile steps against; loops hold the name the whole way
+ * round, so this only has to look unsynchronised. */
+const LOOP_SPREAD = 1.2;
/** Design px that map to the tile's preview stage. The evaluator works in px at
* a 1080 short side; a slide travels 120 of them, which has to read inside a
* stage a few dozen pixels wide. Low enough that a slide clearly leaves. */
const DEMO_REFERENCE_PX = 190;
-/** What a typewriter tile types. */
-const DEMO_WORD = "Text";
+/** A loop's travel is a fraction of a slide's — a float bobs 12 design px — so
+ * it maps against a shorter reference and stays visible at tile size. */
+const LOOP_REFERENCE_PX = 64;
+
+const referencePx = (slot: Slot) => (slot === "loop" ? LOOP_REFERENCE_PX : DEMO_REFERENCE_PX);
type Slot = "in" | "out" | "loop";
-function demoStateAt(slot: Slot, style: string, t: number) {
+const labelOf = (slot: Slot, style: string) =>
+ slot === "loop"
+ ? (OVERLAY_LOOP_STYLE_LABELS[style as OverlayLoopStyle] ?? style)
+ : (OVERLAY_ANIM_STYLE_LABELS[style as OverlayAnimStyle] ?? style);
+
+function demoStateAt(
+ slot: Slot,
+ style: string,
+ t: number,
+ isText: boolean,
+ ramp: number,
+ speed: number
+) {
if (slot === "loop") {
- return evalOverlayAnim({ loop: { style: style as OverlayLoopStyle, speed: 1 } }, t, 60);
+ return evalOverlayAnim({ loop: { style: style as OverlayLoopStyle, speed } }, t, 60, isText);
}
- const local = t % DEMO_CYCLE;
+ const cycle = demoCycle(ramp);
+ const local = t % cycle;
const anim =
slot === "in"
- ? { in: { style: style as OverlayAnimStyle, seconds: DEMO_RAMP } }
- : { out: { style: style as OverlayAnimStyle, seconds: DEMO_RAMP } };
+ ? { in: { style: style as OverlayAnimStyle, seconds: ramp } }
+ : { out: { style: style as OverlayAnimStyle, seconds: ramp } };
// The exit sits at the tail of the window, so an Out tile rests first and
// then leaves — the shape of the thing it is previewing.
- return evalOverlayAnim(anim, local, DEMO_CYCLE);
+ return evalOverlayAnim(anim, local, cycle, isText);
}
-export function AnimationTiles({
+// The stage is the card's own width with no frame of its own: the card is
+// already one, and a second inside it would both box the motion in and steal
+// the room the motion needs. Clipping is what sells a slide leaving.
+const STAGE = "grid h-12 w-full place-items-center overflow-hidden";
+const WORD = "text-[13px] font-semibold whitespace-nowrap";
+
+/** Whether the demo has to lay the name out letter by letter: the per-glyph
+ * ramps and the per-glyph loops both move each character on its own delay. */
+const splitsGlyphs = (slot: Slot, style: string) =>
+ slot === "loop"
+ ? isGlyphLoopStyle(style as OverlayLoopStyle)
+ : isGlyphAnimStyle(style as OverlayAnimStyle);
+
+/** The name standing still: what a card wears until the pointer reaches it,
+ * and what every tile falls back to when the reader asks for less motion. */
+function FrozenName({
slot,
- value,
+ style,
+ textStyle,
+}: {
+ slot: Slot;
+ style: string;
+ textStyle?: CSSProperties;
+}) {
+ return (
+ <span
+ className={`${WORD} ${textStyle ? "" : "text-foreground"}`}
+ style={{ lineHeight: 1, ...textStyle }}
+ >
+ {labelOf(slot, style)}
+ </span>
+ );
+}
+
+/** The style's name playing its own animation. The frames write styles straight
+ * to the element: animating through React state would re-render the inspector
+ * every frame for pixels React has no say over. */
+function LiveName({
+ slot,
+ style,
isText,
- onPick,
+ seconds,
+ speed,
+ index = 0,
+ textStyle,
}: {
slot: Slot;
- /** The style in use, or undefined for none. */
- value?: string;
- /** Typewriter is offered on titles only. */
+ style: string;
isText: boolean;
- onPick: (style: string | null) => void;
+ seconds: number;
+ speed: number;
+ /** Place in the grid. It sets where in its own cycle this demo starts, so a
+ * grid of them spreads out instead of running in unison. */
+ index?: number;
+ /** The element's own look — font, color, stroke, shadow — so the demo
+ * plays on the text it will actually move. */
+ textStyle?: CSSProperties;
}) {
- const ids: string[] =
- slot === "loop"
- ? OVERLAY_LOOP_STYLE_IDS
- : OVERLAY_ANIM_STYLE_IDS.filter((s) => s !== "typewriter" || isText);
- const labels: Record<string, string> =
- slot === "loop" ? OVERLAY_LOOP_STYLE_LABELS : OVERLAY_ANIM_STYLE_LABELS;
-
- // One clock for the whole grid, writing transforms straight to the elements:
- // a dozen tiles animating through React state would re-render the inspector
- // every frame for pixels React has no say over.
- const shapes = useRef(new Map<string, HTMLElement>());
- const register = (id: string) => (el: HTMLElement | null) => {
- if (el) shapes.current.set(id, el);
- else shapes.current.delete(id);
- };
-
- const [hovered, setHovered] = useState<string | null>(null);
-
+ const ref = useRef<HTMLSpanElement>(null);
+ const label = labelOf(slot, style);
+ // Golden-ratio steps around the cycle: neighbouring tiles land far apart in
+ // it, and no run of them ever bunches up mid-motion together.
+ const phase = index * (slot === "loop" ? LOOP_SPREAD : demoCycle(seconds)) * PHASE_STEP;
useEffect(() => {
- const el = hovered ? shapes.current.get(hovered) : null;
+ const el = ref.current;
if (!el) return;
+ const letters = () => Array.from(el.children) as HTMLElement[];
const rest = () => {
el.style.transform = "";
el.style.opacity = "";
+ el.style.clipPath = "";
+ for (const kid of letters()) {
+ kid.style.transform = "";
+ kid.style.opacity = "";
+ }
if (el.dataset.word) el.textContent = el.dataset.word;
};
if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return rest;
let start = 0;
let raf = 0;
+ // Whether the last frame left per-letter styles on the children. A ramp
+ // that ends off-stage leaves them at zero opacity, so the rest beat has to
+ // hand the letters back before the word can read again.
+ let glyphed = false;
const tick = (now: number) => {
if (!start) start = now;
- const st = demoStateAt(slot, hovered!, (now - start) / 1000);
- const px = (v: number) => (v * el.clientWidth) / DEMO_REFERENCE_PX;
- el.style.transform = `translate(${px(st.dx)}px, ${px(st.dy)}px) rotate(${st.rotate}deg) scale(${st.scale})`;
- el.style.opacity = String(st.alpha);
+ const st = demoStateAt(slot, style, (now - start) / 1000 + phase, isText, seconds, speed);
+ const px = (v: number) => (v * el.clientWidth) / referencePx(slot);
+ if (hasGlyphMotion(st)) {
+ // The letters carry the motion; the word itself stays put.
+ const kids = letters();
+ kids.forEach((kid, i) => {
+ const g = glyphStateAt(st, i, kids.length);
+ kid.style.transform = `translate(${px(g.dx)}px, ${px(g.dy)}px) rotate(${g.rotate}deg) scale(${g.sx}, ${g.sy})`;
+ kid.style.opacity = String(g.alpha);
+ });
+ glyphed = true;
+ } else {
+ if (glyphed) {
+ for (const kid of letters()) {
+ kid.style.transform = "";
+ kid.style.opacity = "";
+ }
+ glyphed = false;
+ }
+ el.style.transform = `translate(${px(st.dx)}px, ${px(st.dy)}px) rotate(${st.rotate}deg) scale(${st.scale})`;
+ el.style.opacity = String(st.alpha);
+ }
+ el.style.clipPath =
+ st.reveal !== undefined ? `inset(0 ${(1 - st.reveal) * 100}% 0 0)` : "";
if (st.textProgress !== undefined) {
- el.textContent = DEMO_WORD.slice(0, Math.ceil(st.textProgress * DEMO_WORD.length));
+ const word = el.dataset.word ?? "";
+ el.textContent = word.slice(0, Math.ceil(st.textProgress * word.length));
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
- // Back to rest on the way out, so a tile never freezes mid-animation.
+ // Back to rest on the way out, so a card never freezes mid-animation.
return () => {
cancelAnimationFrame(raf);
rest();
};
- }, [hovered, slot]);
+ }, [slot, style, isText, seconds, speed, phase]);
+
+ return (
+ <span
+ ref={ref}
+ data-word={style === "typewriter" ? label : undefined}
+ className={`${WORD} ${textStyle ? "" : "text-foreground"}`}
+ style={{ willChange: "transform", lineHeight: 1, ...textStyle }}
+ >
+ {isText && splitsGlyphs(slot, style)
+ ? [...label].map((ch, i) => (
+ <span key={i} className="inline-block">
+ {ch}
+ </span>
+ ))
+ : label}
+ </span>
+ );
+}
- // The stage is the tile's own width with no frame of its own: the tile is
- // already a card, and a second one inside it would both box the motion in and
- // steal the room the motion needs. Clipping is what sells a slide leaving.
- const stage = "grid h-11 w-full place-items-center overflow-hidden";
- const tile = "gap-1 px-1 pt-1.5 pb-1";
+/** The name in its tile: the motion itself while the tile is playing, the
+ * plain name when it is not. */
+function AnimName({
+ playing,
+ ...rest
+}: {
+ slot: Slot;
+ style: string;
+ isText: boolean;
+ seconds: number;
+ speed: number;
+ playing: boolean;
+ index?: number;
+ textStyle?: CSSProperties;
+}) {
+ return playing ? (
+ <LiveName {...rest} />
+ ) : (
+ <FrozenName slot={rest.slot} style={rest.style} textStyle={rest.textStyle} />
+ );
+}
+
+/** Whether the element is on screen. A tile off the scroll's edge keeps its
+ * name still and books no frames until it comes into view. */
+function useOnScreen(ref: React.RefObject<HTMLElement | null>) {
+ const [shown, setShown] = useState(false);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const io = new IntersectionObserver(([e]) => setShown(e.isIntersecting), {
+ rootMargin: "64px",
+ });
+ io.observe(el);
+ return () => io.disconnect();
+ }, [ref]);
+ return shown;
+}
+
+function AnimTile({
+ slot,
+ style,
+ isText,
+ seconds,
+ speed,
+ index,
+ selected,
+ onPick,
+ textStyle,
+}: {
+ slot: Slot;
+ style: string;
+ isText: boolean;
+ seconds: number;
+ speed: number;
+ /** Place in the grid, which sets this tile's beat in the cascade. */
+ index: number;
+ selected: boolean;
+ onPick: () => void;
+ textStyle?: CSSProperties;
+}) {
+ const ref = useRef<HTMLButtonElement>(null);
+ const onScreen = useOnScreen(ref);
+ return (
+ <Tile
+ ref={ref}
+ selected={selected}
+ onClick={onPick}
+ title={labelOf(slot, style)}
+ className="p-1"
+ >
+ <span className={STAGE}>
+ <AnimName
+ slot={slot}
+ style={style}
+ isText={isText}
+ seconds={seconds}
+ speed={speed}
+ index={index}
+ playing={onScreen}
+ textStyle={textStyle}
+ />
+ </span>
+ </Tile>
+ );
+}
+
+/**
+ * One picked style as a card outside the picker: the slot it fills in a
+ * corner, the name playing what that slot does, and an × that clears the slot
+ * on the spot. The card itself opens the picker.
+ */
+export function AnimationCard({
+ slot,
+ style,
+ isText,
+ seconds,
+ speed,
+ index = 0,
+ onOpen,
+ onClear,
+ textStyle,
+}: {
+ slot: Slot;
+ style: string;
+ isText: boolean;
+ seconds: number;
+ speed: number;
+ /** Place in the row, which sets where in its cycle this card starts. */
+ index?: number;
+ onOpen: () => void;
+ onClear: () => void;
+ textStyle?: CSSProperties;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const onScreen = useOnScreen(ref);
+ const label = labelOf(slot, style);
+ return (
+ <div ref={ref} className="relative">
+ <button
+ type="button"
+ title={`${label} — change`}
+ className="flex w-full flex-col rounded-lg border border-border p-1 outline-none transition-colors hover:bg-muted/60"
+ onClick={onOpen}
+ >
+ <span className={STAGE}>
+ <AnimName
+ slot={slot}
+ style={style}
+ isText={isText}
+ seconds={seconds}
+ speed={speed}
+ index={index}
+ playing={onScreen}
+ textStyle={textStyle}
+ />
+ </span>
+ </button>
+ <span className="pointer-events-none absolute top-0.5 left-1.5 text-[9px] font-medium text-muted-foreground/70 capitalize">
+ {slot}
+ </span>
+ <button
+ type="button"
+ aria-label={`No ${slot} animation`}
+ title={`No ${slot} animation`}
+ className="absolute top-0.5 right-0.5 grid size-4 place-items-center rounded-full text-muted-foreground/70 transition-colors hover:text-foreground"
+ onClick={onClear}
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ );
+}
+
+export function AnimationTiles({
+ slot,
+ value,
+ isText,
+ seconds,
+ speed,
+ onPick,
+ textStyle,
+}: {
+ slot: Slot;
+ /** The style in use, or undefined for none. */
+ value?: string;
+ /** Typewriter is offered on titles only. */
+ isText: boolean;
+ /** The In/Out length the panel has set — the hover demo's ramp. */
+ seconds: number;
+ /** The loop speed the panel has set — the hover demo's cycle rate. */
+ speed: number;
+ onPick: (style: string | null) => void;
+ /** The element's own look, applied to every tile's demo text. */
+ textStyle?: CSSProperties;
+}) {
+ const ids: string[] =
+ slot === "loop"
+ ? OVERLAY_LOOP_STYLE_IDS
+ : OVERLAY_ANIM_STYLE_IDS.filter((s) => s !== "typewriter" || isText);
return (
- <div className="grid grid-cols-3 gap-1.5">
- <Tile selected={!value} onClick={() => onPick(null)} label="None" className={tile}>
- <span className={stage}>
- <Ban className="size-7 text-muted-foreground/60" />
+ <div className="grid grid-cols-2 gap-[9px]">
+ <Tile selected={!value} onClick={() => onPick(null)} title="None" className="p-1">
+ <span className={STAGE}>
+ <span className={`${WORD} text-muted-foreground/70`}>None</span>
</span>
</Tile>
- {ids.map((id) => (
- <Tile
+ {ids.map((id, i) => (
+ <AnimTile
key={id}
+ slot={slot}
+ style={id}
+ isText={isText}
+ seconds={seconds}
+ speed={speed}
+ index={i}
selected={value === id}
- onClick={() => onPick(id)}
- label={labels[id]}
- className={tile}
- onHover={(on) => setHovered(on ? id : (h) => (h === id ? null : h))}
- >
- <span className={stage}>
- {id === "typewriter" ? (
- <span
- ref={register(id)}
- data-word={DEMO_WORD}
- className="text-[13px] font-semibold text-foreground"
- style={{ willChange: "transform" }}
- >
- {DEMO_WORD}
- </span>
- ) : (
- // Its own wrapper, so the animated transform never fights the
- // icon's sizing.
- <span ref={register(id)} className="block" style={{ willChange: "transform" }}>
- {/* Carries the tile's own muted color and the light stroke the
- transition tiles use, so a grid of stand-ins doesn't read
- heavier than the picture it stands in for. */}
- <ImageIcon className="size-7" strokeWidth={1.5} />
- </span>
- )}
- </span>
- </Tile>
+ onPick={() => onPick(id)}
+ textStyle={textStyle}
+ />
))}
</div>
);
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 209aeef5..ffc71005 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { AlignCenter, AlignLeft, AlignRight, Bold, ChevronLeft, ChevronRight, Diamond, Info, Italic, RotateCcw, SlidersHorizontal, Smile, Trash2, Wand2 } from "lucide-react";
+import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Info, Italic, RotateCcw, SlidersHorizontal, Smile, Trash2, Type, Wand2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmojiPicker } from "@/cut/components/EmojiPicker";
import {
@@ -45,7 +45,10 @@ import {
import { clipWindow, useEditor, type EditorState } from "@/cut/lib/store";
import { usePreviewTime } from "@/cut/lib/playhead";
import { clipKeyed, clipPoseAt } from "@/cut/lib/types";
-import { AnimationTiles } from "@/cut/components/AnimationTiles";
+import { AnimationCard, AnimationTiles } from "@/cut/components/AnimationTiles";
+import { ColorField } from "@/cut/components/ColorField";
+import { NumberField } from "@/cut/components/NumberField";
+import { playAnimPreview, stopAnimPreview } from "@/cut/lib/animPreview";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
import {
parseNumberInput,
@@ -95,16 +98,11 @@ import {
type TextOverlay,
type VideoClip,
} from "@/cut/lib/types";
-import { autoGradeFromImageData, isNeutralGrade, normalizeGrade } from "@donkeycut/effects-kit";
+import { autoGradeFromImageData, isNeutralGrade, normalizeGrade, resolveShadow } from "@donkeycut/effects-kit";
import { getPreviewCanvas, sampleClipFrameData } from "@/cut/lib/previewCanvas";
import { cn } from "@/lib/utils";
import { ScrollArea } from "@/components/ui/scroll-area";
-const SWATCHES = ["#FFFFFF", "#111114", "#FFD60A", "#FF375F", "#0A84FF", "#30D158"];
-
-/** Last three custom colors picked with the eyedropper, newest first. */
-const RECENT_COLORS_KEY = "cut-recent-colors";
-
/**
* One undo checkpoint per slider drag: capture the pre-drag state on the first
* change, then feed live changes through the transient updater so the whole
@@ -124,79 +122,6 @@ function useSliderCheckpoint() {
};
}
-function readRecentColors(): string[] {
- try {
- const v = JSON.parse(localStorage.getItem(RECENT_COLORS_KEY) ?? "[]") as unknown;
- return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, 3) : [];
- } catch {
- return [];
- }
-}
-
-/** Preset swatches, recent custom colors, and an eyedropper. `onBegin` marks
- * an undo checkpoint, `onLive` streams the drag, `onCommit` sets a final pick. */
-function ColorSwatches({
- value,
- onBegin,
- onLive,
- onCommit,
-}: {
- value: string;
- onBegin: () => void;
- onLive: (c: string) => void;
- onCommit: (c: string) => void;
-}) {
- const [recents, setRecents] = useState<string[]>(() =>
- typeof window === "undefined" ? [] : readRecentColors()
- );
-
- const recordRecent = (c: string) => {
- if (SWATCHES.some((s) => s.toUpperCase() === c.toUpperCase())) return;
- const next = [c, ...recents.filter((r) => r.toUpperCase() !== c.toUpperCase())].slice(0, 3);
- setRecents(next);
- try {
- localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(next));
- } catch {
- // Storage full/blocked — recents just won't persist.
- }
- };
-
- return (
- <div className="flex max-w-44 flex-wrap items-center justify-end gap-1.5">
- {[...SWATCHES, ...recents].map((c) => (
- <button
- key={c}
- title={c}
- aria-label={`Color ${c}`}
- className={cn(
- "size-5 rounded-full border border-black/15 transition-transform hover:scale-110",
- value.toUpperCase() === c.toUpperCase() &&
- "ring-2 ring-primary ring-offset-2 ring-offset-card"
- )}
- style={{ background: c }}
- onClick={() => onCommit(c)}
- />
- ))}
- <label
- title="Custom color"
- className="color-picker-well relative size-5 cursor-pointer rounded-full border border-black/15 bg-[conic-gradient(from_0deg,#f43f5e,#f59e0b,#84cc16,#06b6d4,#6366f1,#d946ef,#f43f5e)] transition-transform hover:scale-110"
- >
- <span className="absolute inset-1 rounded-full bg-card" />
- <span className="absolute inset-[5px] rounded-full" style={{ background: value }} />
- <input
- type="color"
- aria-label="Pick a custom color"
- className="absolute inset-0 size-full cursor-pointer opacity-0"
- value={/^#[0-9a-fA-F]{6}$/.test(value) ? value : "#ffffff"}
- onFocus={onBegin}
- onChange={(e) => onLive(e.target.value)}
- onBlur={() => recordRecent(value)}
- />
- </label>
- </div>
- );
-}
-
export function Inspector() {
const selection = useEditor((s) => s.selection);
const clip = useEditor((s) =>
@@ -279,6 +204,54 @@ function Row({
);
}
+/** A control that carries its own caption, for the two-up rows where the
+ * settings sit side by side instead of behind a label on the left. */
+function Field({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="truncate text-[11px] text-muted-foreground">{label}</span>
+ {children}
+ </div>
+ );
+}
+
+/** Icon toggles that belong together, sat in one trough. */
+function SegGroup({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="flex shrink-0 items-center gap-0.5 rounded-md bg-secondary/60 p-0.5">
+ {children}
+ </div>
+ );
+}
+
+function SegToggle({
+ label,
+ active,
+ onClick,
+ children,
+}: {
+ label: string;
+ active: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ aria-pressed={active}
+ className={cn(
+ "grid size-6 place-items-center rounded-[5px] text-muted-foreground transition-colors [&_svg]:size-3.5",
+ active ? "bg-foreground text-background" : "hover:bg-foreground/10 hover:text-foreground"
+ )}
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ );
+}
+
/** Hoverable (i) explaining the control it follows. */
function InfoTip({ label, children }: { label: string; children: React.ReactNode }) {
return (
@@ -1023,8 +996,15 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
);
}
+/** The sizes and spacings a title usually wants, offered under each field's
+ * chevron; any value in range can still be typed or dragged. */
+const TEXT_SIZES = [32, 48, 64, 80, 96, 120, 160, 200, 240];
+const LINE_HEIGHTS = [0.9, 1, 1.15, 1.25, 1.5, 1.75, 2];
+const LETTER_SPACINGS = [-2, 0, 2, 5, 10, 20];
+
function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
const update = useEditor((s) => s.updateOverlay);
+ const [animView, setAnimView] = useState<"closed" | "open" | "returned">("closed");
const sizeCk = useSliderCheckpoint();
const radiusCk = useSliderCheckpoint();
const opacityCk = useSliderCheckpoint();
@@ -1075,6 +1055,8 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
requestAnimationFrame(() => ta?.setSelectionRange(start + emoji.length, start + emoji.length));
};
+ if (animView === "open")
+ return <AnimationPanel overlay={o} onBack={() => setAnimView("returned")} />;
return (
<>
<PanelTitle>Text</PanelTitle>
@@ -1106,77 +1088,66 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
/>
</div>
<StylePresetsRow overlay={o} />
- <Row label="Font">
- <Select
- value={o.font}
- items={Object.fromEntries(fonts.map((f) => [f.id, f.label]))}
- onValueChange={(v) => update(o.id, { font: v as TextOverlay["font"] })}
- >
- <SelectTrigger size="sm" className="w-28">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {fonts.map((f) => (
- <SelectItem key={f.id} value={f.id}>
- <span style={{ fontFamily: f.stack }}>{f.label}</span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Button
- variant="outline"
- size="icon-sm"
- aria-label="Bold"
- aria-pressed={o.weight === 700}
- className={cn(o.weight === 700 && "border-primary bg-primary/15 text-primary")}
- onClick={() => update(o.id, { weight: o.weight === 700 ? 400 : 700 })}
- >
- <Bold />
- </Button>
- <Button
- variant="outline"
- size="icon-sm"
- aria-label="Italic"
- aria-pressed={!!o.italic}
- className={cn(o.italic && "border-primary bg-primary/15 text-primary")}
- onClick={() => update(o.id, { italic: o.italic ? undefined : true })}
- >
- <Italic />
- </Button>
- </Row>
- <Row label="Align">
- {(
- [
- ["left", AlignLeft],
- ["center", AlignCenter],
- ["right", AlignRight],
- ] as const
- ).map(([a, Icon]) => {
- const active = (o.align ?? "center") === a;
- return (
- <Button
+ <Select
+ value={o.font}
+ items={Object.fromEntries(fonts.map((f) => [f.id, f.label]))}
+ onValueChange={(v) => update(o.id, { font: v as TextOverlay["font"] })}
+ >
+ <SelectTrigger size="sm" className="w-full" style={{ fontFamily: fontStack(o.font) }}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {fonts.map((f) => (
+ <SelectItem key={f.id} value={f.id}>
+ <span style={{ fontFamily: f.stack }}>{f.label}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <div className="mt-1 flex items-center gap-2">
+ <SegGroup>
+ <SegToggle
+ label="Bold"
+ active={o.weight === 700}
+ onClick={() => update(o.id, { weight: o.weight === 700 ? 400 : 700 })}
+ >
+ <Bold />
+ </SegToggle>
+ <SegToggle
+ label="Italic"
+ active={!!o.italic}
+ onClick={() => update(o.id, { italic: o.italic ? undefined : true })}
+ >
+ <Italic />
+ </SegToggle>
+ </SegGroup>
+ <SegGroup>
+ {(
+ [
+ ["left", AlignLeft],
+ ["center", AlignCenter],
+ ["right", AlignRight],
+ ] as const
+ ).map(([a, Icon]) => (
+ <SegToggle
key={a}
- variant="outline"
- size="icon-sm"
- aria-label={`Align ${a}`}
- aria-pressed={active}
- className={cn(active && "border-primary bg-primary/15 text-primary")}
+ label={`Align ${a}`}
+ active={(o.align ?? "center") === a}
onClick={() => update(o.id, { align: a === "center" ? undefined : a })}
>
<Icon />
- </Button>
- );
- })}
- </Row>
- <Row label="Size">
- <ValueSlider
+ </SegToggle>
+ ))}
+ </SegGroup>
+ <NumberField
label="Text size"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
+ className="ml-auto w-[74px]"
+ icon={<Type />}
value={o.size}
min={24}
max={240}
step={1}
+ presets={TEXT_SIZES}
format={(v) => String(Math.round(v))}
parse={parseNumberInput}
onDraft={(v) => {
@@ -1189,69 +1160,72 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
sizeCk.end();
}}
/>
- </Row>
+ </div>
+ <div className="mt-1 grid grid-cols-2 gap-2">
+ <Field label="Line height">
+ <NumberField
+ label="Line height"
+ icon={<AlignVerticalSpaceAround />}
+ value={o.lineHeight ?? 1.25}
+ min={0.8}
+ max={2}
+ step={0.05}
+ snap={[1.25]}
+ presets={LINE_HEIGHTS}
+ format={(v) => v.toFixed(2)}
+ parse={parseNumberInput}
+ onDraft={(v) => {
+ lineHeightCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v,
+ });
+ }}
+ onCommit={(v) => {
+ lineHeightCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v,
+ });
+ lineHeightCk.end();
+ }}
+ />
+ </Field>
+ <Field label="Letter spacing">
+ <NumberField
+ label="Letter spacing"
+ icon={<AlignHorizontalSpaceAround />}
+ value={(o.letterSpacing ?? 0) * 100}
+ min={-5}
+ max={30}
+ step={1}
+ snap={[0]}
+ presets={LETTER_SPACINGS}
+ format={(v) => `${Math.round(v)}%`}
+ parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}
+ onDraft={(v) => {
+ spacingCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ letterSpacing: Math.abs(v) < 0.25 ? undefined : v / 100,
+ });
+ }}
+ onCommit={(v) => {
+ spacingCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ letterSpacing: Math.abs(v) < 0.25 ? undefined : v / 100,
+ });
+ spacingCk.end();
+ }}
+ />
+ </Field>
+ </div>
<Row label="Color">
- <ColorSwatches
+ <ColorField
value={o.color}
+ label="Text color"
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { color: c })}
onCommit={(c) => update(o.id, { color: c })}
/>
</Row>
- <Row label="Spacing">
- <ValueSlider
- label="Letter spacing"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={(o.letterSpacing ?? 0) * 100}
- min={-5}
- max={30}
- step={0.5}
- snap={[0]}
- format={(v) => String(Math.round(v))}
- parse={parseNumberInput}
- onDraft={(v) => {
- spacingCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- letterSpacing: Math.abs(v) < 0.25 ? undefined : v / 100,
- });
- }}
- onCommit={(v) => {
- spacingCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- letterSpacing: Math.abs(v) < 0.25 ? undefined : v / 100,
- });
- spacingCk.end();
- }}
- />
- </Row>
- <Row label="Line height">
- <ValueSlider
- label="Line height"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={o.lineHeight ?? 1.25}
- min={0.8}
- max={2}
- step={0.05}
- snap={[1.25]}
- format={(v) => v.toFixed(2)}
- parse={parseNumberInput}
- onDraft={(v) => {
- lineHeightCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v,
- });
- }}
- onCommit={(v) => {
- lineHeightCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v,
- });
- lineHeightCk.end();
- }}
- />
- </Row>
<Section
title="Outline"
enabled={!!o.stroke}
@@ -1262,8 +1236,9 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
{o.stroke && (
<>
<Row label="Color">
- <ColorSwatches
+ <ColorField
value={o.stroke.color}
+ label="Outline color"
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) =>
useEditor.getState().updateOverlayTransient(o.id, {
@@ -1310,8 +1285,9 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
>
<>
<Row label="Color">
- <ColorSwatches
+ <ColorField
value={(typeof o.shadow === "object" ? o.shadow.color : undefined) ?? "#000000"}
+ label="Shadow color"
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) =>
useEditor.getState().updateOverlayTransient(o.id, {
@@ -1323,6 +1299,23 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
shadow: { ...(typeof o.shadow === "object" ? o.shadow : {}), color: c },
})
}
+ opacity={{
+ label: "Shadow opacity",
+ value: (typeof o.shadow === "object" ? o.shadow.opacity : undefined) ?? 0.65,
+ onDraft: (v) => {
+ shadowCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ shadow: { ...(typeof o.shadow === "object" ? o.shadow : {}), opacity: v },
+ });
+ },
+ onCommit: (v) => {
+ shadowCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ shadow: { ...(typeof o.shadow === "object" ? o.shadow : {}), opacity: v },
+ });
+ shadowCk.end();
+ },
+ }}
/>
</Row>
<Row label="Blur">
@@ -1352,33 +1345,6 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
}}
/>
</Row>
- <Row label="Opacity">
- <ValueSlider
- label="Shadow opacity"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={(typeof o.shadow === "object" ? o.shadow.opacity : undefined) ?? 0.65}
- min={0}
- max={1}
- step={0.01}
- snap={[0.65]}
- format={(v) => String(Math.round(v * 100))}
- parse={parsePercentInput}
- onDraft={(v) => {
- shadowCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- shadow: { ...(typeof o.shadow === "object" ? o.shadow : {}), opacity: v },
- });
- }}
- onCommit={(v) => {
- shadowCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- shadow: { ...(typeof o.shadow === "object" ? o.shadow : {}), opacity: v },
- });
- shadowCk.end();
- }}
- />
- </Row>
</>
</Section>
<Section
@@ -1388,33 +1354,24 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
>
<>
<Row label="Color">
- <ColorSwatches
+ <ColorField
value={o.plateColor ?? PLATE_COLOR}
+ label="Backdrop color"
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { plateColor: c })}
onCommit={(c) => update(o.id, { plateColor: c })}
- />
- </Row>
- <Row label="Opacity">
- <ValueSlider
- label="Backdrop opacity"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={o.plateOpacity ?? PLATE_OPACITY}
- min={0}
- max={1}
- step={0.01}
- snap={[PLATE_OPACITY]}
- format={(v) => String(Math.round(v * 100))}
- parse={parsePercentInput}
- onDraft={(v) => {
- opacityCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: v });
- }}
- onCommit={(v) => {
- opacityCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: v });
- opacityCk.end();
+ opacity={{
+ label: "Backdrop opacity",
+ value: o.plateOpacity ?? PLATE_OPACITY,
+ onDraft: (v) => {
+ opacityCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: v });
+ },
+ onCommit: (v) => {
+ opacityCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: v });
+ opacityCk.end();
+ },
}}
/>
</Row>
@@ -1446,7 +1403,11 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
<OverlayMaskSection overlay={o} />
<TransformRows overlay={o} />
<GroupRow overlay={o} />
- <AnimationRows overlay={o} />
+ <AnimationSection
+ overlay={o}
+ onOpen={() => setAnimView("open")}
+ reveal={animView === "returned"}
+ />
</div>
</>
);
@@ -1567,132 +1528,261 @@ function StylePresetsRow({ overlay: o }: { overlay: TextOverlay }) {
);
}
-/** Preset In / Out / Loop animation, shared by every overlay kind. Neutral
- * (all slots off) stores as absence. */
-function AnimationRows({ overlay: o }: { overlay: Overlay }) {
- const lengthCk = useSliderCheckpoint();
- const speedCk = useSliderCheckpoint();
+/** Write an animation patch to the element — and its whole group, since a
+ * grouped element's animation stamps the group. Neutral (all slots off)
+ * stores as absence. */
+function writeOverlayAnim(o: Overlay, anim: OverlayAnim, patch: Partial<OverlayAnim>) {
+ const next = { ...anim, ...patch };
+ if (!next.in) delete next.in;
+ if (!next.out) delete next.out;
+ if (!next.loop) delete next.loop;
+ const value = next.in || next.out || next.loop ? next : undefined;
+ const st = useEditor.getState();
+ const peers = o.groupId ? st.overlays.filter((x) => x.groupId === o.groupId) : [];
+ const ids = peers.length > 1 ? peers.map((p) => p.id) : [o.id];
+ st.updateOverlaysTransient(ids.map((id) => ({ id, patch: { anim: value } })));
+}
+
+/** The set slot's Length (In/Out) or Speed (Loop) slider. */
+function AnimSlotSlider({
+ overlay: o,
+ slot,
+ label,
+}: {
+ overlay: Overlay;
+ slot: "in" | "out" | "loop";
+ label: string;
+}) {
+ const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
const dur = Math.max(0.2, o.end - o.start);
- const writeAnim = (patch: Partial<OverlayAnim>) => {
- const next = { ...anim, ...patch };
- if (!next.in) delete next.in;
- if (!next.out) delete next.out;
- if (!next.loop) delete next.loop;
- const value = next.in || next.out || next.loop ? next : undefined;
- // A grouped element's animation stamps the whole group.
- const st = useEditor.getState();
- const peers = o.groupId ? st.overlays.filter((x) => x.groupId === o.groupId) : [];
- const ids = peers.length > 1 ? peers.map((p) => p.id) : [o.id];
- st.updateOverlaysTransient(ids.map((id) => ({ id, patch: { anim: value } })));
- };
- /** A discrete change — its own undo step. */
- const setAnim = (patch: Partial<OverlayAnim>) => {
- useEditor.getState().pushHistory();
- writeAnim(patch);
- };
/** A drag — one undo step for the whole gesture, not one per frame. */
- const dragAnim = (ck: ReturnType<typeof useSliderCheckpoint>, patch: Partial<OverlayAnim>) => {
+ const drag = (patch: Partial<OverlayAnim>) => {
ck.begin();
- writeAnim(patch);
+ writeOverlayAnim(o, anim, patch);
};
- // In / Out / Loop pick from the same grid, one slot at a time — the tiles
- // are big enough to read the motion, which three stacked grids would not be.
+ if (slot === "loop") {
+ if (!anim.loop) return null;
+ return (
+ <Row label={label}>
+ <ValueSlider
+ label={label}
+ sliderClassName="data-horizontal:w-24"
+ valueClassName="w-9 text-muted-foreground"
+ value={anim.loop.speed}
+ min={0.25}
+ max={4}
+ step={0.25}
+ format={(v) => `${v.toFixed(2)}×`}
+ parse={parseSpeedInput}
+ onDraft={(v) => drag({ loop: { ...anim.loop!, speed: v } })}
+ onCommit={(v) => {
+ drag({ loop: { ...anim.loop!, speed: v } });
+ ck.end();
+ }}
+ />
+ </Row>
+ );
+ }
+ const active = anim[slot];
+ if (!active) return null;
+ return (
+ <Row label={label}>
+ <ValueSlider
+ label={label}
+ sliderClassName="data-horizontal:w-24"
+ valueClassName="w-9 text-muted-foreground"
+ value={active.seconds}
+ min={OVERLAY_ANIM_MIN_SECONDS}
+ max={Math.min(OVERLAY_ANIM_MAX_SECONDS, dur)}
+ step={0.05}
+ snap={[OVERLAY_ANIM_DEFAULT_SECONDS]}
+ format={(v) => `${v.toFixed(2)}s`}
+ parse={parseSecondsInput}
+ onDraft={(v) =>
+ drag({ [slot]: { style: active.style as OverlayAnimStyle, seconds: v } })
+ }
+ onCommit={(v) => {
+ drag({ [slot]: { style: active.style as OverlayAnimStyle, seconds: v } });
+ ck.end();
+ }}
+ />
+ </Row>
+ );
+}
+
+/** A title's own look at tile scale, for the picker's demo text: family,
+ * weight, color, stroke and shadow ride along (the stroke's em units scale
+ * with the demo font); layout knobs stay out. */
+function demoTextStyle(o: Overlay): React.CSSProperties | undefined {
+ if (!isTextOverlay(o)) return undefined;
+ const shadow = resolveShadow(o.shadow);
+ const k = 13 / o.size;
+ return {
+ fontFamily: fontStack(o.font),
+ fontWeight: o.weight,
+ fontStyle: o.italic ? "italic" : undefined,
+ color: o.color,
+ WebkitTextStroke: o.stroke ? `${o.stroke.width * 2}em ${o.stroke.color}` : undefined,
+ paintOrder: o.stroke ? ("stroke fill" as const) : undefined,
+ textShadow: shadow
+ ? `0 ${shadow.offsetY * k}px ${shadow.blur * k}px ${shadow.color}`
+ : undefined,
+ };
+}
+
+/** The Animation entry every overlay panel carries: the current picks at a
+ * glance on a drill-in to the picker, with each set slot's length or speed
+ * right under it. */
+function AnimationSection({
+ overlay: o,
+ onOpen,
+ reveal,
+}: {
+ overlay: Overlay;
+ onOpen: () => void;
+ /** Mounted by the picker's back button: bring the section into view, since
+ * the pushed view scrolled away from it. */
+ reveal?: boolean;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (reveal) ref.current?.scrollIntoView({ block: "nearest" });
+ }, [reveal]);
+ const anim = o.anim ?? {};
+ const slots = (["in", "out", "loop"] as const).filter((s) => anim[s]);
+ const clear = (slot: "in" | "out" | "loop") => {
+ stopAnimPreview();
+ useEditor.getState().pushHistory();
+ writeOverlayAnim(o, anim, { [slot]: undefined });
+ };
+ return (
+ <div ref={ref}>
+ <Section
+ title="Animation"
+ aside={
+ <button
+ type="button"
+ className="anim-open flex h-8 items-center gap-1 rounded-md border border-input px-2.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
+ onClick={onOpen}
+ >
+ {slots.length ? "Change" : "None"}
+ <ChevronRight className="size-3.5 shrink-0" />
+ </button>
+ }
+ >
+ {slots.length > 0 && (
+ <div className="mt-2 mb-1 grid grid-cols-3 gap-1.5">
+ {slots.map((slot, i) => (
+ <AnimationCard
+ key={slot}
+ slot={slot}
+ index={i}
+ style={slot === "loop" ? anim.loop!.style : anim[slot]!.style}
+ isText={isTextOverlay(o)}
+ seconds={slot === "loop" ? OVERLAY_ANIM_DEFAULT_SECONDS : anim[slot]!.seconds}
+ speed={anim.loop?.speed ?? 1}
+ onOpen={onOpen}
+ onClear={() => clear(slot)}
+ textStyle={demoTextStyle(o)}
+ />
+ ))}
+ </div>
+ )}
+ <AnimSlotSlider overlay={o} slot="in" label="In duration" />
+ <AnimSlotSlider overlay={o} slot="out" label="Out duration" />
+ <AnimSlotSlider overlay={o} slot="loop" label="Loop speed" />
+ </Section>
+ </div>
+ );
+}
+
+/** The animation subview an overlay panel pushes into: In / Out / Loop tabs
+ * over the tile grid, the active slot's length or speed under it. The three
+ * slots pick from the same grid, one at a time — the tiles are big enough to
+ * read the motion, which three stacked grids would not be. */
+function AnimationPanel({ overlay: o, onBack }: { overlay: Overlay; onBack: () => void }) {
+ const anim = o.anim ?? {};
const [slot, setSlot] = useState<"in" | "out" | "loop">("in");
const active = anim[slot];
const seconds =
slot === "loop" ? undefined : (anim[slot] as OverlayAnim["in"])?.seconds;
const pick = (style: string | null) => {
- if (!style) return setAnim({ [slot]: undefined });
- if (slot === "loop") {
- setAnim({ loop: { style: style as OverlayLoopStyle, speed: anim.loop?.speed ?? 1 } });
+ if (!style) {
+ stopAnimPreview();
+ useEditor.getState().pushHistory();
+ writeOverlayAnim(o, anim, { [slot]: undefined });
return;
}
- setAnim({
- [slot]: {
- style: style as OverlayAnimStyle,
- seconds: seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS,
- },
- });
+ const patch: Partial<OverlayAnim> =
+ slot === "loop"
+ ? { loop: { style: style as OverlayLoopStyle, speed: anim.loop?.speed ?? 1 } }
+ : {
+ [slot]: {
+ style: style as OverlayAnimStyle,
+ seconds: seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS,
+ },
+ };
+ useEditor.getState().pushHistory();
+ writeOverlayAnim(o, anim, patch);
+ // The pick plays itself on the stage, for exactly its own length.
+ playAnimPreview({ ...o, anim: { ...anim, ...patch } }, slot);
};
+ // A rehearsal belongs to the panel that started it: leaving takes it away.
+ useEffect(() => stopAnimPreview, []);
return (
- <Section title="Animation">
- <div className="mt-0.5 mb-2 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
- {(["in", "out", "loop"] as const).map((id) => (
+ <>
+ {/* The title and the slot tabs ride the top of the scroll: the grid is
+ longer than the panel, and which slot a tile lands in is the one
+ thing a reader cannot afford to lose track of. */}
+ <div className="sticky top-0 z-10 bg-card pb-2">
+ <div className="flex h-10 shrink-0 items-center gap-1 px-2.5 text-sm font-semibold tracking-tight">
<button
- key={id}
type="button"
- className={cn(
- "flex-1 rounded-md px-1.5 py-1 capitalize transition-colors",
- slot === id
- ? "bg-neutral-900 text-white"
- : "text-muted-foreground hover:text-foreground",
- // A dot marks a slot that is already set, so switching tabs is
- // not the only way to see what an element is doing.
- anim[id] && slot !== id && "text-foreground"
- )}
- onClick={() => setSlot(id)}
+ aria-label="Back"
+ className="anim-back grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
+ onClick={onBack}
>
- {id}
- {anim[id] ? " ●" : ""}
+ <ChevronLeft className="size-4" />
</button>
- ))}
+ Animation
+ </div>
+ <div className="mx-3.5 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
+ {(["in", "out", "loop"] as const).map((id) => (
+ <button
+ key={id}
+ type="button"
+ className={cn(
+ "flex-1 rounded-md px-1.5 py-1 capitalize transition-colors",
+ slot === id
+ ? "bg-neutral-900 text-white"
+ : "text-muted-foreground hover:text-foreground",
+ // A slot that is already set reads darker, so switching tabs is
+ // not the only way to see what an element is doing.
+ anim[id] && slot !== id && "text-foreground"
+ )}
+ onClick={() => setSlot(id)}
+ >
+ {id}
+ </button>
+ ))}
+ </div>
</div>
- <AnimationTiles
- slot={slot}
- value={active?.style}
- isText={isTextOverlay(o)}
- onPick={pick}
- />
- {slot !== "loop" && active && (
- <Row label="Length">
- <ValueSlider
- label="Animation length"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS}
- min={OVERLAY_ANIM_MIN_SECONDS}
- max={Math.min(OVERLAY_ANIM_MAX_SECONDS, dur)}
- step={0.05}
- snap={[OVERLAY_ANIM_DEFAULT_SECONDS]}
- format={(v) => `${v.toFixed(2)}s`}
- parse={parseSecondsInput}
- onDraft={(v) =>
- dragAnim(lengthCk, {
- [slot]: { style: active.style as OverlayAnimStyle, seconds: v },
- })
- }
- onCommit={(v) => {
- dragAnim(lengthCk, {
- [slot]: { style: active.style as OverlayAnimStyle, seconds: v },
- });
- lengthCk.end();
- }}
- />
- </Row>
- )}
- {slot === "loop" && anim.loop && (
- <Row label="Speed">
- <ValueSlider
- label="Loop speed"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={anim.loop.speed}
- min={0.25}
- max={4}
- step={0.25}
- format={(v) => `${v.toFixed(2)}×`}
- parse={parseSpeedInput}
- onDraft={(v) => dragAnim(speedCk, { loop: { ...anim.loop!, speed: v } })}
- onCommit={(v) => {
- dragAnim(speedCk, { loop: { ...anim.loop!, speed: v } });
- speedCk.end();
- }}
- />
- </Row>
- )}
- </Section>
+ {/* pt-1 clears the selected tile's ring, which draws outside its box and
+ would otherwise sit under the sticky header. */}
+ <div className="flex flex-col gap-1 px-3.5 pt-1 pb-4">
+ <AnimationTiles
+ slot={slot}
+ value={active?.style}
+ isText={isTextOverlay(o)}
+ seconds={seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS}
+ speed={anim.loop?.speed ?? 1}
+ onPick={pick}
+ textStyle={demoTextStyle(o)}
+ />
+ </div>
+ </>
);
}
@@ -2249,9 +2339,10 @@ function ClipBorderSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Color" grow>
- <ColorSwatches
+ <Row label="Color">
+ <ColorField
value={bs.borderColor ?? "#FFFFFF"}
+ label="Border color"
onBegin={() => st().pushHistory()}
onLive={(c) => write({ borderColor: c })}
onCommit={(c) => st().updateClip(clip.id, { boxStyle: { ...bs, borderColor: c } })}
@@ -2502,47 +2593,44 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
const fillCk = useSliderCheckpoint();
const radiusCk = useSliderCheckpoint();
const strokeCk = useSliderCheckpoint();
+ const [animView, setAnimView] = useState<"closed" | "open" | "returned">("closed");
const boxShape = !lineLikeShape(o.shape);
+ if (animView === "open")
+ return <AnimationPanel overlay={o} onBack={() => setAnimView("returned")} />;
return (
<>
<PanelTitle>{SHAPE_LABELS[o.shape]}</PanelTitle>
<div className="flex flex-col gap-1 px-3.5 pb-4">
<Row label={boxShape ? "Fill" : "Color"}>
- <ColorSwatches
+ <ColorField
value={o.fill}
+ label={boxShape ? "Fill color" : "Shape color"}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { fill: c })}
onCommit={(c) => update(o.id, { fill: c })}
+ opacity={
+ boxShape
+ ? {
+ label: "Fill opacity",
+ value: o.fillOpacity ?? 1,
+ onDraft: (v) => {
+ fillCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ fillOpacity: v >= 0.995 ? undefined : v,
+ });
+ },
+ onCommit: (v) => {
+ fillCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, {
+ fillOpacity: v >= 0.995 ? undefined : v,
+ });
+ fillCk.end();
+ },
+ }
+ : undefined
+ }
/>
</Row>
- {boxShape && (
- <Row label="Fill opacity">
- <ValueSlider
- label="Fill opacity"
- sliderClassName="data-horizontal:w-24"
- valueClassName="w-9 text-muted-foreground"
- value={o.fillOpacity ?? 1}
- min={0}
- max={1}
- step={0.01}
- format={(v) => String(Math.round(v * 100))}
- parse={parsePercentInput}
- onDraft={(v) => {
- fillCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- fillOpacity: v >= 0.995 ? undefined : v,
- });
- }}
- onCommit={(v) => {
- fillCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, {
- fillOpacity: v >= 0.995 ? undefined : v,
- });
- fillCk.end();
- }}
- />
- </Row>
- )}
{o.shape === "rect" && (
<Row label="Corner radius">
<ValueSlider
@@ -2584,8 +2672,9 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
{o.stroke && (
<>
<Row label="Color">
- <ColorSwatches
+ <ColorField
value={o.stroke.color}
+ label="Outline color"
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) =>
useEditor.getState().updateOverlayTransient(o.id, {
@@ -2629,7 +2718,11 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
<OverlayMaskSection overlay={o} />
<TransformRows overlay={o} />
<GroupRow overlay={o} />
- <AnimationRows overlay={o} />
+ <AnimationSection
+ overlay={o}
+ onOpen={() => setAnimView("open")}
+ reveal={animView === "returned"}
+ />
</div>
</>
);
@@ -2816,6 +2909,9 @@ function StickerPanel({ overlay: o }: { overlay: StickerOverlay }) {
const asset = useEditor((s) =>
o.assetId ? s.assets.find((a) => a.id === o.assetId) : undefined
);
+ const [animView, setAnimView] = useState<"closed" | "open" | "returned">("closed");
+ if (animView === "open")
+ return <AnimationPanel overlay={o} onBack={() => setAnimView("returned")} />;
return (
<>
<PanelTitle>Sticker</PanelTitle>
@@ -2850,7 +2946,11 @@ function StickerPanel({ overlay: o }: { overlay: StickerOverlay }) {
<OverlayMaskSection overlay={o} />
<TransformRows overlay={o} />
<GroupRow overlay={o} />
- <AnimationRows overlay={o} />
+ <AnimationSection
+ overlay={o}
+ onOpen={() => setAnimView("open")}
+ reveal={animView === "returned"}
+ />
</div>
</>
);
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 1c298189..85b3e45d 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
+import { releaseAnimRest, useAnimPreview } from "@/cut/lib/animPreview";
import { startDrag } from "@/cut/lib/drag";
import { useSkim, usePreviewTime } from "@/cut/lib/playhead";
import { useEditor } from "@/cut/lib/store";
@@ -15,7 +16,7 @@ import {
subtitleLaneCount,
trackPos,
} from "@/cut/lib/subtitles";
-import { evalOverlayFrame, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, maskFrameAt, paintMaskCoverage, resolveShadow, shapeMetrics, shapePathD, type LottieHandle, type Mask, type MaskKey } from "@donkeycut/effects-kit";
+import { evalOverlayFrame, glyphStateAt, hasGlyphMotion, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, maskFrameAt, paintMaskCoverage, resolveShadow, shapeMetrics, shapePathD, type LottieHandle, type Mask, type MaskKey, type OverlayFrameState } from "@donkeycut/effects-kit";
import {
LINE_HEIGHT,
PLATE_PAD_X,
@@ -37,6 +38,13 @@ import {
type StickerOverlay,
} from "@/cut/lib/types";
import { subjectMatteSnapshot } from "@/cut/lib/behindPass";
+import {
+ BOX_HANDLES,
+ CORNER_HANDLES,
+ HANDLE_AXIS,
+ TransformHandles,
+ type ResizeHandle,
+} from "./TransformHandles";
import { stageEffectFilter, stageEffectTransform } from "@/cut/lib/effectStack";
import { useLiveEffects } from "./StageEffects";
import { cn } from "@/lib/utils";
@@ -485,6 +493,8 @@ function OverlayItem({
rotationGuide: (p: { clientX: number; clientY: number; quarter: number } | null) => void;
}) {
const [editing, setEditing] = useState(false);
+ /** The angle the readout shows while a rotate drag runs; null when idle. */
+ const [spin, setSpin] = useState<number | null>(null);
const editRef = useRef<HTMLDivElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
const frame = frameOf(useEditor((s) => s.aspect));
@@ -511,8 +521,29 @@ function OverlayItem({
// The element's animation state at this exact moment — the same evaluator
// the export samples, applied here as a live CSS transform. Ghosts (shown
- // out of range for editing) render at rest.
- const live = !ghost && isOverlayAnimated(o) ? evalOverlayFrame(o, Math.max(0, t - o.start)) : null;
+ // out of range for editing) render at rest. A rehearsal from the inspector
+ // outranks the clock: the element plays its animation where it stands, and
+ // after the run it holds its resting pose until the clock moves.
+ const rehearsal = useAnimPreview(o.id);
+ const restedAt = useRef<number | null>(null);
+ useEffect(() => {
+ if (rehearsal !== "rest") {
+ restedAt.current = null;
+ return;
+ }
+ if (restedAt.current === null) restedAt.current = t;
+ else if (t !== restedAt.current) releaseAnimRest(o.id);
+ }, [rehearsal, t, o.id]);
+ // A rehearsal draws the slot it is testing on its own — the run carries that
+ // one animation, so an In or a loop never rides along with it.
+ const running = rehearsal !== null && rehearsal !== "rest" ? rehearsal : null;
+ const live =
+ isOverlayAnimated(o) && rehearsal !== "rest" && (running !== null || !ghost)
+ ? evalOverlayFrame(
+ running ? { ...o, anim: running.anim } : o,
+ running ? running.tLocal : Math.max(0, t - o.start)
+ )
+ : null;
const animTransform = live
? ` translate(${live.dx * scale}px, ${live.dy * scale}px)` +
(live.rotation ? ` rotate(${live.rotation}deg)` : "") +
@@ -520,6 +551,10 @@ function OverlayItem({
: o.rotation
? ` rotate(${o.rotation}deg)`
: "";
+ // Per-glyph ramps and loops draw character by character; a wipe uncovers the
+ // box from its left edge. Neither runs while the box is being edited.
+ const glyphs = isText && !editing && live && hasGlyphMotion(live) ? live : null;
+ const reveal = !editing ? live?.reveal : undefined;
// Typewriter: the visible slice of the text (display only, never while
// the box is being edited).
const shownText =
@@ -581,6 +616,9 @@ function OverlayItem({
})()
: {}),
...(maskCss ?? {}),
+ ...(reveal !== undefined
+ ? { clipPath: `inset(0 ${(1 - Math.min(1, Math.max(0, reveal))) * 100}% 0 0)` }
+ : {}),
};
const commitText = () => {
@@ -651,44 +689,80 @@ function OverlayItem({
if (direct.length) s.updateOverlaysTransient(direct);
};
- // The corner handle resizes what the kind actually stores: a title's font
- // size, a shape's box (both axes by the drag ratio), a sticker's width.
- // A group scales as one: every member's size and its offset from the group
- // center ride the same factor.
- const resizeFrom = (e: React.PointerEvent) => {
+ // A grip resizes what the kind actually stores: a title's font size, a
+ // shape's box, a sticker's width. The grip's opposite corner or side stays
+ // planted: a corner takes both axes by how far it travels from the far
+ // corner, a side grip takes width alone measured from the far side, and the
+ // center walks out so the planted edge holds still on screen. A group
+ // scales as one about the same planted point.
+ const resizeFrom = (handle: ResizeHandle, e: React.PointerEvent) => {
const s = useEditor.getState();
s.pushHistory();
- const box = boxRef.current!.getBoundingClientRect();
+ const el = boxRef.current!;
+ const box = el.getBoundingClientRect();
const cx = box.left + box.width / 2;
const cy = box.top + box.height / 2;
- const d0 = Math.max(8, Math.hypot(e.clientX - cx, e.clientY - cy));
+ const axis = HANDLE_AXIS[handle];
+ const rad = (-(live?.rotation ?? o.rotation ?? 0) * Math.PI) / 180;
+ // The box's own size on screen: the bounding rect is the turned box's
+ // envelope, so take the layout size under the pose's scale.
+ const ow = el.offsetWidth * (live?.scale ?? 1);
+ const oh = el.offsetHeight * (live?.scale ?? 1);
+ // The planted point, in the element's own space relative to its center.
+ const ax = (-axis.x * ow) / 2;
+ const ay = (-axis.y * oh) / 2;
+ // The grip's reach from the planted point, in the element's own space: a
+ // corner measures the full diagonal, a side grip only its own axis.
+ const reach = (px: number, py: number) => {
+ const dx = px - cx;
+ const dy = py - cy;
+ const lx = dx * Math.cos(rad) - dy * Math.sin(rad);
+ const ly = dx * Math.sin(rad) + dy * Math.cos(rad);
+ if (axis.y === 0) return Math.abs(lx - ax);
+ if (axis.x === 0) return Math.abs(ly - ay);
+ return Math.hypot(lx - ax, ly - ay);
+ };
+ const d0 = Math.max(8, reach(e.clientX, e.clientY));
const members = groupSnapshot();
- const gx = members.reduce((sum, m) => sum + m.x, 0) / members.length;
- const gy = members.reduce((sum, m) => sum + m.y, 0) / members.length;
+ const self = members.find((m) => m.id === o.id) ?? members[0];
const scaled = (m: Overlay, k: number): Partial<Overlay> => {
if (isTextOverlay(m)) {
return { size: Math.round(Math.min(320, Math.max(16, m.size * k))) };
}
if (m.kind === "shape") {
- return {
- w: Math.min(2, Math.max(0.01, m.w * k)),
- h: Math.min(2, Math.max(0.002, m.h * k)),
- };
+ const w = { w: Math.min(2, Math.max(0.01, m.w * k)) };
+ // A side grip leaves the shape's height where it is.
+ if (axis.y === 0) return w;
+ return { ...w, h: Math.min(2, Math.max(0.002, m.h * k)) };
}
if (m.kind === "sticker") return { w: Math.min(1.5, Math.max(0.02, m.w * k)) };
return {};
};
+ // How much the grabbed element actually grew once its size clamps, so
+ // the planted point holds through the clamp too.
+ const grew = (patch: Partial<Overlay>): number => {
+ const p = patch as { size?: number; w?: number };
+ if (isTextOverlay(self)) return (p.size ?? self.size) / self.size;
+ if (self.kind === "shape" || self.kind === "sticker") return (p.w ?? self.w) / self.w;
+ return 1;
+ };
startDrag(e, {
onMove: (_dx, _dy, ev) => {
- const k = Math.hypot(ev.clientX - cx, ev.clientY - cy) / d0;
+ const k = reach(ev.clientX, ev.clientY) / d0;
+ const keff = grew(scaled(self, k));
+ // The center's walk that keeps the planted point on its screen spot,
+ // rotated back to the screen and into frame fractions.
+ const sx = axis.x ? ((keff - 1) * axis.x * ow) / 2 : 0;
+ const sy = axis.y ? ((keff - 1) * axis.y * oh) / 2 : 0;
+ const mx = (sx * Math.cos(rad) + sy * Math.sin(rad)) / stageWidth;
+ const my = (-sx * Math.sin(rad) + sy * Math.cos(rad)) / stageHeight;
writeTransform(
members.map((m) => ({
id: m.id,
patch: {
...scaled(m, k),
- ...(members.length > 1
- ? { x: clampPos(gx + (m.x - gx) * k), y: clampPos(gy + (m.y - gy) * k) }
- : {}),
+ x: clampPos(self.x + keff * (m.x - self.x) + mx),
+ y: clampPos(self.y + keff * (m.y - self.y) + my),
},
}))
);
@@ -719,6 +793,7 @@ function OverlayItem({
// The cursor turns with the element for the whole drag, so its heads keep
// pointing the way the next bit of travel will take it.
let liveRotation = o.rotation ?? 0;
+ setSpin(liveRotation);
startDrag(e, {
cursor: () => rotateCursor(liveRotation),
onMove: (_dx, _dy, ev) => {
@@ -726,6 +801,7 @@ function OverlayItem({
const { deg, locked } = snapQuarter(norm(angleAt(ev)));
const rotation = Math.round(deg);
liveRotation = rotation;
+ setSpin(rotation);
rotationGuide(locked === null ? null : { clientX: cx, clientY: cy, quarter: locked });
writeTransform([{ id: o.id, patch: { rotation: rotation === 0 ? undefined : rotation } }]);
return;
@@ -735,6 +811,7 @@ function OverlayItem({
const { locked } = snapQuarter(lead);
if (locked !== null) delta = norm(delta + locked - lead);
liveRotation = norm((o.rotation ?? 0) + delta);
+ setSpin(Math.round(liveRotation));
const rad = (delta * Math.PI) / 180;
// Positions are frame fractions with unequal axes; orbit in a square
// space keyed to width so the group turns rigidly on screen.
@@ -769,7 +846,10 @@ function OverlayItem({
}
);
},
- onUp: () => rotationGuide(null),
+ onUp: () => {
+ rotationGuide(null);
+ setSpin(null);
+ },
});
};
@@ -829,6 +909,8 @@ function OverlayItem({
>
{o.text}
</div>
+ ) : glyphs ? (
+ <GlyphText text={shownText} phase={glyphs} scale={scale} />
) : (
<span>{shownText}</span>
)
@@ -840,22 +922,19 @@ function OverlayItem({
</div>
{selected && !editing && (
<>
- {/* The lollipop clears the element's own top edge, so moving is
- never caught by it. */}
- <RotateGrip
- title="Drag to rotate"
- color="#0a84ff"
- className="overlay-rotate absolute -top-8 left-1/2 -translate-x-1/2"
- // The handle rides the element's rotation, so the cursor turns
- // with it and its heads keep pointing along the drag.
- style={{ cursor: rotateCursor(live?.rotation ?? o.rotation ?? 0) }}
- onPointerDown={rotateFrom}
- />
- <Grip
- title="Drag to resize"
+ {/* The rotate button clears the element's own top edge, so moving is
+ never caught by it. Its cursor rides the element's rotation, so
+ the glyph's heads keep pointing along the drag. */}
+ <TransformHandles
color="#0a84ff"
- className="overlay-resize absolute -right-2 -bottom-2 cursor-nwse-resize"
- onPointerDown={resizeFrom}
+ // The selection line draws 3px outside the box (plus half its
+ // stroke); the grips sit centered on it.
+ className="-inset-[3.75px]"
+ rotation={live?.rotation ?? o.rotation ?? 0}
+ angle={spin}
+ rotateCursor={rotateCursor(live?.rotation ?? o.rotation ?? 0)}
+ onResize={resizeFrom}
+ onRotate={rotateFrom}
/>
{o.mask && o.mask.kind !== "subject" && (
<MaskGizmo
@@ -890,6 +969,56 @@ const MASK_CSS_MAX = 512;
/** Empty coverage: hides the element while a computed matte has no person. */
const NO_COVERAGE_MASK = "linear-gradient(transparent, transparent)";
+/**
+ * Text laid out character by character, each one placed by the shared glyph
+ * evaluator. A ramp and a loop both land here, folded together by
+ * `glyphStateAt`. The canvas painter walks the same characters in the same
+ * order — line breaks take a turn too — so the preview and the export agree.
+ */
+function GlyphText({
+ text,
+ phase,
+ scale,
+}: {
+ text: string;
+ phase: OverlayFrameState;
+ scale: number;
+}) {
+ const total = Math.max(1, [...text].length);
+ let gi = 0;
+ return (
+ <>
+ {text.split("\n").map((line, li) => {
+ const chars = [...line].map((ch) => {
+ const i = gi++;
+ const g = glyphStateAt(phase, i, total);
+ return (
+ <span
+ key={i}
+ style={{
+ display: "inline-block",
+ whiteSpace: "pre",
+ opacity: Math.min(1, Math.max(0, g.alpha)),
+ transform:
+ `translate(${g.dx * scale}px, ${g.dy * scale}px)` +
+ ` rotate(${g.rotate}deg) scale(${g.sx}, ${g.sy})`,
+ }}
+ >
+ {ch}
+ </span>
+ );
+ });
+ gi++;
+ return (
+ <span key={li} style={{ display: "block", minHeight: "1em" }}>
+ {chars}
+ </span>
+ );
+ })}
+ </>
+ );
+}
+
function useMaskCss(
o: Overlay,
boxRef: React.RefObject<HTMLDivElement | null>,
@@ -1012,41 +1141,6 @@ function useMaskCss(
}, [active, m, box, o.x, o.y, stageWidth, stageHeight, scale, keyTick, snapTick]);
}
-/** On-canvas handle dot shared by every gizmo: a white dot with a colored
- * ring. The mask's amber is the default; a caller recolors it for its own
- * chrome (elements and clip regions pass selection blue). */
-export function Grip({
- color = "#ff9f0a",
- className,
- style,
- ...rest
-}: React.ComponentProps<"span"> & { color?: string }) {
- return (
- <span
- {...rest}
- className={cn(
- "size-[13px] rounded-full border-[2.5px] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.4)]",
- className
- )}
- style={{ borderColor: color, ...style }}
- />
- );
-}
-
-/** Rotate lollipop: the dot centered in a 28px grab zone, so the rotate
- * cursor shows as the pointer approaches the dot. */
-export function RotateGrip({
- color,
- className,
- ...rest
-}: React.ComponentProps<"span"> & { color?: string }) {
- return (
- <span {...rest} className={cn("grid size-7 place-items-center", className)}>
- <Grip color={color} />
- </span>
- );
-}
-
/**
* On-canvas mask editing, shared by elements and video clips: an amber
* outline tracing the mask's edge — its interior moves the mask, a lollipop
@@ -1090,6 +1184,8 @@ export function MaskGizmoCore({
w?: boolean;
h?: boolean;
} | null>(null);
+ /** The angle the readout shows while a rotate drag runs; null when idle. */
+ const [spin, setSpin] = useState<number | null>(null);
const interiorRef = useRef<HTMLDivElement>(null);
// Screen deltas → the box's local space (undo the element transform).
const toLocal = (dx: number, dy: number) => {
@@ -1111,18 +1207,16 @@ export function MaskGizmoCore({
const w = f.w * stageWidth;
const h = m.kind === "square" ? w : f.h * stageHeight;
const span = stageWidth + stageHeight;
- // The resize grip sits on the mask's corner (mirror: its lower edge),
- // turned by the mask's own angle.
- const gx = m.kind === "mirror" ? 0 : w / 2;
- const gy = h / 2;
- const rx = gx * Math.cos(theta) - gy * Math.sin(theta);
- const ry = gx * Math.sin(theta) + gy * Math.cos(theta);
- // The rotate lollipop clears the top edge (linear: the line itself), turned
- // with the mask so it stays over its top. The gap matches the element's own
- // lollipop: its 28px grab zone sits at -top-8, putting the dot 18px out.
- const lift = (m.kind === "linear" ? 0 : h / 2) + 18;
- const hx = cx + lift * Math.sin(theta);
- const hy = cy - lift * Math.cos(theta);
+ // Which grips the kind can honor: a square's axes move together, a mirror
+ // band only opens and closes, and a linear edge has no size at all.
+ const maskHandles: ResizeHandle[] =
+ m.kind === "square"
+ ? CORNER_HANDLES
+ : m.kind === "mirror"
+ ? ["n", "s"]
+ : sizable
+ ? BOX_HANDLES
+ : [];
const clampSize = (v: number) => Math.min(2, Math.max(0.01, v));
// Detents matching the inspector's: size locks onto exactly full frame,
// the center onto dead center, within a couple percent of the frame.
@@ -1167,15 +1261,67 @@ export function MaskGizmoCore({
const g0 = f;
const norm = (deg: number) => ((((deg + 180) % 360) + 360) % 360) - 180;
let liveRot = rotation + g0.rotation;
+ setSpin(Math.round(g0.rotation));
startDrag(e, {
cursor: () => rotateCursor(liveRot),
onMove: (_dx, _dy, ev) => {
const { deg, locked } = snapQuarter(norm(g0.rotation + (angleAt(ev) - a0)));
const rot = Math.round(deg);
liveRot = rotation + rot;
+ setSpin(rot);
setGuide(locked === null ? null : { rot: locked });
writeGeom({ rotation: rot });
},
+ onUp: () => {
+ setGuide(null);
+ setSpin(null);
+ },
+ });
+ };
+ // A grip pulls its own edge and leaves the opposite one planted: the size
+ // takes the pull and the center walks half of it, so the far edge holds
+ // still. A mirror band is the exception — it opens about its line, which is
+ // the thing it draws.
+ const sizeMask = (handle: ResizeHandle, e: React.PointerEvent) => {
+ e.stopPropagation();
+ begin();
+ const a = HANDLE_AXIS[handle];
+ const g0 = f;
+ startDrag(e, {
+ onMove: (dx, dy) => {
+ const l = toLocal(dx, dy);
+ const mx = l.x * Math.cos(theta) + l.y * Math.sin(theta);
+ const my = -l.x * Math.sin(theta) + l.y * Math.cos(theta);
+ const grow = m.kind === "mirror" ? 2 : 1;
+ const nw = clampSize(snapTo(g0.w + (grow * mx * a.x) / stageWidth, 1));
+ const nh = clampSize(snapTo(g0.h + (grow * my * a.y) / stageHeight, 1));
+ const gw = a.x !== 0 && nw === 1;
+ const gh = a.y !== 0 && nh === 1;
+ setGuide(gw || gh ? { w: gw, h: gh } : null);
+ // The center's walk, in the mask's own axes in px: half of what each
+ // edge actually grew after the clamp. A square's vertical side is `w`
+ // of the frame width too, so its corner shifts both axes by the same
+ // px. Turned by the mask's angle back into the element's space.
+ const dw = (nw - g0.w) * stageWidth;
+ const dh = m.kind === "square" ? dw : (nh - g0.h) * stageHeight;
+ const hx = m.kind === "mirror" ? 0 : (a.x * dw) / 2;
+ const hy = m.kind === "mirror" ? 0 : (a.y * dh) / 2;
+ const ex = hx * Math.cos(theta) - hy * Math.sin(theta);
+ const ey = hx * Math.sin(theta) + hy * Math.cos(theta);
+ const shift =
+ hx || hy ? { x: g0.x + ex / stageWidth, y: g0.y + ey / stageHeight } : {};
+ writeGeom(
+ m.kind === "square"
+ ? { w: nw, ...shift }
+ : m.kind === "mirror"
+ ? { h: nh }
+ : a.y === 0
+ ? { w: nw, ...shift }
+ : a.x === 0
+ ? { h: nh, ...shift }
+ : { w: nw, h: nh, ...shift }
+ );
+ },
onUp: () => setGuide(null),
});
};
@@ -1263,55 +1409,25 @@ export function MaskGizmoCore({
)}
</svg>
)}
- <RotateGrip
- title="Drag to rotate the mask"
- className="absolute z-10 -translate-x-1/2 -translate-y-1/2"
- style={{
- left: `calc(50% + ${hx}px)`,
- top: `calc(50% + ${hy}px)`,
- cursor: rotateCursor(rotation + f.rotation),
+ <TransformHandles
+ className="z-10"
+ color="#ff9f0a"
+ handles={maskHandles}
+ rotation={rotation + f.rotation}
+ angle={spin}
+ rotateCursor={rotateCursor(rotation + f.rotation)}
+ rotateTitle="Drag to rotate the mask"
+ resizeTitle="Drag to resize the mask"
+ frame={{
+ left: `calc(50% + ${cx}px)`,
+ top: `calc(50% + ${cy}px)`,
+ width: Math.max(1, w),
+ height: Math.max(1, h),
+ transform: `translate(-50%, -50%) rotate(${f.rotation}deg)`,
}}
- onPointerDown={rotateMask}
+ onRotate={rotateMask}
+ onResize={sizeMask}
/>
- {sizable && (
- <Grip
- title="Drag to resize the mask"
- className="absolute z-10 cursor-nwse-resize"
- style={{
- left: `calc(50% + ${f.x * stageWidth + rx}px)`,
- top: `calc(50% + ${f.y * stageHeight + ry}px)`,
- transform: "translate(-50%, -50%)",
- }}
- onPointerDown={(e) => {
- e.stopPropagation();
- begin();
- const g0 = f;
- startDrag(e, {
- onMove: (dx, dy) => {
- const l = toLocal(dx, dy);
- // Into the mask's own axes for width/height growth; a square
- // has one side and a mirror band one height.
- const mx = l.x * Math.cos(theta) + l.y * Math.sin(theta);
- const my = -l.x * Math.sin(theta) + l.y * Math.cos(theta);
- const nw = clampSize(snapTo(g0.w + (2 * mx) / stageWidth, 1));
- const nh = clampSize(snapTo(g0.h + (2 * my) / stageHeight, 1));
- const gw = m.kind !== "mirror" && nw === 1;
- const gh = m.kind !== "square" && m.kind !== "mirror" && nh === 1;
- const gm = m.kind === "mirror" && nh === 1;
- setGuide(gw || gh || gm ? { w: gw, h: gh || gm } : null);
- writeGeom(
- m.kind === "square"
- ? { w: nw }
- : m.kind === "mirror"
- ? { h: nh }
- : { w: nw, h: nh }
- );
- },
- onUp: () => setGuide(null),
- });
- }}
- />
- )}
</>
);
}
diff --git a/site/src/cut/lib/animPreview.ts b/site/src/cut/lib/animPreview.ts
new file mode 100644
index 00000000..36d864f3
--- /dev/null
+++ b/site/src/cut/lib/animPreview.ts
@@ -0,0 +1,117 @@
+"use client";
+
+/**
+ * A rehearsal clock for one element.
+ *
+ * Picking an animation in the inspector plays it on the stage right there: the
+ * playhead stays where it is, and this store holds which element is rehearsing
+ * plus the local time to draw it at. While a run is live the overlay takes
+ * that element's time from here, so the run costs one element's re-render per
+ * frame and nothing else on the page moves.
+ *
+ * A run lasts exactly as long as the animation it shows — the In/Out length,
+ * or one cycle of a loop. When it ends the element holds its resting pose:
+ * the paused playhead may sit mid-fade or mid-spin, and snapping there would
+ * leave the element hidden or upside-down right after the pick. The hold
+ * lifts the moment the preview clock moves.
+ */
+
+import { loopPeriod, type OverlayAnim } from "@donkeycut/effects-kit";
+import { useSyncExternalStore } from "react";
+
+/** A live rehearsal: which element, where in the slot's own window, and the
+ * slot on its own — the element's other slots are left out of the run so a
+ * loop rehearsal is a loop and nothing else. */
+export type AnimRun = { id: string; tLocal: number; anim: OverlayAnim };
+
+let run: AnimRun | null = null;
+/** The element holding its resting pose after a finished run. */
+let rested: string | null = null;
+let frame = 0;
+const listeners = new Set<() => void>();
+
+function notify() {
+ for (const fn of listeners) fn();
+}
+
+function subscribe(fn: () => void) {
+ listeners.add(fn);
+ return () => {
+ listeners.delete(fn);
+ };
+}
+
+const at = (id: string): AnimRun | "rest" | null =>
+ run?.id === id ? run : rested === id ? "rest" : null;
+
+/** The rehearsal running on this element, `"rest"` while it holds its resting
+ * pose after a run, or null when the clock owns it. */
+export function useAnimPreview(id: string): AnimRun | "rest" | null {
+ return useSyncExternalStore(
+ subscribe,
+ () => at(id),
+ () => null
+ );
+}
+
+/** End any run in progress and hand the element back to the clock. */
+export function stopAnimPreview(): void {
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ if (!run && !rested) return;
+ run = null;
+ rested = null;
+ notify();
+}
+
+/** Lift the post-run resting hold — the preview clock moved, so the element
+ * follows it again. */
+export function releaseAnimRest(id: string): void {
+ if (rested !== id) return;
+ rested = null;
+ notify();
+}
+
+/**
+ * Play `slot` on `o` from its own starting point: In sweeps the head of the
+ * element, Out its tail, and a loop runs one cycle. The run carries that slot
+ * alone, so rehearsing one animation never drags the element's other two into
+ * the picture. Nothing plays when the slot is empty.
+ */
+export function playAnimPreview(
+ o: { id: string; start: number; end: number; anim?: OverlayAnim },
+ slot: "in" | "out" | "loop"
+): void {
+ stopAnimPreview();
+ const anim: OverlayAnim =
+ slot === "in"
+ ? { in: o.anim?.in }
+ : slot === "out"
+ ? { out: o.anim?.out }
+ : { loop: o.anim?.loop };
+ const dur = Math.max(0.1, o.end - o.start);
+ const window =
+ slot === "loop"
+ ? (loopPeriod(anim) ?? 0)
+ : Math.min((slot === "in" ? anim.in?.seconds : anim.out?.seconds) ?? 0, dur);
+ if (window <= 0) return;
+ // Where the slot lives inside the element: In and a loop start at its head,
+ // Out ends at its tail.
+ const from = slot === "out" ? dur - window : 0;
+ const t0 = performance.now();
+ const step = () => {
+ const elapsed = (performance.now() - t0) / 1000;
+ if (elapsed >= window) {
+ stopAnimPreview();
+ rested = o.id;
+ notify();
+ return;
+ }
+ run = { id: o.id, tLocal: from + elapsed, anim };
+ notify();
+ frame = requestAnimationFrame(step);
+ };
+ run = { id: o.id, tLocal: from, anim };
+ notify();
+ frame = requestAnimationFrame(step);
+}
diff --git a/site/src/cut/lib/behindPass.ts b/site/src/cut/lib/behindPass.ts
index 019ff349..0b430b3b 100644
--- a/site/src/cut/lib/behindPass.ts
+++ b/site/src/cut/lib/behindPass.ts
@@ -9,8 +9,9 @@
* behind effect degrades to the plain picture.
*/
-import { evalOverlayFrame, maskComposite } from "@donkeycut/effects-kit";
+import { evalOverlayFrame, glyphStateAt, hasGlyphMotion, maskComposite } from "@donkeycut/effects-kit";
import { personSegmenter, segmentSubjectAlpha } from "./cutout";
+import { createRasterCanvas } from "./raster";
import { renderElementPng } from "./textRender";
import {
behindSubjectOverlay,
@@ -69,6 +70,10 @@ export function subjectMatteSnapshot(): { canvas: HTMLCanvasElement | null; at:
return published;
}
+/** Scratch off the raster seam. The pass types its surfaces as page canvases;
+ * headless they are server canvases with the same 2D interface. */
+const scratchCanvas = () => createRasterCanvas(1, 1) as HTMLCanvasElement;
+
export class SubjectMaskCompositor {
/** `publishes` marks the live preview's instance, the one whose matte the
* DOM layer reads. */
@@ -147,7 +152,7 @@ export class SubjectMaskCompositor {
this.ensureSegmenter();
if (!this.segmenter) return null;
if (slot.at > -1e8 && Math.abs(t - slot.at) < minInterval) return { alpha: slot.alpha };
- if (!this.small) this.small = document.createElement("canvas");
+ if (!this.small) this.small = scratchCanvas();
const W = source.width;
const H = source.height;
const sw = SEG_WIDTH;
@@ -233,8 +238,8 @@ export class SubjectMaskCompositor {
draw: (ctx: CanvasRenderingContext2D) => void
): CanvasImageSource {
if (!this.stampSurface || !this.stampScratch) {
- this.stampSurface = document.createElement("canvas");
- this.stampScratch = document.createElement("canvas");
+ this.stampSurface = scratchCanvas();
+ this.stampScratch = scratchCanvas();
}
if (this.stampSurface.width !== w) this.stampSurface.width = w;
if (this.stampSurface.height !== h) this.stampSurface.height = h;
@@ -279,7 +284,7 @@ export class SubjectMaskCompositor {
// The person source: the video pixels before any text lands on them.
if (!this.person || this.person.width !== W || this.person.height !== H) {
- this.person = document.createElement("canvas");
+ this.person = scratchCanvas();
this.person.width = W;
this.person.height = H;
}
@@ -302,14 +307,21 @@ export class SubjectMaskCompositor {
const bmp = this.rasterFor(o, W, H, assets);
if (!bmp) continue;
const ev = evalOverlayFrame(o, Math.max(0, t - o.start));
- if (ev.opacity <= 0.001) continue;
+ // One cached picture per element here, so a per-glyph ramp or loop runs
+ // its motion over the whole box as a single letter would.
+ const g = hasGlyphMotion(ev) ? glyphStateAt(ev, 0, 1) : null;
+ const alphaOf = ev.opacity * (g?.alpha ?? 1);
+ if (alphaOf <= 0.001) continue;
const cx = o.x * W;
const cy = o.y * H;
ctx.save();
- ctx.globalAlpha = ev.opacity;
- ctx.translate(ev.x * W + ev.dx * scale, ev.y * H + ev.dy * scale);
- ctx.rotate((ev.rotation * Math.PI) / 180);
- ctx.scale(ev.scale, ev.scale);
+ ctx.globalAlpha = alphaOf;
+ ctx.translate(
+ ev.x * W + (ev.dx + (g?.dx ?? 0)) * scale,
+ ev.y * H + (ev.dy + (g?.dy ?? 0)) * scale
+ );
+ ctx.rotate(((ev.rotation + (g?.rotate ?? 0)) * Math.PI) / 180);
+ ctx.scale(ev.scale * (g?.sx ?? 1), ev.scale * (g?.sy ?? 1));
ctx.translate(-cx, -cy);
ctx.drawImage(bmp, 0, 0, W, H);
ctx.restore();
diff --git a/site/src/cut/lib/overlayModel.test.ts b/site/src/cut/lib/overlayModel.test.ts
index c43d286a..e3a618ba 100644
--- a/site/src/cut/lib/overlayModel.test.ts
+++ b/site/src/cut/lib/overlayModel.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, test } from "bun:test";
import {
evalOverlayAnim,
+ glyphStateAt,
hasOverlayAnim,
loopPeriod,
+ OVERLAY_LOOP_STYLE_IDS,
shapeMetrics,
type OverlayAnim,
} from "@donkeycut/effects-kit";
@@ -248,6 +250,32 @@ describe("evalOverlayAnim", () => {
expect(loopPeriod({ in: { style: "fade", seconds: 1 } }) === null).toBe(true);
});
+ // The frame sampler renders one cycle of pictures and repeats them by
+ // reference, so a loop that drifts by even a hair would jump at the seam.
+ test("every loop repeats exactly on its period", () => {
+ for (const style of OVERLAY_LOOP_STYLE_IDS) {
+ const anim: OverlayAnim = { loop: { style, speed: 1 } };
+ const p = loopPeriod(anim)!;
+ for (const t of [0, 0.37 * p, 0.5 * p, 0.83 * p]) {
+ const a = evalOverlayAnim(anim, t, dur);
+ const b = evalOverlayAnim(anim, t + p, dur);
+ expect(b.dx).toBeCloseTo(a.dx, 5);
+ expect(b.dy).toBeCloseTo(a.dy, 5);
+ expect(b.scale).toBeCloseTo(a.scale, 5);
+ expect(b.alpha).toBeCloseTo(a.alpha, 5);
+ // Spin turns forever, so its angle only matches modulo a full turn.
+ expect((b.rotate - a.rotate) % 360).toBeCloseTo(0, 5);
+ for (let i = 0; i < 4; i++) {
+ const ga = glyphStateAt(a, i, 4);
+ const gb = glyphStateAt(b, i, 4);
+ expect(gb.dx).toBeCloseTo(ga.dx, 5);
+ expect(gb.dy).toBeCloseTo(ga.dy, 5);
+ expect(gb.sy).toBeCloseTo(ga.sy, 5);
+ }
+ }
+ }
+ });
+
test("loop composes with the in ramp", () => {
const anim: OverlayAnim = { in: { style: "fade", seconds: 1 }, loop: { style: "float", speed: 1 } };
const s = evalOverlayAnim(anim, 0.5, dur);
diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.ts
index ce46ee26..0e628e47 100644
--- a/site/src/cut/lib/textRender.ts
+++ b/site/src/cut/lib/textRender.ts
@@ -4,6 +4,7 @@ import {
renderElementPng as kitRenderElementPng,
renderOverlayFrames as kitRenderOverlayFrames,
type OverlayFrameSet,
+ type PaintPhase,
type RenderEnv,
type StickerImage,
} from "@donkeycut/effects-kit";
@@ -72,9 +73,10 @@ export function renderElementPng(
overlay: Overlay,
width: number,
height: number,
- assets: MediaAsset[] = []
+ assets: MediaAsset[] = [],
+ phase?: PaintPhase
): Promise<Blob> {
- return kitRenderElementPng(overlay, width, height, cutRenderEnv(assets));
+ return kitRenderElementPng(overlay, width, height, cutRenderEnv(assets), phase);
}
/** Rasterize an animated element into its region-cropped frame set (the
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 8f7883d5..6ccb71eb 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -131,7 +131,7 @@ Stickers (add_sticker): a project image asset (generated cutouts in the Elements
Custom stickers (create_sticker): one call generates the image, removes the background, adds the die-cut outline, and places it — use it when the user asks for a sticker of something they don't have (it spends credits like image generation).
Effects (add_effect): time-ranged treatments over the finished picture — the footage and everything laid over it. Two families, one list: the treatments (${EFFECT_TREATMENTS.join(", ")}) and the graded looks (${LOOK_EFFECTS.join(", ")}). Placed like any element and tuned with \`amount\` (update_overlay); an effect added over a clip opens covering that clip, and trims like anything else. One effect at a time reads best, amounts under ~0.5.
Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em), line_height, stroke_color/stroke_width (em outline behind the fill), and richer shadows. Bundled Google families join the system set — inter, montserrat, poppins, oswald, space-grotesk, playfair, caveat, bebas, anton, archivo-black, bangers, lobster, pacifico, permanent-marker, dm-serif — and the user can upload .ttf/.otf fonts (they appear as font ids like "asset:<id>").
-Animation (set_overlay_animation): every element takes preset In/Out ramps (${OVERLAY_ANIM_STYLE_IDS.join(", ")} — typewriter for titles only) and a Loop (${OVERLAY_LOOP_STYLE_IDS.join(", ")}) that runs its whole duration. Entrances 0.3–0.6s read well; one loop per scene, sparingly.
+Animation (set_overlay_animation): every element takes preset In/Out ramps (${OVERLAY_ANIM_STYLE_IDS.join(", ")} — typewriter for titles only; the per-letter styles sweep a title character by character) and a Loop (${OVERLAY_LOOP_STYLE_IDS.join(", ")}) that runs its whole duration. Entrances 0.3–0.6s read well; one loop per scene, sparingly.
Keyframes (set_overlay_keyframes): for motion no preset covers — a path across the frame, a slow push in, a drift that holds first. A key is a whole pose (position, scale, rotation, opacity) at a time in seconds from the element's start; the pose moves linearly between keys and holds outside them, and presets still compose on top. Two or three keys carry almost everything; reach for a preset first and keyframes when the user describes a specific path or timing. In the UI the diamond in the inspector adds a key at the playhead, and dragging the element then records into it. set_clip_keyframes is the same track on a video clip (any track): pans, push-ins, picture-in-picture flights, spins, and fades on the footage itself.
Masks (set_mask): trim any element or video clip to a shape — rect, square, circle, linear, mirror — with feather, invert, and its own keyframe track for reveals and wipes. The subject kind trims by the person in the shot (on-device segmentation; preview and export match): inverted sits the item behind the speaker, plain keeps it only on the speaker. Behind-speaker reads well when the speaker is clearly separated from the background; with no detectable person it degrades to the plain picture. Groups: the user can group elements (select several, Group in the inspector) — selecting one selects all, and moves/resize/rotate/timing ride together.
Composite builds: these primitives compose. Stacked overlay video copies, masks and their keys, pose keyframes, staggered starts, and shapes construct effects beyond any preset list. Given a reference (a screenshot or clip of an effect the user wants), reverse-engineer it: