🎥 Make videos programmatically with React
Docs: Expose Studio API table of contents in Markdown (#9289)
Jonny Burger13281b0f8254
diff --git a/packages/docs/copy-raw-docs.ts b/packages/docs/copy-raw-docs.tsindex 2c26856bbf..d9a8e6239b 100644--- a/packages/docs/copy-raw-docs.ts+++ b/packages/docs/copy-raw-docs.ts@@ -2,6 +2,7 @@ import fs from 'fs';import path from 'path';import {expandElementSourceReferences} from './plugins/element-source-utils.js';import {articles} from './src/data/articles';+import {expandRawMarkdownComponents} from './src/raw-markdown/replace-components';const DOCS_DIR = path.join(__dirname, 'docs');const ELEMENTS_DIR = path.join(__dirname, 'elements');@@ -21,7 +22,10 @@ const writeRawMarkdown = ({fs.mkdirSync(destDir, {recursive: true});}- const raw = fs.readFileSync(sourcePath, 'utf8');+ const raw = expandRawMarkdownComponents({+ raw: fs.readFileSync(sourcePath, 'utf8'),+ sourcePath,+ });fs.writeFileSync(destPath,expandElementSourceReferences({diff --git a/packages/docs/docs/studio/TableOfContents.tsx b/packages/docs/docs/studio/TableOfContents.tsxindex 007fa5eb3f..557d8739cd 100644--- a/packages/docs/docs/studio/TableOfContents.tsx+++ b/packages/docs/docs/studio/TableOfContents.tsx@@ -1,77 +1,28 @@import React from 'react';import {Grid} from '../../components/TableOfContents/Grid';import {TOCItem} from '../../components/TableOfContents/TOCItem';+import {studioTableOfContents} from './table-of-contents-data';++const renderDescription = (description: string) => {+ return description.split(/(`[^`]+`)/).map((part, index) => {+ if (part.startsWith('`') && part.endsWith('`')) {+ return <code key={index}>{part.slice(1, -1)}</code>;+ }++ return part;+ });+};export const TableOfContents: React.FC = () => {return (<div><Grid>- <TOCItem link="/docs/studio/get-static-files">- <strong>{'getStaticFiles()'}</strong>- <div>- Get a list of files in the <code>public</code> folder- </div>- </TOCItem>- <TOCItem link="/docs/studio/watch-public-folder">- <strong>{'watchPublicFolder()'}</strong>- <div>Listen to changes in the public folder</div>- </TOCItem>- <TOCItem link="/docs/studio/watch-static-file">- <strong>{'watchStaticFile()'}</strong>- <div>Listen to changes of a static file</div>- </TOCItem>- <TOCItem link="/docs/studio/write-static-file">- <strong>{'writeStaticFile()'}</strong>- <div>Save content to a file in the public directory</div>- </TOCItem>- <TOCItem link="/docs/studio/save-default-props">- <strong>{'saveDefaultProps()'}</strong>- <div>Save default props to the root file</div>- </TOCItem>- <TOCItem link="/docs/studio/update-default-props">- <strong>{'updateDefaultProps()'}</strong>- <div>Update default props in the Props editor</div>- </TOCItem>- <TOCItem link="/docs/studio/delete-static-file">- <strong>{'deleteStaticFile()'}</strong>- <div>Delete a file from the public directory</div>- </TOCItem>- <TOCItem link="/docs/studio/restart-studio">- <strong>{'restartStudio()'}</strong>- <div>Restart the Studio Server.</div>- </TOCItem>- <TOCItem link="/docs/studio/play">- <strong>{'play()'}</strong>- <div>Start playback in the timeline</div>- </TOCItem>- <TOCItem link="/docs/studio/pause">- <strong>{'pause()'}</strong>- <div>Pause playback in the timeline</div>- </TOCItem>- <TOCItem link="/docs/studio/toggle">- <strong>{'toggle()'}</strong>- <div>Toggle playback in the timeline</div>- </TOCItem>- <TOCItem link="/docs/studio/seek">- <strong>{'seek()'}</strong>- <div>Jump to a position in the timeline</div>- </TOCItem>- <TOCItem link="/docs/studio/go-to-composition">- <strong>{'goToComposition()'}</strong>- <div>Select a composition in the composition selector</div>- </TOCItem>- <TOCItem link="/docs/studio/focus-default-props-path">- <strong>{'focusDefaultPropsPath()'}</strong>- <div>Scrolls to a specific field in the default props editor</div>- </TOCItem>- <TOCItem link="/docs/studio/reevaluate-composition">- <strong>{'reevaluateComposition()'}</strong>- <div>Re-runs calculateMetadata() on the current composition</div>- </TOCItem>- <TOCItem link="/docs/studio/visual-control">- <strong>{'visualControl()'}</strong>- <div>Create a control in the right sidebar of the Studio</div>- </TOCItem>+ {studioTableOfContents.map((item) => (+ <TOCItem key={item.link} link={item.link}>+ <strong>{item.label}</strong>+ <div>{renderDescription(item.description)}</div>+ </TOCItem>+ ))}</Grid></div>);diff --git a/packages/docs/docs/studio/table-of-contents-data.ts b/packages/docs/docs/studio/table-of-contents-data.tsnew file mode 100644index 0000000000..9d6a7e4cc4--- /dev/null+++ b/packages/docs/docs/studio/table-of-contents-data.ts@@ -0,0 +1,82 @@+export const studioTableOfContents = [+ {+ link: '/docs/studio/get-static-files',+ label: 'getStaticFiles()',+ description: 'Get a list of files in the `public` folder',+ },+ {+ link: '/docs/studio/watch-public-folder',+ label: 'watchPublicFolder()',+ description: 'Listen to changes in the public folder',+ },+ {+ link: '/docs/studio/watch-static-file',+ label: 'watchStaticFile()',+ description: 'Listen to changes of a static file',+ },+ {+ link: '/docs/studio/write-static-file',+ label: 'writeStaticFile()',+ description: 'Save content to a file in the public directory',+ },+ {+ link: '/docs/studio/save-default-props',+ label: 'saveDefaultProps()',+ description: 'Save default props to the root file',+ },+ {+ link: '/docs/studio/update-default-props',+ label: 'updateDefaultProps()',+ description: 'Update default props in the Props editor',+ },+ {+ link: '/docs/studio/delete-static-file',+ label: 'deleteStaticFile()',+ description: 'Delete a file from the public directory',+ },+ {+ link: '/docs/studio/restart-studio',+ label: 'restartStudio()',+ description: 'Restart the Studio Server.',+ },+ {+ link: '/docs/studio/play',+ label: 'play()',+ description: 'Start playback in the timeline',+ },+ {+ link: '/docs/studio/pause',+ label: 'pause()',+ description: 'Pause playback in the timeline',+ },+ {+ link: '/docs/studio/toggle',+ label: 'toggle()',+ description: 'Toggle playback in the timeline',+ },+ {+ link: '/docs/studio/seek',+ label: 'seek()',+ description: 'Jump to a position in the timeline',+ },+ {+ link: '/docs/studio/go-to-composition',+ label: 'goToComposition()',+ description: 'Select a composition in the composition selector',+ },+ {+ link: '/docs/studio/focus-default-props-path',+ label: 'focusDefaultPropsPath()',+ description: 'Scrolls to a specific field in the default props editor',+ },+ {+ link: '/docs/studio/reevaluate-composition',+ label: 'reevaluateComposition()',+ description: 'Re-runs calculateMetadata() on the current composition',+ },+ {+ link: '/docs/studio/visual-control',+ label: 'visualControl()',+ description: 'Create a control in the right sidebar of the Studio',+ },+] as const;diff --git a/packages/docs/src/raw-markdown/replace-components.ts b/packages/docs/src/raw-markdown/replace-components.tsnew file mode 100644index 0000000000..d4202f3f2c--- /dev/null+++ b/packages/docs/src/raw-markdown/replace-components.ts@@ -0,0 +1,171 @@+import path from 'path';+import {VERSION} from 'remotion';+import {studioTableOfContents} from '../../docs/studio/table-of-contents-data';++export type RawMarkdownComponentReplacement = {+ readonly componentName: string;+ readonly render: (context: {+ readonly attributes: string;+ readonly sourcePath: string;+ }) => string | null;+ readonly appliesTo?: (sourcePath: string) => boolean;+ readonly removeImport?: RegExp;+ readonly required?: boolean;+};++const escapeRegExp = (value: string) => {+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+};++export const getStringAttribute = ({+ attributes,+ name,+}: {+ attributes: string;+ name: string;+}) => {+ const escapedName = escapeRegExp(name);+ const match = attributes.match(+ new RegExp(`(?:^|\\s)${escapedName}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`),+ );++ return match?.[1] ?? match?.[2] ?? null;+};++export const replaceRawMarkdownComponents = ({+ raw,+ sourcePath,+ replacements,+}: {+ raw: string;+ sourcePath: string;+ replacements: readonly RawMarkdownComponentReplacement[];+}) => {+ return replacements.reduce((currentRaw, replacement) => {+ if (replacement.appliesTo && !replacement.appliesTo(sourcePath)) {+ return currentRaw;+ }++ const componentPattern = new RegExp(+ `<${escapeRegExp(replacement.componentName)}\\b([^<>]*?)\\s*/>`,+ 'g',+ );+ let replacementCount = 0;+ const withMarkdown = currentRaw.replace(+ componentPattern,+ (fullMatch, attributes: string) => {+ const markdown = replacement.render({attributes, sourcePath});+ if (markdown === null) {+ return fullMatch;+ }++ replacementCount++;+ return markdown;+ },+ );++ if (replacement.required && replacementCount === 0) {+ throw new Error(+ `Could not expand <${replacement.componentName}> in ${sourcePath}`,+ );+ }++ if (!replacement.removeImport || replacementCount === 0) {+ return withMarkdown;+ }++ const withoutImport = withMarkdown.replace(replacement.removeImport, '');+ if (replacement.required && withoutImport === withMarkdown) {+ throw new Error(+ `Could not remove the <${replacement.componentName}> import in ${sourcePath}`,+ );+ }++ return withoutImport;+ }, raw);+};++const markdownTable = (+ items: readonly {+ link: string;+ label: string;+ description: string;+ }[],+) => {+ return [+ '| API | Description |',+ '| --- | --- |',+ ...items.map(+ (item) => `| [\`${item.label}\`](${item.link}) | ${item.description} |`,+ ),+ ].join('\n');+};++const getInstallationMarkdown = (pkg: string) => {+ const pkgList = pkg.split(' ');+ const allRemotionOnly = pkgList.every(+ (packageName) =>+ packageName.startsWith('@remotion/') || packageName === 'remotion',+ );+ const showRemotionCli =+ allRemotionOnly &&+ !pkgList.includes('remotion') &&+ !pkgList.includes('@remotion/cli');++ const command = showRemotionCli+ ? `npx remotion add ${pkg}`+ : `npm i --save-exact ${pkgList+ .map((packageName) => {+ if (+ packageName.startsWith('@remotion/') ||+ packageName === 'remotion'+ ) {+ return `${packageName}@${VERSION}`;+ }++ return packageName;+ })+ .join(' ')}`;++ return ['```bash', command, '```'].join('\n');+};++const studioApiPath = path.join('docs', 'studio', 'api.mdx');++const rawMarkdownComponentReplacements: readonly RawMarkdownComponentReplacement[] =+ [+ {+ componentName: 'Installation',+ render: ({attributes}) => {+ const pkg = getStringAttribute({attributes, name: 'pkg'});+ if (pkg === null) {+ throw new Error('The <Installation> component is missing a pkg prop');+ }++ return getInstallationMarkdown(pkg);+ },+ },+ {+ componentName: 'TableOfContents',+ appliesTo: (sourcePath) =>+ path.normalize(sourcePath).endsWith(studioApiPath),+ render: () => markdownTable(studioTableOfContents),+ removeImport:+ /^import\s+\{\s*TableOfContents\s*\}\s+from\s+['"]\.\/TableOfContents['"];\s*\n/m,+ required: true,+ },+ ];++export const expandRawMarkdownComponents = ({+ raw,+ sourcePath,+}: {+ raw: string;+ sourcePath: string;+}) => {+ return replaceRawMarkdownComponents({+ raw,+ sourcePath,+ replacements: rawMarkdownComponentReplacements,+ });+};diff --git a/packages/docs/src/test/replace-raw-markdown-components.test.ts b/packages/docs/src/test/replace-raw-markdown-components.test.tsnew file mode 100644index 0000000000..138d8ad064--- /dev/null+++ b/packages/docs/src/test/replace-raw-markdown-components.test.ts@@ -0,0 +1,49 @@+import {expect, test} from 'bun:test';+import {+ expandRawMarkdownComponents,+ getStringAttribute,+ replaceRawMarkdownComponents,+} from '../raw-markdown/replace-components';++test('supports registering additional component replacements', () => {+ const output = replaceRawMarkdownComponents({+ raw: 'Hello <User name="Mia" />!',+ sourcePath: '/docs/example.mdx',+ replacements: [+ {+ componentName: 'User',+ render: ({attributes}) =>+ `**${getStringAttribute({attributes, name: 'name'})}**`,+ },+ ],+ });++ expect(output).toBe('Hello **Mia**!');+});++test('replaces Installation with its default command', () => {+ const output = expandRawMarkdownComponents({+ raw: '<Installation pkg="@remotion/studio" />',+ sourcePath: '/docs/example.mdx',+ });++ expect(output).toBe(+ ['```bash', 'npx remotion add @remotion/studio', '```'].join('\n'),+ );+});++test('replaces the Studio table of contents and removes its import', () => {+ const output = expandRawMarkdownComponents({+ raw: [+ 'import { TableOfContents } from "./TableOfContents";',+ '',+ '<TableOfContents />',+ ].join('\n'),+ sourcePath: '/docs/studio/api.mdx',+ });++ expect(output).not.toContain('TableOfContents');+ expect(output).toContain(+ '| [`getStaticFiles()`](/docs/studio/get-static-files) |',+ );+});