Chart Morph
A line chart with an area fill morphs between points up to a 46k value.
Source
components/kuchi/chart-morph.tsx
1"use client";23import { loadFont } from "@remotion/google-fonts/Manrope";4import { type ReactNode, useId } from "react";5import {6 AbsoluteFill,7 Easing,8 interpolate,9 interpolateColors,10 useCurrentFrame,11 useVideoConfig,12} from "remotion";1314const { fontFamily: sans } = loadFont("normal", {15 weights: ["400", "500"],16 subsets: ["latin"],17});1819export interface ChartMorphDatum {20 label: string;21 value: number;22}2324export interface ChartMorphProps {25 data?: ChartMorphDatum[];26 suffix?: string;27 caption?: string;28 accent?: string;29 /** Text color of the value and the hero label; overrides the theme. */30 ink?: string;31 /** Background fill; "transparent" drops it. */32 background?: string;33 /** Typeface for the value and labels. Load it yourself; Manrope by default. */34 fontFamily?: string;35 /** Weight of the final value. */36 fontWeight?: number;37 /** Frames between bars as they tip up out of the stack. */38 stagger?: number;39 /** Size of the chart, around the frame's center. */40 scale?: number;41 /** Frames to hold the first frame before anything moves. */42 delay?: number;43 /** Film grain over the scene. */44 grain?: boolean;45 theme?: "dark" | "light";46 speed?: number;47}4849const DEFAULT_DATA: ChartMorphDatum[] = [50 { label: "Jan", value: 12 },51 { label: "Feb", value: 18 },52 { label: "Mar", value: 23 },53 { label: "Apr", value: 31 },54 { label: "May", value: 46 },55];5657const EASE_IO = Easing.bezier(0.65, 0, 0.35, 1);58const EASE_OUT = Easing.bezier(0.22, 1, 0.36, 1);59const EASE_DRAW = Easing.bezier(0.55, 0, 0.25, 1);60const CLAMP = {61 extrapolateLeft: "clamp",62 extrapolateRight: "clamp",63} as const;6465const THEMES = {66 dark: {67 bg: "#0A0A0B",68 fg: "#F3F2EF",69 muted: "#8B8A90",70 line: "#E9E8E4",71 hair: "rgba(255,255,255,0.14)",72 grays: ["#5C5B61", "#75747A", "#929197", "#B4B2AE"],73 grain: 0.06,74 // gradients.sh "limb": bg #030308, [#e9ecff, #8a8bff, #4b2bd6, #160c3a]75 limb: ["#4b2bd6", "#8a8bff", "#d4d7ff"],76 heroDot: "#d4d7ff",77 area: 1,78 areaStops: ["#4b2bd6", "#4b2bd6", "#8a8bff"],79 },80 light: {81 bg: "#F5F4F0",82 fg: "#121214",83 muted: "#6E6C67",84 line: "#1D1D20",85 hair: "rgba(18,18,20,0.16)",86 grays: ["#C9C7C1", "#AEACA6", "#8F8D88", "#6C6A66"],87 grain: 0.045,88 limb: ["#160c3a", "#4b2bd6", "#8a8bff"],89 heroDot: "#4b2bd6",90 area: 0.4,91 areaStops: ["#8a8bff", "#4b2bd6", "#8a8bff"],92 },93} as const;9495const DRAW = [0, 24] as const;96const SPIN = [0, 30] as const;97const UNROLL = [30, 60] as const;98const TIP_START = 64;99const TIP_STAGGER = 3;100const TIP_DUR = 24;101const COLLAPSE_START = 100;102const COLLAPSE_STAGGER = 2;103const COLLAPSE_DUR = 22;104const LABEL_IN = 131;105const TAU = Math.PI * 2;106const SAMPLES = 40;107108type Pt = { x: number; y: number };109110function lerp(a: number, b: number, k: number) {111 return a + (b - a) * k;112}113114function lerpPt(a: Pt, b: Pt, k: number): Pt {115 return { x: lerp(a.x, b.x, k), y: lerp(a.y, b.y, k) };116}117118function toPath(pts: Pt[]) {119 return `${pts120 .map((q, i) => `${i === 0 ? "M" : "L"} ${q.x.toFixed(2)} ${q.y.toFixed(2)}`)121 .join(" ")} Z`;122}123124function rotateAbout(q: Pt, c: Pt, a: number): Pt {125 const cs = Math.cos(a);126 const sn = Math.sin(a);127 const dx = q.x - c.x;128 const dy = q.y - c.y;129 return { x: c.x + cs * dx - sn * dy, y: c.y + sn * dx + cs * dy };130}131132function unrollPoint(133 s: number,134 o: number,135 k: number,136 ax: number,137 ay: number,138): Pt {139 if (k < 1e-6) return { x: ax + s, y: ay + o };140 const f = s * k;141 const sn = Math.sin(f);142 const cs = Math.cos(f);143 return {144 x: ax + sn / k + o * sn,145 y: ay - (1 - cs) / k + o * cs,146 };147}148149function bandPath(150 s0: number,151 s1: number,152 thick: number,153 k: number,154 ax: number,155 ay: number,156 spin: number,157 center: Pt,158) {159 const top: Pt[] = [];160 const bot: Pt[] = [];161 for (let j = 0; j <= SAMPLES; j++) {162 const s = lerp(s0, s1, j / SAMPLES);163 top.push(unrollPoint(s, -thick / 2, k, ax, ay));164 bot.push(unrollPoint(s, thick / 2, k, ax, ay));165 }166 const pts = [...top, ...bot.reverse()];167 return toPath(spin ? pts.map((q) => rotateAbout(q, center, spin)) : pts);168}169170/** The foreground at `scale`, around the frame's center; nothing extra at 1. */171function ScaleLayer({172 scale,173 children,174}: {175 scale: number;176 children: ReactNode;177}) {178 if (scale === 1) return children;179 return (180 <AbsoluteFill style={{ transform: `scale(${scale})` }}>181 {children}182 </AbsoluteFill>183 );184}185186function Grain({ opacity }: { opacity: number }) {187 const id = `g${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;188 return (189 <svg190 width="100%"191 height="100%"192 style={{ position: "absolute", inset: 0, opacity }}193 aria-hidden194 >195 <filter id={id}>196 <feTurbulence197 type="fractalNoise"198 baseFrequency="0.9"199 numOctaves={2}200 seed={41}201 stitchTiles="stitch"202 />203 <feColorMatrix values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0.9 0" />204 </filter>205 <rect width="100%" height="100%" filter={`url(#${id})`} />206 </svg>207 );208}209210export function ChartMorph({211 data = DEFAULT_DATA,212 suffix = "k",213 caption,214 accent = "#3B5BFD",215 ink,216 background,217 fontFamily = sans,218 fontWeight = 400,219 stagger = TIP_STAGGER,220 scale = 1,221 delay = 0,222 grain = true,223 theme = "dark",224 speed = 1,225}: ChartMorphProps) {226 const t = Math.max(0, useCurrentFrame() - delay) * speed;227 const { width, height } = useVideoConfig();228 const u = Math.min(width / 1280, height / 720);229 const p = THEMES[theme];230 const fg = ink ?? p.fg;231 const stage = background ?? p.bg;232 // the hollow dots punch out to the stage colour; with no stage, keep the theme's233 const dotFill = background === "transparent" ? p.bg : stage;234 const gid = `cm${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;235236 const list = data.slice(0, 5).map((d) => ({237 ...d,238 value: Math.max(0, d.value),239 }));240 const n = list.length;241 const total = list.reduce((s, d) => s + d.value, 0) || 1;242 let hl = 0;243 list.forEach((d, i) => {244 if (d.value > list[hl].value) hl = i;245 });246 const last = list[n - 1];247 const endCaption = caption ?? `renders in ${last?.label ?? ""}`.trim();248249 const cx = width / 2;250 const cy = height / 2;251 const center = { x: cx, y: cy };252 const ringR = height * 0.26;253 const ringT = height * 0.074;254 const barT = height * 0.084;255 const stackW = width * 0.74;256 const gap = 6 * u;257 const L0 = TAU * ringR;258259 const heroFill = `url(#${gid}-hero)`;260 const colors = (() => {261 let g = 0;262 return list.map((_, i) =>263 i === hl ? heroFill : p.grays[Math.min(g++, p.grays.length - 1)],264 );265 })();266267 let acc = 0;268 const fracs = list.map((d) => {269 const a = acc / total;270 acc += d.value;271 return { a, b: acc / total };272 });273274 const segAt = (i: number, L: number) => ({275 s0: (fracs[i].a - 0.5) * L + gap / 2,276 s1: (fracs[i].b - 0.5) * L - gap / 2,277 });278279 const stack = list.map((_, i) => {280 const { s0, s1 } = segAt(i, stackW);281 return { x0: cx + s0, x1: cx + s1, w: s1 - s0 };282 });283 const maxW = Math.max(...stack.map((s) => s.w), 1);284 const chartTop = (height - (maxW + 44 * u)) / 2 + 16 * u;285 const yB = chartTop + maxW;286 const spacing = width * 0.15;287 const colA = list.map((_, i) => cx + (i - (n - 1) / 2) * spacing);288 const fx0 = width * 0.12;289 const fx1 = width * 0.69;290 const colB = list.map((_, i) =>291 n > 1 ? lerp(fx0, fx1, i / (n - 1)) : (fx0 + fx1) / 2,292 );293 const P = list.map((_, i) => ({ x: colB[i], y: yB - stack[i].w }));294295 const drawK = interpolate(t, [DRAW[0], DRAW[1]], [0, 1], {296 ...CLAMP,297 easing: EASE_DRAW,298 });299 const spin = interpolate(t, [SPIN[0], SPIN[1]], [-0.42, 0], {300 ...CLAMP,301 easing: EASE_IO,302 });303 const un = interpolate(t, [UNROLL[0], UNROLL[1]], [0, 1], {304 ...CLAMP,305 easing: EASE_IO,306 });307 const stageIn = interpolate(t, [0, 8], [0, 1], CLAMP);308 const drift = interpolate(t, [0, 182], [-1, 1], {309 ...CLAMP,310 easing: EASE_IO,311 });312313 const tipK = list.map((_, i) =>314 interpolate(315 t,316 [TIP_START + i * stagger, TIP_START + i * stagger + TIP_DUR],317 [0, 1],318 { ...CLAMP, easing: EASE_IO },319 ),320 );321 const colK = list.map((_, i) =>322 interpolate(323 t,324 [325 COLLAPSE_START + i * COLLAPSE_STAGGER,326 COLLAPSE_START + i * COLLAPSE_STAGGER + COLLAPSE_DUR,327 ],328 [0, 1],329 { ...CLAMP, easing: EASE_IO },330 ),331 );332 const shift = interpolate(333 t,334 [335 COLLAPSE_START,336 COLLAPSE_START + COLLAPSE_DUR + (n - 1) * COLLAPSE_STAGGER,337 ],338 [0, 1],339 { ...CLAMP, easing: EASE_IO },340 );341 const colX = list.map((_, i) => lerp(colA[i], colB[i], shift));342343 const lw = 5 * u;344 const chevron = (i: number) => {345 const Pi = P[i];346 const prev = i > 0 ? P[i - 1] : null;347 const next = i < n - 1 ? P[i + 1] : null;348 const dirTo = (a: Pt, b: Pt) => {349 const dx = b.x - a.x;350 const dy = b.y - a.y;351 const l = Math.hypot(dx, dy) || 1;352 return { x: dx / l, y: dy / l };353 };354 const dL = prev ? dirTo(prev, Pi) : next ? dirTo(Pi, next) : { x: 1, y: 0 };355 const dR = next ? dirTo(Pi, next) : dL;356 const nL = { x: -dL.y, y: dL.x };357 const nR = { x: -dR.y, y: dR.x };358 const ov = 0.8 * u;359 const mL = prev360 ? {361 x: (prev.x + Pi.x) / 2 - dL.x * ov,362 y: (prev.y + Pi.y) / 2 - dL.y * ov,363 }364 : Pi;365 const mR = next366 ? {367 x: (Pi.x + next.x) / 2 + dR.x * ov,368 y: (Pi.y + next.y) / 2 + dR.y * ov,369 }370 : Pi;371 const sum = { x: nL.x + nR.x, y: nL.y + nR.y };372 const sl = Math.hypot(sum.x, sum.y) || 1;373 const m = { x: sum.x / sl, y: sum.y / sl };374 const ml = Math.min(2, 1 / Math.max(0.3, m.x * nL.x + m.y * nL.y));375 const h = lw / 2;376 return [377 { x: mL.x + nL.x * h, y: mL.y + nL.y * h },378 { x: mL.x - nL.x * h, y: mL.y - nL.y * h },379 { x: Pi.x - m.x * h * ml, y: Pi.y - m.y * h * ml },380 { x: mR.x - nR.x * h, y: mR.y - nR.y * h },381 { x: mR.x + nR.x * h, y: mR.y + nR.y * h },382 { x: Pi.x + m.x * h * ml, y: Pi.y + m.y * h * ml },383 ];384 };385386 const barPoly = (i: number) => {387 const xc = colA[i];388 const xl = xc - barT / 2;389 const xr = xc + barT / 2;390 const yT = yB - stack[i].w;391 return [392 { x: xl, y: yB },393 { x: xl, y: yT },394 { x: xc, y: yT },395 { x: xr, y: yT },396 { x: xr, y: yB },397 { x: xc, y: yB },398 ];399 };400401 const shapes = list.map((d, i) => {402 if (t < TIP_START) {403 const L = lerp(L0, stackW, un);404 const k = (TAU / L) * (1 - un);405 const thick = lerp(ringT, barT, un);406 const ay = lerp(cy + ringR, cy, un);407 const seg = segAt(i, L);408 const revealFrom = L / 2 - drawK * L;409 const s0 = Math.max(seg.s0, revealFrom);410 if (s0 >= seg.s1)411 return { key: d.label, d: "", color: colors[i], split: undefined };412 return {413 key: d.label,414 d: bandPath(s0, seg.s1, thick, k, cx, ay, spin, center),415 color: colors[i],416 split: undefined,417 };418 }419 if (t < COLLAPSE_START) {420 const e = tipK[i];421 const s = stack[i];422 const pivot0 = { x: s.x0, y: cy + barT / 2 };423 const pivot1 = { x: colA[i] + barT / 2, y: yB };424 const drop = interpolate(e, [0.25, 1], [0, 1], {425 ...CLAMP,426 easing: EASE_IO,427 });428 const pvl = {429 x: lerp(pivot0.x, pivot1.x, e),430 y: lerp(pivot0.y, pivot1.y, drop),431 };432 const a = (-Math.PI / 2) * e;433 const corners = [434 { x: 0, y: 0 },435 { x: 0, y: -barT },436 { x: s.w, y: -barT },437 { x: s.w, y: 0 },438 ].map((q) => rotateAbout({ x: pvl.x + q.x, y: pvl.y + q.y }, pvl, a));439 return {440 key: d.label,441 d: toPath(corners),442 color: colors[i],443 split: undefined,444 };445 }446 const e = colK[i];447 const from = barPoly(i);448 const to = chevron(i);449 const pts = from.map((q, j) => lerpPt(q, to[j], e));450 const color =451 i === hl ? heroFill : interpolateColors(e, [0, 1], [colors[i], p.line]);452 const toward =453 i === hl454 ? heroFill455 : interpolateColors(456 e,457 [0, 1],458 [colors[i], i < hl ? p.limb[0] : p.limb[2]],459 );460 const split =461 i === hl - 1462 ? { x: pts[2].x, left: color, right: toward }463 : i === hl + 1464 ? { x: pts[2].x, left: toward, right: color }465 : undefined;466 return { key: d.label, d: toPath(pts), color, split };467 });468469 const labelsIn = interpolate(t, [TIP_START + 22, TIP_START + 40], [0, 1], {470 ...CLAMP,471 easing: EASE_OUT,472 });473 const baseIn = interpolate(t, [TIP_START + 14, TIP_START + 38], [0, 1], {474 ...CLAMP,475 easing: EASE_IO,476 });477 const baseL = lerp(colA[0] - barT, colB[0], shift);478 const baseR = lerp(colA[n - 1] + barT, colB[n - 1], shift);479480 const dotsIn = interpolate(t, [LABEL_IN - 6, LABEL_IN + 10], [0, 1], {481 ...CLAMP,482 easing: EASE_OUT,483 });484 const labIn = interpolate(t, [LABEL_IN, LABEL_IN + 20], [0, 1], {485 ...CLAMP,486 easing: EASE_OUT,487 });488 const capIn = interpolate(t, [LABEL_IN + 6, LABEL_IN + 24], [0, 1], {489 ...CLAMP,490 easing: EASE_OUT,491 });492 const push = interpolate(t, [0, LABEL_IN + 40], [1.03, 1], {493 ...CLAMP,494 easing: EASE_IO,495 });496 const end = P[n - 1];497 const areaIn = interpolate(t, [LABEL_IN - 6, LABEL_IN + 22], [0, 1], {498 ...CLAMP,499 easing: EASE_IO,500 });501 const areaRise = interpolate(areaIn, [0, 1], [0.4, 1]);502 const endColor = hl === n - 1 ? p.heroDot : p.line;503 const valueText = `${Math.round(last?.value ?? 0)}${suffix}`;504505 return (506 <AbsoluteFill style={{ background: stage, overflow: "hidden" }}>507 <ScaleLayer scale={scale}>508 <AbsoluteFill509 style={{ transform: `scale(${push})`, transformOrigin: "50% 50%" }}510 >511 <svg512 width={width}513 height={height}514 style={{ position: "absolute", inset: 0, opacity: stageIn }}515 aria-hidden516 >517 <line518 x1={baseL}519 x2={lerp(baseL, baseR, baseIn)}520 y1={yB + 0.5}521 y2={yB + 0.5}522 stroke={p.hair}523 strokeWidth={Math.max(1, u)}524 opacity={baseIn > 0 ? 1 : 0}525 />526 <defs>527 <linearGradient id={`${gid}-hero`} x1={0} y1={1} x2={1} y2={0}>528 <stop offset={0} stopColor={p.limb[0]} />529 <stop offset={0.55 + 0.1 * drift} stopColor={p.limb[1]} />530 <stop offset={1} stopColor={p.limb[2]} />531 </linearGradient>532 <linearGradient533 id={`${gid}-area`}534 gradientUnits="userSpaceOnUse"535 x1={P[0]?.x ?? 0}536 y1={yB}537 x2={end?.x ?? width}538 y2={end?.y ?? 0}539 >540 <stop offset={0} stopColor={p.areaStops[0]} stopOpacity={0.2} />541 <stop542 offset={0.6}543 stopColor={p.areaStops[1]}544 stopOpacity={0.55}545 />546 <stop offset={1} stopColor={p.areaStops[2]} stopOpacity={0.9} />547 </linearGradient>548 <linearGradient549 id={`${gid}-fade`}550 gradientUnits="userSpaceOnUse"551 x1={0}552 y1={end?.y ?? 0}553 x2={0}554 y2={yB}555 >556 <stop offset={0} stopColor="#fff" stopOpacity={1} />557 <stop offset={1} stopColor="#fff" stopOpacity={0} />558 </linearGradient>559 <mask id={`${gid}-mask`}>560 <rect561 width={width}562 height={height}563 fill={`url(#${gid}-fade)`}564 />565 </mask>566 {shapes.map((s, i) =>567 s.split ? (568 <linearGradient569 key={s.key}570 id={`${gid}-${i}`}571 gradientUnits="userSpaceOnUse"572 x1={s.split.x - 0.5}573 x2={s.split.x + 0.5}574 y1={0}575 y2={0}576 >577 <stop offset="0" stopColor={s.split.left} />578 <stop offset="0.5" stopColor={s.split.left} />579 <stop offset="0.5" stopColor={s.split.right} />580 <stop offset="1" stopColor={s.split.right} />581 </linearGradient>582 ) : null,583 )}584 </defs>585 {areaIn > 0 && n > 1 ? (586 <path587 d={`${P.map((q, i) => `${i ? "L" : "M"} ${q.x.toFixed(2)} ${(yB - (yB - q.y) * areaRise).toFixed(2)}`).join(" ")} L ${P[n - 1].x} ${yB} L ${P[0].x} ${yB} Z`}588 fill={`url(#${gid}-area)`}589 mask={`url(#${gid}-mask)`}590 opacity={areaIn * p.area}591 />592 ) : null}593 {shapes.map((s, i) =>594 s.d ? (595 <path596 key={s.key}597 d={s.d}598 fill={s.split ? `url(#${gid}-${i})` : s.color}599 />600 ) : null,601 )}602 {P.slice(0, n - 1).map((q, i) => (603 <circle604 key={list[i].label}605 cx={q.x}606 cy={q.y}607 r={(4 + 2 * dotsIn) * u}608 fill={dotFill}609 stroke={p.line}610 strokeWidth={2.5 * u}611 opacity={dotsIn}612 />613 ))}614 {end ? (615 <>616 <circle617 cx={end.x}618 cy={end.y}619 r={(10 + 6 * dotsIn) * u}620 fill="none"621 stroke={accent}622 strokeWidth={1.5 * u}623 opacity={0.7 * dotsIn}624 />625 <circle626 cx={end.x}627 cy={end.y}628 r={(5 + 3 * dotsIn) * u}629 fill={endColor}630 opacity={dotsIn}631 />632 </>633 ) : null}634 </svg>635636 {list.map((d, i) => (637 <div638 key={d.label}639 style={{640 position: "absolute",641 left: colX[i],642 top: yB + 18 * u,643 transform: `translateX(-50%) translateY(${(1 - labelsIn) * 8 * u}px)`,644 fontFamily,645 fontWeight: 500,646 fontSize: 16 * u,647 letterSpacing: "0.01em",648 color: i === hl ? fg : p.muted,649 opacity: labelsIn,650 whiteSpace: "nowrap",651 }}652 >653 {d.label}654 </div>655 ))}656657 {end ? (658 <div659 style={{660 position: "absolute",661 left: end.x + 34 * u,662 top: end.y,663 transform: "translateY(-50%)",664 display: "flex",665 flexDirection: "column",666 alignItems: "flex-start",667 }}668 >669 <div670 style={{671 fontFamily,672 fontWeight,673 fontSize: 116 * u,674 lineHeight: 0.92,675 letterSpacing: "-0.05em",676 color: fg,677 fontVariantNumeric: "tabular-nums",678 whiteSpace: "nowrap",679 opacity: labIn,680 transform: `translateX(${(1 - labIn) * -18 * u}px)`,681 filter:682 labIn < 0.99 ? `blur(${(1 - labIn) * 6 * u}px)` : undefined,683 }}684 >685 {valueText}686 </div>687 <div688 style={{689 marginTop: 10 * u,690 fontFamily,691 fontWeight: 400,692 fontSize: 21 * u,693 letterSpacing: "-0.01em",694 color: p.muted,695 whiteSpace: "nowrap",696 opacity: capIn,697 transform: `translateY(${(1 - capIn) * 6 * u}px)`,698 }}699 >700 {endCaption}701 </div>702 </div>703 ) : null}704 </AbsoluteFill>705 </ScaleLayer>706707 <AbsoluteFill708 style={{709 background: `radial-gradient(ellipse 85% 85% at 50% 50%, transparent 62%, ${stage} 100%)`,710 opacity: 0.5,711 }}712 />713 {grain ? <Grain opacity={p.grain} /> : null}714 </AbsoluteFill>715 );716}









