@softure-ai/marketing-kit 0.42.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.
@@ -1,7 +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 { getSpacingWidth, toDraftAssSize, toDraftSpacing, wrapDraftLine, type DraftFont } from "./draft-text-width.js";
4
+ import { DEFAULT_CONTENT_AREA, getSpacingWidth, toDraftAssSize, toDraftSpacing, wrapDraftLine, type DraftFont } from "./draft-text-width.js";
5
5
  import { HAND_FONT, getHandFontAssSize } from "./hand-font.js";
6
6
  import { getCounterSeconds, getOverlayColors, getPlaceCardTimes, getTypingTimes, type OverlayColors } from "./overlay-html.js";
7
7
  import {
@@ -37,7 +37,14 @@ import {
37
37
  getChipCoveredTimes,
38
38
  getChipParts,
39
39
  getChipTickPoints,
40
+ COUNTER_UNIT_GAP_EM,
41
+ getCounterCard,
40
42
  getDrawnOverlayCard,
43
+ getKeywordMarkBlock,
44
+ getSideTextLayout,
45
+ KEYWORD_EDGE_EM,
46
+ MARK_PADDING_EM,
47
+ MARK_RADIUS_EM,
41
48
  getListCardsByItem,
42
49
  getListItemTimes,
43
50
  getListStops,
@@ -55,7 +62,9 @@ import {
55
62
  type OverlayBox,
56
63
  type OverlayFontRole,
57
64
  type OverlayPoint,
65
+ type OverlayTextMeasure,
58
66
  type ResolvedOverlay,
67
+ type SideTextLayout,
59
68
  } from "./overlays.js";
60
69
 
61
70
  /**
@@ -188,6 +197,13 @@ interface DraftContext {
188
197
  spacing: (spacingEm: number, cssPx: number) => string;
189
198
  /** The brand's style: the cards' radius, shadow and border; absent: each kind's own corner, no shadow, no border. */
190
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 };
191
207
  }
192
208
 
193
209
  /**
@@ -429,10 +445,6 @@ export function getDropText(text: string, times: readonly number[], eventStart:
429
445
  .join("");
430
446
  }
431
447
 
432
- /** A highlight mark's padding round its text and its corner, in font sizes (as the render's `.ov-mark`). */
433
- const MARK_PADDING_EM = { x: 0.22, y: 0.04 } as const;
434
- const MARK_RADIUS_EM = 0.14;
435
-
436
448
  /**
437
449
  * A highlight backdrop's marks under one line of text (`style.backdrop` highlight): a tight rounded box in the card
438
450
  * colour, its width the text shown so far (each typed letter widens it, as the render's box grows), anchored where
@@ -450,14 +462,22 @@ function getBackdropMarkEvents(input: {
450
462
  typing: number | null;
451
463
  /** When the line starts typing, if not at the span's start (a second line of a title). */
452
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 };
453
471
  }): string[] {
454
- const { fontSize, span } = input;
472
+ const { fontSize, span, measured } = input;
455
473
  const pad = { x: fontSize * MARK_PADDING_EM.x, y: fontSize * MARK_PADDING_EM.y };
456
- 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;
457
477
  const boxFor = (shown: string): OverlayBox => {
458
- const width = estimateTextWidth(shown, fontSize) + 2 * pad.x;
478
+ const width = (measured === undefined ? estimateTextWidth(shown, fontSize) : measured.measure(shown)) + 2 * pad.x;
459
479
  const left = input.align === "left" ? input.x - pad.x : input.align === "right" ? input.x + pad.x - width : input.x - width / 2;
460
- return { left, top: input.top - pad.y, width, height };
480
+ return { left, top, width, height };
461
481
  };
462
482
  const clean = toAssText(input.text);
463
483
  const steps =
@@ -499,6 +519,7 @@ function getUnderlineEvent(overlay: Extract<ResolvedOverlay, { kind: "keyword" }
499
519
  */
500
520
  function getSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" | "lower_third" | "list" }>, context: DraftContext): string[] {
501
521
  if (overlay.kind === "list") return getListEvents(overlay, context);
522
+ if (context.layout !== undefined) return getLaidOutSideTextEvents(overlay, context, context.layout);
502
523
  const colors = getOverlayColors(overlay, context.brand);
503
524
  const { fontSize, side } = overlay;
504
525
  // A side text always has a card: only a punch_in has none.
@@ -531,6 +552,104 @@ function getSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" |
531
552
  return [...shape, ...text({ x, y }, steps), ...(overlay.kind === "keyword" ? getUnderlineEvent(overlay, card, colors.accent, motion) : [])];
532
553
  }
533
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
+
534
653
  /** A list's card grows to its next point's size over these seconds, in this many steps along the render's ease. */
535
654
  const LIST_GROW_SECONDS = 0.35;
536
655
  const LIST_GROW_STEPS = 3;
@@ -762,7 +881,9 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
762
881
  const motion = getDraftMotion(overlay, name, box, context);
763
882
  const span = { start: overlay.start, end: overlay.end };
764
883
  const isMarked = overlay.kind === "hook_title" && overlay.backdrop === "highlight";
765
- 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);
766
887
  const { x: padX, y: padY } = getOverlayPadding(overlay);
