Card Rail
Card carousel animation: cards flicked sideways on a tilted 3D plane. A rail of cards flicked sideways across a tilted plane.
Source
components/kuchi/card-rail.tsx
1"use client";23import { loadFont as loadSans } from "@remotion/google-fonts/Figtree";4import type { CSSProperties } from "react";5import { forwardRef, useCallback, useState } from "react";6import {7 AbsoluteFill,8 continueRender,9 delayRender,10 getRemotionEnvironment,11 staticFile,12 useCurrentFrame,13 useVideoConfig,14} from "remotion";15import {16 Item,17 mixOklch,18 parseColor,19 resolveFont,20 type KuchiTheme,21 useKuchiTheme,22} from "@/lib/kuchi-ui";2324/**25 * A rail of cards flicked sideways across a tilted plane.26 *27 * The cards do not crawl past on a loop. They are *flicked* — the rail leaves at28 * speed, decelerates for well over a second, and comes to rest one card further29 * along, the way a carousel behaves under a thumb rather than under a timer. A30 * title holds the top of the frame and does not move with them.31 *32 * ## The plane is tilted, and that is the whole look33 *34 * The rail is not flat to the camera. Measured on the card edges of a recording,35 * the horizontal scale grows **0.000825 per pixel of height** about the frame's36 * own centre line — the bottom of a card is 22% wider than its top — while37 * horizontals stay horizontal and the type stays upright. That is a plane38 * rotated about a horizontal axis under perspective, and it is why a row of39 * plain rectangles reads as a surface receding into the frame.40 *41 * The three numbers that describe it are `DEPTH`, `TILT` and `HORIZON`, and they42 * are deliberately separate from the card metrics: change the card size and the43 * plane does not move.44 *45 * ## The flick is measured, not eased46 *47 * `FLICK` is the curve off the recording — it peaks at 29px a frame three frames48 * in and is still moving at 2px a frame a second later. No standard ease has that49 * tail; a cubic-out arrives four times too early and a spring overshoots50 * something that never overshoots.51 */5253const { fontFamily: SANS } = loadSans("normal", {54 weights: ["400", "500", "600", "700"],55 subsets: ["latin"],56});5758/* ─────────────────────────────────────────────────────────────────────────59 The stage, in the recording's own 714 × 396 pixels60 ───────────────────────────────────────────────────────────────────────── */6162export const REF_W = 714;63export const REF_H = 396;6465/** Title: cap height and baseline, measured on its own ink. */66export const HEAD_CAP = 20.81;67export const HEAD_BASE = 64.45;6869/** The card, in layout pixels — before the plane tilts it. */70export const CARD_W = 259.2;71export const CARD_TOP = 79.8;72export const GAP = 54.2;73export const RADIUS = 10;74/**75 * The card runs to the foot of the frame — the rail is a surface passing76 * through the shot, not a row of objects sitting in it.77 *78 * Its own number rather than `REF_H - CARD_TOP`, because `CARD_TOP` is a79 * *layout* height on a tilted plane and the two are not the same measurement:80 * the plane pushes the card 54px down the frame on its way to the camera.81 */82export const CARD_H = 323.3;83/** The picture's share of the card's width, as an aspect. */84export const SHOT_ASPECT = 16 / 9;8586/**87 * The plane.88 *89 * `HORIZON` is the height at which the plane is exactly life-size — above it the90 * rail is smaller and further away, below it nearer and larger. It is measured,91 * not chosen: solving the card's width at two heights puts it at 300.6, which is92 * most of the way down the visible card rather than at the frame's middle.93 */94export const DEPTH = 740;95export const TILT = 30;96export const HORIZON = 300;9798/**99 * The backdrop's axis, in degrees.100 *101 * Fitted, not guessed: a plane's corners have to satisfy TL + BR = TR + BL for a102 * linear gradient, and the recording's do to within five parts in 235 — so it is103 * linear, and the angle that puts its measured corners on one line is 138°.104 */105export const ANGLE = 138;106107/**108 * How far the rail travels, and the curve it travels on.109 *110 * One card pitch, so the rail comes to rest showing the next card where the last111 * one stood. The table is seconds → share of that distance, straight off the112 * recording: 29px on frame three, 2px a second later, and no analytic curve in113 * between that fits both ends.114 */115/**116 * Not `CARD_W + GAP`, and the difference is the point.117 *118 * A rail that advanced by exactly one pitch would be an assumption; measured, the119 * recording's travels 333 where its pitch is 325. A flick is a flick — it ends120 * where the momentum ran out, not on a snap — and eight pixels of overshoot is121 * the whole difference between a carousel and a surface someone pushed.122 */123export const TRAVEL = 323;124export const FLICK: readonly (readonly [number, number])[] = [125 [0, 0],126 [0.0333, 0.009],127 [0.0667, 0.0338],128 [0.1, 0.07508],129 [0.1333, 0.13213],130 [0.1667, 0.21021],131 [0.2, 0.2973],132 [0.225, 0.38138],133 [0.2583, 0.45345],134 [0.2917, 0.51351],135 [0.325, 0.56757],136 [0.3583, 0.60961],137 [0.3917, 0.65165],138 [0.4333, 0.68468],139 [0.4583, 0.71171],140 [0.4917, 0.73874],141 [0.525, 0.76276],142 [0.5583, 0.78378],143 [0.5917, 0.8018],144 [0.625, 0.81982],145 [0.6583, 0.83483],146 [0.6917, 0.84985],147 [0.73, 0.86186],148 [0.7633, 0.87387],149 [0.7967, 0.88288],150 [0.8383, 0.89189],151 [0.8717, 0.9009],152 [0.905, 0.90991],153 [0.9383, 0.91592],154 [0.9717, 0.92492],155 [0.9967, 0.93093],156 [1.03, 0.93694],157 [2.2, 1],158];159160/** Linear read of a rising table, clamped at both ends. */161export function read(162 table: readonly (readonly [number, number])[],163 x: number,164): number {165 const first = table[0];166 const last = table[table.length - 1];167 if (!first || !last) return 0;168 if (x <= first[0]) return first[1];169 if (x >= last[0]) return last[1];170 for (let i = 1; i < table.length; i++) {171 const hi = table[i];172 const lo = table[i - 1];173 if (hi && lo && x <= hi[0]) {174 return lo[1] + ((hi[1] - lo[1]) * (x - lo[0])) / (hi[0] - lo[0]);175 }176 }177 return last[1];178}179180/** One card. Leave the words out and the picture is the whole card. */181export interface RailCard {182 image?: string;183 title?: string;184 /** A line of small print under the title. */185 note?: string;186 tag?: string;187}188189const POSTERS = "https://kuchi-media.kalarislabs.com/components/art/";190191export const DEFAULT_CARDS: readonly RailCard[] = (192 [193 ["orbit-gallery", "Orbit Gallery", 300],194 ["moodboard-reveal", "Moodboard Reveal", 150],195 ["hero-launch", "Hero Launch", 170],196 ["phone-frame", "Phone Frame", 240],197 ["count-grid", "Count Grid", 47],198 ["terminal-simulator", "Terminal Simulator", 200],199 ["logo-flicker", "Logo Flicker", 100],200 ["laptop-frame", "Laptop Frame", 240],201 ["announce-title", "Announce Title", 170],202 ] as const203).map(([slug, title, frames]) => ({204 image: `${POSTERS}art-${String((slug.length % 12) + 1).padStart(2, '0')}.svg`,205 title,206 note: `Scene · ${frames} frames`,207 tag: `@kuchi/${slug}`,208}));209210export interface CardRailProps {211 /**212 * The cards, in order. The rail repeats them if it runs out.213 *214 * Also accepts one string, for the customizer and for quick edits: cards215 * split by `|`, and each card's picture, title, small print and tag split by216 * `>` — `"https://… > Inbox > 4 screens > @acme/inbox | https://…"`. A card217 * that is only a URL is only a picture. Not commas or `;`: a data: URL has218 * both.219 */220 cards?: readonly RailCard[] | string;221 /** The line that holds the top of the frame. */222 heading?: string;223 /** Frame the first flick starts on. Negative starts the scene already moving. */224 from?: number;225 /** How many flicks. Each one carries the rail about another card along. */226 flicks?: number;227 /** Frames between one flick leaving and the next. */228 every?: number;229 /** Where the rail sits before it moves, in layout pixels. */230 offset?: number;231 /**232 * The backdrop: two colour stops split by `|`, or one picture.233 *234 * A picture because a brand backdrop is often not a gradient at all — the235 * recording this was measured from has corners that satisfy a linear fit and a236 * middle that is 40 levels darker than one, which is a mesh or a painted plate237 * and not something two stops can be talked into.238 */239 backdrop?: string;240 theme?: Partial<KuchiTheme>;241 mode?: "light" | "dark";242 fontFamily?: string;243}244245export function CardRail({246 cards = DEFAULT_CARDS,247 heading = "Browse scenes",248 from = 0,249 flicks = 3,250 every = 30,251 offset = 0,252 backdrop = "",253 theme,254 mode = "light",255 fontFamily = "Default",256}: CardRailProps) {257 const frame = useCurrentFrame();258 const { fps, width, height } = useVideoConfig();259 const t = useKuchiTheme(theme, mode);260 const face = resolveFont(fontFamily) ?? SANS;261262 const u = height / REF_H;263 const ox = (width - REF_W * u) / 2;264265 const deck = toCards(cards);266 // No cards is a rail of blank ones, not a modulo by zero.267 const count = Math.max(1, deck.length);268 const stops = split(backdrop);269 const only = stops.length === 1 ? (stops[0] ?? "") : "";270 const plate = only.startsWith("data:") || only.startsWith("/") ? only : "";271272 /**273 * Flicks add up.274 *275 * Each one is the same measured curve started `every` frames after the last,276 * and the rail's position is their sum — so a flick begun while the one before277 * it is still creeping carries that creep with it, which is what repeated278 * swipes actually do. `read` clamps at both ends, so a flick that has not279 * started contributes nothing and one that has finished contributes all of it.280 */281 let travelled = 0;282 for (let k = 0; k < Math.max(1, Math.round(flicks)); k++) {283 travelled += TRAVEL * read(FLICK, (frame - from - k * every) / fps);284 }285 const pitch = CARD_W + GAP;286287 // Enough cards to cover the frame at its widest, plus one leaving and one288 // arriving. The rail repeats the list rather than running out.289 const span = Math.ceil(REF_W / pitch) + 3;290 // The rail has a beginning. Cards repeat to the right for as long as the flick291 // needs them, but nothing is drawn before the first one — a loop that wraps292 // round puts a card in the empty half of the frame the scene opens on.293 const first = Math.max(0, Math.floor((travelled - offset) / pitch));294 // The rail can show one card twice. Studio outlines the copy nearest the295 // middle of the frame; the other is only a picture of it.296 const nearest = new Map<number, number>();297 for (let n = 0; n < span; n++) {298 const i = first + n;299 const k = ((i % count) + count) % count;300 const d = Math.abs(i * pitch - travelled + offset - (REF_W - CARD_W) / 2);301 const held = nearest.get(k);302 const dHeld =303 held === undefined304 ? Number.POSITIVE_INFINITY305 : Math.abs(held * pitch - travelled + offset - (REF_W - CARD_W) / 2);306 if (d < dHeld) nearest.set(k, i);307 }308309 // Both stops are mixed toward *blues*, never toward the page. The page is a310 // near-neutral, its hue in oklch is undefined, and interpolating the accent311 // through it comes out somewhere else entirely — measured once already, a blue312 // accent over a warm off-white mixed to a pale green.313 const from0 = stops[0] ?? mixOklch(t.primary, "#0b1f3d", 0.55);314 const to0 = stops[1] ?? mixOklch(t.primary, "#dceaff", 0.78);315 // A theme with a transparent page asks for no page: no backdrop, so the rail316 // sits on whatever is under it, and a heading in ink rather than mixed off it.317 const bare = parseColor(t.background).alpha === 0;318319 return (320 <AbsoluteFill321 style={322 bare323 ? undefined324 : plate325 ? { backgroundColor: t.background }326 : { background: `linear-gradient(${ANGLE}deg, ${from0}, ${to0})` }327 }328 >329 {plate && !bare && (330 <Plate331 src={plate}332 style={{ position: "absolute", inset: 0, objectFit: "cover" }}333 />334 )}335 <div336 style={{337 position: "absolute",338 left: ox,339 top: 0,340 width: REF_W * u,341 height: REF_H * u,342 fontFamily: face,343 textRendering: "geometricPrecision",344 overflow: "hidden",345 }}346 >347 {heading && (348 <div349 style={{350 position: "absolute",351 left: 0,352 right: 0,353 top: (HEAD_BASE - HEAD_CAP * 1.32) * u,354 textAlign: "center",355 fontSize: HEAD_CAP * 1.38 * u,356 lineHeight: 1,357 fontWeight: 500,358 color: bare ? t.foreground : mixOklch(to0, t.background, 0.62),359 }}360 >361 {heading}362 </div>363 )}364 <div365 style={{366 position: "absolute",367 inset: 0,368 // The plane. `HORIZON` is where it is life-size, so the tilt pivots369 // about a line inside the visible band rather than about the top of370 // a box nobody can see.371 perspective: DEPTH * u,372 perspectiveOrigin: `50% ${HORIZON * u}px`,373 }}374 >375 <div376 style={{377 position: "absolute",378 inset: 0,379 transform: `rotateX(${TILT}deg)`,380 transformOrigin: `50% ${HORIZON * u}px`,381 transformStyle: "preserve-3d",382 }}383 >384 {Array.from({ length: span }, (_, n) => {385 const i = first + n;386 const x = i * pitch - travelled + offset;387 const k = ((i % count) + count) % count;388 const card = deck[k] ?? {};389 return (390 <Item key={i} index={k} primary={nearest.get(k) === i}>391 <Card392 x={x * u}393 src={card.image ?? ""}394 title={card.title ?? ""}395 note={card.note ?? ""}396 tag={card.tag ?? ""}397 t={t}398 u={u}399 />400 </Item>401 );402 })}403 </div>404 </div>405 </div>406 </AbsoluteFill>407 );408}409410const split = (s: string) =>411 s412 .split("|")413 .map((v) => v.trim())414 .filter(Boolean);415416/** The string form of `cards`: see `CardRailProps.cards`. */417export function toCards(418 input: readonly RailCard[] | string,419): readonly RailCard[] {420 if (typeof input !== "string") return input;421 return input422 .split("|")423 .filter((c) => c.trim())424 .map((c) => {425 const [image = "", title = "", note = "", tag = ""] = c426 .split(">")427 .map((v) => v.trim());428 return { image, title, note, tag };429 });430}431432/**433 * One card: a picture, and under it a title and a line of small print. Forwards434 * its `ref` and takes a `style` on top of its own so Remotion Studio can435 * outline it and nudge it (see `Item`) — forwardRef, not a `ref` prop, which436 * React 18 would drop.437 */438const Card = forwardRef<439 HTMLDivElement,440 {441 x: number;442 src: string;443 title: string;444 note: string;445 tag: string;446 t: KuchiTheme;447 u: number;448 style?: CSSProperties;449 }450>(function Card({ x, src, title, note, tag, t, u, style }, ref) {451 const bodied = Boolean(title || note || tag);452 const shot = CARD_W / SHOT_ASPECT;453 return (454 <div455 ref={ref}456 style={{457 ...style,458 position: "absolute",459 left: x,460 top: CARD_TOP * u,461 width: CARD_W * u,462 height: CARD_H * u,463 borderRadius: RADIUS * u,464 overflow: "hidden",465 background: t.card,466 }}467 >468 <Plate469 src={src}470 style={{471 display: "block",472 width: CARD_W * u,473 // With no body the picture *is* the card. That is not a special case474 // for its own sake — it is what lets a whole card be handed in as one475 // image when the layout below is somebody else's.476 height: (bodied ? shot : CARD_H) * u,477 objectFit: "cover",478 }}479 />480 {bodied && (481 <div style={{ padding: `${13 * u}px ${15 * u}px` }}>482 <div483 style={{484 fontSize: 15 * u,485 lineHeight: 1.25,486 fontWeight: 700,487 color: t.foreground,488 }}489 >490 {title}491 </div>492 <div493 style={{494 marginTop: 5 * u,495 fontSize: 12.5 * u,496 lineHeight: 1.3,497 color: t.mutedForeground,498 }}499 >500 {note}501 </div>502 {tag && (503 <div504 style={{505 marginTop: 14 * u,506 display: "inline-block",507 padding: `${5 * u}px ${10 * u}px`,508 borderRadius: 999,509 fontSize: 11.5 * u,510 lineHeight: 1.2,511 fontWeight: 500,512 color: t.mutedForeground,513 border: `1px solid ${t.border}`,514 }}515 >516 {tag}517 </div>518 )}519 </div>520 )}521 </div>522 );523});524525/**526 * A root-relative asset is a `public/` file. Only the site's own Player serves527 * it at that path; Remotion Studio and a render know its URL through528 * `staticFile()` alone — so every environment but the Player rewrites it.529 */530function resolveSrc(src: string): string {531 const isLocal = src.startsWith("/") && !src.startsWith("//");532 if (!isLocal || getRemotionEnvironment().isPlayer) return src;533 // A value that already came out of staticFile() carries the static base534 // (`/static-<hash>/…`); running it through again would prefix it twice.535 const base = staticFile("_").slice(0, -2);536 if (base && src.startsWith(`${base}/`)) return src;537 try {538 return staticFile(src.replace(/^\/+/, ""));539 } catch {540 return src;541 }542}543544/**545 * A picture that holds the render until it has actually loaded.546 *547 * Without it a frame can be captured before the image arrives and the card comes548 * out empty — invisible in the Player, where an image simply appears, and silent549 * in an mp4 until somebody watches it. Remotion's own `Img` is avoided for the550 * reason `hero-launch` documents: it awaits `decode()`, which the headless551 * compositor rejects for some progressive JPEGs and hangs the export.552 */553function Plate({ src, style }: { src: string; style: CSSProperties }) {554 // No picture is an empty surface, not an <img> that never loads and holds555 // the render open.556 return src ? <Picture src={src} style={style} /> : <div style={style} />;557}558559function Picture({ src, style }: { src: string; style: CSSProperties }) {560 const [handle] = useState(() => delayRender(`card-rail: ${src}`));561 const release = useCallback(() => continueRender(handle), [handle]);562 return (563 // biome-ignore lint/performance/noImgElement: Remotion frame, not a Next route.564 <img // eslint-disable-line @remotion/warn-native-media-tag -- onLoad releases the frame; <Img> hangs on some JPEGs565 src={resolveSrc(src)}566 alt=""567 // Tailwind's preflight sets `img { max-width: 100% }`, which collapses an568 // image inside a shrink-to-fit box to zero pixels wide on the site while569 // rendering perfectly in an mp4. Size it here and say so.570 style={{ ...style, maxWidth: "none" }}571 onLoad={release}572 onError={release}573 />574 );575}









