Skip to content

Production-ready animations, transitions, backgrounds, and scenes for Remotion

13.0 KB
Raw Blame
{
  "type": "remotion-element",
  "version": 1,
  "element": {
    "assets": [],
    "dependencies": [
      {
        "name": "@remotion/google-fonts",
        "version": null
      }
    ],
    "dimensions": null,
    "displayName": "Whole Page",
    "initialProps": null,
    "slug": "whole-page",
    "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Gloock\";\nimport React, { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ComponentProps } from \"react\";\nimport { AbsoluteFill, Easing, Interactive, Sequence, continueRender, delayRender, interpolate, interpolateColors, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst gloock = loadFont(\"normal\", { weights: [\"400\"], subsets: [\"latin\"] });\n\ninterface WholePageProps {\n  beliefs?: string[];\n  title?: string;\n  accent?: string;\n  background?: string;\n  speed?: number;\n  theme?: \"dark\" | \"light\";\n}\n\nconst DEFAULT_BELIEFS = [\n  \"A launch video is part of the launch, not the chore you do after it.\",\n  \"If it lives in code, it can live in the repo with everything else.\",\n  \"Every frame you install is a file you are free to rewrite.\",\n  \"Motion should explain the product. It should never show off.\",\n  \"A team of one deserves a real film, too.\",\n  \"The video goes out the same day the product does.\",\n];\n\nconst THEMES = {\n  dark: { bg: \"#0A1230\", ink: \"#FFFFFF\", accent: \"#FF4436\" },\n  light: { bg: \"#F7F3EC\", ink: \"#14161F\", accent: \"#D92B1E\" },\n} as const;\n\nconst TRACK = -0.02;\nconst LH = 1.12;\nconst START = 6;\nconst PULL = 36;\nconst HOLD = 40;\nconst DIM = 0;\nconst EASE_OUT = Easing.bezier(0.22, 1, 0.36, 1);\nconst EASE_IO = Easing.bezier(0.65, 0, 0.35, 1);\nconst CLAMP = {\n  extrapolateLeft: \"clamp\",\n  extrapolateRight: \"clamp\",\n} as const;\n\nlet measureCtx: CanvasRenderingContext2D | null = null;\n\nfunction em(s: string): number {\n  if (!measureCtx) {\n    measureCtx = document.createElement(\"canvas\").getContext(\"2d\");\n  }\n  if (!measureCtx) return s.length * 0.5;\n  measureCtx.font = `400 100px \"${gloock.fontFamily}\"`;\n  return measureCtx.measureText(s).width / 100 + TRACK * Array.from(s).length;\n}\n\nfunction useFontReady() {\n  const [ready, setReady] = useState(false);\n  const [handle] = useState(() => delayRender(\"whole-page: font\"));\n  useEffect(() => {\n    let live = true;\n    gloock\n      .waitUntilDone()\n      .then(() => document.fonts.load(`400 100px \"${gloock.fontFamily}\"`))\n      .catch(() => undefined)\n      .then(() => {\n        if (!live) return;\n        setReady(true);\n        continueRender(handle);\n      });\n    return () => {\n      live = false;\n    };\n  }, [handle]);\n  return ready;\n}\n\ninterface Laid {\n  words: { text: string; x: number; line: number }[];\n  lines: number;\n}\n\nfunction wrapAt(words: string[], widths: number[], maxEm: number): Laid {\n  const space = em(\" \");\n  const out: { text: string; x: number; line: number }[] = [];\n  let line = 0;\n  let x = 0;\n  words.forEach((w, i) => {\n    if (x > 0 && x + widths[i] > maxEm) {\n      line += 1;\n      x = 0;\n    }\n    out.push({ text: w, x, line });\n    x += widths[i] + space;\n  });\n  return { words: out, lines: line + 1 };\n}\n\nfunction balanced(text: string, maxEm: number): Laid {\n  const words = text.split(/\\s+/).filter(Boolean);\n  const widths = words.map(em);\n  const base = wrapAt(words, widths, maxEm);\n  let lo = Math.max(...widths, 0.1);\n  let hi = maxEm;\n  for (let i = 0; i < 14; i++) {\n    const mid = (lo + hi) / 2;\n    if (wrapAt(words, widths, mid).lines <= base.lines) hi = mid;\n    else lo = mid;\n  }\n  return wrapAt(words, widths, hi);\n}\n\nfunction WholePageBase({\n  beliefs = DEFAULT_BELIEFS,\n  title = \"What we believe\",\n  accent,\n  background,\n  speed = 1,\n  theme = \"dark\",\n}: WholePageProps) {\n  const frame = useCurrentFrame();\n  const t = frame * speed;\n  const { width: W, height: H, durationInFrames } = useVideoConfig();\n  const c = THEMES[theme];\n  const hi = accent ?? c.accent;\n  const stage =\n    background === \"transparent\" ? \"transparent\" : (background ?? c.bg);\n  const ready = useFontReady();\n\n  if (!ready || beliefs.length === 0) {\n    return (\n      <div style={{ position: \"absolute\", inset: 0, background: stage }} />\n    );\n  }\n\n  const n = beliefs.length;\n  const portrait = H > W * 1.1;\n  const cols = Math.min(n, portrait ? 2 : 3);\n  const rows = Math.ceil(n / cols);\n  const mx = W * (portrait ? 0.08 : 0.07);\n  const top = H * (portrait ? 0.08 : 0.1);\n  const Ft = H * (portrait ? 0.022 : 0.04);\n  const gridTop = title ? top + Ft * 2.6 : top;\n  const gutter = W * (portrait ? 0.06 : 0.04);\n  const colW = (W - mx * 2 - gutter * (cols - 1)) / cols;\n  const gridH = H * (portrait ? 0.9 : 0.9) - gridTop;\n\n  const layoutAt = (F: number) => {\n    const lays = beliefs.map((b) => balanced(b, colW / F));\n    const rowLines = Array.from({ length: rows }, (_, r) =>\n      Math.max(...lays.slice(r * cols, r * cols + cols).map((l) => l.lines), 1),\n    );\n    const total =\n      rowLines.reduce((s, l) => s + l * LH * F, 0) + (rows - 1) * F * 1.1;\n    return { lays, rowLines, total };\n  };\n\n  const widestWord = Math.max(\n    ...beliefs.flatMap((b) => b.split(/\\s+/).map(em)),\n  );\n  const fits = (F: number) =>\n    layoutAt(F).total <= gridH && widestWord * F <= colW;\n  const orphaned = (F: number) =>\n    layoutAt(F).lays.some(\n      (l) =>\n        l.lines > 1 && l.words.filter((w) => w.line === l.lines - 1).length < 2,\n    );\n  let Fp = 0;\n  let firstFit = 0;\n  for (let F = H * 0.12; F > 6 && Fp === 0; F *= 0.985) {\n    if (!fits(F)) continue;\n    if (firstFit === 0) firstFit = F;\n    if (!orphaned(F) || F < firstFit * 0.9) Fp = F;\n  }\n  if (Fp === 0) Fp = firstFit || 6;\n  const { lays, rowLines } = layoutAt(Fp);\n  const rowTop: number[] = [];\n  let acc = gridTop;\n  for (let r = 0; r < rows; r++) {\n    rowTop.push(acc);\n    acc += rowLines[r] * LH * Fp + Fp * 1.1;\n  }\n  const slack = portrait ? Math.max(0, (H * 0.9 - (acc - Fp * 1.1)) / 2) : 0;\n  const paras = lays.map((l, i) => ({\n    x: mx + (i % cols) * (colW + gutter),\n    y: rowTop[Math.floor(i / cols)] + slack,\n    h: l.lines * LH * Fp,\n    lay: l,\n  }));\n  const zoomOf = paras.map((p) => {\n    const lineW = Math.max(...p.lay.words.map((w) => w.x + em(w.text)), 0.1);\n    return Math.max(\n      1,\n      Math.min(\n        (W - mx * 2) / (lineW * Fp),\n        (H * (portrait ? 0.6 : 0.78)) / p.h,\n        (H * (portrait ? 0.1 : 0.16)) / Fp,\n      ),\n    );\n  });\n  const ax = mx;\n  const ay = H * (portrait ? 0.1 : 0.1);\n\n  const D = durationInFrames * speed;\n  const per = Math.max(30, (D - START - PULL - HOLD) / n);\n  const pan = Math.min(16, per * 0.36);\n  const arriveAt = (i: number) => START + i * per;\n  const pullAt = START + n * per - 6;\n\n  let qx = paras[0].x;\n  let qy = paras[0].y;\n  let S = zoomOf[0];\n  for (let i = 1; i < n; i++) {\n    const p = interpolate(t, [arriveAt(i) - pan, arriveAt(i)], [0, 1], {\n      ...CLAMP,\n      easing: EASE_IO,\n    });\n    if (p > 0) {\n      qx = paras[i - 1].x + (paras[i].x - paras[i - 1].x) * p;\n      qy = paras[i - 1].y + (paras[i].y - paras[i - 1].y) * p;\n      S = zoomOf[i - 1] * (zoomOf[i] / zoomOf[i - 1]) ** p;\n    }\n  }\n  const pull = interpolate(t, [pullAt, pullAt + PULL], [0, 1], {\n    ...CLAMP,\n    easing: EASE_IO,\n  });\n  const z = S ** (1 - pull);\n  const zp = (S - z) / Math.max(0.0001, S - 1);\n  const cx = qx + (ax - qx) * zp;\n  const cy = qy + (ay - qy) * zp;\n  const tx = ax - cx * z;\n  const ty = ay - cy * z;\n\n  const intro = interpolate(t, [0, 18], [0, 1], {\n    ...CLAMP,\n    easing: EASE_OUT,\n  });\n  const settle = interpolate(pull, [0.35, 1], [0, 1], CLAMP);\n\n  const nodes: React.ReactNode[] = [];\n  paras.forEach((para, i) => {\n    const arrive = i === 0 ? START : arriveAt(i);\n    const leaveAt = arriveAt(i + 1) - pan;\n    const leave =\n      i < n - 1\n        ? interpolate(t, [leaveAt, leaveAt + pan * 0.55], [0, 1], {\n            ...CLAMP,\n            easing: Easing.bezier(0.55, 0, 1, 0.45),\n          })\n        : 0;\n    const isLast = i === n - 1;\n    const wordsN = para.lay.words.length;\n    const stagger = Math.min(1.6, 14 / Math.max(1, wordsN));\n    para.lay.words.forEach((w, wi) => {\n      const on = interpolate(\n        t,\n        [\n          arrive - pan * 0.5 + wi * stagger,\n          arrive - pan * 0.5 + 12 + wi * stagger,\n        ],\n        [0, 1],\n        { ...CLAMP, easing: EASE_OUT },\n      );\n      const focus = on * (1 - leave);\n      const read = t >= arrive - pan * 0.5 + 12 + wi * stagger ? 1 : 0;\n      const base = DIM + (1 - DIM) * focus;\n      const finalOp = read ? 1 : DIM;\n      const opacity = (base + (finalOp - base) * settle) * intro;\n      const color = isLast\n        ? interpolateColors(Math.max(focus, settle * read), [0, 1], [c.ink, hi])\n        : c.ink;\n      const rise = i === 0 ? (1 - intro) * Fp * 0.3 : 0;\n      nodes.push(\n        <div\n          key={`p${i}w${wi}`}\n          style={{\n            position: \"absolute\",\n            left: para.x + w.x * Fp,\n            top: para.y + w.line * LH * Fp + rise,\n            fontFamily: gloock.fontFamily,\n            fontWeight: 400,\n            fontSize: Fp,\n            lineHeight: `${LH * Fp}px`,\n            letterSpacing: `${TRACK}em`,\n            whiteSpace: \"pre\",\n            color,\n            opacity,\n          }}\n        >\n          {w.text}\n        </div>,\n      );\n    });\n  });\n\n  const titleOp = interpolate(pull, [0.4, 1], [0, 1], CLAMP);\n\n  return (\n    <AbsoluteFill style={{ background: stage, overflow: \"hidden\" }}>\n      <div\n        style={{\n          position: \"absolute\",\n          left: 0,\n          top: 0,\n          width: W,\n          height: H,\n          transformOrigin: \"0 0\",\n          transform: `translate(${tx.toFixed(2)}px, ${ty.toFixed(2)}px) scale(${z.toFixed(5)})`,\n        }}\n      >\n        {title ? (\n          <div\n            style={{\n              position: \"absolute\",\n              left: mx,\n              top: top + slack,\n              fontFamily: gloock.fontFamily,\n              fontWeight: 400,\n              fontSize: Ft,\n              lineHeight: 1,\n              letterSpacing: \"-0.01em\",\n              whiteSpace: \"pre\",\n              color: c.ink,\n              opacity: 0.6 * titleOp,\n            }}\n          >\n            {title}\n          </div>\n        ) : null}\n        {nodes}\n      </div>\n    </AbsoluteFill>\n  );\n}\n\nconst elementSchema = {\n  ...Interactive.baseSchema,\n  theme: {\n    type: \"enum\",\n    default: \"dark\",\n    variants: {\n      dark: {},\n      light: {},\n    },\n    description: \"Theme\",\n  },\n  title: {\n    type: \"text-content\",\n    default: \"What we believe\",\n    description: \"Title\",\n  },\n  speed: {\n    type: \"number\",\n    default: 1,\n    min: 0.25,\n    max: 4,\n    step: 0.25,\n    description: \"Speed\",\n    hiddenFromList: false,\n  },\n  ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"theme\",\"title\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n  theme: \"dark\",\n  title: \"What we believe\",\n  speed: 1,\n};\n\ntype WholePageElementProps = InteractiveBaseProps &\n  InteractiveTransformProps &\n  ComponentProps<typeof WholePageBase>;\n\nconst WholePageInner = forwardRef<\n  HTMLDivElement,\n  WholePageElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n  const outlineRef = useRef<HTMLDivElement>(null);\n  useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n  const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n  const sequenceProps: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(rest)) {\n    if (ELEMENT_PROP_KEYS.has(key)) {\n      if (value !== undefined) componentProps[key] = value;\n    } else {\n      sequenceProps[key] = value;\n    }\n  }\n  return (\n    <Sequence\n      layout=\"none\"\n      {...sequenceProps}\n      controls={controls}\n      name={name ?? \"<WholePage>\"}\n      outlineRef={outlineRef}\n    >\n      <div\n        ref={outlineRef}\n        style={{\n          position: \"relative\",\n          width: \"100%\",\n          height: \"100%\",\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          ...style,\n        }}\n      >\n        <WholePageBase\n          {...(componentProps as unknown as ComponentProps<typeof WholePageBase>)}\n        />\n      </div>\n    </Sequence>\n  );\n});\n\nexport const WholePage = Interactive.withSchema({\n  Component: WholePageInner,\n  componentName: \"<WholePage>\",\n  componentIdentity: null,\n  schema: elementSchema,\n  supportsEffects: false,\n});\n",
    "durationInFrames": 344,
    "installationMode": "component-owned-sequence"
  },
  "durationInFrames": 344
}