767
888
  const centerX = box.left + box.width / 2;
768
889
  const tagsFor = (role: OverlayFontRole) => getTextTags(overlay, colors, context, role);
@@ -803,14 +924,21 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
803
924
  const lineStart = overlay.typing === null ? span.start : span.start + typedBefore / overlay.typing;
804
925
  if (isMarked) {
805
926
  const align = isLeft ? "left" : "center";
806
- 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 }));
807
933
  }
808
934
  const steps =
809
935
  overlay.entrance === "drop"
810
936
  ? [{ from: span.start, to: span.end, text: getDropText(line, letters.slice(typedBefore, typedBefore + [...line].length), span.start) }]
811
937
  : getTypedSteps(line, { start: lineStart, end: span.end }, overlay.typing, !isLeft);
812
938
  const isQuiet = overlay.entrance === "drop" || (!isLeft && overlay.typing !== null);
813
- 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));
814
942
  typedBefore += [...line].length;
815
943
  y += fontSize * lineHeight;
816
944
  });
@@ -845,7 +973,10 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
845
973
  return events;
846
974
  }
847
975
  if (overlay.kind === "counter") {
848
- const unit = overlay.unit === null ? "" : `{\\fs${context.toAssSize("heading", 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)}`;
849
980
  const count = getCounterSeconds(overlay);
850
981
  const steps: TextStep[] = [];
851
982
  const ticks = Math.max(1, Math.round(count.duration / COUNT_STEP));
@@ -858,7 +989,27 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
858
989
  const value = overlay.from + (overlay.value - overlay.from) * eased;
859
990
  steps.push({ from: count.start + (tick - 1) * COUNT_STEP, to: tick === ticks ? span.end : count.start + tick * COUNT_STEP, text: show(value) });
860
991
  }
861
- 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)];
862
1013
  }
863
1014
  const isRight = overlay.side === "right";
864
1015
  const x = isRight ? box.left + box.width - padX : box.left + padX;
@@ -1027,7 +1178,9 @@ export function buildDraftOverlayEvents(
1027
1178
  toAssSize: (role, cssPx) => (drawn === undefined ? cssPx : toDraftAssSize(cssPx, drawn[role].assScale)),
1028
1179
  measure: (role, text, cssPx, spacingEm) => (drawn === undefined ? estimateTextWidth(text, cssPx) : drawn[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx)),
1029
1180
  spacing: (spacingEm, cssPx) => (drawn === undefined || spacingEm === 0 ? "" : `\\fsp${String(toDraftSpacing(spacingEm, cssPx))}`),
1181
+ contentArea: (role) => drawn?.[role].contentArea ?? DEFAULT_CONTENT_AREA,
1030
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) }),
1031
1184
  };
1032
1185
  return overlays.flatMap((overlay) => {
1033
1186
  if (overlay.kind === "punch_in") return [];
@@ -16,6 +16,18 @@ interface Metrics {
16
16
  /** The font's units per em (`head`), what a browser sizes it by; 0 when the font has no `head`. */
17
17
  unitsPerEm: number;
18
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) };
19
31
  }
20
32
 
21
33
  function readMetrics(font: Buffer): Metrics | null {
@@ -32,7 +44,7 @@ function readMetrics(font: Buffer): Metrics | null {
32
44
  const head = tables.value.get("head");
33
45
  const unitsPerEm = head === undefined ? 0 : readUint16(head, 18);
34
46
  // Glyphs past `numberOfHMetrics` share the last advance (OpenType `hmtx`).
35
- return { unitsPerSize, unitsPerEm, 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) };
36
48
  }
37
49
 
38
50
  /**
@@ -69,8 +81,16 @@ export interface DraftFont {
69
81
  assScale: number;
70
82
  /** A line's width in CSS px at a CSS font size (advances per em; kerning not read). */
