Open source CapCut alternative.
TypeScript
fix(editor): wrap resized text without distorting glyphs [rebuild]
David Le789b35367554
diff --git a/site/packages/effects-kit/src/render.ts b/site/packages/effects-kit/src/render.tsindex 68837ffc..92b635b1 100644--- a/site/packages/effects-kit/src/render.ts+++ b/site/packages/effects-kit/src/render.ts@@ -26,7 +26,6 @@ import { elementPlugin } from "./registry";import { kitCanvas } from "./surface";import {lineLikeShape,- textStretch,type Overlay,type ShapeOverlay,type StickerOverlay,@@ -262,6 +261,11 @@ export function textRoom(x: number, frameWidth: number): number {return Math.min(TEXT_SAFE_WIDTH, anchored) * frameWidth;}+/** Explicit boxes wrap at their width; auto-width text stays within the frame. */+export function textWrapRoom(o: Pick<TextOverlay, "x" | "wrapWidth">, frameWidth: number): number {+ return o.wrapWidth && Number.isFinite(o.wrapWidth) ? Math.max(0.01, o.wrapWidth) * frameWidth : textRoom(o.x, frameWidth);+}+/*** Break text into lines that each fit `room`, keeping the author's own breaks.*@@ -343,35 +347,7 @@ async function paintText(overlay: TextOverlay,frame: PaintFrame,env: RenderEnv,- /** Width a line may measure, in the space this call draws in. The stretch- * pass hands its own down, because everything measured under `ctx.scale` is- * drawn wider than it measures. */- room?: number) {- // Glyph stretch scales everything the element paints — plate, stroke,- // per-glyph motion — about its center, the same space the DOM pair- // stretches with its CSS transform.- const { sx, sy } = textStretch(overlay);- if (sx !== 1 || sy !== 1) {- const cx = overlay.x * frame.width;- const cy = overlay.y * frame.height;- ctx.save();- ctx.translate(cx, cy);- ctx.scale(sx, sy);- ctx.translate(-cx, -cy);- try {- await paintText(- ctx,- { ...overlay, stretchX: undefined, stretchY: undefined },- frame,- env,- textRoom(overlay.x, frame.width) / sx- );- } finally {- ctx.restore();- }- return;- }const { width, scale } = frame;const fpx = overlay.size * scale;const cssFont = textCssFont(overlay, fpx, env);@@ -387,7 +363,7 @@ async function paintText(// Words stay in the picture: a line wider than the room its anchor leaves// is broken here, measured on the very context that is about to draw it.- const lines = wrapTextToRoom(overlay.text, room ?? textRoom(overlay.x, width), (line) =>+ const lines = wrapTextToRoom(overlay.text, textWrapRoom(overlay, width), (line) =>ctx.measureText(line).width).split("\n");const lineH = fpx * (overlay.lineHeight ?? LINE_HEIGHT);@@ -461,7 +437,7 @@ async function paintText(});})();const widthsOf = runs ? runs.map((r) => r.lineW) : lines.map((l) => ctx.measureText(l).width);- const maxW = Math.max(...widthsOf, 1);+ const maxW = overlay.wrapWidth ? textWrapRoom(overlay, width) : Math.max(...widthsOf, 1);if (overlay.plate) {const padX = PLATE_PAD_X * fpx;@@ -784,11 +760,10 @@ export async function measureElementBounds(const ctx = scratch.getContext("2d")!;ctx.font = cssFont;if ("letterSpacing" in ctx) ctx.letterSpacing = `${(o.letterSpacing ?? 0) * fpx}px`;- const { sx, sy } = textStretch(o);- const lines = wrapTextToRoom(o.text, textRoom(o.x, frame.width) / sx, (line) =>+ const lines = wrapTextToRoom(o.text, textWrapRoom(o, frame.width), (line) =>ctx.measureText(line).width).split("\n");- const maxW = Math.max(...lines.map((l) => ctx.measureText(l).width), 1);+ const maxW = o.wrapWidth ? textWrapRoom(o, frame.width) : Math.max(...lines.map((l) => ctx.measureText(l).width), 1);const lineH = fpx * (o.lineHeight ?? LINE_HEIGHT);let w = maxW;let h = lines.length * lineH;@@ -796,7 +771,7 @@ export async function measureElementBounds(w += PLATE_PAD_X * fpx * 2;h += PLATE_PAD_Y * fpx * 2;}- if (opts?.pad === false) return { cx, cy, w: w * sx, h: h * sy };+ if (opts?.pad === false) return { cx, cy, w, h };const strokePad = (o.stroke?.width ?? 0) * fpx * 2;const shadow = resolveShadow(o.shadow);const shadowPad = shadow ? (shadow.blur + Math.abs(shadow.offsetY)) * frame.scale : 0;@@ -804,8 +779,8 @@ export async function measureElementBounds(return {cx,cy,- w: (w + strokePad * 2 + shadowPad * 2) * sx,- h: (h + fpx * 0.3 + strokePad * 2 + shadowPad * 2) * sy,+ w: (w + strokePad * 2 + shadowPad * 2),+ h: (h + fpx * 0.3 + strokePad * 2 + shadowPad * 2),};}diff --git a/site/packages/effects-kit/src/textBox.test.ts b/site/packages/effects-kit/src/textBox.test.tsnew file mode 100644index 00000000..da762f82--- /dev/null+++ b/site/packages/effects-kit/src/textBox.test.ts@@ -0,0 +1,42 @@+import { expect, test } from "bun:test";+import { Canvas } from "skia-canvas";+import { measureElementBounds, paintElement, textWrapRoom, wrapTextToRoom, type RenderEnv } from "./render";+import type { TextOverlay } from "./types";++const frame = { width: 1080, height: 1920, scale: 1 };+const env: RenderEnv = { fontStack: () => "Arial", createCanvas: (w, h) => new Canvas(w, h) as unknown as HTMLCanvasElement };+const title: TextOverlay = { id: "title", text: "POV: refreshing GitHub until I get my 300th star", start: 0, end: 4, x: 0.5, y: 0.5, size: 60, font: "sf", weight: 700, color: "#fff", plate: false, shadow: false };++test("narrowing the box wraps lines and grows height at the same font size", async () => {+ const wide = await measureElementBounds({ ...title, wrapWidth: 0.8 }, frame, env, { pad: false });+ const narrow = await measureElementBounds({ ...title, wrapWidth: 0.3 }, frame, env, { pad: false });+ expect(wide.w).toBeCloseTo(864);+ expect(narrow.w).toBeCloseTo(324);+ expect(narrow.h).toBeGreaterThan(wide.h);+});++test("stored glyph stretch no longer changes painting or bounds", async () => {+ const saved = { ...title, stretchX: 0.4, stretchY: 2 };+ expect(await measureElementBounds(saved, frame, env)).toEqual(await measureElementBounds(title, frame, env));+ const paint = async (o: TextOverlay) => {+ const canvas = new Canvas(frame.width, frame.height);+ await paintElement(canvas.getContext("2d") as unknown as CanvasRenderingContext2D, o, frame, env);+ return canvas.toBuffer("png");+ };+ expect(await paint(saved)).toEqual(await paint(title));+});++test("proportional scaling grows a wrapped box equally on both axes", async () => {+ const o = { ...title, wrapWidth: 0.35 };+ const before = await measureElementBounds(o, frame, env, { pad: false });+ const after = await measureElementBounds({ ...o, size: o.size * 2, wrapWidth: o.wrapWidth * 2 }, frame, env, { pad: false });+ expect(after.w / before.w).toBeCloseTo(2);+ expect(after.h / before.h).toBeCloseTo(2);+});++test("explicit wrapping width stays fixed when the box moves", () => {+ expect(textWrapRoom({ x: 0.02, wrapWidth: 0.4 }, 1080)).toBe(432);+ expect(textWrapRoom({ x: 0.5, wrapWidth: 0.4 }, 1080)).toBe(432);+ const wrap = (width: number) => wrapTextToRoom("one two three four", width, (line) => line.length * 10);+ expect(wrap(textWrapRoom({ x: 0.5, wrapWidth: 0.1 }, 1000))).toBe("one two\nthree four");+});diff --git a/site/packages/effects-kit/src/types.ts b/site/packages/effects-kit/src/types.tsindex 58756c84..711a873a 100644--- a/site/packages/effects-kit/src/types.ts+++ b/site/packages/effects-kit/src/types.ts@@ -77,11 +77,9 @@ export interface TextOverlay extends OverlayBase {/** How lines align inside the text block; absent = center. The block* itself stays centered on (x, y). */align?: TextAlign;- /** Glyph stretch: width and height multipliers on the laid-out block,- * applied about its center. The frame's side grips write these; absent- * means 1. */- stretchX?: number;- stretchY?: number;+ /** Text box width as a frame-width fraction. Omitted means auto width.+ * Width changes wrap lines; height follows the content. */+ wrapWidth?: number;/** Drop shadow: `true` = the legacy default look, an object customizes it. */shadow: boolean | TextShadowSpec;plate: boolean; // rounded plate behind the text@@ -158,11 +156,6 @@ export function isTextOverlay(o: Overlay): o is TextOverlay {return (o.kind ?? "text") === "text";}-/** A text element's glyph stretch, resolved to concrete multipliers. */-export function textStretch(o: TextOverlay): { sx: number; sy: number } {- return { sx: o.stretchX ?? 1, sy: o.stretchY ?? 1 };-}-export function isShapeOverlay(o: Overlay): o is ShapeOverlay {return o.kind === "shape";}diff --git a/site/src/cut/components/GroupPanel.tsx b/site/src/cut/components/GroupPanel.tsxindex fcce4899..de77a745 100644--- a/site/src/cut/components/GroupPanel.tsx+++ b/site/src/cut/components/GroupPanel.tsx@@ -1,11 +1,11 @@"use client";import { useMemo, useState } from "react";-import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, FlipHorizontal2, FlipVertical2, Italic, StretchHorizontal, StretchVertical, Type } from "lucide-react";+import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, FlipHorizontal2, FlipVertical2, Italic, StretchHorizontal, Type } from "lucide-react";import { hasOverlayKeys, hasSpeedCurve, lineLikeShape, poseAt, retimeOf, ZOOM_LEVELS, ZOOM_RAMP_MAX, zoomRampOf } from "@donkeycut/effects-kit";import { ColorField } from "@/cut/components/ColorField";import { FontPicker } from "@/cut/components/FontPicker";-import { LETTER_SPACINGS, LINE_HEIGHTS, SoundQualityPanel, SoundQualityRow, STRETCHES, StylePresetsRow } from "@/cut/components/Inspector";+import { LETTER_SPACINGS, LINE_HEIGHTS, SoundQualityPanel, SoundQualityRow, TEXT_WIDTHS, StylePresetsRow } from "@/cut/components/Inspector";import { NumberField } from "@/cut/components/NumberField";import { Field, Row, Section, SegGroup, SegToggle, useSliderCheckpoint, Value } from "@/cut/components/panelBits";import { parseNumberInput, parsePercentInput, parseSecondsInput, parseSpeedInput, ScrubValue } from "@/cut/components/ScrubValue";@@ -353,8 +353,7 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {const align = sharedValue(texts.map((t) => t.align ?? "center"));const lineHeight = sharedNumber(texts.map((t) => t.lineHeight ?? 1.25));const letterSpacing = sharedNumber(texts.map((t) => (t.letterSpacing ?? 0) * 100));- const stretchX = sharedNumber(texts.map((t) => (t.stretchX ?? 1) * 100));- const stretchY = sharedNumber(texts.map((t) => (t.stretchY ?? 1) * 100));+ const wrapWidth = sharedNumber(texts.map((t) => (t.wrapWidth ?? 0) * 100));const color = sharedValue(texts.map((t) => t.color.toLowerCase()));const outlined = texts.every((t) => !!t.stroke);const strokeColor = sharedValue(texts.map((t) => t.stroke?.color.toLowerCase() ?? ""));@@ -473,32 +472,13 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {/></Field></div>- <div className="mt-1 grid grid-cols-2 gap-2">- {(- [- ["stretchX", "Width", stretchX, StretchHorizontal],- ["stretchY", "Height", stretchY, StretchVertical],- ] as const- ).map(([axis, label, shared, Icon]) => (- <Field key={axis} label={label}>- <NumberField- label={`${label} stretch`}- icon={<Icon />}- value={shared.value}- mixed={shared.mixed}- min={25}- max={400}- step={5}- snap={[100]}- presets={STRETCHES}- format={(v) => `${Math.round(v)}%`}- parse={parsePercentText}- onDraft={(v) => write.draft(() => set({ [axis]: Math.abs(v - 100) < 0.5 ? undefined : v / 100 }))}- onCommit={(v) => write.commit(() => set({ [axis]: Math.abs(v - 100) < 0.5 ? undefined : v / 100 }))}- />- </Field>- ))}- </div>+ <Field label="Text width">+ <NumberField label="Text box width" icon={<StretchHorizontal />} value={wrapWidth.value} mixed={wrapWidth.mixed}+ min={0} max={200} step={1} presets={TEXT_WIDTHS} format={(v) => v === 0 ? "Auto" : `${Math.round(v)}%`} parse={parsePercentText}+ onDraft={(v) => write.draft(() => set({ wrapWidth: v > 0 ? v / 100 : undefined }))}+ onCommit={(v) => write.commit(() => set({ wrapWidth: v > 0 ? v / 100 : undefined }))}+ />+ </Field><Row label="Color"><ColorFieldvalue={color.value}diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.tsindex d4a70152..1c0c3bd2 100644--- a/site/src/cut/components/Inspector.tools.ts+++ b/site/src/cut/components/Inspector.tools.ts@@ -87,8 +87,7 @@ export const INSPECTOR_TOOLS = [align: { type: "string", enum: ["left", "center", "right"], description: "Multi-line alignment (titles)" },letter_spacing: num("Tracking in em (titles; 0 = normal)"),line_height: num("Line height multiplier (titles; default 1.25)"),- stretch_x: num("Glyph stretch, width multiplier 0.25..4 (titles; 1 clears)"),- stretch_y: num("Glyph stretch, height multiplier 0.25..4 (titles; 1 clears)"),+ wrap_width: num("Text box width as a frame-width fraction, 0.01..2; 0 restores auto width. Text wraps and height follows content."),shadow: bool("Drop shadow (titles)"),plate: bool("Backdrop plate (titles)"),w: num("Width, fraction of frame width (shapes/stickers)"),diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 2453e530..9d0d2041 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -2,7 +2,7 @@import { useQueryClient } from "@tanstack/react-query";import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, FlipHorizontal2, FlipVertical2, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, PanelTopClose, PenTool, Scissors, Smile, Sparkles, StretchHorizontal, StretchVertical, Trash2, Type, User, Volume2 } from "lucide-react";+import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, FlipHorizontal2, FlipVertical2, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, PanelTopClose, PenTool, Scissors, Smile, Sparkles, StretchHorizontal, Trash2, Type, User, Volume2 } from "lucide-react";import { Button } from "@/components/ui/button";import { EmojiPicker } from "@/cut/components/EmojiPicker";import { FontPicker } from "@/cut/components/FontPicker";@@ -1911,7 +1911,7 @@ function AudioPanel({ clip }: { clip: AudioClip }) {export const LINE_HEIGHTS = [0.9, 1, 1.15, 1.25, 1.5, 1.75, 2];export const LETTER_SPACINGS = [-2, 0, 2, 5, 10, 20];/** Glyph stretch stops, percent of the face's own width or height. */-export const STRETCHES = [50, 75, 100, 125, 150, 200];+export const TEXT_WIDTHS = [0, 25, 50, 75, 100];function TextPanel({ overlay: o }: { overlay: TextOverlay }) {const update = useEditor((s) => s.updateOverlay);@@ -1920,7 +1920,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {const opacityCk = useSliderCheckpoint();const spacingCk = useSliderCheckpoint();const lineHeightCk = useSliderCheckpoint();- const stretchCk = useSliderCheckpoint();+ const widthCk = useSliderCheckpoint();const strokeCk = useSliderCheckpoint();const shadowCk = useSliderCheckpoint();const taRef = useRef<HTMLTextAreaElement>(null);@@ -2112,39 +2112,15 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {/></Field></div>- {/* Glyph stretch: the face drawn wider or taller than designed, the- same fields the stage's corner grip and the assistant write. */}- <div className="mt-1 grid grid-cols-2 gap-2">- {(["stretchX", "stretchY"] as const).map((axis) => (- <Field key={axis} label={axis === "stretchX" ? "Width" : "Height"}>- <NumberField- label={axis === "stretchX" ? "Width stretch" : "Height stretch"}- icon={axis === "stretchX" ? <StretchHorizontal /> : <StretchVertical />}- value={(o[axis] ?? 1) * 100}- min={25}- max={400}- step={5}- snap={[100]}- presets={STRETCHES}- format={(v) => `${Math.round(v)}%`}- parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}- onDraft={(v) => {- stretchCk.begin();- useEditor.getState().updateOverlayTransient(o.id, {- [axis]: Math.abs(v - 100) < 0.5 ? undefined : v / 100,- });- }}- onCommit={(v) => {- stretchCk.begin();- useEditor.getState().updateOverlayTransient(o.id, {- [axis]: Math.abs(v - 100) < 0.5 ? undefined : v / 100,- });- stretchCk.end();- }}- />- </Field>- ))}- </div>+ <Field label="Text width">+ <NumberField label="Text box width" icon={<StretchHorizontal />}+ value={(o.wrapWidth ?? 0) * 100} min={0} max={200} step={1} presets={TEXT_WIDTHS}+ format={(v) => v === 0 ? "Auto" : `${Math.round(v)}%`}+ parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}+ onDraft={(v) => { widthCk.begin(); useEditor.getState().updateOverlayTransient(o.id, { wrapWidth: v > 0 ? v / 100 : undefined }); }}+ onCommit={(v) => { widthCk.begin(); useEditor.getState().updateOverlayTransient(o.id, { wrapWidth: v > 0 ? v / 100 : undefined }); widthCk.end(); }}+ />+ </Field><Row label="Color"><ColorFieldvalue={o.color}diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxindex ac575741..fd8351a2 100644--- a/site/src/cut/components/OverlayLayer.tsx+++ b/site/src/cut/components/OverlayLayer.tsx@@ -18,7 +18,7 @@ import {subtitleLaneCount,trackPos,} from "@/cut/lib/subtitles";-import { evalOverlayFrame, glyphStateAt, hasGlyphMotion, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, MASK_FEATHER_MAX, MASK_RADIUS_MAX, maskFrameAt, maskHasRadius, maskInverts, maskOutlinePathD, maskSizeAxes, overlayWords, paintMaskCoverage, PEN_MIN_POINTS, penClosed, resolveShadow, shapeMetrics, shapePathD, textStretch, WORD_ACCENT_DEFAULT, wordDrawsAt, type LottieHandle, type Mask, type MaskKey, type MaskPoint, type OverlayFrameState, type WordDraw } from "@donkeycut/effects-kit";+import { evalOverlayFrame, glyphStateAt, hasGlyphMotion, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, MASK_FEATHER_MAX, MASK_RADIUS_MAX, maskFrameAt, maskHasRadius, maskInverts, maskOutlinePathD, maskSizeAxes, overlayWords, paintMaskCoverage, PEN_MIN_POINTS, penClosed, resolveShadow, shapeMetrics, shapePathD, WORD_ACCENT_DEFAULT, wordDrawsAt, type LottieHandle, type Mask, type MaskKey, type MaskPoint, type OverlayFrameState, type WordDraw } from "@donkeycut/effects-kit";import {LINE_HEIGHT,PLATE_PAD_X,@@ -28,7 +28,7 @@ import {SHADOW,wordDrawCss,} from "@/cut/lib/textRender";-import { fitTextToFrame } from "@/cut/lib/textFit";+import { fitTextToFrame, textBoxSize } from "@/cut/lib/textFit";import {behindSubjectOverlay,clampOverlayPos,@@ -709,18 +709,13 @@ function OverlayItem({// The box carries position, rotation, and opacity; the content wrapper// inside it carries a title's type styles (the edit caret inherits them)// and the mask.- // A title's glyph stretch rides the box transform, so every rect the stage- // reads off the box — snapping, the rotate gesture — is the stretched one.- // The chrome twin composes its own transform from the base, keeping its- // grips circular.- const { sx, sy } = isText ? textStretch(o) : { sx: 1, sy: 1 };const baseTransform = `translate(-50%, -50%)${animTransform}`;const chromeTransform = `translate(-50%, -50%)${animMove}`;const style: CSSProperties = {// A keyframed element is placed by its pose, not by its resting x/y.left: `${(live?.x ?? o.x) * 100}%`,top: `${(live?.y ?? o.y) * 100}%`,- transform: sx !== 1 || sy !== 1 ? `${baseTransform} scale(${sx}, ${sy})` : baseTransform,+ transform: baseTransform,opacity: (live ? live.opacity : (o.opacity ?? 1)) * (ghost ? 0.35 : 1),};const contentStyle: CSSProperties = {@@ -728,6 +723,7 @@ function OverlayItem({? (() => {const shadow = resolveShadow(o.shadow);return {+ width: o.wrapWidth ? o.wrapWidth * stageWidth + (o.plate ? 2 * PLATE_PAD_X * o.size * scale : 0) : undefined,fontSize: o.size * scale,fontFamily: fontStack(o.font),fontWeight: o.weight,@@ -831,7 +827,7 @@ function OverlayItem({// A grip resizes what the kind actually stores: a corner takes a title's// font size, a shape's box, a sticker's width; a side grip takes one axis- // alone — a shape's width or height, a title's glyph stretch. The grip's+ // alone — a shape's width or height, a title's wrapping 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 its own axis measured// from the far side, and the center walks out so the planted edge holds@@ -846,10 +842,9 @@ function OverlayItem({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 and the glyph- // stretch.- const ow = el.offsetWidth * (live?.scale ?? 1) * sx;- const oh = el.offsetHeight * (live?.scale ?? 1) * sy;+ // 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;@@ -867,11 +862,7 @@ function OverlayItem({const d0 = Math.max(8, reach(e.clientX, e.clientY));const members = groupSnapshot();const self = members.find((m) => m.id === o.id) ?? members[0];- // A stretch multiplier, clamped and stored as absence at 1.- const stretchVal = (v: number): number | undefined => {- const c = Math.round(Math.min(4, Math.max(0.25, v)) * 1000) / 1000;- return Math.abs(c - 1) < 0.005 ? undefined : c;- };+ const textSizes = new Map(members.filter(isTextOverlay).map((m) => [m.id, textBoxSize(m, frame.w)]));const stickerSize = (v: number) => Math.min(1.5, Math.max(0.02, v));// A sticker's resting height as a frame fraction: the one it stores, or// the grabbed box laid out under the source's own aspect. A side grip@@ -884,11 +875,12 @@ function OverlayItem({};const scaled = (m: Overlay, k: number): Partial<Overlay> => {if (isTextOverlay(m)) {- // A side grip pulls one axis of the glyph stretch; a corner scales- // the font, stretch carried along.- if (axis.y === 0) return { stretchX: stretchVal((m.stretchX ?? 1) * k) };- if (axis.x === 0) return { stretchY: stretchVal((m.stretchY ?? 1) * k) };- return { size: Math.round(Math.min(320, Math.max(16, m.size * k))) };+ if (axis.y === 0) {+ const width = Math.max(frame.w * 0.01, textSizes.get(m.id)!.width * k - (m.plate ? 2 * PLATE_PAD_X * m.size : 0));+ return { wrapWidth: Math.min(2, width / frame.w) };+ }+ const size = Math.min(320, Math.max(16, m.size * k));+ return { size, ...(m.wrapWidth ? { wrapWidth: m.wrapWidth * size / m.size } : {}) };}if (m.kind === "shape") {const w = { w: Math.min(2, Math.max(0.01, m.w * k)) };@@ -916,15 +908,12 @@ function OverlayItem({size?: number;w?: number;h?: number;- stretchX?: number;- stretchY?: number;+ wrapWidth?: number;};if (isTextOverlay(self)) {- const ks = (p.size ?? self.size) / self.size;- return {- kx: "stretchX" in p ? (p.stretchX ?? 1) / (self.stretchX ?? 1) : ks,- ky: "stretchY" in p ? (p.stretchY ?? 1) / (self.stretchY ?? 1) : ks,- };+ const before = textSizes.get(self.id)!;+ const after = textBoxSize({ ...self, size: p.size ?? self.size, wrapWidth: p.wrapWidth ?? self.wrapWidth }, frame.w);+ return { kx: after.width / before.width, ky: after.height / before.height };}if (self.kind === "shape")return { kx: (p.w ?? self.w) / self.w, ky: (p.h ?? self.h) / self.h };@@ -944,7 +933,7 @@ function OverlayItem({// The center's walk that keeps the planted point on its screen spot,// rotated back to the screen and into frame fractions.const wx = axis.x ? ((kx - 1) * axis.x * ow) / 2 : 0;- const wy = axis.y ? ((ky - 1) * axis.y * oh) / 2 : 0;+ const wy = axis.y ? ((ky - 1) * axis.y * oh) / 2 : isTextOverlay(self) ? ((ky - 1) * oh) / 2 : 0;const mx = (wx * Math.cos(rad) + wy * Math.sin(rad)) / stageWidth;const my = (-wx * Math.sin(rad) + wy * Math.cos(rad)) / stageHeight;writeTransform(@@ -1091,7 +1080,7 @@ function OverlayItem({rotateCursor={rotateCursor(live?.rotation ?? o.rotation ?? 0)}// Every element wears the whole frame; a line has only its own// length to pull on.- handles={o.kind === "shape" && lineLikeShape(o.shape) ? BOX_HANDLES : FRAME_HANDLES}+ handles={isText || (o.kind === "shape" && lineLikeShape(o.shape)) ? BOX_HANDLES : FRAME_HANDLES}onResize={resizeFrom}onRotate={rotateFrom}/>@@ -1106,8 +1095,8 @@ function OverlayItem({style={{left: "50%",top: "50%",- width: chromeLifted ? chromeSize.w * sx : "100%",- height: chromeLifted ? chromeSize.h * sy : "100%",+ width: chromeLifted ? chromeSize.w : "100%",+ height: chromeLifted ? chromeSize.h : "100%",transform: `translate(-50%, -50%)${chromeLifted ? ` scale(${poseZoom})` : ""}`,}}>@@ -1146,7 +1135,7 @@ function OverlayItem({editing ? (<divref={editRef}- className="min-w-2 outline-none select-text"+ className="min-w-2 whitespace-pre-wrap break-words outline-none select-text"contentEditablesuppressContentEditableWarningonBlur={commitText}@@ -1185,7 +1174,7 @@ function OverlayItem({createPortal((() => {// The twin: same placement, the base transform chain, the box's- // laid-out size with the glyph stretch folded into it — so the+ // laid-out size — so the// chrome lands exactly on the element while escaping the frame's// clipping, and the grips it carries stay circular.const ringStyle: CSSProperties = { inset: -4.5, borderRadius: 5, borderWidth: 1.5 };@@ -1195,8 +1184,8 @@ function OverlayItem({// The zoom lands in the size, never in the transform: translating// by half of the grown box centers it exactly where scaling the// small one did, and every line and grip inside stays screen-sized.- width: chromeSize.w * sx * poseZoom,- height: chromeSize.h * sy * poseZoom,+ width: chromeSize.w * poseZoom,+ height: chromeSize.h * poseZoom,transform: chromeTransform,};return (@@ -1329,10 +1318,6 @@ function useMaskCss(disabled: boolean): CSSProperties | undefined {const m = o.mask;- // The mask image lands on the content wrapper, inside the box's glyph- // stretch — so the frame-space geometry pre-divides by the stretch, and the- // transform lands it back where every canvas renderer draws it.- const { sx, sy } = isTextOverlay(o) ? textStretch(o) : { sx: 1, sy: 1 };// A behind (inverted subject) element renders in the canvas pass; the DOM// masks shapes and front subject elements.const subjectFront = !!m && m.kind === "subject" && !m.invert;@@ -1387,15 +1372,15 @@ function useMaskCss(ctx.drawImage(snap.canvas, 0, 0);ctx.filter = "none";const url = canvas.toDataURL();- const posX = box.w / 2 - (o.x * stageWidth) / sx;- const posY = box.h / 2 - (o.y * stageHeight) / sy;+ const posX = box.w / 2 - (o.x * stageWidth);+ const posY = box.h / 2 - (o.y * stageHeight);return {maskImage: `url(${url})`,WebkitMaskImage: `url(${url})`,maskRepeat: "no-repeat",WebkitMaskRepeat: "no-repeat",- maskSize: `${stageWidth / sx}px ${stageHeight / sy}px`,- WebkitMaskSize: `${stageWidth / sx}px ${stageHeight / sy}px`,+ maskSize: `${stageWidth}px ${stageHeight}px`,+ WebkitMaskSize: `${stageWidth}px ${stageHeight}px`,maskPosition: `${posX}px ${posY}px`,WebkitMaskPosition: `${posX}px ${posY}px`,};@@ -1423,7 +1408,6 @@ function useMaskCss(// box center, which is where the painter anchors the mask.ctx.scale(s, s);ctx.translate(box.w / 2, box.h / 2);- ctx.scale(1 / sx, 1 / sy);ctx.translate(-o.x * stageWidth, -o.y * stageHeight);paintMaskCoverage(ctx,@@ -1444,7 +1428,7 @@ function useMaskCss(// The keyed tick folds a 15fps-quantized tLocal in only when the mask// actually animates; the matte stamp refreshes the subject branch.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [active, m, box, o.x, o.y, sx, sy, stageWidth, stageHeight, scale, keyTick, snapTick]);+ }, [active, m, box, o.x, o.y, stageWidth, stageHeight, scale, keyTick, snapTick]);}/**diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 977118ba..2f37697f 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -740,7 +740,6 @@ function describeOverlay(o: Overlay) {shadow: o.shadow,plate: o.plate,...(o.plateRadius !== undefined && { plateRadius: r(o.plateRadius) }),- ...(o.stretchX !== undefined ? { stretchX: r(o.stretchX) } : {}),- ...(o.stretchY !== undefined ? { stretchY: r(o.stretchY) } : {}),+ ...(o.wrapWidth !== undefined ? { wrapWidth: r(o.wrapWidth) } : {}),};}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 5c631019..7341b4df 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -5897,10 +5897,8 @@ function overlayPatch(input: Record<string, unknown>, kind: "text" | "shape" | "patch.letterSpacing = Math.abs(input.letter_spacing) < 0.0025 ? undefined : clamp(input.letter_spacing, -0.05, 0.5);if (isNum(input.line_height))patch.lineHeight = Math.abs(input.line_height - 1.25) < 0.01 ? undefined : clamp(input.line_height, 0.7, 2.5);- if (isNum(input.stretch_x))- patch.stretchX = Math.abs(input.stretch_x - 1) < 0.005 ? undefined : clamp(input.stretch_x, 0.25, 4);- if (isNum(input.stretch_y))- patch.stretchY = Math.abs(input.stretch_y - 1) < 0.005 ? undefined : clamp(input.stretch_y, 0.25, 4);+ if (isNum(input.wrap_width))+ patch.wrapWidth = input.wrap_width <= 0 ? undefined : clamp(input.wrap_width, 0.01, 2);if (typeof input.shadow === "boolean") patch.shadow = input.shadow;if (typeof input.plate === "boolean") patch.plate = input.plate;if (isNum(input.plateRadius)) patch.plateRadius = clamp(input.plateRadius, 0, 1);diff --git a/site/src/cut/lib/previewSelection.test.ts b/site/src/cut/lib/previewSelection.test.tsindex 8357a232..537d2000 100644--- a/site/src/cut/lib/previewSelection.test.ts+++ b/site/src/cut/lib/previewSelection.test.ts@@ -98,7 +98,7 @@ test("scaling grows what each kind stores about the anchor", () => {expect(st().clips[0].frame).toEqual({ x: 0.0, y: 0.0, w: 0.6, h: 0.6 });scalePreviewSelection(st(), snapshot, { x: 0.2, y: 0.2 }, 2, 1);expect((st().overlays[0] as TextOverlay).size).toBe(60);- expect((st().overlays[0] as TextOverlay).stretchX).toBeCloseTo(2);+ expect((st().overlays[0] as TextOverlay).wrapWidth).toBeCloseTo(snapshot[0].text!.width * 2);});test("rotating orbits every center and turns every item", () => {@@ -113,3 +113,15 @@ test("rotating orbits every center and turns every item", () => {expect(st().clips[0].rotation).toBe(90);expect(st().clips[0].frame!.x + 0.15).toBeCloseTo(0.75);});++test("chat changes text wrapping without changing font size", async () => {+ const a = { ...title("a", 0.5, 0.5), lane: 0 };+ const b = { ...title("b", 0.5, 0.5), lane: 1 };+ const moving = { ...title("moving", 0.5, 0.5), start: 5, end: 8, lane: 0 };+ useEditor.setState({ overlays: [a, b, moving] });+ await runAiTool("update_overlay", { id: "moving", wrap_width: 0.3 });+ expect((st().overlays[2] as TextOverlay).wrapWidth).toBe(0.3);+ expect((st().overlays[2] as TextOverlay).size).toBe(60);+ await runAiTool("update_overlay", { id: "moving", wrap_width: 0 });+ expect((st().overlays[2] as TextOverlay).wrapWidth).toBeUndefined();+});diff --git a/site/src/cut/lib/previewSelection.ts b/site/src/cut/lib/previewSelection.tsindex 9d0de981..7ec6cb0c 100644--- a/site/src/cut/lib/previewSelection.ts+++ b/site/src/cut/lib/previewSelection.ts@@ -1,6 +1,7 @@-import { hasOverlayKeys, keyAt, upsertKey, type OverlayKey } from "@donkeycut/effects-kit";+import { textBoxSize } from "@/cut/lib/textFit";+import { PLATE_PAD_X, hasOverlayKeys, keyAt, upsertKey, type OverlayKey } from "@donkeycut/effects-kit";import { clipLen, type EditorState } from "@/cut/lib/store";-import { clampOverlayPos, clipKeyed, clipPoseAt, isShapeOverlay, isTextOverlay, rectOf, type FrameRect, type OverlayPatch, type Selection } from "@/cut/lib/types";+import { frameOf, clampOverlayPos, clipKeyed, clipPoseAt, isShapeOverlay, isTextOverlay, rectOf, type FrameRect, type OverlayPatch, type Selection } from "@/cut/lib/types";import { captionStyle, laneHidden, trackPos } from "@/cut/lib/subtitles";export const SELECTABLE_ITEM_KINDS = ["clip", "audio", "overlay", "cue"] as const;@@ -23,9 +24,9 @@ type Position = {/** The item's angle at the gesture's start, degrees clockwise. */rotation: number;/** What a scale gesture grows: a shape or sticker's box, a title's size or- * stretch, a clip's frame. A keyed item scales its key instead. */+ * wrapping width, a clip's frame. A keyed item scales its key instead. */box?: { w: number; h?: number };- text?: { size: number; stretchX: number; stretchY: number };+ text?: { size: number; wrapWidth?: number; width: number };};/** Into (-180, 180], the range every rotation is stored in. */@@ -43,7 +44,7 @@ export function previewSelectionSnapshot(s: EditorState, t: number): Position[]kind: "overlay", id: o.id, x: key?.x ?? o.x, y: key?.y ?? o.y, key, keys: o.kf,rotation: key?.rotation ?? o.rotation ?? 0,box: isShapeOverlay(o) || o.kind === "sticker" ? { w: o.w, h: o.h } : undefined,- text: isTextOverlay(o) ? { size: o.size, stretchX: o.stretchX ?? 1, stretchY: o.stretchY ?? 1 } : undefined,+ text: isTextOverlay(o) ? { size: o.size, wrapWidth: o.wrapWidth, width: (textBoxSize(o, frameOf(s.aspect).w).width - (o.plate ? 2 * PLATE_PAD_X * o.size : 0)) / frameOf(s.aspect).w } : undefined,});}for (const c of s.clips) {@@ -126,7 +127,7 @@ const clipCenter = (p: Position) => ({ x: p.x + (p.key ? 0 : p.frame!.w / 2), y:/*** Scale the selection about an anchor (frame fractions) by kx and ky: every* center walks out from the anchor, and each item grows what it stores — a- * shape's box, a sticker's width, a title's size (or its stretch on a+ * shape's box, a sticker's width, a title's size (or its wrapping width on a* one-axis pull), a clip's frame, a keyed item's scale.*/export function scalePreviewSelection(s: EditorState, positions: Position[], anchor: { x: number; y: number }, kx: number, ky: number) {@@ -150,21 +151,14 @@ export function scalePreviewSelection(s: EditorState, positions: Position[], anc// whichever axis the pull moved.own = { w: Math.max(0.01, p.box.w * (p.box.h === undefined && kx === 1 ? ky : kx)), ...(p.box.h !== undefined ? { h: Math.max(0.01, p.box.h * ky) } : {}) };} else if (p.text) {- // Every frame writes the whole set from the snapshot, so a pull that- // turns uniform mid-drag lands cleanly on one of the two.- own = uniform- ? { size: Math.max(8, p.text.size * k), stretchX: stretch(p.text.stretchX), stretchY: stretch(p.text.stretchY) }- : { size: p.text.size, stretchX: stretch(p.text.stretchX * kx), stretchY: stretch(p.text.stretchY * ky) };+ own = uniform || kx === 1+ ? { size: Math.max(8, p.text.size * k), wrapWidth: p.text.wrapWidth === undefined ? undefined : p.text.wrapWidth * k }+ : { size: p.text.size, wrapWidth: Math.max(0.01, Math.min(2, (p.text.wrapWidth ?? p.text.width) * kx)) };}return { p, x: clampOverlayPos(cx), y: clampOverlayPos(cy), own };}));}-const stretch = (v: number) => {- const c = Math.max(0.25, Math.min(4, v));- return Math.abs(c - 1) < 1e-6 ? undefined : c;-};-/*** Turn the selection rigidly about a center (frame fractions) by `delta`* degrees: every center orbits, in a square space keyed to width so the setdiff --git a/site/src/cut/lib/textFit.ts b/site/src/cut/lib/textFit.tsindex 43243cfe..ba36612f 100644--- a/site/src/cut/lib/textFit.ts+++ b/site/src/cut/lib/textFit.ts@@ -1,6 +1,6 @@"use client";-import { textRoom, wrapTextToRoom } from "@donkeycut/effects-kit";+import { textWrapRoom, wrapTextToRoom, LINE_HEIGHT, PLATE_PAD_X, PLATE_PAD_Y } from "@donkeycut/effects-kit";import { createRasterCanvas } from "./raster";import { fontStack, type TextOverlay } from "./types";@@ -98,14 +98,17 @@ export function textFontOf(* anchor leaves in the frame. Returns the text unchanged when it already fits,* so nothing re-renders for an element that was never in trouble. */export function fitTextToFrame(o: TextOverlay, frameW: number): string {- // A stretched element is measured at its own size and drawn wider, so the- // room shrinks by the stretch — the same arithmetic the kit painter does- // under `ctx.scale`, which keeps the two breaking in the same places.const size = o.size;const font = textFontOf(o, size);- const room = textRoom(o.x, frameW) / Math.max(0.01, o.stretchX ?? 1);+ const room = textWrapRoom(o, frameW);const width = (line: string) => measureLine(line, font, size, o.letterSpacing ?? 0);if (o.text.split("\n").every((line) => width(line) <= room)) return o.text;return wrapTextToRoom(o.text, room, width);}+/** Resting box in design pixels, measured once for resize gestures. */+export function textBoxSize(o: TextOverlay, frameW: number): { width: number; height: number } {+ const lines = fitTextToFrame(o, frameW).split("\n");+ const width = o.wrapWidth ? textWrapRoom(o, frameW) : Math.max(1, ...lines.map((line) => measureLine(line, textFontOf(o, o.size), o.size, o.letterSpacing ?? 0)));+ return { width: width + (o.plate ? 2 * PLATE_PAD_X * o.size : 0), height: (lines.length * (o.lineHeight ?? LINE_HEIGHT) + (o.plate ? 2 * PLATE_PAD_Y : 0)) * o.size };+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 9b257a55..1269519c 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -363,7 +363,7 @@ Shapes (add_shape): rect, ellipse, line, arrow. w/h are frame fractions; rect/elStickers (add_sticker): a project image asset (generated cutouts in the Elements panel carry origin "sticker"); w is a frame-width fraction and height follows the source's aspect unless h sets it. Lottie JSON uploads become animated stickers that loop for the element's duration.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 cut. Three families, one list: the picture treatments (${EFFECT_TREATMENTS.join(", ")}), the graded looks (${LOOK_EFFECTS.join(", ")}), and the audio treatments (${AUDIO_EFFECT_IDS.join(", ")}). A picture effect treats the footage and everything laid over it; an audio effect treats everything audible under its window at once — clip sound, upper-track sound and the soundtrack — so "make this bit sound like a phone call", "put an echo on that line", or "muffle the music here" is an effect element over that stretch, and a per-clip volume, fade or duck is the audio tools instead. A handover on the sound at a cut belongs to the transition on that cut — the audiocross style — not here. Placed like any element and tuned with \`amount\` (update_overlay), and trims like anything else: a picture effect dropped over a clip opens covering that clip, while an audio effect opens at the standard length wherever it was placed — a treatment on the sound is aimed at a moment, so give it the window you mean. One effect at a time reads best, amounts under ~0.5. Effects are stylized post treatments on a stretch of timeline; pure color — exposure, warmth, a cinematic or film palette on one clip — is the per-clip grading tools instead (color-grading skill), whose preset catalog is separate from the look effects.-Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em), line_height, stretch_x/stretch_y (glyph stretch multipliers, the side grips' axis-only resize), stroke_color/stroke_width (em outline behind the fill), and richer shadows. Bundled Google families join the system set — ${GOOGLE_FONT_IDS.join(", ")} — and so do the user's own: a .ttf/.otf/.woff/.woff2 file dropped on the Library is offered in every project under a font id like "font:<key>". Editor_state lists the ones this account has under \`fonts\` — use an id from there instead of guessing at a family name, and when someone asks for a typeface that is not in the list, tell them the Library takes font files.+Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em), line_height, wrap_width (frame-width fraction; side grips wrap text, height follows content; corners scale type proportionally), stroke_color/stroke_width (em outline behind the fill), and richer shadows. Bundled Google families join the system set — ${GOOGLE_FONT_IDS.join(", ")} — and so do the user's own: a .ttf/.otf/.woff/.woff2 file dropped on the Library is offered in every project under a font id like "font:<key>". Editor_state lists the ones this account has under \`fonts\` — use an id from there instead of guessing at a family name, and when someone asks for a typeface that is not in the list, tell them the Library takes font files.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), a Loop (${OVERLAY_LOOP_STYLE_IDS.join(", ")}) that runs its whole duration, and a Move that says what it does WHILE it holds. A title takes one more: Words (${WORD_EFFECT_IDS.join(", ")}), which plays the line word by word — an emphasis travelling along a line that is fully up, or a build assembling the line as it is spoken. Entrances 0.3–0.6s read well; one loop per scene, sparingly; a move on the lines that matter. All of them are slots on the element, applied internally, and they compose over its keyframe track. A slot is the reach when the motion is per-letter or per-word — typewriter, the glyph sweeps, the word effects — which one pose track cannot express; what the whole element does is keyed.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. This is the default way to animate an element: a key names the exact pose at the exact second, where a named ramp only approximates it. Two or three keys carry almost everything. 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 — ${MASK_SHAPE_KINDS.join(", ")} — with feather, invert, rounded corners on a box, and its own keyframe track for reveals and wipes. The pen kind takes an outline as points, for any region the fixed shapes miss: the gap framed between two hands, a doorway, a screen — read the region's corners off a captured frame in frame fractions, and stack a masked copy of the shot (a filter, a title) so it shows through only there. 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. Group and Ungroup are in the timeline toolbar (⌘/Ctrl+G and ⇧⌘/Ctrl+G).