π₯ Make videos programmatically with React
Elements: Add visual library (#9821)
Igor Samokhovets5f648fa36a1b
diff --git a/.agents/skills/publish-element/SKILL.md b/.agents/skills/publish-element/SKILL.mdindex 5f942f314e..7594cbb164 100644--- a/.agents/skills/publish-element/SKILL.md+++ b/.agents/skills/publish-element/SKILL.md@@ -36,10 +36,12 @@ If the Element imports a package that is not available to `packages/docs`, add i## 3. Add it to the gallery-- Add the Element page to `packages/docs/elements/<category>/index.mdx`.+- Confirm that the entry in `packages/docs/src/components/Elements/element-definitions.ts` places the Element in the generated overview and category library.- Add `'<category>/<slug>/index'` to the matching category in `packages/docs/elements-sidebars.ts`.-Preserve the ordering used by the category page and sidebar. If the task explicitly introduces a new category, create its category index and sidebar group as part of this step.+Preserve the ordering used by the sidebar. Do not add a manual link to the category index: the visual and raw Markdown libraries are generated from the central definitions. If the task explicitly introduces a new category, create an index that renders the filtered `ElementLibrary` and add its sidebar group as part of this step.++Before considering gallery registration complete, verify that the Element appears on the overview page, its category page, and the generated raw Markdown routes.Do not edit `packages/docs/src/remotion/Root.tsx`; Element compositions are derived from the central definitions.@@ -102,4 +104,4 @@ git diff --checkgit status --short```-Before finishing, verify that the page is listed in its category and sidebar, all checks pass, and only intended files are part of the change. Report the commands run, their results, and the preview files inspected.+Before finishing, verify that the page is listed in the generated overview and category library, the generated raw Markdown, and the sidebar; all checks pass; and only intended files are part of the change. Report the commands run, their results, and the preview files inspected.diff --git a/packages/docs/elements/backgrounds/index.mdx b/packages/docs/elements/backgrounds/index.mdxindex c6deb3483e..699e09c4b1 100644--- a/packages/docs/elements/backgrounds/index.mdx+++ b/packages/docs/elements/backgrounds/index.mdx@@ -3,11 +3,8 @@ title: Backgroundsdescription: Drop-in background Elements for Remotion videos.----# Backgrounds+import {ElementLibrary} from '@site/src/components/Elements/ElementLibrary';-Elements:+# Backgrounds-- [Liquid contours](/elements/backgrounds/liquid-contours/)-- [Notebook paper](/elements/backgrounds/notebook-paper/)-- [Paper texture](/elements/backgrounds/paper-texture/)-- [Rotating starburst](/elements/backgrounds/rotating-starburst/)+<ElementLibrary category="backgrounds" />diff --git a/packages/docs/elements/data/index.mdx b/packages/docs/elements/data/index.mdxindex f64ff6cc25..3dc6362948 100644--- a/packages/docs/elements/data/index.mdx+++ b/packages/docs/elements/data/index.mdx@@ -3,10 +3,8 @@ title: Datadescription: Animated data visualization Elements for Remotion videos.----# Data+import {ElementLibrary} from '@site/src/components/Elements/ElementLibrary';-Elements:+# Data-- [Horizontal Bar Chart](/elements/data/horizontal-bar-chart/)-- [Number Counter](/elements/data/number-counter/)-- [Product Offer](/elements/data/product-offer/)+<ElementLibrary category="data" />diff --git a/packages/docs/elements/index.mdx b/packages/docs/elements/index.mdxindex 4d7f1bb25f..ed50bf8766 100644--- a/packages/docs/elements/index.mdx+++ b/packages/docs/elements/index.mdx@@ -4,6 +4,8 @@ sidebar_label: Overviewdescription: Drop-in, remixable video building blocks for Remotion.---+import {ElementLibrary} from '@site/src/components/Elements/ElementLibrary';+# Remotion Elements:::warning Work in progress@@ -16,7 +18,9 @@ Remotion Elements are drop-in, HTML-first Remotion components designed to be plaThey are practical video building blocks: captions, lower thirds, overlays, callouts, transitions, data cards, audio visuals, and title cards.-Browse the categories in the sidebar to find an Element for your project.+Browse the library to find an Element for your project.++<ElementLibrary category={null} />To learn what makes a useful, portable Element, read the [Element Guidelines](/elements/guidelines).diff --git a/packages/docs/elements/overlays/index.mdx b/packages/docs/elements/overlays/index.mdxindex 73b0de0804..d1582fb482 100644--- a/packages/docs/elements/overlays/index.mdx+++ b/packages/docs/elements/overlays/index.mdx@@ -3,9 +3,8 @@ title: Overlaysdescription: Drop-in overlay Elements for Remotion videos.----# Overlays+import {ElementLibrary} from '@site/src/components/Elements/ElementLibrary';-Elements:+# Overlays-- [Location Lower Third](/elements/overlays/location-lower-third/)-- [Name Lower Third](/elements/overlays/lower-third/)+<ElementLibrary category="overlays" />diff --git a/packages/docs/elements/text/index.mdx b/packages/docs/elements/text/index.mdxindex f530057902..e5e8165e50 100644--- a/packages/docs/elements/text/index.mdx+++ b/packages/docs/elements/text/index.mdx@@ -3,13 +3,8 @@ title: Textdescription: Drop-in text Elements for Remotion videos.----# Text+import {ElementLibrary} from '@site/src/components/Elements/ElementLibrary';-Elements:+# Text-- [Circle Marker](/elements/text/circle-marker/)-- [Crossed Off](/elements/text/crossed-off/)-- [News Article Headline Highlight](/elements/text/news-article-headline-highlight/)-- [Strike Through](/elements/text/strike-through/)-- [Text Marker](/elements/text/text-marker/)-- [Timed Captions](/elements/text/timed-captions/)+<ElementLibrary category="text" />diff --git a/packages/docs/src/components/Elements/ElementLibrary.module.css b/packages/docs/src/components/Elements/ElementLibrary.module.cssnew file mode 100644index 0000000000..e6e6b710a2--- /dev/null+++ b/packages/docs/src/components/Elements/ElementLibrary.module.css@@ -0,0 +1,120 @@+.library {+ container: element-library / inline-size;+ margin-top: 32px;+}++.section + .section {+ margin-top: 48px;+}++.categoryTitle {+ margin: 0 0 20px;+ font-weight: 500;+ text-wrap: balance;+}++.grid {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: 16px;+ margin: 0;+ padding: 0;+ list-style: none;+}++.cardItem {+ min-width: 0;+}++.library .card {+ display: flex;+ height: 100%;+ min-width: 0;+ flex-direction: column;+ overflow: hidden;+ border: 1px solid var(--ifm-color-emphasis-300);+ border-radius: min(3vw, 12px);+ background: var(--ifm-background-surface-color);+ color: var(--ifm-font-color-base);+ text-decoration: none;+}++.library .card:hover {+ border-color: var(--ifm-color-primary);+ color: var(--ifm-font-color-base);+ text-decoration: none;+}++.library .card:focus-visible {+ outline: 2px solid var(--ifm-color-primary);+ outline-offset: 2px;+ text-decoration: none;+}++.preview {+ position: relative;+ aspect-ratio: 16 / 9;+ overflow: hidden;+}++.previewMedia {+ position: absolute;+ inset: 0;+ display: block;+ width: 100%;+ height: 100%;+ object-fit: contain;+ object-position: center;+}++.content {+ min-width: 0;+ padding: 18px;+}++.title {+ margin: 0;+ font-size: 1.125rem;+ font-weight: 500;+ text-wrap: balance;+}++.description {+ margin: 10px 0 0;+ color: var(--ifm-color-emphasis-800);+ font-size: 1rem;+ line-height: 1.6;+ text-wrap: pretty;+}++.card:hover .title {+ color: var(--ifm-color-primary);+}++@container element-library (min-width: 600px) {+ .grid {+ grid-template-columns: repeat(auto-fit, minmax(270px, 1fr));+ gap: 24px;+ }++ .content {+ padding: 16px;+ }++ .title {+ font-size: 1rem;+ }++ .description {+ font-size: 0.9375rem;+ }+}++@container element-library (min-width: 900px) {+ .grid {+ grid-template-columns: repeat(+ auto-fit,+ minmax(calc((100% - 48px) / 3), 1fr)+ );+ }+}diff --git a/packages/docs/src/components/Elements/ElementLibrary.tsx b/packages/docs/src/components/Elements/ElementLibrary.tsxnew file mode 100644index 0000000000..9a7e6070c8--- /dev/null+++ b/packages/docs/src/components/Elements/ElementLibrary.tsx@@ -0,0 +1,192 @@+import React, {useEffect, useRef, useState} from 'react';+import type {ElementDefinition} from './element-definitions';+import {+ getElementDocumentationUrl,+ getElementLibrarySections,+ type ElementCategory,+} from './element-library-data';+import {ELEMENT_PREVIEW_BACKGROUND} from './ElementPreviewComposition';+import styles from './ElementLibrary.module.css';++const reducedMotionQuery = '(prefers-reduced-motion: reduce)';++const usePrefersReducedMotion = () => {+ const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);++ useEffect(() => {+ const mediaQuery = window.matchMedia(reducedMotionQuery);+ const updatePreference = () => {+ setPrefersReducedMotion(mediaQuery.matches);+ };++ updatePreference();+ mediaQuery.addEventListener('change', updatePreference);++ return () => {+ mediaQuery.removeEventListener('change', updatePreference);+ };+ }, []);++ return prefersReducedMotion;+};++const ElementCard: React.FC<{+ readonly definition: ElementDefinition;+ readonly headingLevel: 2 | 3;+ readonly prefersReducedMotion: boolean;+}> = ({definition, headingLevel, prefersReducedMotion}) => {+ const [isFocused, setIsFocused] = useState(false);+ const [isPointerOver, setIsPointerOver] = useState(false);+ const [playbackFailed, setPlaybackFailed] = useState(false);+ const videoRef = useRef<HTMLVideoElement>(null);+ const shouldPlay =+ !prefersReducedMotion && !playbackFailed && (isFocused || isPointerOver);+ const Heading = headingLevel === 2 ? 'h2' : 'h3';++ useEffect(() => {+ const video = videoRef.current;+ if (!video) {+ return;+ }++ let canceled = false;+ video.currentTime = 0;+ video.play().catch(() => {+ if (!canceled) {+ setPlaybackFailed(true);+ }+ });++ return () => {+ canceled = true;+ video.pause();+ video.currentTime = 0;+ };+ }, [shouldPlay]);++ const activateFromPointer = (+ event: React.PointerEvent<HTMLAnchorElement>,+ ) => {+ if (event.pointerType === 'touch') {+ return;+ }++ setPlaybackFailed(false);+ setIsPointerOver(true);+ };++ return (+ <li className={styles.cardItem}>+ <a+ className={styles.card}+ href={getElementDocumentationUrl(definition)}+ onBlur={() => setIsFocused(false)}+ onFocus={() => {+ setPlaybackFailed(false);+ setIsFocused(true);+ }}+ onPointerEnter={activateFromPointer}+ onPointerLeave={() => setIsPointerOver(false)}+ >+ <div+ aria-hidden="true"+ className={styles.preview}+ style={{backgroundColor: ELEMENT_PREVIEW_BACKGROUND}}+ >+ <img+ alt=""+ className={styles.previewMedia}+ decoding="async"+ loading="lazy"+ src={definition.preview.posterUrl}+ />+ {shouldPlay ? (+ <video+ ref={videoRef}+ aria-hidden="true"+ className={styles.previewMedia}+ loop+ muted+ onError={() => setPlaybackFailed(true)}+ playsInline+ poster={definition.preview.posterUrl}+ preload="metadata"+ src={definition.preview.videoUrl}+ />+ ) : null}+ </div>+ <div className={styles.content}>+ <Heading className={styles.title}>{definition.displayName}</Heading>+ <p className={styles.description}>{definition.description}</p>+ </div>+ </a>+ </li>+ );+};++const ElementGrid: React.FC<{+ readonly definitions: readonly ElementDefinition[];+ readonly headingLevel: 2 | 3;+ readonly prefersReducedMotion: boolean;+}> = ({definitions, headingLevel, prefersReducedMotion}) => {+ return (+ <ul className={styles.grid} role="list">+ {definitions.map((definition) => (+ <ElementCard+ key={definition.slug}+ definition={definition}+ headingLevel={headingLevel}+ prefersReducedMotion={prefersReducedMotion}+ />+ ))}+ </ul>+ );+};++export const ElementLibrary: React.FC<{+ readonly category: ElementCategory | null;+}> = ({category}) => {+ const sections = getElementLibrarySections(category);+ const prefersReducedMotion = usePrefersReducedMotion();++ return (+ <div className={styles.library}>+ {sections.map((section) => {+ if (category !== null) {+ return (+ <section+ key={section.category}+ aria-label={`${section.label} Elements`}+ className={styles.section}+ >+ <ElementGrid+ definitions={section.definitions}+ headingLevel={2}+ prefersReducedMotion={prefersReducedMotion}+ />+ </section>+ );+ }++ const categoryHeadingId = `element-category-${section.category}`;++ return (+ <section+ key={section.category}+ aria-labelledby={categoryHeadingId}+ className={styles.section}+ >+ <h2 className={styles.categoryTitle} id={categoryHeadingId}>+ {section.label}+ </h2>+ <ElementGrid+ definitions={section.definitions}+ headingLevel={3}+ prefersReducedMotion={prefersReducedMotion}+ />+ </section>+ );+ })}+ </div>+ );+};diff --git a/packages/docs/src/components/Elements/element-library-data.ts b/packages/docs/src/components/Elements/element-library-data.tsnew file mode 100644index 0000000000..c6bc973e6c--- /dev/null+++ b/packages/docs/src/components/Elements/element-library-data.ts@@ -0,0 +1,63 @@+import {+ elementDefinitions,+ type ElementDefinition,+} from './element-definitions';++type RegisteredElementDefinition =+ (typeof elementDefinitions)[keyof typeof elementDefinitions];++export type ElementCategory = RegisteredElementDefinition['category'];++export type ElementLibrarySection = {+ readonly category: ElementCategory;+ readonly definitions: readonly ElementDefinition[];+ readonly label: string;+};++const compareStrings = (a: string, b: string) => {+ if (a < b) {+ return -1;+ }++ if (a > b) {+ return 1;+ }++ return 0;+};++const elementCategories = Array.from(+ new Set(Object.values(elementDefinitions).map(({category}) => category)),+).sort(compareStrings) as ElementCategory[];++export const getElementCategoryLabel = (category: ElementCategory) => {+ return category+ .split('-')+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(' ');+};++export const isElementCategory = (+ category: string,+): category is ElementCategory => {+ return (elementCategories as readonly string[]).includes(category);+};++export const getElementLibrarySections = (+ category: ElementCategory | null,+): readonly ElementLibrarySection[] => {+ const categories = category === null ? elementCategories : [category];+ const definitions = Object.values(elementDefinitions);++ return categories.map((currentCategory) => ({+ category: currentCategory,+ definitions: definitions+ .filter((definition) => definition.category === currentCategory)+ .sort((a, b) => compareStrings(a.displayName, b.displayName)),+ label: getElementCategoryLabel(currentCategory),+ }));+};++export const getElementDocumentationUrl = (definition: ElementDefinition) => {+ return `/elements/${definition.slug}/` as const;+};diff --git a/packages/docs/src/raw-markdown/replace-components.ts b/packages/docs/src/raw-markdown/replace-components.tsindex d4202f3f2c..522b9a3b66 100644--- a/packages/docs/src/raw-markdown/replace-components.ts+++ b/packages/docs/src/raw-markdown/replace-components.ts@@ -1,6 +1,12 @@import path from 'path';import {VERSION} from 'remotion';import {studioTableOfContents} from '../../docs/studio/table-of-contents-data';+import {+ getElementDocumentationUrl,+ getElementLibrarySections,+ isElementCategory,+ type ElementCategory,+} from '../components/Elements/element-library-data';export type RawMarkdownComponentReplacement = {readonly componentName: string;@@ -132,8 +138,49 @@ const getInstallationMarkdown = (pkg: string) => {const studioApiPath = path.join('docs', 'studio', 'api.mdx');+const renderElementLibraryMarkdown = (attributes: string) => {+ const categoryAttribute = getStringAttribute({+ attributes,+ name: 'category',+ });+ let category: ElementCategory | null;++ if (categoryAttribute !== null) {+ if (!isElementCategory(categoryAttribute)) {+ throw new Error(`Invalid Element category: ${categoryAttribute}`);+ }++ category = categoryAttribute;+ } else if (/(?:^|\s)category\s*=\s*\{\s*null\s*\}/.test(attributes)) {+ category = null;+ } else {+ throw new Error(+ 'The <ElementLibrary> component is missing a category prop',+ );+ }++ return getElementLibrarySections(category)+ .map((section) => {+ const list = section.definitions+ .map(+ (definition) =>+ `- [${definition.displayName}](${getElementDocumentationUrl(definition)}) β ${definition.description}`,+ )+ .join('\n');++ return category === null ? `## ${section.label}\n\n${list}` : list;+ })+ .join('\n\n');+};+const rawMarkdownComponentReplacements: readonly RawMarkdownComponentReplacement[] =[+ {+ componentName: 'ElementLibrary',+ render: ({attributes}) => renderElementLibraryMarkdown(attributes),+ removeImport:+ /^import\s+\{\s*ElementLibrary\s*\}\s+from\s+['"]@site\/src\/components\/Elements\/ElementLibrary['"];?\s*\n/m,+ },{componentName: 'Installation',render: ({attributes}) => {diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.tsindex bc828bfe66..927cf9be41 100644--- a/packages/docs/src/test/elements.test.ts+++ b/packages/docs/src/test/elements.test.ts@@ -1,16 +1,23 @@import {describe, expect, test} from 'bun:test';import {existsSync, readdirSync, readFileSync, statSync} from 'fs';import path from 'path';+import React from 'react';+import {renderToStaticMarkup} from 'react-dom/server';import {expandElementSourceReferences,getRemotionElementDependencies,} from '../../plugins/element-source-utils';import remarkElementSource from '../../plugins/remark-element-source';import {elementDefinitions} from '../components/Elements/element-definitions';+import {+ getElementDocumentationUrl,+ getElementLibrarySections,+} from '../components/Elements/element-library-data';import {getElementCompositionId,getElementDimensionsLabel,} from '../components/Elements/element-utils';+import {ElementLibrary} from '../components/Elements/ElementLibrary';import {getElementPreviewDimensions} from '../components/Elements/ElementPreviewComposition';const elementsRoot = path.join(__dirname, '..', '..', 'elements');@@ -202,6 +209,51 @@ describe('Elements must follow the colocated single-file format', () => {}});+describe('Element library', () => {+ test('renders every definition and filters the real category entry points', () => {+ const overviewMarkup = renderToStaticMarkup(+ React.createElement(ElementLibrary, {category: null}),+ );+ const sections = getElementLibrarySections(null);++ for (const definition of elementDefinitionList) {+ expect(+ overviewMarkup.split(`>${definition.displayName}</h3>`),+ ).toHaveLength(2);+ expect(overviewMarkup).toContain(definition.description);+ expect(overviewMarkup).toContain(definition.preview.posterUrl);+ expect(overviewMarkup).toContain(getElementDocumentationUrl(definition));+ }++ expect(overviewMarkup).not.toContain('.mp4');++ for (const section of sections) {+ const categoryMarkup = renderToStaticMarkup(+ React.createElement(ElementLibrary, {category: section.category}),+ );+ const categoryIndex = readFileSync(+ path.join(elementsRoot, section.category, 'index.mdx'),+ 'utf8',+ );++ expect(categoryIndex).toContain(+ `<ElementLibrary category="${section.category}" />`,+ );++ for (const definition of elementDefinitionList) {+ if (definition.category === section.category) {+ expect(categoryMarkup).toContain(definition.displayName);+ expect(categoryMarkup).toContain(+ getElementDocumentationUrl(definition),+ );+ } else {+ expect(categoryMarkup).not.toContain(definition.displayName);+ }+ }+ }+ });+});+describe('Element preview definitions', () => {test('contains every production Element exactly once', () => {const elementSlugs = productionElementsdiff --git a/packages/docs/src/test/replace-raw-markdown-components.test.ts b/packages/docs/src/test/replace-raw-markdown-components.test.tsindex 138d8ad064..2eb69c990f 100644--- a/packages/docs/src/test/replace-raw-markdown-components.test.ts+++ b/packages/docs/src/test/replace-raw-markdown-components.test.ts@@ -1,4 +1,11 @@import {expect, test} from 'bun:test';+import {readFileSync} from 'fs';+import path from 'path';+import {elementDefinitions} from '../components/Elements/element-definitions';+import {+ getElementDocumentationUrl,+ getElementLibrarySections,+} from '../components/Elements/element-library-data';import {expandRawMarkdownComponents,getStringAttribute,@@ -21,6 +28,64 @@ test('supports registering additional component replacements', () => {expect(output).toBe('Hello **Mia**!');});+test('expands the actual Element overview into categorized Markdown', () => {+ const sourcePath = path.join(__dirname, '..', '..', 'elements', 'index.mdx');+ const output = expandRawMarkdownComponents({+ raw: readFileSync(sourcePath, 'utf8'),+ sourcePath,+ });++ expect(output).not.toContain('ElementLibrary');+ for (const section of getElementLibrarySections(null)) {+ expect(output).toContain(`## ${section.label}`);+ }++ for (const definition of Object.values(elementDefinitions)) {+ expect(output).toContain(+ `[${definition.displayName}](${getElementDocumentationUrl(definition)})`,+ );+ expect(output).toContain(definition.description);+ }+});++test('expands the actual Element category indexes without unrelated entries', () => {+ const sections = getElementLibrarySections(null);++ for (const section of sections) {+ const sourcePath = path.join(+ __dirname,+ '..',+ '..',+ 'elements',+ section.category,+ 'index.mdx',+ );+ const output = expandRawMarkdownComponents({+ raw: readFileSync(sourcePath, 'utf8'),+ sourcePath,+ });++ expect(output).not.toContain('ElementLibrary');+ for (const definition of Object.values(elementDefinitions)) {+ const elementLink = `[${definition.displayName}](${getElementDocumentationUrl(definition)})`;+ if (definition.category === section.category) {+ expect(output).toContain(elementLink);+ } else {+ expect(output).not.toContain(elementLink);+ }+ }+ }+});++test('rejects an invalid Element category in raw Markdown', () => {+ expect(() =>+ expandRawMarkdownComponents({+ raw: '<ElementLibrary category="invalid" />',+ sourcePath: '/elements/invalid/index.mdx',+ }),+ ).toThrow('Invalid Element category: invalid');+});+test('replaces Installation with its default command', () => {const output = expandRawMarkdownComponents({raw: '<Installation pkg="@remotion/studio" />',