Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/packages/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1609,6 +1609,12 @@ Overlap is judged on the text a viewer can see: a part of a text block that an
overflow clip, a `clip-path` or a gradient `mask-image` (on the text or an ancestor)
keeps from painting does not count.

`text_word_split` (warning) reports Korean text where a line break lands inside
a word: between two Hangul syllables, or between a Hangul particle and the Latin
word or number it is attached to (`HyperFrames|로`). Chrome's default
`word-break: normal` allows those breaks; set `word-break: keep-all` on the text
or a parent so Korean lines break only at spaces.

#### Mark intentional layout choices

When the audit is wrong because the layout is deliberate, say so in the HTML and
Expand Down
94 changes: 94 additions & 0 deletions packages/cli/src/commands/layout-audit.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,98 @@
return issues;
}

// Korean puts spaces between words, yet under the default `word-break: normal`
// Chrome may end a line between any two Hangul syllables, or between a Hangul
// particle and the Latin word or number it is attached to ("HyperFrames로"),
// so a caption word wraps in half. `word-break: keep-all` keeps them together.
// Hangul Jamo, Compatibility Jamo, Jamo Extended-A, Syllables, Jamo Extended-B.
const HANGUL_CHAR = /[ᄀ-ᇿ㄰-㆏ꥠ-꥿가-힯ힰ-퟿]/;
const WORD_CHAR = /[\p{L}\p{M}\p{N}]/u;
const WORD_SPLIT_SCAN_LIMIT = 2000;

function joinsKoreanWord(left, right) {
return (
WORD_CHAR.test(left) &&
WORD_CHAR.test(right) &&
(HANGUL_CHAR.test(left) || HANGUL_CHAR.test(right))
);
}

function charRect(range, node, index) {
range.setStart(node, index);
range.setEnd(node, index + 1);
const rect = range.getBoundingClientRect();
return rect.width > 0.5 && rect.height > 0.5 ? rect : null;
}

// Line boxes stack vertically: two adjacent characters whose centres sit more
// than half a glyph apart are on different lines. A font-fallback fragment on
// the same line shifts by a few px; a small caption tilt barely moves it.
function onLaterLine(before, after) {
const centre = (rect) => rect.top + rect.height / 2;
return Math.abs(centre(after) - centre(before)) > Math.max(before.height, after.height) / 2;
}

function wordAround(text, index) {
let start = index;
while (start > 0 && WORD_CHAR.test(text[start - 1])) start--;
let end = index;
while (end < text.length && WORD_CHAR.test(text[end])) end++;
return `${text.slice(start, index)}|${text.slice(index, end)}`;
}

/** Where a line break first cuts a Korean word in this text node ("줄바꿈되는|지"), or null. */
function splitKoreanWord(node) {
const text = (node.textContent || "").slice(0, WORD_SPLIT_SCAN_LIMIT);
if (!HANGUL_CHAR.test(text)) return null;
const range = document.createRange();
try {
range.selectNodeContents(node);
// One client rect per line box: a node on a single line cannot split a word.
const lines = Array.from(range.getClientRects()).filter(
(rect) => rect.width > 0.5 && rect.height > 0.5,
);
if (lines.length < 2) return null;
let previous = null;
for (let index = 1; index < text.length; index++) {
if (!joinsKoreanWord(text[index - 1], text[index])) continue;
const before =
previous && previous.index === index - 1
? previous.rect
: charRect(range, node, index - 1);
const after = charRect(range, node, index);
previous = { index, rect: after };
if (before && after && onLaterLine(before, after)) return wordAround(text, index);
}
return null;
} finally {
range.detach();
}
}

function koreanWordSplitIssue(element, time) {
for (const node of directTextNodes(element)) {
const split = splitKoreanWord(node);
if (!split) continue;
const keepAll = getComputedStyle(element).wordBreak === "keep-all";
return {
code: "text_word_split",
severity: "warning",
time,
selector: uniqueSelectorFor(element),
text: textContentFor(element, true),
message: `A line break cuts a Korean word in two ("${split}").`,
rect:
unionRects(textClientRects(element, true).map(toRect)) ||
toRect(element.getBoundingClientRect()),
fixHint: keepAll
? "The word is wider than its line even with word-break: keep-all: widen the box or lower the font size."
: "Set word-break: keep-all on the text or a parent so Korean lines break only at spaces.",
};
}
return null;
}

