Skip to content

Open source CapCut alternative.

TypeScript

fix(site): a caption uses the whole width the frame gives it

David Le5990c530d3d3
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 9b2c9e71..a27326fa 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -467,7 +467,7 @@ function SubtitleCaption({
<div
ref={(el) => registerBox(subtitleBoxId(lane), el)}
className={cn(
- "sub-caption pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab text-center whitespace-pre-wrap active:cursor-grabbing",
+ "sub-caption pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab text-center whitespace-pre active:cursor-grabbing",
armed && "outline-[1.5px] outline-offset-[3px] outline-[#0a84ff]"
)}
onPointerDown={(e) => {
@@ -492,9 +492,12 @@ function SubtitleCaption({
style={{
left: `${ov.x * 100}%`,
top: `${ov.y * 100}%`,
- // Hard cap at the safe area so a caption can never spill past the
- // frame edge, even if a line slips past the wrap estimate.
- maxWidth: `${0.9 * stageWidth}px`,
+ // The caption draws the lines `cueOverlay` already broke it into,
+ // measured against the room the export gives it. An absolutely
+ // positioned box otherwise shrinks to whatever is left of the stage
+ // beside its own anchor — half of it for a centered caption — and
+ // re-breaks lines the rendered file keeps whole.
+ width: "max-content",
fontSize: ov.size * scale,
fontFamily: fontStack(ov.font),
fontWeight: ov.weight,
diff --git a/site/src/cut/lib/captionWords.test.ts b/site/src/cut/lib/captionWords.test.ts
index 9dad9d4c..44e74614 100644
--- a/site/src/cut/lib/captionWords.test.ts
+++ b/site/src/cut/lib/captionWords.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, test } from "bun:test";
import { CAPTION_STYLES, cueOverlay, cueWordFrames, cueWords, trackPos } from "./subtitles";
+import { measureLine, textFontOf } from "./textFit";
import { emptySubtitles, type SubtitleCue, type SubtitlesBlock } from "./types";
+import { textRoom } from "@donkeycut/effects-kit";
/**
* A caption's word effect against the speech it was measured from.
@@ -92,6 +94,59 @@ describe("burn-in spans", () => {
});
});
+describe("the lines a caption is broken into", () => {
+ // The preview draws these lines in the DOM and the export paints them on a
+ // canvas; neither reflows, so the break decided here is what both show.
+ const long: SubtitleCue = {
+ id: "c2",
+ start: 0,
+ end: 3,
+ text: "Don't wait for someone to give you a chance to start the thing you keep talking about",
+ };
+ const linesAt = (size: number, frameW: number, x = 0.5) =>
+ cueOverlay(long, { ...CAPTION_STYLES.clean, size, x }, false, undefined, undefined, frameW)
+ .text.split("\n");
+
+ test("each line fits the room the frame leaves it", () => {
+ for (const line of linesAt(42, 1080)) {
+ expect(measureLine(line, textFontOf(CAPTION_STYLES.clean, 42), 42)).toBeLessThanOrEqual(
+ textRoom(0.5, 1080)
+ );
+ }
+ });
+
+ test("uses the width the frame has, not a share of it", () => {
+ // A caption centered in a 1080-wide frame gets the whole safe width. The
+ // regression this pins: laying it out against half the frame, which broke
+ // a line that had most of the picture still empty beside it.
+ const lines = linesAt(42, 1080);
+ const widest = Math.max(
+ ...lines.map((l) => measureLine(l, textFontOf(CAPTION_STYLES.clean, 42), 42))
+ );
+ expect(widest).toBeGreaterThan(textRoom(0.5, 1080) / 2);
+ });
+
+ test("evens the lines out instead of leaving an orphan", () => {
+ const lines = cueOverlay(
+ { ...long, text: "Don't wait for someone to give you a chance" },
+ CAPTION_STYLES.clean,
+ false,
+ undefined,
+ undefined,
+ 1080
+ ).text.split("\n");
+ expect(lines).toHaveLength(2);
+ const widths = lines.map((l) => measureLine(l, textFontOf(CAPTION_STYLES.clean, 42), 42));
+ expect(Math.min(...widths) / Math.max(...widths)).toBeGreaterThan(0.7);
+ });
+
+ test("breaks in design space, so every render size shows the same lines", () => {
+ expect(linesAt(42, 1080)).toEqual(linesAt(42, 1080));
+ // A caption dragged off-center has less room and breaks sooner.
+ expect(linesAt(42, 1080, 0.2).length).toBeGreaterThan(linesAt(42, 1080).length);
+ });
+});
+
describe("the caption's own settings", () => {
test("reach the drawn words", () => {
const faint = cueOverlay(
diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.ts
index ae9fa82f..1c07711a 100644
--- a/site/src/cut/lib/subtitles.ts
+++ b/site/src/cut/lib/subtitles.ts
@@ -299,18 +299,6 @@ export function captionStyle(style: CaptionStyleId | undefined): CaptionStyle {
return CAPTION_STYLES[style ?? "clean"] ?? CAPTION_STYLES.clean;
}
-/** Balance a caption onto up to two lines so it never overflows the frame. */
-export function wrapCaption(text: string): string {
- const t = text.trim().replace(/\s+/g, " ");
- if (t.length <= 26) return t;
- const mid = t.length / 2;
- let best = -1;
- for (let i = t.indexOf(" "); i !== -1; i = t.indexOf(" ", i + 1)) {
- if (best === -1 || Math.abs(i - mid) < Math.abs(best - mid)) best = i;
- }
- return best === -1 ? t : t.slice(0, best) + "\n" + t.slice(best + 1);
-}
-
/**
* Wrap a caption into as many lines as it takes to keep every line inside the
* frame width at font `size` in `font`. The export burn-in renders each
@@ -320,7 +308,8 @@ export function wrapCaption(text: string): string {
* The line is measured on the face it will be drawn in. A character count has
* to assume the widest glyph that face could hold, which broke short cues onto
* two lines with most of the frame still empty beside them; a measured line
- * puts a cue on one line whenever one line fits.
+ * puts a cue on one line whenever one line fits. A cue that needs more than
+ * one gets its words spread evenly across them.
*/
export function wrapCaptionForSize(
text: string,
@@ -333,7 +322,32 @@ export function wrapCaptionForSize(
const flat = text.trim().replace(/\s+/g, " ");
if (!flat) return "";
const css = textFontOf({ font, weight, italic: undefined }, size);
- return wrapTextToRoom(flat, textRoom(x, frameW), (line) => measureLine(line, css, size));
+ return balanceCaption(flat, textRoom(x, frameW), (line) => measureLine(line, css, size));
+}
+
+/**
+ * The fewest lines the caption fits in, evened out.
+ *
+ * Filling each line to the edge and letting the rest fall through leaves the
+ * last line holding a word or two under a full one — the orphan that makes a
+ * caption look broken. So the line count is settled first (fill greedily
+ * against the real room), and then the same fill is run again at the
+ * narrowest width that still needs no extra line, which spreads the words
+ * across the lines it already committed to. Nothing here can widen a line
+ * past the room: every candidate width is inside it.
+ */
+function balanceCaption(text: string, room: number, measure: (line: string) => number): string {
+ const greedy = wrapTextToRoom(text, room, measure);
+ const lines = greedy.split("\n").length;
+ if (lines < 2 || !(room > 0)) return greedy;
+ let lo = 0;
+ let hi = room;
+ for (let i = 0; i < 12; i++) {
+ const mid = (lo + hi) / 2;
+ if (wrapTextToRoom(text, mid, measure).split("\n").length <= lines) hi = mid;
+ else lo = mid;
+ }
+ return wrapTextToRoom(text, hi, measure);
}
/** A cue as a synthetic overlay, so captions ride the title pipeline. The style