🎥 Make videos programmatically with React
Add fit-text-on-n-lines utils to layout-utils
Hitesh1aa7250a236a
diff --git a/packages/docs/components/TableOfContents/LayoutUtils.tsx b/packages/docs/components/TableOfContents/LayoutUtils.tsxindex daa0bc0912..0064e2f026 100644--- a/packages/docs/components/TableOfContents/LayoutUtils.tsx+++ b/packages/docs/components/TableOfContents/LayoutUtils.tsx@@ -3,22 +3,26 @@ import { Grid } from "./Grid";import { TOCItem } from "./TOCItem";export const TableOfContents: React.FC = () => {- return (- <div>- <Grid>- <TOCItem link="/docs/layout-utils/measure-text">- <strong>measureText()</strong>- <div>Get dimensions of text</div>- </TOCItem>- <TOCItem link="/docs/layout-utils/fill-text-box">- <strong>fillTextBox()</strong>- <div>Find line breaks and overflows in a text box</div>- </TOCItem>- <TOCItem link="/docs/layout-utils/fit-text">- <strong>fitText()</strong>- <div>Get font size to fit text in a box</div>- </TOCItem>- </Grid>- </div>- );+ return (+ <div>+ <Grid>+ <TOCItem link="/docs/layout-utils/measure-text">+ <strong>measureText()</strong>+ <div>Get dimensions of text</div>+ </TOCItem>+ <TOCItem link="/docs/layout-utils/fill-text-box">+ <strong>fillTextBox()</strong>+ <div>Find line breaks and overflows in a text box</div>+ </TOCItem>+ <TOCItem link="/docs/layout-utils/fit-text">+ <strong>fitText()</strong>+ <div>Get font size to fit text in a box</div>+ </TOCItem>+ <TOCItem link="/docs/layout-utils/fit-text-on-n-lines">+ <strong>fitTextOnNLines()</strong>+ <div>Get font size to fit text on n lines</div>+ </TOCItem>+ </Grid>+ </div>+ );};diff --git a/packages/docs/docs/layout-utils/fit-text-on-n-lines.mdx b/packages/docs/docs/layout-utils/fit-text-on-n-lines.mdxnew file mode 100644index 0000000000..e2ede33e12--- /dev/null+++ b/packages/docs/docs/layout-utils/fit-text-on-n-lines.mdx@@ -0,0 +1,188 @@+---+image: /generated/articles-docs-layout-utils-fit-text-on-n-lines.png+title: fitTextOnNLines()+crumb: '@remotion/layout-utils'+---++\_Part of the [`@remotion/layout-utils`](/docs/layout-utils) package. Available from v4.0.312++Calculates the `font-size` needed to fit a text into a given width while respecting a maximum number of lines.++```tsx twoslash title="FitTextOnNLines.tsx"+import {fitTextOnNLines} from '@remotion/layout-utils';++const text = 'Hello World';+const width = 100;+const maxLines = 2;+const fontFamily = 'Arial';+const fontWeight = 'bold';++const {fontSize} = fitTextOnNLines({+ text,+ maxBoxWidth: width,+ maxLines,+ fontFamily: fontFamily,+ fontWeight: fontWeight,+ textTransform: 'uppercase',+});++// Example markup:+<div+ style={{+ fontSize,+ width,+ fontFamily,+ fontWeight,+ textTransform: 'uppercase',+ }}+>+ {text}+</div>;+```++## API++Accepts an object with the following properties:++### `text`++_string_++The text to fit.++### `maxBoxWidth`++_number_++The maximum width the text should fit into.++:::info+In the default Remotion stylesheet, borders shrink the container due to `box-sizing: border-box`.+Subtract any borders, or use `outline` instead of `border`.+:::++### `maxLines`++_number_++The maximum number of lines the text should be distributed across.++### `fontFamily`++_string_++The `font-family` CSS property you are going to assign to the text.++:::info+The font needs to be loaded before this API is being called.+If you use [`@remotion/google-fonts`](/docs/google-fonts), wait until [`waitUntilDone()`](/docs/google-fonts/load-font#waituntildone) resolves first.+:::++### `fontWeight`++_string | number, optional_++Pass this option if you are going to assign a `font-weight` CSS property to the text.++### `letterSpacing`++_string, optional_++Pass this option if you are going to assign a `letter-spacing` CSS property to the text.++### `fontVariantNumeric`++_string, optional_++Pass this option if you are going to assign a `font-variant-numeric` CSS property to the text.++### `textTransform`++_string_++Same as CSS style `text-transform`.++### `validateFontIsLoaded?`++_boolean_++If set to `true`, will take a second measurement with the fallback font and if it produces the same measurements, it assumes the fallback font was used and will throw an error.++### `additionalStyles`++_object, optional_++Additional CSS properties that affect the layout of the text.++## Return value++An object with `fontSize` in pixels. Assign this to the `style` prop of your text element.++## Example++```tsx twoslash+import {fitTextOnNLines} from '@remotion/layout-utils';+import React from 'react';+import {AbsoluteFill} from 'remotion';++const boxWidth = 600;+const maxLines = 2;+// Must be loaded before calling fitTextOnNLines()+const fontFamily = 'Helvetica';+const fontWeight = 'bold';++export const FitTextOnNLines: React.FC<{text: string}> = ({text}) => {+ const fontSize = Math.min(+ 80,+ fitTextOnNLines({+ fontFamily,+ text,+ maxBoxWidth: boxWidth,+ maxLines,+ fontWeight,+ }).fontSize,+ );++ return (+ <AbsoluteFill+ style={{+ justifyContent: 'center',+ alignItems: 'center',+ backgroundColor: 'white',+ }}+ >+ <div+ style={{+ width: boxWidth,+ outline: '1px dashed rgba(0, 0, 0, 0.5)',+ height: 100,+ fontSize,+ fontWeight,+ fontFamily,+ display: 'flex',+ alignItems: 'center',+ }}+ >+ {text}+ </div>+ </AbsoluteFill>+ );+};+```++Notes:++- A maximum font size of `80` was specified to prevent the text from becoming too large.+- The `fontFamily` and `fontWeight` were passed to the `div` element to ensure that the text is rendered with the same font as the one used by `fitTextOnNLines()`.+- The `outline` CSS property was used instead of `border`.+ This is because in Remotion, the border is inside by default and shrinks the container, due to `box-sizing: border-box` being in the default stylesheet.++## Important considerations++See [Best practices](/docs/layout-utils/best-practices) to ensure you get correct measurements.++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/layout-utils/src/layouts/fit-text-on-n-lines.ts)+- [`@remotion/layout-utils`](/docs/layout-utils)+- [`@remotion/google-fonts`](/docs/google-fonts)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 5f0e62f5d8..4a7222ffc8 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -629,6 +629,7 @@ module.exports = {'layout-utils/measure-text','layout-utils/fill-text-box','layout-utils/fit-text',+ 'layout-utils/fit-text-on-n-lines','layout-utils/debug',],},diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex e32c71706a..a1204dd200 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2564,6 +2564,15 @@ export const articles = [noAi: false,slug: 'layout-utils/fill-text-box',},+ {+ id: 'layout-utils/fit-text-on-n-lines',+ title: 'fitTextOnNLines()',+ relativePath: 'docs/layout-utils/fit-text-on-n-lines.mdx',+ compId: 'articles-docs-layout-utils-fit-text-on-n-lines',+ crumb: '@remotion/layout-utils',+ noAi: false,+ slug: 'layout-utils/fit-text-on-n-lines',+ },{id: 'layout-utils/fit-text',title: 'fitText()',diff --git a/packages/docs/static/generated/articles-docs-layout-utils-fit-text-on-n-lines.png b/packages/docs/static/generated/articles-docs-layout-utils-fit-text-on-n-lines.pngnew file mode 100644index 0000000000..fe0260d0d5Binary files /dev/null and b/packages/docs/static/generated/articles-docs-layout-utils-fit-text-on-n-lines.png differdiff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex d8d4e1b3ac..359fe18c42 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -130,6 +130,7 @@ import {PremountOnTransitionSeries} from './PremountOnTransitionSeries';import {SmoothTextTransition} from './SmoothTextTransition';import {Seek} from './StudioApis/Seek';import {TikTokTextBoxPlayground} from './TikTokTextbox/TikTokTextBox';+import {FitTextOnNLines, fitTextOnNLinesSchema} from './Title/FitTextOnNLines';import {TransitionRounding} from './TransitionRounding';import {VisualControls} from './VisualControls';import {VoiceVisualization} from './voice-visualization';@@ -602,6 +603,17 @@ export const Index: React.FC = () => {line: 'Test',}}/>+ <Still+ id="FitTextOnNLines"+ component={FitTextOnNLines}+ width={800}+ height={900}+ schema={fitTextOnNLinesSchema}+ defaultProps={{+ line: 'Test '.repeat(20),+ maxLines: 2,+ }}+ /><Compositionid="beta-text"component={BetaText}diff --git a/packages/example/src/Title/FitTextOnNLines.tsx b/packages/example/src/Title/FitTextOnNLines.tsxnew file mode 100644index 0000000000..bcb588ef14--- /dev/null+++ b/packages/example/src/Title/FitTextOnNLines.tsx@@ -0,0 +1,58 @@+import {fitTextOnNLines} from '@remotion/layout-utils';+import React from 'react';+import {AbsoluteFill} from 'remotion';+import {z} from 'zod';++const boxWidth = 600;+const fontFamily = 'GT Planar';+const fontWeight = 'bold';++export const fitTextOnNLinesSchema = z.object({+ line: z.string(),+ maxLines: z.number(),+});++export const FitTextOnNLines: React.FC<+ z.infer<typeof fitTextOnNLinesSchema>+> = ({line, maxLines}) => {+ const fontSize = Math.min(+ 80,+ fitTextOnNLines({+ maxLines,+ maxBoxWidth: boxWidth,+ fontFamily,+ text: line,+ fontWeight,+ textTransform: 'uppercase',+ }).fontSize,+ );++ return (+ <AbsoluteFill+ style={{+ justifyContent: 'center',+ alignItems: 'center',+ backgroundColor: 'white',+ }}+ >+ <div style={{backgroundColor: '#0B84F3', padding: 20}}>+ <div+ style={{+ width: boxWidth,+ outline: '1px dashed rgba(255, 255, 255, 0.5)',+ fontSize,+ overflow: 'auto',+ fontWeight,+ fontFamily,+ display: 'flex',+ alignItems: 'center',+ color: 'white',+ textTransform: 'uppercase',+ }}+ >+ {line}+ </div>+ </div>+ </AbsoluteFill>+ );+};diff --git a/packages/layout-utils/src/index.ts b/packages/layout-utils/src/index.tsindex ecc09cc704..c79fe83e51 100644--- a/packages/layout-utils/src/index.ts+++ b/packages/layout-utils/src/index.ts@@ -1,3 +1,4 @@export {fillTextBox} from './layouts/fill-text-box';export {fitText} from './layouts/fit-text';+export {fitTextOnNLines} from './layouts/fit-text-on-n-lines';export {Dimensions, TextTransform, measureText} from './layouts/measure-text';diff --git a/packages/layout-utils/src/layouts/fit-text-on-n-lines.ts b/packages/layout-utils/src/layouts/fit-text-on-n-lines.tsnew file mode 100644index 0000000000..4fcf7d8838--- /dev/null+++ b/packages/layout-utils/src/layouts/fit-text-on-n-lines.ts@@ -0,0 +1,89 @@+import {fillTextBox} from './fill-text-box';+import type {TextTransform} from './measure-text';++const PRECISION = 100;++type FitTextOnNLinesProps = {+ text: string;+ maxLines: number;+ maxBoxWidth: number;+ fontFamily: string;+ fontWeight?: number | string;+ letterSpacing?: string;+ fontVariantNumeric?: string;+ validateFontIsLoaded?: boolean;+ textTransform?: TextTransform;+ additionalStyles?: Record<string, string>;+};++export const fitTextOnNLines = ({+ text,+ maxLines,+ maxBoxWidth,+ fontFamily,+ fontWeight,+ letterSpacing,+ fontVariantNumeric,+ validateFontIsLoaded,+ textTransform,+ additionalStyles,+}: FitTextOnNLinesProps) => {+ // Fixed max font size since we are using binary search a+ const maxFontSize = 2000;+ const minFontSize = 0.1;++ // Binary search to find the optimal font size+ let left = Math.floor(minFontSize * PRECISION);+ let right = Math.floor(maxFontSize * PRECISION);+ let optimalFontSize = minFontSize;+ while (left <= right) {+ const mid = Math.floor((left + right) / 2);+ const fontSize = mid / PRECISION;++ // Create a text box with current font size+ const textBox = fillTextBox({+ maxBoxWidth,+ maxLines,+ });++ // Split text into words and try to fit them+ const words = text.split(' ');+ let exceedsBox = false;+ let currentLine = 0;++ for (const word of words) {+ const result = textBox.add({+ text: word + ' ',+ fontFamily,+ fontWeight,+ fontSize,+ letterSpacing,+ fontVariantNumeric,+ validateFontIsLoaded,+ textTransform,+ additionalStyles,+ });++ if (result.exceedsBox) {+ exceedsBox = true;+ break;+ }++ if (result.newLine) {+ currentLine++;+ }+ }++ // If text fits within the box and number of lines+ if (!exceedsBox && currentLine < maxLines) {+ optimalFontSize = fontSize;+ left = mid + 1;+ } else {+ right = mid - 1;+ }+ }++ return {+ fontSize: optimalFontSize,+ };+};