function isNowrapTextChild(child) {
if (!isVisibleElement(child) || hasAllowOverflowFlag(child)) return false;
if (getComputedStyle(child).whiteSpace !== "nowrap") return false;
Expand Down Expand Up @@ -3051,6 +3143,8 @@
const clipped = clippedTextIssue(element, time, tolerance);
if (clipped) issues.push(clipped);
issues.push(...textOverflowIssues(element, root, rootRect, time, tolerance, clipped));
const split = koreanWordSplitIssue(element, time);
if (split) issues.push(split);
const occluded = occludedTextIssue(element, time, proseCoverageFloor, matteResults);
if (occluded) {
const lifetime = clipLifetime(element);
Expand Down
78 changes: 78 additions & 0 deletions packages/cli/src/commands/layout-audit.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4254,3 +4254,81 @@ function rect({ left, top, width, height }: RectInput): DOMRect {
},
} as DOMRect;
}

describe("layout-audit.browser Korean word splits", () => {
// One 60 px glyph per character; characters from `breakAt` on sit on a second line,
// and a range gets one client rect per line it spans, as in Chrome.
function auditKoreanCaption(
text: string,
breakAt: number,
style: Partial<CSSStyleDeclaration> = {},
): AuditIssue[] {
document.body.innerHTML = `<div id="root" data-composition-id="main" data-width="1080" data-height="1920"><p id="caption">${text}</p></div>`;
installGeometry(
{
root: rect({ left: 0, top: 0, width: 1080, height: 1920 }),
caption: rect({ left: 90, top: 600, width: 900, height: 144 }),
},
{ caption: style },
);
const glyph = (index: number) => {
const line = index < breakAt ? 0 : 1;
const column = line === 0 ? index : index - breakAt;
return rect({ left: 90 + column * 60, top: 600 + line * 72, width: 60, height: 60 });
};
vi.spyOn(document, "createRange").mockImplementation(() => {
let start = 0;
let end = 0;
const glyphs = () =>
Array.from({ length: Math.max(0, end - start) }, (_, i) => glyph(start + i));
const lineRects = () => {
const byLine = new Map<number, DOMRect[]>();
for (const item of glyphs()) byLine.set(item.top, [...(byLine.get(item.top) ?? []), item]);
return [...byLine.values()].map((line) => boundingTextRect(line) as DOMRect);
};
return {
selectNodeContents(node: Node) {
start = 0;
end = node.textContent?.length ?? 0;
},
setStart(_node: Node, offset: number) {
start = offset;
},
setEnd(_node: Node, offset: number) {
end = offset;
},
getClientRects: () => lineRects() as unknown as DOMRectList,
getBoundingClientRect: () =>
boundingTextRect(glyphs()) ?? rect({ left: 0, top: 0, width: 0, height: 0 }),
detach() {},
} as unknown as Range;
});
installAuditScript();
return runAudit().filter((issue) => issue.code === "text_word_split");
}

it("reports a Korean word that a line break cuts between syllables", () => {
const [issue] = auditKoreanCaption("자막이 줄바꿈되는지", 9);
expect(issue).toMatchObject({ selector: "#caption", text: "자막이 줄바꿈되는지" });
expect(issue?.message).toContain('"줄바꿈되는|지"');
expect(issue?.fixHint).toContain("word-break: keep-all");
});

it("reports a Korean particle cut from the Latin word it is attached to", () => {
const [issue] = auditKoreanCaption("HyperFrames로", 11);
expect(issue?.message).toContain('"HyperFrames|로"');
});

it("stays quiet when Korean lines break at spaces", () => {
expect(auditKoreanCaption("자막이 줄바꿈되는지", 4)).toEqual([]);
});

it("stays quiet for text without Hangul", () => {
expect(auditKoreanCaption("Launch faster", 3)).toEqual([]);
});

it("asks for room instead of keep-all when keep-all is already set", () => {
const [issue] = auditKoreanCaption("줄바꿈되는지", 5, { wordBreak: "keep-all" });
expect(issue?.fixHint).toContain("wider than its line");
});
});
55 changes: 55 additions & 0 deletions packages/cli/src/commands/layout-audit.chromium.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,61 @@ describe.runIf(executablePath)("layout audit in Chromium", () => {
expect(codes).toContain("text_not_painted");
});

