@softure-ai/marketing-kit 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +13 -0
  3. package/dist/compose/timeline.d.ts +6 -0
  4. package/dist/compose/timeline.d.ts.map +1 -1
  5. package/dist/compose/timeline.js +9 -1
  6. package/dist/compose/timeline.js.map +1 -1
  7. package/dist/footage/compose.d.ts.map +1 -1
  8. package/dist/footage/compose.js +3 -3
  9. package/dist/footage/compose.js.map +1 -1
  10. package/dist/footage/draft-overlays.d.ts +21 -1
  11. package/dist/footage/draft-overlays.d.ts.map +1 -1
  12. package/dist/footage/draft-overlays.js +180 -26
  13. package/dist/footage/draft-overlays.js.map +1 -1
  14. package/dist/footage/draft-text-width.d.ts +43 -0
  15. package/dist/footage/draft-text-width.d.ts.map +1 -1
  16. package/dist/footage/draft-text-width.js +62 -1
  17. package/dist/footage/draft-text-width.js.map +1 -1
  18. package/dist/footage/draft.d.ts +29 -2
  19. package/dist/footage/draft.d.ts.map +1 -1
  20. package/dist/footage/draft.js +64 -29
  21. package/dist/footage/draft.js.map +1 -1
  22. package/dist/footage/overlay-html.d.ts.map +1 -1
  23. package/dist/footage/overlay-html.js +6 -5
  24. package/dist/footage/overlay-html.js.map +1 -1
  25. package/dist/footage/overlays.d.ts +74 -2
  26. package/dist/footage/overlays.d.ts.map +1 -1
  27. package/dist/footage/overlays.js +115 -2
  28. package/dist/footage/overlays.js.map +1 -1
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +4 -4
  32. package/dist/index.js.map +1 -1
  33. package/package.json +1 -1
  34. package/src/compose/timeline.ts +12 -1
  35. package/src/footage/compose.ts +3 -3
  36. package/src/footage/draft-overlays.ts +226 -27
  37. package/src/footage/draft-text-width.ts +90 -1
  38. package/src/footage/draft.ts +91 -32
  39. package/src/footage/overlay-html.ts +6 -4
  40. package/src/footage/overlays.ts +135 -2
  41. package/src/index.ts +29 -1
