Remotion LabRemotion Lab
參數化影片Schema 驗證

Schema 驗證

用 Zod Schema 為影片 Props 定義型別和驗證規則。

為什麼需要 Schema?

當你定義了影片的 Props,你會希望:

  • Studio 能自動產生 UI 控制項
  • 從 CLI 或 API 傳入的 Props 被正確驗證
  • TypeScript 型別自動推導

Zod Schema 同時解決這三個問題。

安裝 Zod

npm install zod

定義 Schema

import { z } from "zod";
 
export const myVideoSchema = z.object({
  title: z.string().describe("影片標題"),
  subtitle: z.string().optional().describe("副標題"),
  backgroundColor: z.string().describe("背景顏色"),
  fontSize: z.number().min(12).max(200).describe("字體大小"),
  showLogo: z.boolean().describe("顯示 Logo"),
  theme: z.enum(["light", "dark"]).describe("主題"),
});
 
type MyVideoProps = z.infer<typeof myVideoSchema>;

在 Composition 中使用

<Composition
  id="MyVideo"
  component={MyVideo}
  durationInFrames={90}
  fps={30}
  width={1920}
  height={1080}
  schema={myVideoSchema}
  defaultProps={{
    title: "預設標題",
    backgroundColor: "#0f0f1a",
    fontSize: 72,
    showLogo: true,
    theme: "dark",
  }}
/>

Studio UI 自動產生

定義 Schema 後,Remotion Studio 會根據型別自動產生對應的控制項:

Zod 型別Studio 控制項
z.string()文字輸入框
z.number()數字輸入框(含滑桿)
z.boolean()開關
z.enum([...])下拉選單
z.string().optional()文字輸入框(可清空)
z.array(z.string())可新增/刪除的列表

.describe("...") 的文字會顯示為欄位標籤。

進階型別

顏色選擇器

import { zColor } from "@remotion/zod-types";
 
const schema = z.object({
  color: zColor().describe("主題顏色"),
});

zColor() 會在 Studio 中顯示顏色選擇器。

巢狀物件

const schema = z.object({
  header: z.object({
    title: z.string(),
    subtitle: z.string(),
  }),
  style: z.object({
    color: z.string(),
    fontSize: z.number(),
  }),
});

Studio 會以摺疊區塊顯示巢狀物件。

陣列

const schema = z.object({
  items: z.array(
    z.object({
      label: z.string(),
      value: z.number(),
    })
  ),
});

Studio 會提供新增和刪除項目的介面。

驗證錯誤

如果從 CLI 傳入的 Props 不符合 Schema,Remotion 會直接報錯並顯示哪個欄位有問題:

# 這會報錯,因為 fontSize 超出範圍
npx remotion render MyVideo out/video.mp4 \
  --props='{"title": "test", "fontSize": 999}'

小結

  • 用 Zod 定義 Schema 可以同時獲得型別安全、UI 產生和驗證
  • Studio 會根據 Zod 型別自動產生對應的控制項
  • .describe() 設定 Studio 中顯示的標籤
  • zColor() 等特殊型別可以產生進階 UI