71
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 };
72
89
  }
73
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
+
74
94
  /** The ASS size (`Fontsize`, `\fs`) that draws a font of `assScale` as large as the render's `cssPx`, to 0.01. */
75
95
  export function toDraftAssSize(cssPx: number, assScale: number): number {
76
96
  return Math.round(cssPx * assScale * 100) / 100;
@@ -107,6 +127,7 @@ export function createDraftFont(source: { family: string; file: string }, data:
107
127
  family: source.family,
108
128
  file: source.file,
109
129
  assScale: metrics.unitsPerSize / unitsPerEm,
130
+ contentArea: { ascentEm: metrics.ascent / unitsPerEm, descentEm: metrics.descent / unitsPerEm },
110
131
  measure: (text, fontSize) => {
111
132
  let units = 0;
112
133
  for (const character of text) units += metrics.advances(map.getGlyph(character.codePointAt(0) ?? 0));
@@ -16,12 +16,12 @@ import { toAssColor } from "./draft-color.js";
16
16
  import { buildDraftOverlayEvents, getDraftOverlayStyles, getRoundedRectDrawing } from "./draft-overlays.js";
17
17
  import { getCaptionCornerRadius, getCornerRadiusPx, getStylePadding, type BrandStyle } from "./brand-style.js";
18
18
  import { getDraftBoxEvents } from "./draft-boxes.js";
19
- import { createDraftFont, toDraftAssSize, toDraftSpacing, withLetterSpacing, wrapDraftLine, type DraftFont, type DraftTextMeasure } from "./draft-text-width.js";
19
+ import { createDraftFont, getSpacingWidth, toDraftAssSize, toDraftSpacing, withLetterSpacing, wrapDraftLine, type DraftFont, type DraftTextMeasure } from "./draft-text-width.js";
20
20
  import { CAPTION_LETTER_SPACING_EM, CAPTION_PILL_PADDING, CAPTION_RIBBON_LETTER_SPACING_EM } from "../compose/timeline.js";
21
21
  import { estimateTextWidth, isHandFontNeeded } from "./overlays.js";
22
22
  import { HAND_FONT } from "./hand-font.js";
23
23
  import type { OverlayColors } from "./overlay-html.js";
24
- import { resolveEdlOverlays, type OverlayFontRole, type ResolvedOverlay } from "./overlays.js";
24
+ import { resolveEdlOverlays, type OverlayFontRole, type OverlayTextMeasure, type ResolvedOverlay } from "./overlays.js";
25
25
  import { chooseFootageDraftFont } from "./draft-font.js";
26
26
  import { getEdlDuration, getSegmentStarts, remapWords, type Edl } from "./edl.js";
27
27
  import { declickSpeech, describeDeclick, type DeclickReport } from "./declick.js";
@@ -101,6 +101,15 @@ export function loadFootageDraftFonts(fonts: Partial<Record<"body" | OverlayFont
101
101
  return { body, heading: forRole("heading"), interface: forRole("interface") };
102
102
  }
103
103
 
104
+ /**
105
+ * The render's measure of overlay text (`OverlayTextMeasure`) from the draft's fonts: a line's width in CSS px in the
106
+ * font of its role, its letters spaced as the render spaces them. With it `getDrawnOverlayCard` answers the card the
107
+ * render lays out, as the draft draws it, so an app reports where a card really stands.
108
+ */
109
+ export function createOverlayTextMeasure(fonts: FootageDraftFonts): OverlayTextMeasure {
110
+ return (role, text, cssPx, spacingEm) => fonts[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx);
111
+ }
112
+
104
113
  /** How far a segment marked `kenburns` zooms when the film's `kenBurnsPercent` is 0, as in the render. */
105
114
  const HAND_KEN_BURNS_PERCENT = 4;
106
115
  const DRAFT_CRF = 28;
@@ -436,9 +436,20 @@ export function getSideTextLines(overlay: SideTextOverlay): string[] {
436
436
  * The card a drawn overlay shows, in px of the frame, or null for a `punch_in`. A keyword, a lower third and a list
437
437
  * are placed in the whole width they may take (`box`); their card fits their widest line (by `estimateTextWidth`)
438
438
  * plus its padding, on its side, as tall as the box. Every other kind's card is its box (`getOverlayBounds`). The
439
- * draft draws this card, so a report of where an overlay sits (does it cover a face?) reads the same box.
439
+ * draft draws this card, so a report of where an overlay sits (does it cover a face?) reads the same box. With the
440
+ * brand fonts' `measure` (`createOverlayTextMeasure`), a keyword's, a lower third's and a counter's card is the one the
441
+ * render lays out (`getSideTextLayout`, `getCounterCard`, the counter at its final value), as the draft then draws it;
442
+ * a highlighted keyword or hook title (no card of its own) answers where its marks show.
440
443
  */
441
- export function getDrawnOverlayCard(overlay: ResolvedOverlay): OverlayBox | null {
444
+ export function getDrawnOverlayCard(overlay: ResolvedOverlay, measure?: OverlayTextMeasure): OverlayBox | null {
445
+ if (measure !== undefined && overlay.kind === "keyword" && overlay.backdrop === "highlight") {
446
+ const layout = getSideTextLayout(overlay, measure);
447
+ return getKeywordMarkBlock(overlay, layout, layout.lines, measure);
448
+ }
449
+ if (measure !== undefined && (overlay.kind === "keyword" || overlay.kind === "lower_third")) return getSideTextLayout(overlay, measure).card;
450
+ if (measure !== undefined && overlay.kind === "hook_title" && overlay.backdrop === "highlight") return getMarkedTitleBounds(overlay, measure) ?? overlay.box;
451
+ // The counter's widest number: its final value, grouped as en-US groups it (as `measureCounter` sizes its box).
452
+ if (measure !== undefined && overlay.kind === "counter") return getCounterCard(overlay, formatOverlayNumber(overlay.value, overlay.decimals, "en-US"), measure);
442
453
  if (overlay.kind !== "keyword" && overlay.kind !== "lower_third" && overlay.kind !== "list") return getOverlayBounds(overlay);
443
454
  if (overlay.kind === "list" && overlay.chips !== undefined) return getBoxesUnion(overlay.chips);
444
455
  return getSideTextCard(overlay, getSideTextLines(overlay), overlay.box.height);
@@ -455,6 +466,123 @@ function getSideTextCard(overlay: SideTextOverlay, lines: readonly string[], hei
455
466
  return { left, top: box.top, width, height };
456
467
  }
457
468
 
469
+ /**
470
+ * A line's width in CSS px in the brand font of `role` at `cssPx`, its letters spaced `spacingEm` (the render's
471
+ * `letter-spacing`): the render's own measure, read from the font files (`createOverlayTextMeasure`).
472
+ */
473
+ export type OverlayTextMeasure = (role: OverlayFontRole, text: string, cssPx: number, spacingEm: number) => number;
474
+
475
+ /** A lower third's accent dot and the gap after it, in ems of its font size (the render's `.ov-dot` and card gap). */
476
+ export const OVERLAY_DOT_EM = { size: 0.36, gap: 0.45 } as const;
477
+ /** A keyword card's accent edge under its text, in ems (the render's `border-bottom`). */
478
+ export const KEYWORD_EDGE_EM = 0.12;
479
+ /** The gap between a counter's number and its unit, in ems of the number's size. */
480
+ export const COUNTER_UNIT_GAP_EM = 0.3;
481
+ /** A highlight mark's padding round its text and its corner, in ems (the render's `.ov-mark`). */
482
+ export const MARK_PADDING_EM = { x: 0.22, y: 0.04 } as const;
483
+ export const MARK_RADIUS_EM = 0.14;
484
+
485
+ /** A keyword's or a lower third's card as the render lays it out: its text's lines, the card, where the text starts and its dot. */
486
+ export interface SideTextLayout {
487
+ /** The text broken as the render's card breaks it, one entry a line. */
488
+ lines: string[];
489
+ card: OverlayBox;
490
+ /** Where the first letter of every line starts (a centred keyword: the card's middle). */
491
+ textX: number;
492
+ /** The top of the first line (inside a highlight mark's padding). */
493
+ textTop: number;
494
+ /** A lower third's accent dot; null for a keyword. */
495
+ dot: { centre: OverlayPoint; radius: number } | null;
496
+ }
497
+
498
+ /** `words` broken greedily into lines no wider than `width` by `measureLine`, as a browser breaks a line (a word wider than a line stands alone). */
499
+ function breakLines(words: readonly string[], width: number, measureLine: (line: string) => number): string[] {
500
+ const lines: string[] = [];
501
+ for (const word of words) {
502
+ const last = lines[lines.length - 1];
503
+ if (last !== undefined && measureLine(`${last} ${word}`) <= width) lines[lines.length - 1] = `${last} ${word}`;
504
+ else lines.push(word);
505
+ }
506
+ return lines;
507
+ }
508
+
509
+ /**
510
+ * A keyword's or a lower third's card as the render lays it out (`.ov-card` in its box): its text broken inside the
511
+ * box less the padding (and a highlight mark's padding, a lower third's dot), the card as wide as its widest line (the
512
+ * whole box once it wraps), as tall as its lines plus padding and a keyword's accent edge; a keyword's card hangs from
513
+ * the box's top, a lower third's stands on its foot. `measure` reads the brand font, as the browser does.
514
+ */
515
+ export function getSideTextLayout(overlay: Extract<ResolvedOverlay, { kind: "keyword" | "lower_third" }>, measure: OverlayTextMeasure): SideTextLayout {
516
+ const { box, fontSize, side } = overlay;
517
+ const pad = getOverlayPadding(overlay);
518
+ const role = OVERLAY_FONT_ROLES[overlay.kind];
519
+ const isMarked = overlay.kind === "keyword" && overlay.backdrop === "highlight";
520
+ const markPad = isMarked ? fontSize * MARK_PADDING_EM.x : 0;
521
+ const dotRoom = overlay.kind === "lower_third" ? fontSize * (OVERLAY_DOT_EM.size + OVERLAY_DOT_EM.gap) : 0;
522
+ const measureLine = (line: string): number => measure(role, line, fontSize, OVERLAY_LETTER_SPACING_EM.card);
523
+ const words = overlay.text.replace(/\s+/g, " ").trim().split(" ");
524
+ const lines = breakLines(words, box.width - 2 * pad.x - dotRoom - 2 * markPad, measureLine);
525
+ const textWidth = Math.max(0, ...lines.map(measureLine)) + 2 * markPad + dotRoom;
526
+ const width = lines.length > 1 ? box.width : Math.min(box.width, Math.ceil(textWidth + 2 * pad.x));
527
+ // A highlighted keyword's card draws no border; an underlined one keeps its edge's room, transparent.
528
+ const edge = overlay.kind === "keyword" && !isMarked ? Math.round(fontSize * KEYWORD_EDGE_EM) : 0;
529
+ // A highlighted keyword's text is one block (a flex item) on its mark, padded on every side.
530
+ const markPadY = isMarked ? fontSize * MARK_PADDING_EM.y : 0;
531
+ const height = Math.ceil(lines.length * fontSize * OVERLAY_LINE_HEIGHT + 2 * markPadY + 2 * pad.y + edge);
532
+ const isCentred = overlay.kind === "keyword" && overlay.isCentred === true;
533
+ const left = isCentred ? box.left + Math.round((box.width - width) / 2) : side === "right" ? box.left + box.width - width : box.left;
534
+ const top = overlay.kind === "lower_third" ? box.top + box.height - height : box.top;
535
+ const card = { left, top, width, height };
536
+ const textTop = top + pad.y + markPadY;
537
+ const dot =
538
+ overlay.kind === "lower_third" ? { centre: { x: left + pad.x + (fontSize * OVERLAY_DOT_EM.size) / 2, y: top + height / 2 }, radius: (fontSize * OVERLAY_DOT_EM.size) / 2 } : null;
539
+ return { lines, card, textX: isCentred ? left + width / 2 : left + pad.x + dotRoom + markPad, textTop, dot };
540
+ }
541
+
542
+ /**
543
+ * A highlighted keyword's mark as the render draws it (`.ov-mark` is a flex item of the card, so one block): round
544
+ * `lines` (the whole text's, or the letters typed so far on theirs), as wide as the widest line, or all the card's
545
+ * room once the text wraps, as tall as the lines, padded by `MARK_PADDING_EM`.
546
+ */
547
+ export function getKeywordMarkBlock(overlay: Extract<ResolvedOverlay, { kind: "keyword" }>, layout: SideTextLayout, lines: readonly string[], measure: OverlayTextMeasure): OverlayBox {
548
+ const { fontSize } = overlay;
549
+ const pad = { x: fontSize * MARK_PADDING_EM.x, y: fontSize * MARK_PADDING_EM.y };
550
+ const measureLine = (line: string): number => measure(OVERLAY_FONT_ROLES.keyword, line, fontSize, OVERLAY_LETTER_SPACING_EM.card);
551
+ const width = lines.length > 1 ? layout.card.width - 2 * getOverlayPadding(overlay).x : Math.max(0, ...lines.map(measureLine)) + 2 * pad.x;
552
+ const height = lines.length * fontSize * OVERLAY_LINE_HEIGHT + 2 * pad.y;
553
+ const left = overlay.isCentred === true ? layout.textX - width / 2 : layout.textX - pad.x;
554
+ return { left, top: layout.textTop - pad.y, width, height };
555
+ }
556
+
557
+ /**
558
+ * Where a highlighted hook title shows (its card is transparent): round its lines' marks, as wide as the widest line
559
+ * and its marks' padding, as tall as its lines; null when it names a place (its row is not a mark).
560
+ */
561
+ function getMarkedTitleBounds(overlay: Extract<ResolvedOverlay, { kind: "hook_title" }>, measure: OverlayTextMeasure): OverlayBox | null {
562
+ if (overlay.place !== null) return null;
563
+ const { fontSize } = overlay;
564
+ const content = getTitleContentBox(overlay);
565
+ const padX = fontSize * MARK_PADDING_EM.x;
566
+ const width = Math.max(0, ...overlay.lines.map((line) => measure("heading", line, fontSize, OVERLAY_LETTER_SPACING_EM.hookTitle))) + 2 * padX;
567
+ const left = overlay.align === "left" ? content.left : content.left + content.width / 2 - width / 2;
568
+ return { left, top: content.top, width, height: content.height };
569
+ }
570
+
571
+ /**
572
+ * A counter's card as the render lays it out while it shows `text` (its number, as formatted): as wide as the number,
573
+ * its unit and the gap between, plus padding; one line tall; in the middle of its box, from its top.
574
+ */
575
+ export function getCounterCard(overlay: Extract<ResolvedOverlay, { kind: "counter" }>, text: string, measure: OverlayTextMeasure): OverlayBox {
576
+ const { box, fontSize, unit, unitFontSize } = overlay;
577
+ const pad = getOverlayPadding(overlay);
578
+ const role = OVERLAY_FONT_ROLES.counter;
579
+ // The card's letter spacing is set in ems of the card's size and inherited as px by the unit.
580
+ const unitWidth = unit === null ? 0 : fontSize * COUNTER_UNIT_GAP_EM + measure(role, unit, unitFontSize, (OVERLAY_LETTER_SPACING_EM.card * fontSize) / unitFontSize);
581
+ const width = Math.ceil(measure(role, text, fontSize, OVERLAY_LETTER_SPACING_EM.card) + unitWidth + 2 * pad.x);
582
+ const height = Math.ceil(fontSize * OVERLAY_LINE_HEIGHT + 2 * pad.y);
583
+ return { left: box.left + Math.round((box.width - width) / 2), top: box.top, width, height };
584
+ }
585
+
458
586
  /** The smallest box round every box of a non-empty list. */
459
587
  function getBoxesUnion(boxes: readonly OverlayBox[]): OverlayBox {
460
588
  const left = Math.min(...boxes.map((box) => box.left));
package/src/index.ts CHANGED
@@ -158,6 +158,7 @@ export {
158
158
  type StyleShadow,
159
159
  } from "./footage/brand-style.js";
160
160
  export {
161
+ DEFAULT_CONTENT_AREA,
161
162
  createDraftFont,
162
163
  createDraftTextMeasure,
163
164
  getSpacingWidth,
@@ -190,7 +191,17 @@ export {
190
191
  getChipCoveredTimes,
191
192
  getChipParts,
192
193
  getChipTickPoints,
194
+ getCounterCard,
193
195
  getDrawnOverlayCard,
196
+ getKeywordMarkBlock,
197
+ getSideTextLayout,
198
+ COUNTER_UNIT_GAP_EM,
199
+ KEYWORD_EDGE_EM,
200
+ MARK_PADDING_EM,
201
+ MARK_RADIUS_EM,
202
+ OVERLAY_DOT_EM,
203
+ type OverlayTextMeasure,
204
+ type SideTextLayout,
194
205
  getListCardsByItem,
195
206
  getListItemTimes,
196
207
  getListStops,
@@ -702,6 +713,7 @@ export {
702
713
  FOOTAGE_DRAFT_FONT,
703
714
  FOOTAGE_DRAFT_WIDTH,
704
715
  loadFootageDraftFonts,
716
+ createOverlayTextMeasure,
705
717
  type FootageDraftFonts,
706
718
  buildFootageDraftArgs,
707
719
  buildFootageDraftCaptions,