// Chrome may end a line between any two Hangul syllables unless word-break is keep-all.
it.each([
{
name: "a Korean word wrapped between syllables",
text: "가나다라마바사아",
css: "",
split: true,
},
{
name: "that word under a caption tilt",
text: "가나다라마바사아",
css: "transform:rotate(-4deg)",
split: true,
},
{
name: "a Latin word with its Korean particle wrapped apart",
text: "HyperFrames로",
css: "width:6.9em;font-family:Arial",
split: true,
},
{
name: "Korean wrapped at spaces with keep-all",
text: "가나다 라마바 사아자",
css: "word-break:keep-all",
split: false,
},
{
name: "a Latin face with Korean fallback, wrapped at spaces",
text: "HyperFrames로 만든 자막",
css: "width:8.5em;word-break:keep-all;font-family:Arial",
split: false,
},
{
name: "Korean on one line",
text: "가나다라마바사아",
css: "width:auto;white-space:nowrap",
split: false,
},
{
name: "Korean lines split by <br>",
text: "가나다<br>라마바",
css: "width:auto",
split: false,
},
{ name: "wrapped English", text: "Launch faster ship sooner", css: "", split: false },
{ name: "wrapped Japanese", text: "日本語の字幕はどこでも改行できます", css: "", split: false },
])("text_word_split: $name", async ({ text, css, split }) => {
const codes = await auditCodes(
stage(
`<p style="position:absolute;left:100px;top:100px;width:3.5em;margin:0;font:700 80px/1.2 sans-serif;${css}">${text}</p>`,
),
);
expect(codes.includes("text_word_split")).toBe(split);
});

it.each([
{ name: "padding", css: "padding-top:150px" },
{ name: "text indentation", css: "text-indent:1000px;white-space:nowrap" },
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/utils/checkBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2380,6 +2380,7 @@ const LAYOUT_ISSUE_CODES: readonly LayoutIssueCode[] = [
"canvas_covered",
"video_alpha_unread",
"text_not_painted",
"text_word_split",
"caption_zone_collision",
"outside_safe_zone",
"frame_out_of_frame",
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/utils/layoutAudit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export type LayoutIssueCode =
| "canvas_covered"
| "video_alpha_unread"
| "text_not_painted"
| "text_word_split"
| "caption_zone_collision"
| "outside_safe_zone"
| "frame_out_of_frame"
Expand Down Expand Up @@ -214,6 +215,7 @@ const PERSISTENCE_TIERED_CODES: ReadonlySet<LayoutIssueCode> = new Set([
"content_overlap",
"visibility_escapes_segment",
"text_occluded",
"text_word_split",
"escaped_container",
"panel_out_of_canvas",
"canvas_content_at_edge",
Expand Down
2 changes: 1 addition & 1 deletion scripts/package-size-budgets.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
},
"@hyperframes/cli": {
"packed": 8577627,
"unpacked": 25830000
"unpacked": 26350000
},
"@hyperframes/core": {
"packed": 1948041,
Expand Down
2 changes: 1 addition & 1 deletion skills-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"files": 4
},
"hyperframes": {
"hash": "d0cfc4072c8f2797",
"hash": "a16353de93d4841a",
"files": 87
},
"hyperframes-cli": {
Expand Down
1 change: 1 addition & 0 deletions skills/hyperframes/references/captions.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ tl.set(group, { opacity: 0, visibility: "hidden" }, end);
## Fit and place

- Size each group to fit: `window.__hyperframes.fitTextFontSize(text, { fontFamily, fontWeight, maxWidth })` returns `{ fontSize }`. Defaults: `maxWidth` 1600 landscape, 900 portrait; base 78, minimum 42, step 2. When a word scales up for emphasis, divide `maxWidth` by that scale.
- Korean caption text takes `word-break: keep-all`. Chrome otherwise wraps between any two syllables and cuts a word in half; `check` reports it as `text_word_split`.
- A full-width absolute container, centred with text alignment. Never `left: 50%; transform: translateX(-50%)`, which clips at the frame edges.
- `overflow: visible`, not `hidden`, which cuts off scaled words and glows.
- Landscape: 80–120 px from the bottom. Portrait (1080×1920): the bottom edge of the caption at least 672 px from the bottom (y 1248), the lowest every 9:16 safe area allows. Never over the speaker's face; inside the 80% title-safe box.
Expand Down
Loading