@@ -62,6 +62,17 @@ export interface CaptionLayout extends TextBox {
62
62
  /** The caption text's line height, in font sizes (the pill and the phrase alike). */
63
63
  export const CAPTION_LINE_HEIGHT = 1.18;
64
64
 
65
+ /** The caption text's letter spacing, in em (the pill and the phrase alike); a ribbon's capitals are spaced by `CAPTION_RIBBON_LETTER_SPACING_EM`. */
66
+ export const CAPTION_LETTER_SPACING_EM = -0.01;
67
+
68
+ /** A ribbon caption's letter spacing, in em. */
69
+ export const CAPTION_RIBBON_LETTER_SPACING_EM = 0.01;
70
+
71
+ /** A letter spacing in em as the render's CSS writes it (`-0.015` → `-.015em`). */
72
+ export function toCssEm(em: number): string {
73
+ return `${String(em).replace(/^(-?)0\./, "$1.")}em`;
74
+ }
75
+
65
76
  /** The highlight pill's padding around its text, in px. */
66
77
  export const CAPTION_PILL_PADDING = { y: 16, x: 28 } as const;
67
78
 
@@ -72,7 +83,7 @@ export function getCaptionPositionCss(caption: CaptionLayout): string {
72
83
 
73
84
  /** The highlight pill's text CSS: weight, size, line height and padding (the colours are the caller's). */
74
85
  export function getCaptionPillCss(fontSize: number): string {
75
- return `font-weight:650;font-size:${fontSize}px;line-height:${CAPTION_LINE_HEIGHT};letter-spacing:-.01em;text-align:center;padding:${CAPTION_PILL_PADDING.y}px ${CAPTION_PILL_PADDING.x}px`;
86
+ return `font-weight:650;font-size:${fontSize}px;line-height:${CAPTION_LINE_HEIGHT};letter-spacing:${toCssEm(CAPTION_LETTER_SPACING_EM)};text-align:center;padding:${CAPTION_PILL_PADDING.y}px ${CAPTION_PILL_PADDING.x}px`;
76
87
  }
77
88
 
78
89
  export interface EndCardLayout extends TextBox {
@@ -2,7 +2,7 @@ import type { BrandColors } from "../config/colors.js";
2
2
  import type { SfxEvent } from "../config/schema.js";
3
3
  import type { ComposeFont } from "../compose/compose.js";
4
4
  import { assertLocalReferences, escapeHtml, fontFaces, fontStack } from "../compose/html.js";
5
- import { CAPTION_LINE_HEIGHT, getCaptionPillCss, getCaptionPositionCss, type CaptionLayout } from "../compose/timeline.js";
5
+ import { CAPTION_LETTER_SPACING_EM, CAPTION_LINE_HEIGHT, CAPTION_RIBBON_LETTER_SPACING_EM, getCaptionPillCss, getCaptionPositionCss, toCssEm, type CaptionLayout } from "../compose/timeline.js";
6
6
  import type { TimedWord } from "../voice/voiceover.js";
7
7
  import { CAPTION_HIGHLIGHT_BOX_PADDING_EM, CAPTION_HIGHLIGHT_BOX_RADIUS, CAPTION_HIGHLIGHT_SECONDS, CAPTION_UNDERLINE_EM, getCaptionEntranceTween, getCaptionHighlight } from "./caption-highlight.js";
8
8
  import { CAPTION_SAFE_ZONES, getCaptionChunkLayouts, getCaptionRibbonTilt, getCaptionSpans, getFootageCaptionChunks, isSameCaptionPlace, toCaptionDisplayText, type CaptionSpan } from "./captions.js";
@@ -346,7 +346,7 @@ ${isBox ? `.pill{position:relative;z-index:0}
346
346
  .hl{position:absolute;top:0;bottom:0;left:-${CAPTION_HIGHLIGHT_BOX_PADDING_EM}em;right:-${CAPTION_HIGHLIGHT_BOX_PADDING_EM}em;z-index:-1;border-radius:${CAPTION_HIGHLIGHT_BOX_RADIUS}px;background:${look.box};opacity:0}
347
347
  ` : ""}${isUnderline ? `.pill span{position:relative}
348
348
  .ul{position:absolute;left:0;right:0;top:${CAPTION_UNDERLINE_EM.top}em;height:${CAPTION_UNDERLINE_EM.thickness}em;border-radius:${CAPTION_UNDERLINE_EM.thickness / 2}em;background:${look.color};opacity:0}
349
- ` : ""}${isRibbon ? `${getRibbonCaptionCss(captionBox.fontSize, getCaptionRibbonTilt(film), { background: c.captionBackground, text: c.captionText })}\n` : ""}.phrase{font-weight:650;font-size:${captionBox.fontSize}px;line-height:${CAPTION_LINE_HEIGHT};letter-spacing:-.01em;text-align:center;color:#fff;text-shadow:0 2px 6px rgba(0,0,0,.55),0 0 18px rgba(0,0,0,.35)}
349
+ ` : ""}${isRibbon ? `${getRibbonCaptionCss(captionBox.fontSize, getCaptionRibbonTilt(film), { background: c.captionBackground, text: c.captionText })}\n` : ""}.phrase{font-weight:650;font-size:${captionBox.fontSize}px;line-height:${CAPTION_LINE_HEIGHT};letter-spacing:${toCssEm(CAPTION_LETTER_SPACING_EM)};text-align:center;color:#fff;text-shadow:0 2px 6px rgba(0,0,0,.55),0 0 18px rgba(0,0,0,.35)}
350
350
  .endcard{position:absolute;inset:0;display:flex;flex-direction:column;justify-content:center;align-items:center;padding:0 80px;text-align:center}
351
351
  .brand{display:flex;justify-content:center;align-items:center;gap:18px;font-family:${headingFont};font-size:46px}
352
352
  .logo{height:60px;width:auto}
@@ -410,7 +410,7 @@ export function getRibbonCaptionCss(fontSize: number, tilt: number, colors: { ba
410
410
  const { lineHeight, padding, radius, weight } = CAPTION_RIBBON;
411
411
  return [
412
412
  `.caption.turned{transform:rotate(${String(-tilt)}deg);transform-origin:50% 50%}`,
413
- `.ribbon{font-weight:${String(weight)};font-size:${String(fontSize)}px;line-height:${String(lineHeight)};letter-spacing:.01em;text-align:center;color:${colors.text}}`,
413
+ `.ribbon{font-weight:${String(weight)};font-size:${String(fontSize)}px;line-height:${String(lineHeight)};letter-spacing:${toCssEm(CAPTION_RIBBON_LETTER_SPACING_EM)};text-align:center;color:${colors.text}}`,
414
414
  `.rb{background:${colors.background};padding:${String(padding.y)}em ${String(padding.x)}em;border-radius:${String(radius)}px;-webkit-box-decoration-break:clone;box-decoration-break:clone}`,
415
415
  ].join("\n");
416
416
  }
@@ -1,6 +1,7 @@
1
1
  import { getCornerRadiusPx, type BrandStyle, type CornerRadius } from "./brand-style.js";
2
2
  import { getDraftBoxEvents } from "./draft-boxes.js";
3
3
  import { toAssColor } from "./draft-color.js";
4
+ import { DEFAULT_CONTENT_AREA, getSpacingWidth, toDraftAssSize, toDraftSpacing, wrapDraftLine, type DraftFont } from "./draft-text-width.js";
4
5
  import { HAND_FONT, getHandFontAssSize } from "./hand-font.js";
5
6
  import { getCounterSeconds, getOverlayColors, getPlaceCardTimes, getTypingTimes, type OverlayColors } from "./overlay-html.js";
6
7
  import {
@@ -26,6 +27,7 @@ import {
26
27
  OVERLAY_FONT_ROLES,
27
28
  OVERLAY_LINE_HEIGHT,
28
29
  OVERLAY_LIST_LINE_HEIGHT,
30
+ OVERLAY_LETTER_SPACING_EM,
29
31
  OVERLAY_TITLE_LINE_HEIGHT,
30
32
  SEARCH_BAR_ICON_EM,
31
33
  SEARCH_BAR_PADDING_EM,
@@ -35,7 +37,14 @@ import {
35
37
  getChipCoveredTimes,
36
38
  getChipParts,
37
39
  getChipTickPoints,
40
+ COUNTER_UNIT_GAP_EM,
41
+ getCounterCard,
38
42
  getDrawnOverlayCard,
43
+ getKeywordMarkBlock,
44
+ getSideTextLayout,
45
+ KEYWORD_EDGE_EM,
46
+ MARK_PADDING_EM,
47
+ MARK_RADIUS_EM,
39
48
  getListCardsByItem,
40
49
  getListItemTimes,
41
50
  getListStops,
@@ -53,7 +62,9 @@ import {
53
62
  type OverlayBox,
54
63
  type OverlayFontRole,
55
64
  type OverlayPoint,
65
+ type OverlayTextMeasure,
56
66
  type ResolvedOverlay,
67
+ type SideTextLayout,
57
68
  } from "./overlays.js";
58
69
 
59
70
  /**
@@ -166,14 +177,33 @@ export function getGlassDrawing(at: OverlayPoint, size: number): string {
166
177
  return `${ring} ${handle}`;
167
178
  }
168
179
 
180
+ /** The font an overlay's text is drawn in: the body font (the styles' own) or an overlay role's. */
181
+ export type DraftFontRole = "body" | OverlayFontRole;
182
+
183
+ /** A character that stands for a line break in an overlay's text until it is written as ASS (`\\N`): one character, as the space it replaces. */
184
+ const LINE_BREAK = "\uE000";
185
+
169
186
  interface DraftContext {
170
187
  brand: OverlayColors;
171
188
  scale: number;
172
189
  locale: string;
173
190
  /** The font family per role, when it is not the styles' own. */
174
191
  fonts: Partial<Record<OverlayFontRole, string>>;
192
+ /** The ASS size of a CSS px size in the font of `role` (`body`: the styles' own font, which a role without its own family draws in). */
193
+ toAssSize: (role: DraftFontRole, cssPx: number) => number;
194
+ /** A line's width in CSS px in the font of `role`, its letters spaced `spacingEm` (the render's `letter-spacing`). */
195
+ measure: (role: DraftFontRole, text: string, cssPx: number, spacingEm: number) => number;
196
+ /** The `\\fsp` tag that spaces letters `spacingEm` at a CSS size as the render does; empty without the draft's fonts (as before). */
197
+ spacing: (spacingEm: number, cssPx: number) => string;
175
198
  /** The brand's style: the cards' radius, shadow and border; absent: each kind's own corner, no shadow, no border. */
176
199
  style?: BrandStyle;
200
+ /**
201
+ * With the draft's fonts: the render's measure, so side texts, counters and highlight marks are laid out as the
202
+ * render lays them out (`getSideTextLayout`, `getCounterCard`); absent: the estimated cards of before.
203
+ */
204
+ layout?: OverlayTextMeasure;
205
+ /** The content area (ascent, descent in ems) of the font of `role`, as a browser sizes an inline box. */
206
+ contentArea: (role: DraftFontRole) => { ascentEm: number; descentEm: number };
177
207
  }
178
208
 
179
209
  /**
@@ -415,10 +445,6 @@ export function getDropText(text: string, times: readonly number[], eventStart:
415
445
  .join("");
416
446
  }
417
447
 
418
- /** A highlight mark's padding round its text and its corner, in font sizes (as the render's `.ov-mark`). */
419
- const MARK_PADDING_EM = { x: 0.22, y: 0.04 } as const;
420
- const MARK_RADIUS_EM = 0.14;
421
-
422
448
  /**
423
449
  * A highlight backdrop's marks under one line of text (`style.backdrop` highlight): a tight rounded box in the card
424
450
  * colour, its width the text shown so far (each typed letter widens it, as the render's box grows), anchored where
@@ -436,14 +462,22 @@ function getBackdropMarkEvents(input: {
436
462
  typing: number | null;
437
463
  /** When the line starts typing, if not at the span's start (a second line of a title). */
438
464
  typeFrom?: number;
465
+ /**
466
+ * The render's measure of a line in the text's font and its content area: the mark is the text's width and its
467
+ * content area tall, centred in a line `lineHeight` tall from `top` (an inline box's background); absent: the
468
+ * estimated width and the whole line's height.
469
+ */
470
+ measured?: { measure: (text: string) => number; contentArea: { ascentEm: number; descentEm: number }; lineHeight: number };
439
471
  }): string[] {
440
- const { fontSize, span } = input;
472
+ const { fontSize, span, measured } = input;
441
473
  const pad = { x: fontSize * MARK_PADDING_EM.x, y: fontSize * MARK_PADDING_EM.y };
442
- const height = fontSize * OVERLAY_LINE_HEIGHT + 2 * pad.y;
474
+ const content = measured === undefined ? fontSize * OVERLAY_LINE_HEIGHT : fontSize * (measured.contentArea.ascentEm + measured.contentArea.descentEm);
475
+ const height = content + 2 * pad.y;
476
+ const top = measured === undefined ? input.top - pad.y : input.top + (fontSize * measured.lineHeight - content) / 2 - pad.y;
443
477
  const boxFor = (shown: string): OverlayBox => {
444
- const width = estimateTextWidth(shown, fontSize) + 2 * pad.x;
478
+ const width = (measured === undefined ? estimateTextWidth(shown, fontSize) : measured.measure(shown)) + 2 * pad.x;
445
479
  const left = input.align === "left" ? input.x - pad.x : input.align === "right" ? input.x + pad.x - width : input.x - width / 2;
446
- return { left, top: input.top - pad.y, width, height };
480
+ return { left, top, width, height };
447
481
  };
448
482
  const clean = toAssText(input.text);
449
483
  const steps =
@@ -485,32 +519,137 @@ function getUnderlineEvent(overlay: Extract<ResolvedOverlay, { kind: "keyword" }
485
519
  */
486
520
  function getSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" | "lower_third" | "list" }>, context: DraftContext): string[] {
487
521
  if (overlay.kind === "list") return getListEvents(overlay, context);
522
+ if (context.layout !== undefined) return getLaidOutSideTextEvents(overlay, context, context.layout);
488
523
  const colors = getOverlayColors(overlay, context.brand);
489
524
  const { fontSize, side } = overlay;
490
525
  // A side text always has a card: only a punch_in has none.
491
526
  const card = getDrawnOverlayCard(overlay) as OverlayBox;
492
527
  const { x: padX, y: padY } = getOverlayPadding(overlay);
493
528
  const isCentred = overlay.kind === "keyword" && overlay.isCentred === true;
494
- const isRight = !isCentred && side === "right";
495
- const x = isCentred ? card.left + card.width / 2 : isRight ? card.left + card.width - padX : card.left + padX;
529
+ const role = OVERLAY_FONT_ROLES[overlay.kind];
530
+ // The render's card wraps its text inside the box (`max-width: 100%`): the same breaks, by the font's own widths.
531
+ const wrapped = getWrappedText(overlay.text, overlay.box.width - 2 * padX, fontSize, (line, size) => context.measure(role, line, size, OVERLAY_LETTER_SPACING_EM.card));
532
+ // A wrapped card fills its box and its lines start at its left on either side, as the render's do (`text-align` start).
533
+ const isWrapped = wrapped.includes(LINE_BREAK);
534
+ const isRight = !isCentred && side === "right" && !isWrapped;
535
+ const x = isCentred ? card.left + card.width / 2 : isRight ? card.left + card.width - padX : (isWrapped ? overlay.box.left : card.left) + padX;
496
536
  const isFoot = overlay.kind === "lower_third";
497
537
  const y = isFoot ? card.top + card.height - padY : card.top + padY;
498
538
  // \an: 7 top left, 8 top centre, 9 top right, 1 bottom left, 3 bottom right.
499
539
  const align = isFoot ? (isRight ? 3 : 1) : isCentred ? 8 : isRight ? 9 : 7;
500
540
  const motion = getDraftMotion(overlay, overlay.entrance === null || overlay.entrance === "type" ? "fade" : overlay.entrance, card, context);
501
541
  const span = { start: overlay.start, end: overlay.end };
502
- const tags = `\\an${align}\\fs${fontSize}${getTextTags(overlay, colors, context, OVERLAY_FONT_ROLES[overlay.kind])}`;
503
- const text = (pos: OverlayPoint, steps: TextStep[], own = motion) => getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags, steps, motion: own });
542
+ const tags = `\\an${align}\\fs${context.toAssSize(role, fontSize)}${context.spacing(OVERLAY_LETTER_SPACING_EM.card, fontSize)}${getTextTags(overlay, colors, context, role)}`;
543
+ const text = (pos: OverlayPoint, steps: TextStep[], own = motion) =>
544
+ getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags, steps: steps.map((step) => ({ ...step, text: step.text.replaceAll(LINE_BREAK, "\\N") })), motion: own });
504
545
  const isMarked = overlay.kind === "keyword" && overlay.backdrop === "highlight";
505
546
  const shape = isMarked
506
547
  ? getBackdropMarkEvents({ text: overlay.text, x, align: isCentred ? "center" : isRight ? "right" : "left", top: y, fontSize, colour: colors.background, motion, span, typing: overlay.typing })
507
548
  : getCardShapeEvents(overlay, card, fontSize, colors, motion, context);
508
- if (overlay.entrance === "drop") return [...shape, ...text({ x, y }, [{ from: span.start, to: span.end, text: getDropText(overlay.text, getDropLetterTimes(span.start, overlay.text), span.start) }], getPlainMotion(motion))];
549
+ if (overlay.entrance === "drop") return [...shape, ...text({ x, y }, [{ from: span.start, to: span.end, text: getDropText(wrapped, getDropLetterTimes(span.start, overlay.text), span.start) }], getPlainMotion(motion))];
509
550
  // A keyword or a lower third types in only when its entrance says so.
510
- const steps = overlay.entrance === null ? [{ from: span.start, to: span.end, text: toAssText(overlay.text) }] : getTypedSteps(overlay.text, span, overlay.typing, isCentred);
551
+ const steps = overlay.entrance === null ? [{ from: span.start, to: span.end, text: toAssText(wrapped) }] : getTypedSteps(wrapped, span, overlay.typing, isCentred);
511
552
  return [...shape, ...text({ x, y }, steps), ...(overlay.kind === "keyword" ? getUnderlineEvent(overlay, card, colors.accent, motion) : [])];
512
553
  }
513
554
 
555
+ /**
556
+ * A highlighted keyword's mark as the render draws it (`getKeywordMarkBlock`): one rounded block round its lines;
557
+ * while it types, the block of the letters typed so far, on the lines they take in the whole text.
558
+ */
559
+ function getBlockMarkEvents(input: {
560
+ overlay: Extract<ResolvedOverlay, { kind: "keyword" }>;
561
+ layout: SideTextLayout;
562
+ measure: OverlayTextMeasure;
563
+ colour: string;
564
+ motion: DraftMotion;
565
+ }): string[] {
566
+ const { overlay, layout } = input;
567
+ const { fontSize } = overlay;
568
+ const blockFor = (lines: readonly string[]): OverlayBox => getKeywordMarkBlock(overlay, layout, lines, input.measure);
569
+ const span = { start: overlay.start, end: overlay.end };
570
+ const text = layout.lines.join(" ");
571
+ const steps =
572
+ overlay.typing === null || overlay.entrance === null || overlay.entrance === "drop"
573
+ ? [{ from: span.start, to: span.end, lines: layout.lines }]
574
+ : getTypingTimes(span.start, text, overlay.typing).map((at, index, times) => {
575
+ // The typed letters stay on the lines they take in the whole text.
576
+ let left = index + 1;
577
+ const lines = layout.lines.map((line) => {
578
+ const shown = [...line].slice(0, Math.max(0, left)).join("").trimEnd();
579
+ left -= [...line].length + 1;
580
+ return shown;
581
+ });
582
+ return { from: Math.min(at, span.end), to: Math.min(times[index + 1] ?? span.end, span.end), lines: lines.filter((line) => line.length > 0) };
583
+ });
584
+ const visible = steps.filter((step) => step.to > step.from && step.lines.length > 0);
585
+ return visible.map((step, index) =>
586
+ getShapeEvent({ start: step.from, end: step.to }, getRoundedRectDrawing(blockFor(step.lines), fontSize * MARK_RADIUS_EM), input.colour, input.motion, 3, {
587
+ start: step.from,
588
+ end: step.to,
589
+ isFirst: index === 0,
590
+ isLast: index === visible.length - 1,
591
+ }),
592
+ );
593
+ }
594
+
595
+ /**
596
+ * A keyword or a lower third laid out as the render lays it out (`getSideTextLayout`): its card as wide and tall as
597
+ * its lines (a keyword with its accent edge, a lower third with its dot), each line its own event one CSS line apart,
598
+ * so libass's own line pitch does not stretch them; a highlighted keyword has one mark per line.
599
+ */
600
+ function getLaidOutSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" | "lower_third" }>, context: DraftContext, measure: OverlayTextMeasure): string[] {
601
+ const colors = getOverlayColors(overlay, context.brand);
602
+ const { fontSize } = overlay;
603
+ const layout = getSideTextLayout(overlay, measure);
604
+ const { card } = layout;
605
+ const role = OVERLAY_FONT_ROLES[overlay.kind];
606
+ const isCentred = overlay.kind === "keyword" && overlay.isCentred === true;
607
+ const isMarked = overlay.kind === "keyword" && overlay.backdrop === "highlight";
608
+ const motion = getDraftMotion(overlay, overlay.entrance === null || overlay.entrance === "type" ? "fade" : overlay.entrance, card, context);
609
+ const span = { start: overlay.start, end: overlay.end };
610
+ const lineHeight = fontSize * OVERLAY_LINE_HEIGHT;
611
+ const tags = `\\an${isCentred ? 8 : 7}\\fs${context.toAssSize(role, fontSize)}${context.spacing(OVERLAY_LETTER_SPACING_EM.card, fontSize)}${getTextTags(overlay, colors, context, role)}`;
612
+ const edge = overlay.kind === "keyword" && !isMarked ? Math.round(fontSize * KEYWORD_EDGE_EM) : 0;
613
+ const shapes: string[] = [];
614
+ if (isMarked) {
615
+ // The render's highlighted keyword is one block (a flex item): one mark round all its lines, growing as it types.
616
+ shapes.push(...getBlockMarkEvents({ overlay, layout, measure, colour: colors.background, motion }));
617
+ } else {
618
+ const fill = getCardShapeEvents(overlay, { ...card, height: card.height - edge }, fontSize, colors, motion, context);
619
+ // The keyword's accent edge: the whole card in the accent under its fill, which leaves the edge's height at its foot.
620
+ const radius = getDraftCardRadius(overlay, card, context, getOwnCardRadius(overlay, card, fontSize));
621
+ const edgeEvents = edge === 0 || (overlay.kind === "keyword" && overlay.underline === true) ? [] : [getShapeEvent(overlay, getRoundedRectDrawing(card, radius), colors.accent, motion)];
622
+ const under = context.style?.shadow === "soft" ? 1 : 0;
623
+ shapes.push(...fill.slice(0, under), ...edgeEvents, ...fill.slice(under));
624
+ }
625
+ if (layout.dot !== null) {
626
+ // The dot settles in with the card (the render scales it in a little later; the draft shows it with its card).
627
+ shapes.push(getShapeEvent(overlay, getCircleDrawing(layout.dot.centre, layout.dot.radius), colors.accent, motion, 4));
628
+ }
629
+ const text = layout.lines.join(" ");
630
+ const letters = overlay.entrance === "drop" ? getDropLetterTimes(span.start, text) : [];
631
+ const isTyped = overlay.entrance !== null && overlay.entrance !== "drop" && overlay.typing !== null;
632
+ let typedBefore = 0;
633
+ const lines = layout.lines.flatMap((line, index) => {
634
+ const pos = { x: layout.textX, y: layout.textTop + index * lineHeight };
635
+ const lineStart = overlay.typing === null ? span.start : span.start + typedBefore / overlay.typing;
636
+ const count = [...line].length;
637
+ const steps =
638
+ overlay.entrance === "drop"
639
+ ? [{ from: span.start, to: span.end, text: getDropText(line, letters.slice(typedBefore, typedBefore + count), span.start) }]
640
+ : isTyped
641
+ ? getTypedSteps(line, { start: lineStart, end: span.end }, overlay.typing, isCentred)
642
+ : [{ from: span.start, to: span.end, text: toAssText(line) }];
643
+ typedBefore += count + 1;
644
+ // A left line holds its place transparent from the start, so its first event carries the entrance.
645
+ const held = isTyped && !isCentred ? steps.map((step, at) => (at === 0 ? { ...step, from: span.start } : step)) : steps;
646
+ const own = overlay.entrance === "drop" || (isTyped && isCentred) ? getPlainMotion(motion) : motion;
647
+ return getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags, steps: held, motion: own });
648
+ });
649
+ const underline = overlay.kind === "keyword" ? getUnderlineEvent(overlay, { ...card, height: card.height - edge }, colors.accent, motion) : [];
650
+ return [...shapes, ...lines, ...underline];
651
+ }
652
+
514
653
  /** A list's card grows to its next point's size over these seconds, in this many steps along the render's ease. */
515
654
  const LIST_GROW_SECONDS = 0.35;
516
655
  const LIST_GROW_STEPS = 3;
@@ -566,7 +705,7 @@ function getListEvents(overlay: Extract<ResolvedOverlay, { kind: "list" }>, cont
566
705
  const textTags = getTextTags(overlay, colors, context, OVERLAY_FONT_ROLES.list);
567
706
  const lines = getSideTextLines(overlay);
568
707
  const write = (pos: OverlayPoint, align: number, steps: TextStep[], motion: DraftMotion, clip = "") =>
569
- getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags: `\\an${align}\\fs${fontSize}${textTags}${clip}`, steps, motion });
708
+ getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags: `\\an${align}\\fs${context.toAssSize(OVERLAY_FONT_ROLES.list, fontSize)}${context.spacing(OVERLAY_LETTER_SPACING_EM.card, fontSize)}${textTags}${clip}`, steps, motion });
570
709
  if (overlay.chips !== undefined) {
571
710
  const covered = getChipCoveredTimes(overlay);
572
711
  return overlay.chips.flatMap((_chip, index) => {
@@ -587,7 +726,7 @@ function getListEvents(overlay: Extract<ResolvedOverlay, { kind: "list" }>, cont
587
726
  return [
588
727
  ...getCardShapeEvents(overlay, place.box, fontSize, colors, motion, context, span),
589
728
  ...write({ x: parts.textX, y: place.box.top + pad.y }, 8, steps, motion),
590
- ...getChipBadgeEvents({ index, span, until, parts, colors, motion }),
729
+ ...getChipBadgeEvents({ index, span, until, parts, colors, motion, toAssSize: (cssPx) => context.toAssSize("body", cssPx) }),
591
730
  ];
592
731
  });
593
732
  });
@@ -633,6 +772,8 @@ function getChipBadgeEvents(input: {
633
772
  parts: ReturnType<typeof getChipParts>;
634
773
  colors: OverlayColors;
635
774
  motion: DraftMotion;
775
+ /** The ASS size of the number's CSS size (it is drawn in the styles' own font). */
776
+ toAssSize: (cssPx: number) => number;
636
777
  }): string[] {
637
778
  const { span, until, parts, colors, motion } = input;
638
779
  const { centre, radius } = parts.badge;
@@ -645,7 +786,7 @@ function getChipBadgeEvents(input: {
645
786
  layer: 6,
646
787
  style: "OverlayPlain",
647
788
  pos: centre,
648
- tags: `\\an5\\fs${numberSize}\\b1\\1c${toTagColor(colors.background)}`,
789
+ tags: `\\an5\\fs${input.toAssSize(numberSize)}\\b1\\1c${toTagColor(colors.background)}`,
649
790
  steps: [{ from: span.start, to: numberEnd, text: String(input.index + 1) }],
650
791
  motion: numberEnd === span.end ? motion : { ...motion, exit: { ...motion.exit, kind: "none" } },
651
792
  })
@@ -740,12 +881,17 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
740
881
  const motion = getDraftMotion(overlay, name, box, context);
741
882
  const span = { start: overlay.start, end: overlay.end };
742
883
  const isMarked = overlay.kind === "hook_title" && overlay.backdrop === "highlight";
743
- const events = isMarked ? [] : getCardShapeEvents(overlay, box, fontSize, colors, motion, context);
884
+ // A laid-out counter draws its card with each number it shows (below), as the render's card follows its text.
885
+ const isCounterLaidOut = overlay.kind === "counter" && context.layout !== undefined;
886
+ const events = isMarked || isCounterLaidOut ? [] : getCardShapeEvents(overlay, box, fontSize, colors, motion, context);
744
887
  const { x: padX, y: padY } = getOverlayPadding(overlay);
745
888
  const centerX = box.left + box.width / 2;
746
889
  const tagsFor = (role: OverlayFontRole) => getTextTags(overlay, colors, context, role);
890
+ // The render spaces a title's heading lines tighter than the rest of a card's text, and a search query not at all.
891
+ const spacingFor = (role: OverlayFontRole): number =>
892
+ overlay.kind === "search_bar" ? 0 : role !== "heading" ? OVERLAY_LETTER_SPACING_EM.card : overlay.kind === "hook_title" ? OVERLAY_LETTER_SPACING_EM.hookTitle : overlay.kind === "place_card" ? OVERLAY_LETTER_SPACING_EM.placeTitle : OVERLAY_LETTER_SPACING_EM.card;
747
893
  const text = (pos: OverlayPoint, align: number, size: number, role: OverlayFontRole, steps: TextStep[], own: DraftMotion = motion) =>
748
- getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags: `\\an${align}\\fs${r0(size)}${tagsFor(role)}`, steps, motion: own });
894
+ getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags: `\\an${align}\\fs${context.toAssSize(role, r0(size))}${context.spacing(spacingFor(role), r0(size))}${tagsFor(role)}`, steps, motion: own });
749
895
  const plain = { ...motion, name: "none" as const, entrance: { kind: "none" as const } };
750
896
  if (overlay.kind === "hook_title" || overlay.kind === "place_card") {
751
897
  // The text block sits in the card's middle; centred lines on its axis, left ones from its left edge (RV-131).
@@ -778,14 +924,21 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
778
924
  const lineStart = overlay.typing === null ? span.start : span.start + typedBefore / overlay.typing;
779
925
  if (isMarked) {
780
926
  const align = isLeft ? "left" : "center";
781
- events.push(...getBackdropMarkEvents({ text: line, x: lineX, align, top: y, fontSize, colour: colors.background, motion, span, typing: overlay.typing, typeFrom: lineStart }));
927
+ const { layout } = context;
928
+ const measured =
929
+ layout === undefined
930
+ ? {}
931
+ : { measured: { measure: (shown: string) => layout("heading", shown, fontSize, spacingFor("heading")), contentArea: context.contentArea("heading"), lineHeight } };
932
+ events.push(...getBackdropMarkEvents({ text: line, x: lineX, align, top: y, fontSize, colour: colors.background, motion, span, typing: overlay.typing, typeFrom: lineStart, ...measured }));
782
933
  }
783
934
  const steps =
784
935
  overlay.entrance === "drop"
785
936
  ? [{ from: span.start, to: span.end, text: getDropText(line, letters.slice(typedBefore, typedBefore + [...line].length), span.start) }]
786
937
  : getTypedSteps(line, { start: lineStart, end: span.end }, overlay.typing, !isLeft);
787
938
  const isQuiet = overlay.entrance === "drop" || (!isLeft && overlay.typing !== null);
788
- events.push(...text({ x: lineX, y }, lineAlign, fontSize, "heading", isLeft && overlay.entrance !== "drop" ? steps.map((step, index) => (index === 0 ? { ...step, from: span.start } : step)) : steps, isQuiet ? plain : motion));
939
+ // A left mark's padding pushes its text in, as an inline box's padding does in the render.
940
+ const textX = isMarked && isLeft && context.layout !== undefined ? lineX + fontSize * MARK_PADDING_EM.x : lineX;
941
+ events.push(...text({ x: textX, y }, lineAlign, fontSize, "heading", isLeft && overlay.entrance !== "drop" ? steps.map((step, index) => (index === 0 ? { ...step, from: span.start } : step)) : steps, isQuiet ? plain : motion));
789
942
  typedBefore += [...line].length;
790
943
  y += fontSize * lineHeight;
791
944
  });
@@ -820,7 +973,10 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
820
973
  return events;
821
974
  }
822
975
  if (overlay.kind === "counter") {
823
- const unit = overlay.unit === null ? "" : `{\\fs${overlay.unitFontSize}} ${toAssText(overlay.unit)}`;
976
+ // Laid out, the unit stands the render's gap after the number: a hard space widened to it.
977
+ const gap = context.layout === undefined ? null : toDraftSpacing(overlay.fontSize * COUNTER_UNIT_GAP_EM - context.layout("heading", " ", overlay.unitFontSize, 0), 1);
978
+ const space = gap === null ? " " : `{\\fsp${String(gap)}}\\h{\\fsp${String(toDraftSpacing(OVERLAY_LETTER_SPACING_EM.card, fontSize))}}`;
979
+ const unit = overlay.unit === null ? "" : `{\\fs${context.toAssSize("heading", overlay.unitFontSize)}}${space}${toAssText(overlay.unit)}`;
824
980
  const count = getCounterSeconds(overlay);
825
981
  const steps: TextStep[] = [];
826
982
  const ticks = Math.max(1, Math.round(count.duration / COUNT_STEP));
@@ -833,7 +989,27 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
833
989
  const value = overlay.from + (overlay.value - overlay.from) * eased;
834
990
  steps.push({ from: count.start + (tick - 1) * COUNT_STEP, to: tick === ticks ? span.end : count.start + tick * COUNT_STEP, text: show(value) });
835
991
  }
836
- return [...events, ...text({ x: centerX, y: box.top + box.height / 2 }, 5, fontSize, "heading", steps.filter((step) => step.to > step.from))];
992
+ const shown = steps.filter((step) => step.to > step.from);
993
+ const { layout } = context;
994
+ if (layout === undefined) return [...events, ...text({ x: centerX, y: box.top + box.height / 2 }, 5, fontSize, "heading", shown)];
995
+ // The render's card follows its number: one card per width the count shows, the entrance on the first, the exit on the last.
996
+ const cardFor = (value: string): OverlayBox => getCounterCard(overlay, value, layout);
997
+ // The number alone: the unit's override tags start at the first brace.
998
+ const values = shown.map((step) => {
999
+ const brace = step.text.indexOf("{");
1000
+ return brace === -1 ? step.text : step.text.slice(0, brace);
1001
+ });
1002
+ const runs: { card: OverlayBox; from: number; to: number }[] = [];
1003
+ shown.forEach((step, index) => {
1004
+ const card = cardFor(values[index] as string);
1005
+ const last = runs[runs.length - 1];
1006
+ if (last !== undefined && last.card.width === card.width) last.to = step.to;
1007
+ else runs.push({ card, from: step.from, to: step.to });
1008
+ });
1009
+ const final = runs[runs.length - 1]?.card ?? cardFor(formatOverlayNumber(overlay.value, overlay.decimals, context.locale));
1010
+ const counted = { ...motion, card: final };
1011
+ const cards = runs.flatMap((run, index) => getCardShapeEvents(overlay, run.card, fontSize, colors, counted, context, { start: run.from, end: run.to, isFirst: index === 0, isLast: index === runs.length - 1 }));
1012
+ return [...cards, ...text({ x: centerX, y: final.top + final.height / 2 }, 5, fontSize, "heading", shown, counted)];
837
1013
  }
838
1014
  const isRight = overlay.side === "right";
839
1015
  const x = isRight ? box.left + box.width - padX : box.left + padX;
@@ -927,8 +1103,8 @@ function getNoteEvents(overlay: Extract<ResolvedOverlay, { kind: "note" }>, cont
927
1103
  const font = isStrip ? `${context.fonts.heading === undefined ? "" : `\\fn${context.fonts.heading}`}\\b1` : `\\fn${HAND_FONT.family}\\b0`;
928
1104
  const textMotion = getPlainMotion(motion);
929
1105
  // libass sizes the hand font by its ascent and descent: its \\fs is scaled so the letters match the render's.
930
- const assSize = isStrip ? overlay.fontSize : getHandFontAssSize(overlay.fontSize);
931
- const tags = `\\an7\\fs${assSize}${font}\\1c${toTagColor(colors.ink)}${turn}`;
1106
+ const assSize = isStrip ? context.toAssSize("heading", overlay.fontSize) : getHandFontAssSize(overlay.fontSize);
1107
+ const tags = `\\an7\\fs${assSize}${isStrip ? context.spacing(OVERLAY_LETTER_SPACING_EM.strip, overlay.fontSize) : ""}${font}\\1c${toTagColor(colors.ink)}${turn}`;
932
1108
  getNoteWordsByLine(overlay).forEach((words, index) => {
933
1109
  const pos = { x: textBox.left, y: textBox.top + index * lineHeight };
934
1110
  const line = overlay.lines[index] as string;
@@ -972,6 +1148,17 @@ function getEndWordEvents(overlay: Extract<ResolvedOverlay, { kind: "end_word" }
972
1148
  return getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags, steps: [{ from: span.start, to: span.end, text: toAssText(overlay.text) }], motion });
973
1149
  }
974
1150
 
1151
+ /**
1152
+ * `text` with the spaces it breaks at turned into `LINE_BREAK`, greedily as a browser breaks a line that does not fit
1153
+ * `width` (a word wider than a line stands alone); the text as it is when it fits on one line.
1154
+ */
1155
+ function getWrappedText(text: string, width: number, fontSize: number, measure: (line: string, size: number) => number): string {
1156
+ const words = text.replace(/\s+/g, " ").trim().split(" ");
1157
+ return wrapDraftLine(words, width, fontSize, measure)
1158
+ .map((line) => line.join(" "))
1159
+ .join(LINE_BREAK);
1160
+ }
1161
+
975
1162
  /**
976
1163
  * The overlays as ASS events, layers 3 and 4. `fonts` names the heading and interface families where they are not the
977
1164
  * styles' own (the captions' font); `locale` groups a counter's number as the render does.
@@ -980,9 +1167,21 @@ export function buildDraftOverlayEvents(
980
1167
  overlays: readonly ResolvedOverlay[],
981
1168
  colors: OverlayColors,
982
1169
  frame: { width: number; height: number },
983
- options: { fonts?: Partial<Record<OverlayFontRole, string>>; locale?: string; style?: BrandStyle } = {},
1170
+ options: { fonts?: Partial<Record<OverlayFontRole, string>>; locale?: string; style?: BrandStyle; drawnFonts?: Record<DraftFontRole, DraftFont> } = {},
984
1171
  ): string[] {
985
- const context: DraftContext = { brand: colors, scale: frame.width / 1080, locale: options.locale ?? "en-US", fonts: options.fonts ?? {}, ...(options.style === undefined ? {} : { style: options.style }) };
1172
+ const drawn = options.drawnFonts;
1173
+ const context: DraftContext = {
1174
+ brand: colors,
1175
+ scale: frame.width / 1080,
1176
+ locale: options.locale ?? "en-US",
1177
+ fonts: options.fonts ?? {},
1178
+ toAssSize: (role, cssPx) => (drawn === undefined ? cssPx : toDraftAssSize(cssPx, drawn[role].assScale)),
1179
+ measure: (role, text, cssPx, spacingEm) => (drawn === undefined ? estimateTextWidth(text, cssPx) : drawn[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx)),
1180
+ spacing: (spacingEm, cssPx) => (drawn === undefined || spacingEm === 0 ? "" : `\\fsp${String(toDraftSpacing(spacingEm, cssPx))}`),
1181
+ contentArea: (role) => drawn?.[role].contentArea ?? DEFAULT_CONTENT_AREA,
1182
+ ...(options.style === undefined ? {} : { style: options.style }),
1183
+ ...(drawn === undefined ? {} : { layout: (role: OverlayFontRole, text: string, cssPx: number, spacingEm: number) => drawn[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx) }),
1184
+ };
986
1185
  return overlays.flatMap((overlay) => {
987
1186
  if (overlay.kind === "punch_in") return [];
988
1187
  if (overlay.kind === "arrow" || overlay.kind === "highlight") return getMarkEvents(overlay, context);
@@ -13,7 +13,21 @@ export type DraftTextMeasure = (text: string, fontSize: number) => number;
13
13
  interface Metrics {
14
14
  /** The font's units per libass font size: `usWinAscent + usWinDescent`. */
15
15
  unitsPerSize: number;
16
+ /** The font's units per em (`head`), what a browser sizes it by; 0 when the font has no `head`. */
17
+ unitsPerEm: number;
16
18
  advances: (glyph: number) => number;
19
+ /** The ascent and descent of a browser's inline box, in font units: `hhea`'s, or OS/2's typo metrics when the font says to use them. */
20
+ ascent: number;
21
+ descent: number;
22
+ }
23
+
24
+ /** OS/2 `fsSelection` bit 7: a browser takes the typo ascender and descender for the line's content area. */
25
+ const USE_TYPO_METRICS = 1 << 7;
26
+
27
+ /** The content area's ascent and descent in font units, as a browser reads them (`hhea`, or typo metrics on request). */
28
+ function readContentArea(hhea: Buffer, os2: Buffer | undefined): { ascent: number; descent: number } {
29
+ if (os2 !== undefined && os2.length >= 72 && (readUint16(os2, 62) & USE_TYPO_METRICS) !== 0) return { ascent: readInt16(os2, 68), descent: -readInt16(os2, 70) };
30
+ return { ascent: readInt16(hhea, 4), descent: -readInt16(hhea, 6) };
17
31
  }
18
32
 
19
33
  function readMetrics(font: Buffer): Metrics | null {
@@ -27,8 +41,10 @@ function readMetrics(font: Buffer): Metrics | null {
27
41
  const unitsPerSize = winSum > 0 ? winSum : readInt16(hhea, 4) - readInt16(hhea, 6);
28
42
  const count = readUint16(hhea, 34);
29
43
  if (unitsPerSize <= 0 || count === 0 || hmtx.length < count * 4) return null;
44
+ const head = tables.value.get("head");
45
+ const unitsPerEm = head === undefined ? 0 : readUint16(head, 18);
30
46
  // Glyphs past `numberOfHMetrics` share the last advance (OpenType `hmtx`).
31
- return { unitsPerSize, advances: (glyph) => readUint16(hmtx, Math.min(glyph, count - 1) * 4) };
47
+ return { unitsPerSize, unitsPerEm, advances: (glyph) => readUint16(hmtx, Math.min(glyph, count - 1) * 4), ...readContentArea(hhea, os2) };
32
48
  }
33
49
 
34
50
  /**
@@ -52,6 +68,79 @@ export function createDraftTextMeasure(font: Buffer): DraftTextMeasure | null {
52
68
  }
53
69
  }
54
70
 
71
+ /**
72
+ * A font of a footage draft as the render sizes it. Every size in the draft is a CSS px size, as in the render; libass
73
+ * sizes a font by `usWinAscent + usWinDescent`, so an ASS size is written through `toAssSize`, and the text is as large
74
+ * as the browser draws it (an em of `cssPx`). `measure` gives a line's width at a CSS size, as the browser lays it.
75
+ */
76
+ export interface DraftFont {
77
+ /** The family libass knows the file by (its `name` table). */
78
+ family: string;
79
+ file: string;
80
+ /** The libass size that draws one CSS px: `(usWinAscent + usWinDescent) / unitsPerEm`. */
81
+ assScale: number;
82
+ /** A line's width in CSS px at a CSS font size (advances per em; kerning not read). */
83
+ measure: DraftTextMeasure;
84
+ /**
85
+ * The ascent and descent of the render's inline box (a highlight mark's background), in ems; absent for a font made
86
+ * elsewhere, which then takes `DEFAULT_CONTENT_AREA`.
87
+ */
88
+ contentArea?: { ascentEm: number; descentEm: number };
89
+ }
90
+
91
+ /** The content area a font without its own is given, in ems: a common sans serif's. */
92
+ export const DEFAULT_CONTENT_AREA = { ascentEm: 0.93, descentEm: 0.24 } as const;
93
+
94
+ /** The ASS size (`Fontsize`, `\fs`) that draws a font of `assScale` as large as the render's `cssPx`, to 0.01. */
95
+ export function toDraftAssSize(cssPx: number, assScale: number): number {
96
+ return Math.round(cssPx * assScale * 100) / 100;
97
+ }
98
+
99
+ /** The ASS letter spacing (`\\fsp`, `Spacing`, in the frame's px) of the render's `letter-spacing` of `spacingEm` at `cssPx`, to 0.01. */
100
+ export function toDraftSpacing(spacingEm: number, cssPx: number): number {
101
+ return Math.round(spacingEm * cssPx * 100) / 100;
102
+ }
103
+
104
+ /** What a letter spacing of `spacingEm` adds to a line at `cssPx`: once after every character, as a browser spaces them. */
105
+ export function getSpacingWidth(text: string, spacingEm: number, cssPx: number): number {
106
+ // `+ 0` turns an empty line's -0 into 0.
107
+ return [...text].length * spacingEm * cssPx + 0;
108
+ }
109
+
110
+ /** `measure` with the letters spaced `spacingEm`, as the render's `letter-spacing` spaces them. */
111
+ export function withLetterSpacing(measure: DraftTextMeasure, spacingEm: number): DraftTextMeasure {
112
+ return (text, fontSize) => Math.ceil(measure(text, fontSize) + getSpacingWidth(text, spacingEm, fontSize) - 1e-9);
113
+ }
114
+
115
+ /**
116
+ * The draft font of `data` (a TrueType or OpenType file) known to libass as `family`, or null when its tables cannot be
117
+ * read (no `hhea`, `hmtx`, `head` or `cmap`). A character the font lacks is measured as its `.notdef` glyph.
118
+ */
119
+ export function createDraftFont(source: { family: string; file: string }, data: Buffer): DraftFont | null {
120
+ try {
121
+ const metrics = readMetrics(data);
122
+ const characters = readCharacterMap(data);
123
+ if (metrics === null || metrics.unitsPerEm === 0 || !characters.ok) return null;
124
+ const map = characters.value;
125
+ const { unitsPerEm } = metrics;
126
+ return {
127
+ family: source.family,
128
+ file: source.file,
129
+ assScale: metrics.unitsPerSize / unitsPerEm,
130
+ contentArea: { ascentEm: metrics.ascent / unitsPerEm, descentEm: metrics.descent / unitsPerEm },
131
+ measure: (text, fontSize) => {
132
+ let units = 0;
133
+ for (const character of text) units += metrics.advances(map.getGlyph(character.codePointAt(0) ?? 0));
134
+ // Float noise must not round a whole width up; `+ 0` turns an empty line's -0 into 0.
135
+ return Math.ceil((units * fontSize) / unitsPerEm - 1e-9) + 0;
136
+ },
137
+ };
138
+ } catch (error) {
139
+ if (error instanceof OutOfBounds) return null;
140
+ throw error;
141
+ }
142
+ }
143
+
55
144
  /**
56
145
  * Words broken into lines that fit `width` by `measure`, greedily as a browser breaks the render's pill: each line is
57
146
  * its words, and a word wider than a line stands alone on its own.