Skip to content

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

13.8 KB
Raw Blame
{
  "type": "remotion-element",
  "version": 1,
  "element": {
    "assets": [],
    "dependencies": [
      {
        "name": "@remotion/google-fonts",
        "version": null
      }
    ],
    "dimensions": null,
    "displayName": "Stripe Type",
    "initialProps": null,
    "slug": "stripe-type",
    "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n  weights: [\"100\", \"900\"],\n  subsets: [\"latin\"],\n});\n\ntype StripeTypeSettle = \"striped\" | \"solid\";\n\ninterface StripeTypeProps {\n  text?: string;\n  fontSize?: number;\n  fontWeight?: number;\n  fontFamily?: string;\n  color?: string;\n  stripes?: number;\n  gap?: number;\n  settle?: StripeTypeSettle;\n  exit?: boolean;\n  hold?: number;\n  speed?: number;\n  className?: string;\n}\n\nconst stripeTypeDefaults = {\n  text: \"Launch\",\n  fontSize: 180,\n  fontWeight: 800,\n  fontFamily: INTER,\n  color: \"#fafafa\",\n  stripes: 8,\n  gap: 0.35,\n  settle: \"striped\",\n  exit: true,\n  hold: 30,\n  speed: 1,\n} satisfies Required<Omit<StripeTypeProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nconst stripeTypeTiming = {\n  stagger: 2,\n  travel: 16,\n  close: 10,\n  /** Frames of empty screen after the exit in the preview. */\n  tail: 10,\n} as const;\n\n/** Ink box of Inter in a `line-height: 1` box, in em from the top, until measured. */\nconst INTER_INK = { top: 0.136, bottom: 0.864 + 0.24 };\nconst MEASURE_SIZE = 100;\n\nconst CLAMP = {\n  extrapolateLeft: \"clamp\",\n  extrapolateRight: \"clamp\",\n} as const;\n\n// Expo-shaped curves that land exactly on 0 and 1 (Easing.exp stops 2⁻¹⁰ short).\nconst easeOutExpo = Easing.bezier(0.16, 1, 0.3, 1);\nconst easeInExpo = Easing.bezier(0.7, 0, 0.84, 0);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n  return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getStripeTypeTime(\n  frame: number,\n  options: { fps?: number; speed?: number } = {},\n) {\n  const fps = Math.max(1, finite(options.fps, 30));\n  const speed = Math.max(0, finite(options.speed, 1));\n  return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\nfunction stripeCount(stripes: number | undefined) {\n  return Math.max(1, Math.round(finite(stripes, stripeTypeDefaults.stripes)));\n}\n\ninterface StripeBand {\n  /** Top of the band as a share of the ink box height. */\n  top: number;\n  /** Bottom of the band as a share of the ink box height. */\n  bottom: number;\n}\n\n/**\n * Bands over the ink box. With `n` bands and gap share `g` the pitch is\n * `1 / (n − g)`: the first band starts at the top, the last ends at the\n * bottom.\n */\nfunction getStripeBands(stripes: number, gap: number): StripeBand[] {\n  const n = stripeCount(stripes);\n  const g = Math.min(0.95, Math.max(0, finite(gap, 0)));\n  const pitch = 1 / (n - g);\n  return Array.from({ length: n }, (_, k) => ({\n    top: k * pitch,\n    bottom: k * pitch + pitch * (1 - g),\n  }));\n}\n\ninterface StripeTypeTimeline {\n  /** Frame where the last band has locked. */\n  entered: number;\n  /** Frame where the gaps have closed (equals `entered` when striped). */\n  settled: number;\n  exitStart: number;\n  exitEnd: number;\n  /** Frames the preview needs. */\n  duration: number;\n}\n\nfunction getStripeTypeTimeline(\n  options: Pick<StripeTypeProps, \"stripes\" | \"settle\" | \"exit\" | \"hold\"> = {},\n): StripeTypeTimeline {\n  const n = stripeCount(options.stripes);\n  const { stagger, travel, close, tail } = stripeTypeTiming;\n  const entered = stagger * (n - 1) + travel;\n  const settled = options.settle === \"solid\" ? entered + close : entered;\n  const hold = Math.max(0, finite(options.hold, stripeTypeDefaults.hold));\n  const exitStart = settled + hold;\n  const exitEnd = exitStart + stagger * (n - 1) + travel;\n  const exit = options.exit !== false;\n  return {\n    entered,\n    settled,\n    exitStart,\n    exitEnd,\n    duration: exit ? exitEnd + tail : settled + hold,\n  };\n}\n\n/** Preview length for the given options and speed. */\nfunction getStripeTypeDuration(\n  options: Pick<\n    StripeTypeProps,\n    \"stripes\" | \"settle\" | \"exit\" | \"hold\" | \"speed\"\n  > = {},\n) {\n  const speed = finite(options.speed, 1);\n  if (speed <= 0) return 1;\n  return Math.ceil(getStripeTypeTimeline(options).duration / speed);\n}\n\n/**\n * Horizontal offset of band `k` as a share of its travel distance: −1 or 1\n * off the frame, 0 locked. Even bands enter from the left, odd from the right,\n * and on the exit each band passes on through the other side.\n */\nfunction getStripeBandOffset(\n  t: number,\n  k: number,\n  options: Pick<StripeTypeProps, \"stripes\" | \"settle\" | \"exit\" | \"hold\"> = {},\n) {\n  const { stagger, travel } = stripeTypeTiming;\n  const timeline = getStripeTypeTimeline(options);\n  const side = k % 2 === 0 ? -1 : 1;\n  const inStart = stagger * k;\n  const enter = interpolate(t, [inStart, inStart + travel], [1, 0], {\n    ...CLAMP,\n    easing: easeOutExpo,\n  });\n  // `|| 0` folds −0 into 0 for a locked band.\n  if (options.exit === false) return side * enter || 0;\n  const outStart = timeline.exitStart + stagger * k;\n  const leave = interpolate(t, [outStart, outStart + travel], [0, 1], {\n    ...CLAMP,\n    easing: easeInExpo,\n  });\n  return side * enter - side * leave || 0;\n}\n\n/** Gap share over time: the set gap, closing to 0 when `settle` is solid. */\nfunction getStripeGap(\n  t: number,\n  gap: number,\n  options: Pick<StripeTypeProps, \"stripes\" | \"settle\"> = {},\n) {\n  if (options.settle !== \"solid\") return gap;\n  const { entered, settled } = getStripeTypeTimeline(options);\n  return interpolate(t, [entered, settled], [gap, 0], {\n    ...CLAMP,\n    easing: easeInOutCubic,\n  });\n}\n\n/** Ink box of the word in its `line-height: 1` box, and its width, in em. */\nfunction useInkBox(text: string, font: string) {\n  const [ink, setInk] = useState<{\n    top: number;\n    bottom: number;\n    width: number;\n  } | null>(null);\n\n  useEffect(() => {\n    const handle = delayRender(\"stripe-type: measuring the word\");\n    let released = false;\n    const release = () => {\n      if (released) return;\n      released = true;\n      continueRender(handle);\n    };\n    const measure = () => {\n      if (released) return;\n      const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n      if (ctx) {\n        ctx.font = font;\n        const m = ctx.measureText(text);\n        const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;\n        const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;\n        const baseline = (1 - (ascent + descent)) / 2 + ascent;\n        if (ascent > 0) {\n          setInk({\n            top: baseline - m.actualBoundingBoxAscent / MEASURE_SIZE,\n            bottom: baseline + m.actualBoundingBoxDescent / MEASURE_SIZE,\n            width: m.width / MEASURE_SIZE,\n          });\n        }\n      }\n      release();\n    };\n    document.fonts.load(font, text).then(measure, measure);\n    return release;\n  }, [text, font]);\n\n  return ink;\n}\n\nfunction StripeTypeBase({\n  text = stripeTypeDefaults.text,\n  fontSize = stripeTypeDefaults.fontSize,\n  fontWeight = stripeTypeDefaults.fontWeight,\n  fontFamily = stripeTypeDefaults.fontFamily,\n  color = stripeTypeDefaults.color,\n  stripes = stripeTypeDefaults.stripes,\n  gap = stripeTypeDefaults.gap,\n  settle = stripeTypeDefaults.settle,\n  exit = stripeTypeDefaults.exit,\n  hold = stripeTypeDefaults.hold,\n  speed = stripeTypeDefaults.speed,\n  className,\n}: StripeTypeProps) {\n  const frame = useCurrentFrame();\n  const { fps, width, height } = useVideoConfig();\n  const unit = height / 720;\n  const size = fontSize * unit;\n  const t = getStripeTypeTime(frame, { fps, speed });\n  const measured = useInkBox(\n    text,\n    `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,\n  );\n  const ink = measured ?? {\n    ...INTER_INK,\n    width: 0.6 * Array.from(text).length,\n  };\n  const options = { stripes, settle, exit, hold };\n  const bands = getStripeBands(stripes, getStripeGap(t, gap, options));\n  const inkHeight = ink.bottom - ink.top;\n  // Far enough that a band starting on either side is fully off the frame.\n  const travel = (width + ink.width * size) / 2 + 0.2 * size;\n\n  const type = {\n    fontFamily,\n    fontSize: size,\n    lineHeight: 1,\n    fontWeight,\n    fontVariationSettings: `\"wght\" ${fontWeight}`,\n    color,\n    whiteSpace: \"pre\",\n  } as const;\n\n  return (\n    <div\n      className={className}\n      style={{\n        position: \"absolute\",\n        inset: 0,\n        display: \"flex\",\n        alignItems: \"center\",\n        justifyContent: \"center\",\n        overflow: \"hidden\",\n      }}\n    >\n      <div style={{ position: \"relative\" }}>\n        <div aria-hidden style={{ ...type, visibility: \"hidden\" }}>\n          {text}\n        </div>\n        {bands.map((band, k) => {\n          const top = (ink.top + band.top * inkHeight) * 100;\n          // Each band reaches a pixel into the next gap, so closed gaps leave\n          // no antialiased seam between bands.\n          const bleed = k < bands.length - 1 ? Math.max(1, unit) / size : 0;\n          const bottom =\n            (1 - (ink.top + band.bottom * inkHeight) - bleed) * 100;\n          const offset = getStripeBandOffset(t, k, options);\n          return (\n            <div\n              key={k}\n              aria-hidden={k > 0}\n              style={{\n                ...type,\n                position: \"absolute\",\n                inset: 0,\n                clipPath: `inset(${top}% -1% ${bottom}% -1%)`,\n                transform: `translateX(${offset * travel}px)`,\n              }}\n            >\n              {text}\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\nconst elementSchema = {\n  ...Interactive.baseSchema,\n  text: {\n    type: \"text-content\",\n    default: \"Launch\",\n    description: \"Text\",\n  },\n  color: {\n    type: \"color\",\n    default: \"#fafafa\",\n    description: \"Text color\",\n  },\n  settle: {\n    type: \"enum\",\n    default: \"striped\",\n    variants: {\n      striped: {},\n      solid: {},\n    },\n    description: \"Settle\",\n  },\n  fontSize: {\n    type: \"number\",\n    default: 180,\n    min: 60,\n    max: 320,\n    step: 2,\n    description: \"Font size\",\n    hiddenFromList: false,\n  },\n  fontWeight: {\n    type: \"number\",\n    default: 800,\n    min: 100,\n    max: 900,\n    step: 50,\n    description: \"Weight\",\n    hiddenFromList: false,\n  },\n  stripes: {\n    type: \"number\",\n    default: 8,\n    min: 2,\n    max: 16,\n    step: 1,\n    description: \"Stripes\",\n    hiddenFromList: false,\n  },\n  gap: {\n    type: \"number\",\n    default: 0.35,\n    min: 0,\n    max: 0.8,\n    step: 0.05,\n    description: \"Gap\",\n    hiddenFromList: false,\n  },\n  hold: {\n    type: \"number\",\n    default: 30,\n    min: 0,\n    max: 120,\n    step: 5,\n    description: \"Hold\",\n    hiddenFromList: false,\n  },\n  exit: {\n    type: \"boolean\",\n    default: true,\n    description: \"Exit\",\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([\"text\",\"color\",\"settle\",\"fontSize\",\"fontWeight\",\"stripes\",\"gap\",\"hold\",\"exit\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n  text: \"Launch\",\n  color: \"#fafafa\",\n  settle: \"striped\",\n  fontSize: 180,\n  fontWeight: 800,\n  stripes: 8,\n  gap: 0.35,\n  hold: 30,\n  exit: true,\n  speed: 1,\n};\n\ntype StripeTypeElementProps = InteractiveBaseProps &\n  InteractiveTransformProps &\n  ComponentProps<typeof StripeTypeBase>;\n\nconst StripeTypeInner = forwardRef<\n  HTMLDivElement,\n  StripeTypeElementProps & { 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 ?? \"<StripeType>\"}\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        <StripeTypeBase\n          {...(componentProps as unknown as ComponentProps<typeof StripeTypeBase>)}\n        />\n      </div>\n    </Sequence>\n  );\n});\n\nexport const StripeType = Interactive.withSchema({\n  Component: StripeTypeInner,\n  componentName: \"<StripeType>\",\n  componentIdentity: null,\n  schema: elementSchema,\n  supportsEffects: false,\n});\n",
    "durationInFrames": 30,
    "installationMode": "component-owned-sequence"
  },
  "durationInFrames": 30
}