Skip to content

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

12.5 KB
Raw Blame
{
  "type": "remotion-element",
  "version": 1,
  "element": {
    "assets": [],
    "dependencies": [],
    "dimensions": null,
    "displayName": "Inline Word Roll",
    "initialProps": null,
    "slug": "inline-word-roll",
    "sourceCode": "import { forwardRef, useImperativeHandle, useLayoutEffect, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, useCurrentFrame, useDelayRender, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ninterface InlineWordRollProps {\n  prefix?: string;\n  /** Separate words or phrases with | or newlines. */\n  text?: string;\n  suffix?: string;\n  fontSize?: number;\n  fontFamily?: string;\n  fontWeight?: number;\n  color?: string;\n  /** Initial interval between switches, in frames. */\n  interval?: number;\n  /** Each following interval is multiplied by this number; 1 keeps a steady pace. */\n  acceleration?: number;\n  transitionFrames?: number;\n}\n\nconst inlineWordRollDefaultText =\n  \"leads | customers | subscribers | appointments | demos | quotes | registrants | trials | conversions\";\n\nconst parseInlineWords = (text: string) =>\n  text\n    .split(/[|\\n\\r]+/)\n    .map((word) => word.trim())\n    .filter(Boolean);\n\nconst finite = (value: number, fallback: number) =>\n  Number.isFinite(value) ? value : fallback;\nconst clamp = (n: number) => Math.max(0, Math.min(1, n));\nconst ease = Easing.bezier(0.22, 0.75, 0.25, 1);\n\nfunction getInlineWordRollState(\n  frame: number,\n  count: number,\n  interval = 12,\n  acceleration = 0.9,\n  transitionFrames = 6,\n) {\n  const transition = Math.max(1, finite(transitionFrames, 6));\n  const gap = Math.max(transition, finite(interval, 12));\n  const rate = Math.min(1, Math.max(0.5, finite(acceleration, 0.9)));\n  const f = Math.max(0, finite(frame, 0));\n  let start = 0;\n  for (let index = 1; index < count; index++) {\n    start += Math.max(transition, gap * rate ** (index - 1));\n    if (f < start) return { from: index - 1, to: index - 1, progress: 1 };\n    if (f < start + transition)\n      return {\n        from: index - 1,\n        to: index,\n        progress: clamp((f - start) / transition),\n      };\n  }\n  const last = Math.max(0, count - 1);\n  return { from: last, to: last, progress: 1 };\n}\n\nfunction getInlineWordRollDuration({\n  text = inlineWordRollDefaultText,\n  interval = 12,\n  acceleration = 0.9,\n  transitionFrames = 6,\n}: Pick<\n  InlineWordRollProps,\n  \"text\" | \"interval\" | \"acceleration\" | \"transitionFrames\"\n> = {}) {\n  const count = parseInlineWords(text).length;\n  const transition = Math.max(1, finite(transitionFrames, 6));\n  const gap = Math.max(transition, finite(interval, 12));\n  const rate = Math.min(1, Math.max(0.5, finite(acceleration, 0.9)));\n  let total = 0;\n  for (let index = 0; index < count - 1; index++)\n    total += Math.max(transition, gap * rate ** index);\n  return count < 2 ? 0 : Math.ceil(total + transition);\n}\n\nfunction InlineWordRollBase({\n  prefix = \"Looking for\",\n  text = inlineWordRollDefaultText,\n  suffix = \"?\",\n  fontSize = 60,\n  fontFamily = \"Arial, Helvetica, sans-serif\",\n  fontWeight = 400,\n  color = \"#f5f5f5\",\n  interval = 12,\n  acceleration = 0.9,\n  transitionFrames = 6,\n}: InlineWordRollProps) {\n  const frame = useCurrentFrame();\n  const { width, height } = useVideoConfig();\n  const { delayRender, continueRender, cancelRender } = useDelayRender();\n  const words = parseInlineWords(text);\n  const measurement = useRef<HTMLDivElement>(null);\n  const pending = useRef<number | null>(null);\n  const [metrics, setMetrics] = useState<{\n    prefix: number;\n    words: number[];\n  } | null>(null);\n  const size = Math.max(1, finite(fontSize, 60));\n  const typography = {\n    fontFamily,\n    fontSize: size,\n    fontWeight,\n    letterSpacing: \"-0.035em\",\n    lineHeight: 1.2,\n    whiteSpace: \"pre\" as const,\n  };\n\n  useLayoutEffect(() => {\n    let cancelled = false;\n    const handle = delayRender(\"Measure Inline Word Roll font\");\n    pending.current = handle;\n    void document.fonts\n      .load(\n        `${fontWeight} ${size}px ${fontFamily}`,\n        `${prefix} ${text}${suffix}`,\n      )\n      .then(() => {\n        if (cancelled || !measurement.current) return;\n        const children = Array.from(measurement.current.children);\n        // Computed widths are in composition pixels. Bounding rectangles include\n        // the Player's preview scale and would shrink our layout a second time.\n        const measure = (node: Element) =>\n          Number.parseFloat(getComputedStyle(node).width);\n        setMetrics({\n          prefix: measure(children[0]),\n          words: children.slice(1).map(measure),\n        });\n      })\n      .catch((error: unknown) => {\n        if (!cancelled)\n          cancelRender(\n            error instanceof Error ? error : new Error(String(error)),\n          );\n      });\n    return () => {\n      cancelled = true;\n      continueRender(handle);\n      if (pending.current === handle) pending.current = null;\n    };\n  }, [\n    prefix,\n    text,\n    suffix,\n    size,\n    fontFamily,\n    fontWeight,\n    delayRender,\n    continueRender,\n    cancelRender,\n  ]);\n\n  useLayoutEffect(() => {\n    if (metrics && pending.current !== null) {\n      continueRender(pending.current);\n      pending.current = null;\n    }\n  }, [metrics, continueRender]);\n\n  const state = getInlineWordRollState(\n    frame,\n    words.length,\n    interval,\n    acceleration,\n    transitionFrames,\n  );\n  const moving = state.from !== state.to;\n  const p = ease(state.progress);\n  const gap = prefix ? size * 0.23 : 0;\n  const prefixWidth = metrics?.prefix ?? 0;\n  const fromWidth = metrics?.words[state.from] ?? 0;\n  const toWidth = metrics?.words[state.to] ?? 0;\n  const slotWidth = fromWidth + (toWidth - fromWidth) * p;\n  const totalWidth = prefixWidth + gap + slotWidth;\n  const widest = prefixWidth + gap + Math.max(0, ...(metrics?.words ?? []));\n  const fit = Math.min(\n    1,\n    (width * 0.84) / Math.max(1, widest),\n    (height * 0.5) / (size * 1.2),\n  );\n  const rowHeight = size * 1.2;\n\n  return (\n    <div\n      role=\"img\"\n      aria-label={[prefix, words[state.to] ? `${words[state.to]}${suffix}` : \"\"]\n        .filter(Boolean)\n        .join(\" \")}\n      style={{ position: \"absolute\", inset: 0, overflow: \"hidden\", color }}\n    >\n      <div\n        ref={measurement}\n        aria-hidden=\"true\"\n        style={{\n          ...typography,\n          position: \"absolute\",\n          visibility: \"hidden\",\n          pointerEvents: \"none\",\n        }}\n      >\n        <span style={{ display: \"inline-block\" }}>{prefix}</span>\n        {words.map((word, index) => (\n          <span key={`${index}:${word}`} style={{ display: \"inline-block\" }}>\n            {word}\n            {suffix}\n          </span>\n        ))}\n      </div>\n      <div\n        aria-hidden=\"true\"\n        style={{\n          position: \"absolute\",\n          left: \"50%\",\n          top: \"50%\",\n          scale: fit,\n          visibility: metrics && words.length ? \"visible\" : \"hidden\",\n        }}\n      >\n        <div\n          style={{\n            ...typography,\n            position: \"absolute\",\n            left: -totalWidth / 2,\n            top: -rowHeight / 2,\n            height: rowHeight,\n          }}\n        >\n          <span style={{ position: \"absolute\", left: 0 }}>{prefix}</span>\n          <div\n            style={{\n              position: \"absolute\",\n              left: prefixWidth + gap,\n              top: 0,\n              width: Math.max(fromWidth, toWidth) + size * 0.12,\n              height: rowHeight,\n              overflow: \"hidden\",\n              maskImage:\n                \"linear-gradient(to bottom, transparent, black 12%, black 88%, transparent)\",\n            }}\n          >\n            <span\n              style={{\n                position: \"absolute\",\n                left: 0,\n                top: 0,\n                translate: `0 ${moving ? -p * rowHeight : 0}px`,\n                opacity: moving ? 1 - clamp(p * 1.2) : 1,\n              }}\n            >\n              {words[state.from]}\n              {words.length ? suffix : \"\"}\n            </span>\n            {moving ? (\n              <span\n                style={{\n                  position: \"absolute\",\n                  left: 0,\n                  top: 0,\n                  translate: `0 ${(1 - p) * rowHeight}px`,\n                  opacity: clamp(p * 1.6),\n                }}\n              >\n                {words[state.to]}\n                {suffix}\n              </span>\n            ) : null}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst elementSchema = {\n  ...Interactive.baseSchema,\n  prefix: {\n    type: \"text-content\",\n    default: \"Looking for\",\n    description: \"Fixed text\",\n  },\n  text: {\n    type: \"text-content\",\n    default: \"leads | customers | subscribers | appointments | demos | quotes | registrants | trials | conversions\",\n    description: \"Words separated by |\",\n  },\n  suffix: {\n    type: \"text-content\",\n    default: \"?\",\n    description: \"Word suffix\",\n  },\n  fontSize: {\n    type: \"number\",\n    default: 60,\n    min: 16,\n    max: 160,\n    step: 1,\n    description: \"Font size\",\n    hiddenFromList: false,\n  },\n  interval: {\n    type: \"number\",\n    default: 12,\n    min: 6,\n    max: 60,\n    step: 1,\n    description: \"Initial frames per word\",\n    hiddenFromList: false,\n  },\n  acceleration: {\n    type: \"number\",\n    default: 0.9,\n    min: 0.5,\n    max: 1,\n    step: 0.01,\n    description: \"Interval multiplier\",\n    hiddenFromList: false,\n  },\n  transitionFrames: {\n    type: \"number\",\n    default: 6,\n    min: 1,\n    max: 20,\n    step: 1,\n    description: \"Roll duration\",\n    hiddenFromList: false,\n  },\n  color: {\n    type: \"color\",\n    default: \"#f5f5f5\",\n    description: \"Color\",\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([\"prefix\",\"text\",\"suffix\",\"fontSize\",\"interval\",\"acceleration\",\"transitionFrames\",\"color\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n  prefix: \"Looking for\",\n  text: \"leads | customers | subscribers | appointments | demos | quotes | registrants | trials | conversions\",\n  suffix: \"?\",\n  fontSize: 60,\n  interval: 12,\n  acceleration: 0.9,\n  transitionFrames: 6,\n  color: \"#f5f5f5\",\n  speed: 1,\n};\n\ntype InlineWordRollElementProps = InteractiveBaseProps &\n  InteractiveTransformProps &\n  ComponentProps<typeof InlineWordRollBase>;\n\nconst InlineWordRollInner = forwardRef<\n  HTMLDivElement,\n  InlineWordRollElementProps & { 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 ?? \"<InlineWordRoll>\"}\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        <InlineWordRollBase\n          {...(componentProps as unknown as ComponentProps<typeof InlineWordRollBase>)}\n        />\n      </div>\n    </Sequence>\n  );\n});\n\nexport const InlineWordRoll = Interactive.withSchema({\n  Component: InlineWordRollInner,\n  componentName: \"<InlineWordRoll>\",\n  componentIdentity: null,\n  schema: elementSchema,\n  supportsEffects: false,\n});\n",
    "durationInFrames": 75,
    "installationMode": "component-owned-sequence"
  },
  "durationInFrames": 75
}