Skip to content

🎥 Make videos programmatically with React

measureText() validation

Jonny Burger9fe99c374f7c
diff --git a/packages/layout-utils/src/layouts/measure-text.ts b/packages/layout-utils/src/layouts/measure-text.ts
index ea7f785ac9..8ecdb12ccf 100644
--- a/packages/layout-utils/src/layouts/measure-text.ts
+++ b/packages/layout-utils/src/layouts/measure-text.ts
@@ -14,23 +14,23 @@ export type Word = {
const wordCache = new Map<string, Dimensions>();
-export const measureText = ({
+const takeMeasurement = ({
text,
fontFamily,
fontSize,
fontWeight,
letterSpacing,
fontVariantNumeric,
-}: Word): Dimensions => {
- const key = `${text}-${fontFamily}-${fontWeight}-${fontSize}-${letterSpacing}`;
+}: Omit<Word, 'fontFamily'> & {fontFamily: string | null}): {
+ boundingBox: DOMRect;
+ computedFontFamily: string;
+} => {
+ const node = document.createElement('span');
- if (wordCache.has(key)) {
- return wordCache.get(key) as Dimensions;
+ if (fontFamily) {
+ node.style.fontFamily = fontFamily;
}
- const node = document.createElement('span');
-
- node.style.fontFamily = fontFamily;
node.style.display = 'inline-block';
node.style.position = 'absolute';
node.style.top = `-10000px`;
@@ -55,6 +55,58 @@ export const measureText = ({
document.body.appendChild(node);
const boundingBox = node.getBoundingClientRect();
document.body.removeChild(node);
+ return {
+ boundingBox,
+ computedFontFamily: window.getComputedStyle(node).fontFamily,
+ };
+};
+
+export const measureText = ({
+ text,
+ fontFamily,
+ fontSize,
+ fontWeight,
+ letterSpacing,
+ fontVariantNumeric,
+}: Word): Dimensions => {
+ const key = `${text}-${fontFamily}-${fontWeight}-${fontSize}-${letterSpacing}`;
+
+ if (wordCache.has(key)) {
+ return wordCache.get(key) as Dimensions;
+ }
+
+ const {boundingBox, computedFontFamily} = takeMeasurement({
+ fontFamily,
+ fontSize,
+ text,
+ fontVariantNumeric,
+ fontWeight,
+ letterSpacing,
+ });
+
+ const {
+ boundingBox: boundingBoxOfFallbackFont,
+ computedFontFamily: computedFallback,
+ } = takeMeasurement({
+ fontFamily,
+ fontSize,
+ text,
+ fontVariantNumeric,
+ fontWeight,
+ letterSpacing,
+ });
+
+ const sameAsFallbackFont =
+ boundingBox.height === boundingBoxOfFallbackFont.height &&
+ boundingBox.width === boundingBoxOfFallbackFont.width;
+
+ if (sameAsFallbackFont && computedFallback !== computedFontFamily) {
+ const err = [
+ `Called measureText() with "fontFamily" ${fontFamily} but it looks like the font is not loaded at the time of calling.`,
+ `A measurement with the fallback font ${computedFallback} was taken and had the same dimensions, indicating that the browser used the fallback font.`,
+ ];
+ throw new Error(err.join('\n'));
+ }
const result = {height: boundingBox.height, width: boundingBox.width};
wordCache.set(key, result);