Production-ready animations, transitions, backgrounds, and scenes for Remotion
TypeScript ai-agentsclaude-codedemo-videomcpmcp-servermodel-context-protocolmotion-designproduct-demoreactremotionshadcnvideo
internal: demo video script
dev_wandryf57e26d669ed
diff --git a/package.json b/package.jsonindex 246ebb24..0b6f4c80 100644--- a/package.json+++ b/package.json@@ -11,6 +11,7 @@"registry:build": "shadcn build","remotion:browser": "bun scripts/ensure-browser.mts","bundle:remotion": "bun scripts/bundle-remotion.mts",+ "render:demos": "bun scripts/render-demos.mts","postinstall": "fumadocs-mdx"},"dependencies": {diff --git a/scripts/render-demos.mts b/scripts/render-demos.mtsnew file mode 100644index 00000000..0f578d62--- /dev/null+++ b/scripts/render-demos.mts@@ -0,0 +1,128 @@+import { mkdirSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { bundle } from "@remotion/bundler";+import {+ ensureBrowser,+ getCompositions,+ renderMedia,+} from "@remotion/renderer";+import { tsconfigWebpackAlias } from "./tsconfig-webpack-alias.mts";++/**+ * Render every docs example to an mp4 under `out/demos/`.+ *+ * Bundles `src/remotion/demos-entry.ts` once (which auto-declares one+ * composition per `examples` entry), then renders each sequentially — Remotion+ * already parallelises frames across Chromium tabs within a single render, so+ * running renders concurrently would only contend for CPU.+ *+ * Run:+ * bun run render:demos # all examples, one cycle each+ * bun run render:demos --only button-example+ * bun run render:demos --loops 3 # repeat each cycle 3×+ *+ * Concurrency (tabs per render) is env-tunable: REMOTION_CONCURRENCY (default 4).+ */++const here = path.dirname(fileURLToPath(import.meta.url));+const root = path.resolve(here, "..");++function getFlag(name: string): string | undefined {+ const i = process.argv.indexOf(`--${name}`);+ if (i !== -1 && i + 1 < process.argv.length) return process.argv[i + 1];+ const eq = process.argv.find((a) => a.startsWith(`--${name}=`));+ return eq ? eq.slice(name.length + 3) : undefined;+}++function remotionConcurrency(): number {+ const parsed = Number(process.env.REMOTION_CONCURRENCY);+ return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : 4;+}++async function main() {+ const only = getFlag("only");+ const loops = Math.max(1, Math.floor(Number(getFlag("loops") ?? "1")) || 1);++ const entryPoint = path.join(root, "src", "remotion", "demos-entry.ts");+ const outDir = path.join(root, "out", "demos");+ mkdirSync(outDir, { recursive: true });++ await ensureBrowser();++ // Webpack doesn't read tsconfig `paths`. The examples reach into the registry+ // via specific mappings (e.g. `@/lib/remocn-ui`, `@/components/remocn/use-*`),+ // not just the `@/*` catch-all, so translate the whole `paths` map to aliases.+ const tsAliases = tsconfigWebpackAlias(root);++ console.log("Bundling demos entry…");+ const serveUrl = await bundle({+ entryPoint,+ webpackOverride: (config) => {+ // Remotion's default alias is an object; fold it into the ordered array+ // form (first match wins) so our specific entries keep their precedence.+ const existing = Object.entries(config.resolve?.alias ?? {}).map(+ ([name, alias]) => ({+ name: name.replace(/\$$/, ""),+ alias: alias as string,+ onlyModule: name.endsWith("$"),+ }),+ );+ return {+ ...config,+ resolve: {+ ...config.resolve,+ alias: [...existing, ...tsAliases],+ },+ };+ },+ });+ console.log("Bundle ready.");++ const inputProps = { loops };+ let comps = await getCompositions(serveUrl, { inputProps });+ if (only) comps = comps.filter((c) => c.id === only);++ if (comps.length === 0) {+ console.error(+ only+ ? `No composition matched --only ${only}`+ : "No compositions found in the demos bundle",+ );+ process.exit(1);+ }++ const concurrency = remotionConcurrency();+ console.log(+ `Rendering ${comps.length} demo(s) → ${path.relative(root, outDir)} ` ++ `(loops=${loops}, concurrency=${concurrency})`,+ );++ let i = 0;+ for (const composition of comps) {+ i += 1;+ const name = composition.id.replace(/-example$/, "");+ const tag = `[${i}/${comps.length}] ${name}`;+ const outputLocation = path.join(outDir, `${name}.mp4`);++ await renderMedia({+ serveUrl,+ composition,+ codec: "h264",+ inputProps,+ outputLocation,+ concurrency,+ onProgress: ({ progress }) => {+ process.stdout.write(`\r${tag} ${Math.round(progress * 100)}% `);+ },+ });+ process.stdout.write(`\r${tag} ✓ \n`);+ }++ console.log(`Done. ${comps.length} file(s) in ${path.relative(root, outDir)}`);+}++main().catch((err) => {+ console.error("\nrender-demos failed:", err);+ process.exit(1);+});diff --git a/scripts/tsconfig-webpack-alias.mts b/scripts/tsconfig-webpack-alias.mtsnew file mode 100644index 00000000..f2f93dc8--- /dev/null+++ b/scripts/tsconfig-webpack-alias.mts@@ -0,0 +1,75 @@+import { readFileSync } from "node:fs";+import path from "node:path";++/**+ * Translate the project's `tsconfig.json` `compilerOptions.paths` into a webpack+ * `resolve.alias` ARRAY that the Remotion bundler (plain webpack — it doesn't+ * read tsconfig) can honour.+ *+ * Why this is needed: a flat `{ "@": root }` alias only covers the catch-all+ * `@/* → ./*`. The registry uses far more specific mappings — e.g.+ * "@/lib/remocn-ui" -> registry/remocn-ui/core/index.ts+ * "@/components/remocn/<name>" -> registry/remocn-ui/<name>/index.tsx+ * "@/components/remocn/use-button-transition" -> button/use-button-transition.ts+ * which a bare `@`-alias resolves to non-existent paths under `lib/`/`components/`.+ *+ * Webpack alias semantics we lean on:+ * - ARRAY form preserves order → first match wins, so we emit most-specific+ * first (exact mappings, then prefixes, longest name first, catch-all last).+ * - `onlyModule: true` ⇒ the request must equal `name` exactly (tsconfig's+ * no-wildcard keys); prefix entries rewrite `name/<rest>` → `target/<rest>`.+ * - A prefix that points at a directory (e.g. `@/components/remocn`) relies on+ * webpack's directory-index resolution to find `<dir>/<name>/index.tsx`.+ */++interface AliasItem {+ name: string;+ alias: string;+ onlyModule: boolean;+}++export function tsconfigWebpackAlias(root: string): AliasItem[] {+ const tsconfig = JSON.parse(+ readFileSync(path.join(root, "tsconfig.json"), "utf8"),+ );+ const paths: Record<string, string[]> =+ tsconfig.compilerOptions?.paths ?? {};+ const baseUrl: string = tsconfig.compilerOptions?.baseUrl ?? ".";+ const base = path.resolve(root, baseUrl);++ const exact: AliasItem[] = [];+ const prefix: AliasItem[] = [];++ for (const [key, targets] of Object.entries(paths)) {+ const target = targets[0];+ if (!target) continue;++ if (key.includes("*")) {+ // Wildcard key: map the literal segment before the `*` to the literal+ // segment of the target before ITS `*` (a directory we prefix-rewrite into).+ const name = key.slice(0, key.indexOf("*")).replace(/\/$/, "");+ const targetDir = target.slice(0, target.indexOf("*")).replace(/\/$/, "");+ prefix.push({+ name,+ alias: path.resolve(base, targetDir),+ onlyModule: false,+ });+ } else {+ // Exact key: resolve straight to the file.+ exact.push({+ name: key,+ alias: path.resolve(base, target),+ onlyModule: true,+ });+ }+ }++ const byNameLenDesc = (a: AliasItem, b: AliasItem) =>+ b.name.length - a.name.length;+ exact.sort(byNameLenDesc);+ prefix.sort(byNameLenDesc);++ // Exact before prefix; within each, longest name first. Catch-all `@` (from+ // `@/*`) is the shortest prefix, so it naturally lands last.+ return [...exact, ...prefix];+}diff --git a/src/remotion/demos-entry.ts b/src/remotion/demos-entry.tsnew file mode 100644index 00000000..48f1df2e--- /dev/null+++ b/src/remotion/demos-entry.ts@@ -0,0 +1,5 @@+// Bundler entry for the demos render script (scripts/render-demos.mts).+// Importing the root runs `registerRoot(DemosRoot)`. Kept separate from+// index.ts so the github-stars server bundle and the demos bundle don't collide+// (a bundle registers exactly one root). Side-effect-only by design.+import "./demos-root";diff --git a/src/remotion/demos-root.tsx b/src/remotion/demos-root.tsxnew file mode 100644index 00000000..5612380b--- /dev/null+++ b/src/remotion/demos-root.tsx@@ -0,0 +1,93 @@+import type { ComponentType } from "react";+import { loadFont } from "@remotion/google-fonts/Geist";+import { AbsoluteFill, Composition, Loop, registerRoot } from "remotion";+import { examples } from "@/components/docs/examples";+import { blockExamples } from "@/components/docs/examples/blocks";++/**+ * Every renderable scene: the ui-tier `examples` (keyed `<name>-example`) plus+ * the composition `blockExamples` (keyed `<name>-flow`). Key namespaces don't+ * overlap, and both records share the timing/scene shape this root consumes.+ */+const ALL_SCENES = { ...examples, ...blockExamples };++/**+ * Demos bundle root. Auto-declares one Remotion composition per docs example+ * (the `examples` record is the single source of truth for timing + scene), so+ * `scripts/render-demos.mts` can render every example to an mp4. Kept separate+ * from `Root.tsx`/`index.ts` (the github-stars server bundle) — that entry is+ * untouched; this one is bundled only by the demos render script.+ *+ * Two fidelity bridges make the mp4 match the on-site @remotion/player preview:+ * - white stage background (= `--card` light = the `.surface-card` the preview+ * sits on); self-painting scenes (e.g. blur-in) just cover it.+ * - Geist loaded via @remotion/google-fonts, exposed as `--font-geist-sans` so+ * the CSS var the scenes reference resolves to the real face (the site gets+ * this from next/font, which doesn't exist in a standalone Remotion bundle).+ */++const { fontFamily: GEIST } = loadFont();++interface StageProps {+ // Remotion requires composition props to extend Record<string, unknown>.+ [key: string]: unknown;+ /** One animation cycle, in frames (from the example's `durationInFrames`). */+ loopFrames: number;+ /** Repeat the cycle this many times (CLI `--loops`, default 1). */+ loops: number;+}++/**+ * Bind each example's scene at bundle time via closure — components are not+ * JSON-serializable, so they can't ride through `defaultProps`/`inputProps`.+ * Only the numeric loop knobs cross that boundary.+ */+function makeStage(Example: ComponentType) {+ return function DemoStage({ loopFrames }: StageProps) {+ return (+ <AbsoluteFill+ style={{+ backgroundColor: "#ffffff",+ ["--font-geist-sans" as string]: GEIST,+ fontFamily: GEIST,+ }}+ >+ <Loop durationInFrames={loopFrames}>+ <Example />+ </Loop>+ </AbsoluteFill>+ );+ };+}++// Stable component reference per composition (don't re-create inside render).+const STAGES: Record<string, ReturnType<typeof makeStage>> = Object.fromEntries(+ Object.entries(ALL_SCENES).map(([id, entry]) => [+ id,+ makeStage(entry.Component),+ ]),+);++export function DemosRoot() {+ return (+ <>+ {Object.entries(ALL_SCENES).map(([id, entry]) => (+ <Composition+ key={id}+ id={id}+ component={STAGES[id]}+ durationInFrames={entry.durationInFrames}+ fps={entry.fps}+ width={entry.width}+ height={entry.height}+ defaultProps={{ loopFrames: entry.durationInFrames, loops: 1 }}+ calculateMetadata={({ props }) => ({+ durationInFrames: props.loopFrames * Math.max(1, props.loops),+ })}+ />+ ))}+ </>+ );+}++registerRoot(DemosRoot);