Glass Capsule
A glass capsule slides over the focus word of a two-line headline, magnifying it in italic.
Source
components/kuchi/glass-capsule.tsx
1"use client";23import { loadFont as loadSans } from "@remotion/google-fonts/InstrumentSans";4import { loadFont as loadSerif } from "@remotion/google-fonts/InstrumentSerif";5import type React from "react";6import { Fragment, useEffect, useId, useMemo, useState } from "react";7import {8 AbsoluteFill,9 continueRender,10 delayRender,11 Easing,12 interpolate,13 useCurrentFrame,14 useVideoConfig,15} from "remotion";1617const SANS = loadSans("normal", { weights: ["500"], subsets: ["latin"] });18const SERIF = loadSerif("italic", { weights: ["400"], subsets: ["latin"] });1920/* Lines are Instrument Sans 500; the focus word is Instrument Serif italic. */21const SANS_TRACK = -0.035;22const SERIF_TRACK = -0.01;23const SANS_FONT = (px: number, family: string = SANS.fontFamily) =>24 `500 ${px}px "${family}"`;25const SERIF_FONT = (px: number) => `italic 400 ${px}px "${SERIF.fontFamily}"`;2627/* gradients.sh "silk" palette, as the clip-text fill the focus word lights up into. */28const SILK = ["#3b3fd8", "#f3d6c0", "#8a7bff"] as const;2930function silkFill(theme: "dark" | "light", d: number) {31 const [c0, c1, c2] = SILK;32 const o = (d * 18).toFixed(1);33 return theme === "dark"34 ? `linear-gradient(100deg, ${c2} ${o}%, ${c1} ${(52 + d * 10).toFixed(1)}%, ${c2} ${(104 + d * 10).toFixed(1)}%)`35 : `linear-gradient(100deg, ${c0} ${o}%, ${c2} ${(56 + d * 10).toFixed(1)}%, ${c0} ${(108 + d * 10).toFixed(1)}%)`;36}3738export interface GlassCapsuleProps {39 lines?: string[];40 focus?: string;41 /** How much the capsule magnifies the focus word once it rests. */42 magnify?: number;43 accent?: string;44 /** Text color; overrides the theme ink. */45 ink?: string;46 background?: string;47 /** Typeface for the lines; the focus word stays Instrument Serif. Load it yourself; Instrument Sans by default. */48 fontFamily?: string;49 /** Size of the text block, around the frame's center. */50 scale?: number;51 /** Frames to hold the first frame before anything moves. */52 delay?: number;53 /** Film grain over the scene. */54 grain?: boolean;55 speed?: number;56 theme?: "dark" | "light";57}5859const EASE_IO = Easing.bezier(0.65, 0, 0.35, 1);60const EASE_OUT = Easing.bezier(0.22, 1, 0.36, 1);61const EASE_GLIDE = Easing.bezier(0.33, 0, 0.12, 1);62const CLAMP = {63 extrapolateLeft: "clamp",64 extrapolateRight: "clamp",65} as const;6667const THEMES = {68 dark: {69 bg: "#0A0A0B",70 fg: "#F3F2EF",71 inner: "#0A0A0B",72 tint: "rgba(255,255,255,0.03)",73 rimHi: 0.9,74 rimLo: 0.24,75 shadow: "rgba(0,0,0,0.75)",76 edgeLine: "rgba(255,255,255,0.06)",77 innerShade: "rgba(0,0,0,0.45)",78 sheen: 0.12,79 grain: 0.06,80 },81 light: {82 bg: "#F5F4F0",83 fg: "#121214",84 inner: "#F5F4F0",85 tint: "rgba(255,255,255,0.08)",86 rimHi: 1,87 rimLo: 0.5,88 shadow: "rgba(60,52,40,0.26)",89 edgeLine: "rgba(18,18,20,0.08)",90 innerShade: "rgba(60,52,40,0.16)",91 sheen: 0.5,92 grain: 0.045,93 },94} as const;9596type Palette = (typeof THEMES)[keyof typeof THEMES];9798let measureCtx: CanvasRenderingContext2D | null = null;99100/** (ascent - descent) in em of the face's line metrics, for baseline matching. */101function emLift(serif: boolean, ready: boolean, family: string) {102 if (!ready || typeof document === "undefined") return 0;103 if (!measureCtx)104 measureCtx = document.createElement("canvas").getContext("2d");105 if (!measureCtx) return 0;106 measureCtx.font = serif ? SERIF_FONT(100) : SANS_FONT(100, family);107 const m = measureCtx.measureText("Hg");108 return (m.fontBoundingBoxAscent - m.fontBoundingBoxDescent) / 100;109}110111/** Advance width in em of `s` (tracking included); a rough table until fonts load. */112function emWidth(s: string, serif: boolean, ready: boolean, family: string) {113 const track = serif ? SERIF_TRACK : SANS_TRACK;114 if (ready && typeof document !== "undefined") {115 if (!measureCtx)116 measureCtx = document.createElement("canvas").getContext("2d");117 if (measureCtx) {118 measureCtx.font = serif ? SERIF_FONT(100) : SANS_FONT(100, family);119 return measureCtx.measureText(s).width / 100 + track * [...s].length;120 }121 }122 let w = 0;123 for (const ch of s) {124 if (ch === " ") w += 0.24;125 else if ("iljtfr,.;:!'|".includes(ch)) w += 0.28;126 else if ("mwMW".includes(ch)) w += 0.8;127 else if (ch >= "A" && ch <= "Z") w += 0.64;128 else w += serif ? 0.44 : 0.54;129 w += track;130 }131 return w;132}133134function Grain({ opacity }: { opacity: number }) {135 const id = `g${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;136 return (137 <svg138 width="100%"139 height="100%"140 style={{ position: "absolute", inset: 0, opacity, pointerEvents: "none" }}141 aria-hidden142 >143 <filter id={id}>144 <feTurbulence145 type="fractalNoise"146 baseFrequency="0.9"147 numOctaves={2}148 seed={29}149 stitchTiles="stitch"150 />151 <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" />152 </filter>153 <rect width="100%" height="100%" filter={`url(#${id})`} />154 </svg>155 );156}157158function lensMap(w: number, h: number, edge: number) {159 const r = h / 2;160 const iw = Math.max(1, w - edge * 2);161 const ih = Math.max(1, h - edge * 2);162 const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='${w}' height='${h}'><defs><linearGradient id='x'><stop offset='0' stop-color='#000'/><stop offset='1' stop-color='#f00'/></linearGradient><linearGradient id='y' x2='0' y2='1'><stop offset='0' stop-color='#000'/><stop offset='1' stop-color='#0f0'/></linearGradient><filter id='b' x='-50%' y='-50%' width='200%' height='200%'><feGaussianBlur stdDeviation='${edge * 0.5}'/></filter></defs><rect width='${w}' height='${h}' rx='${r}' fill='url(#x)'/><rect width='${w}' height='${h}' rx='${r}' fill='url(#y)' style='mix-blend-mode:screen'/><rect x='${edge}' y='${edge}' width='${iw}' height='${ih}' rx='${Math.max(0, r - edge)}' fill='rgb(128,128,0)' filter='url(#b)'/></svg>`;163 return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;164}165166function splitFocus(lines: string[], focus: string) {167 const clean = (w: string) => w.replace(/[^\p{L}\p{N}]/gu, "").toLowerCase();168 const target = clean(focus);169 for (let li = lines.length - 1; li >= 0; li--) {170 const words = lines[li].split(" ");171 const wi = words.findIndex((w) => clean(w) === target);172 if (wi >= 0) {173 const word = words[wi];174 const before = [...words.slice(0, wi), ""].join(" ");175 const after =176 wi < words.length - 1 ? ["", ...words.slice(wi + 1)].join(" ") : "";177 return { line: li, before, word, after };178 }179 }180 const li = lines.length - 1;181 const words = lines[li].split(" ");182 const last = words[words.length - 1];183 return {184 line: li,185 before: [...words.slice(0, -1), ""].join(" "),186 word: last,187 after: "",188 };189}190191interface Seg {192 before: string;193 word: string;194 after: string;195}196197/** The focus line laid out around its word: `left: 0` is the word's centre. */198function AnchoredLine({199 seg,200 color,201 wordStyle,202 wordNode,203 style,204 room,205 beforeW,206 wordW,207}: {208 wordNode: React.ReactNode;209 seg: Seg;210 color: string;211 wordStyle: React.CSSProperties;212 style: React.CSSProperties;213 room: number;214 beforeW: number;215 wordW: number;216}) {217 return (218 <div219 style={{220 position: "absolute",221 left: -(beforeW + wordW / 2),222 top: 0,223 display: "flex",224 color,225 }}226 >227 <span style={{ ...style, transform: `translateX(${-room}px)` }}>228 {seg.before}229 </span>230 <span style={wordStyle}>{wordNode}</span>231 <span style={{ ...style, transform: `translateX(${room}px)` }}>232 {seg.after}233 </span>234 </div>235 );236}237238function Capsule({239 fg,240 inner,241 t,242 seg,243 lw,244 lh,245 lineH,246 offset,247 mag,248 disp,249 wordStyle,250 wordNode,251 textStyle,252 p,253 u,254 enter,255 room,256 beforeW,257 wordW,258}: {259 fg: string;260 inner: string;261 wordNode: React.ReactNode;262 room: number;263 beforeW: number;264 wordW: number;265 t: number;266 seg: Seg;267 lw: number;268 lh: number;269 lineH: number;270 offset: number;271 mag: number;272 disp: number;273 wordStyle: React.CSSProperties;274 textStyle: React.CSSProperties;275 p: Palette;276 u: number;277 enter: number;278}) {279 const fid = `cap${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;280 const radius = lh / 2;281 const edge = lh * 0.26;282 const M = Math.ceil(disp + 8 * u);283 const map = lensMap(Math.round(lw), Math.round(lh), edge);284 const rimX = 24 + interpolate(t, [10, 80], [0, 14], CLAMP);285 return (286 <div287 style={{288 position: "absolute",289 left: "50%",290 top: (lineH - lh) / 2,291 width: lw,292 height: lh,293 transform: `translateX(${-lw / 2 + offset}px)`,294 opacity: enter,295 }}296 >297 <svg width={0} height={0} style={{ position: "absolute" }} aria-hidden>298 <defs>299 <filter300 id={fid}301 x={0}302 y={0}303 width={lw + M * 2}304 height={lh + M * 2}305 filterUnits="userSpaceOnUse"306 primitiveUnits="userSpaceOnUse"307 colorInterpolationFilters="sRGB"308 >309 <feImage310 href={map}311 x={M}312 y={M}313 width={lw}314 height={lh}315 preserveAspectRatio="none"316 result="map"317 />318 {[319 ["r", 1, "1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0"],320 ["g", 0.94, "0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0"],321 ["b", 0.88, "0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0"],322 ].map(([k, s, m]) => (323 <Fragment key={k as string}>324 <feDisplacementMap325 in="SourceGraphic"326 in2="map"327 scale={disp * (s as number)}328 xChannelSelector="R"329 yChannelSelector="G"330 result={`d${k}`}331 />332 <feColorMatrix333 in={`d${k}`}334 type="matrix"335 values={m as string}336 result={`c${k}`}337 />338 </Fragment>339 ))}340 <feComposite341 in="cr"342 in2="cg"343 operator="arithmetic"344 k2={1}345 k3={1}346 result="rg"347 />348 <feComposite in="rg" in2="cb" operator="arithmetic" k2={1} k3={1} />349 </filter>350 </defs>351 </svg>352 <div353 style={{354 position: "absolute",355 inset: 0,356 borderRadius: radius,357 boxShadow: `0 0 0 1px ${p.edgeLine}, 0 ${20 * u}px ${40 * u}px -${12 * u}px ${p.shadow}, 0 ${4 * u}px ${10 * u}px -${3 * u}px ${p.shadow}`,358 }}359 />360 <div361 style={{362 position: "absolute",363 inset: 0,364 borderRadius: radius,365 overflow: "hidden",366 isolation: "isolate",367 }}368 >369 <div370 style={{371 position: "absolute",372 left: -M,373 top: -M,374 width: lw + M * 2,375 height: lh + M * 2,376 filter: `url(#${fid})`,377 }}378 >379 <div380 style={{381 position: "absolute",382 inset: 0,383 background: inner,384 }}385 />386 <div387 style={{388 position: "absolute",389 inset: 0,390 transform: `scale(${mag})`,391 transformOrigin: "50% 50%",392 }}393 >394 <div395 style={{396 position: "absolute",397 left: M + lw / 2 - offset,398 top: M + (lh - lineH) / 2,399 }}400 >401 <AnchoredLine402 seg={seg}403 color={fg}404 wordStyle={wordStyle}405 wordNode={wordNode}406 style={textStyle}407 room={room}408 beforeW={beforeW}409 wordW={wordW}410 />411 </div>412 </div>413 </div>414 <div style={{ position: "absolute", inset: 0, background: p.tint }} />415 <div416 style={{417 position: "absolute",418 inset: 0,419 borderRadius: radius,420 boxShadow: `inset 0 ${-8 * u}px ${18 * u}px -${6 * u}px ${p.innerShade}, inset 0 0 ${10 * u}px ${p.innerShade}`,421 }}422 />423 <div424 style={{425 position: "absolute",426 left: radius * 0.4,427 right: radius * 0.4,428 top: 2 * u,429 height: lh * 0.4,430 borderRadius: `${radius}px ${radius}px ${radius * 0.6}px ${radius * 0.6}px`,431 background: `linear-gradient(180deg, rgba(255,255,255,${p.sheen}), rgba(255,255,255,0.02) 60%, rgba(255,255,255,0) 100%)`,432 }}433 />434 <div435 style={{436 position: "absolute",437 inset: 0,438 borderRadius: radius,439 padding: 1.5 * u,440 background: `radial-gradient(ellipse 40% 70% at ${rimX}% 0%, rgba(255,255,255,${p.rimHi}), transparent 100%), radial-gradient(ellipse 36% 60% at ${100 - rimX}% 100%, rgba(255,255,255,${p.rimLo}), transparent 100%), rgba(255,255,255,${p.rimLo * 0.3})`,441 WebkitMask:442 "linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)",443 WebkitMaskComposite: "xor",444 maskComposite: "exclude",445 }}446 />447 <div448 style={{449 position: "absolute",450 inset: 0,451 borderRadius: radius,452 boxShadow: `inset 0 0 0 1px rgba(255,255,255,${p.rimLo * 0.5})`,453 }}454 />455 </div>456 </div>457 );458}459460/** The foreground at `scale`, around the frame's center; nothing extra at 1. */461function ScaleLayer({462 scale,463 children,464}: {465 scale: number;466 children: React.ReactNode;467}) {468 if (scale === 1) return children;469 return (470 <AbsoluteFill style={{ transform: `scale(${scale})` }}>471 {children}472 </AbsoluteFill>473 );474}475476export function GlassCapsule({477 lines = ["Launch films", "that move."],478 focus = "move",479 magnify = 1.1,480 accent = "#3B5BFD",481 ink,482 background,483 fontFamily = SANS.fontFamily,484 scale = 1,485 delay = 0,486 grain = true,487 speed = 1,488 theme = "dark",489}: GlassCapsuleProps) {490 const t = Math.max(0, useCurrentFrame() - delay) * speed;491 const { width, height, durationInFrames } = useVideoConfig();492 const p = THEMES[theme];493 const fg = ink ?? p.fg;494 const stage =495 background === "transparent" ? "transparent" : (background ?? p.bg);496 // The capsule hides the line behind it, so its inside stays opaque.497 const inner =498 background === undefined || background === "transparent"499 ? p.inner500 : background;501 const u = height / 720;502503 const [ready, setReady] = useState(false);504 const [handle] = useState(() => delayRender("glass-capsule: fonts"));505 useEffect(() => {506 let alive = true;507 const done = () => {508 if (alive) setReady(true);509 };510 Promise.all([SANS.waitUntilDone(), SERIF.waitUntilDone()])511 .then(() =>512 typeof document !== "undefined" && document.fonts513 ? Promise.all([514 document.fonts.load(SANS_FONT(100, fontFamily)),515 document.fonts.load(SERIF_FONT(100)),516 ])517 : undefined,518 )519 .then(done, done);520 return () => {521 alive = false;522 };523 }, [fontFamily]);524 useEffect(() => {525 if (ready) continueRender(handle);526 }, [ready, handle]);527528 const seg = splitFocus(lines, focus);529 const em = useMemo(() => {530 const lineEm = lines.map((l, i) =>531 i === seg.line532 ? emWidth(seg.before, false, ready, fontFamily) +533 emWidth(seg.word, true, ready, fontFamily) +534 emWidth(seg.after, false, ready, fontFamily)535 : emWidth(l, false, ready, fontFamily),536 );537 return {538 lines: lineEm,539 before: emWidth(seg.before, false, ready, fontFamily),540 word: emWidth(seg.word, true, ready, fontFamily),541 // Serif baseline offset vs the sans baseline, both on the same line-height.542 drop:543 (emLift(false, ready, fontFamily) - emLift(true, ready, fontFamily)) /544 2,545 };546 }, [lines, seg.line, seg.before, seg.word, seg.after, ready, fontFamily]);547548 const longest = Math.max(...em.lines, 0.1);549 const size = Math.min(550 176 * u,551 (width * 0.8) / longest,552 (height * 0.62) / (lines.length * 1.04),553 );554 const lineH = size * 1.06;555 const blockH = lines.length * lineH;556 const top = (height - blockH) / 2;557558 const wordW = em.word * size;559 const beforeW = em.before * size;560 const lineW = em.lines[seg.line] * size;561 const wordCenter = (width - lineW) / 2 + beforeW + wordW / 2;562 const restMag = magnify;563 const padX = (wordW * (restMag - 1)) / 2 + size * 0.24;564 const lw = wordW + padX * 2;565 const lh = size * 1.0;566567 const glide = EASE_GLIDE(interpolate(t, [10, 74], [0, 1], CLAMP));568 const start = -(wordCenter + lw / 2 + 40 * u);569 const settle =570 t > 74571 ? Math.sin(((t - 74) / 16) * Math.PI) *572 Math.exp(-(t - 74) / 9) *573 5 *574 u *575 (t < 106 ? 1 : 0)576 : 0;577 const offset = start * (1 - glide) + settle;578 const travel = 1 - glide;579 const mag =580 1.05 + (restMag - 1.05) * EASE_IO(interpolate(t, [52, 80], [0, 1], CLAMP));581 const disp = (18 + 16 * travel) * u;582 const enter = interpolate(t, [8, 14], [0, 1], CLAMP);583 const lit = interpolate(t, [72, 90], [0, 1], { ...CLAMP, easing: EASE_OUT });584 const sheen = interpolate(585 t,586 [72, Math.max(73, durationInFrames)],587 [0, 1],588 CLAMP,589 );590591 const room =592 Math.max(0, padX - size * 0.15) *593 EASE_IO(interpolate(t, [50, 80], [0, 1], CLAMP));594 const shiftLine = seg.after ? 0 : room / 2;595 const rise = (d: number) =>596 interpolate(t, [d, d + 20], [0, 1], { ...CLAMP, easing: EASE_OUT });597598 const textStyle: React.CSSProperties = {599 fontFamily,600 fontWeight: 500,601 fontSize: size,602 letterSpacing: `${SANS_TRACK}em`,603 lineHeight: `${lineH}px`,604 height: lineH,605 whiteSpace: "pre",606 };607 // The word lights from ink into the silk gradient; the accent marks its full stop.608 const wordStyle: React.CSSProperties = {609 ...textStyle,610 fontFamily: SERIF.fontFamily,611 fontStyle: "italic",612 fontWeight: 400,613 letterSpacing: `${SERIF_TRACK}em`,614 paddingRight: size * 0.06,615 marginRight: -size * 0.06,616 display: "inline-block",617 transform: `translateY(${(em.drop * size).toFixed(2)}px)`,618 backgroundImage: silkFill(theme, sheen),619 WebkitBackgroundClip: "text",620 backgroundClip: "text",621 color: "transparent",622 WebkitTextFillColor: `color-mix(in oklab, ${fg} ${((1 - lit) * 100).toFixed(1)}%, transparent)`,623 };624 const stop = /[.!?…]$/.test(seg.word);625 const wordNode = (626 <>627 {stop ? seg.word.slice(0, -1) : seg.word}628 {stop ? (629 <span630 style={{631 WebkitTextFillColor: `color-mix(in oklab, ${accent} ${(lit * 100).toFixed(1)}%, ${fg})`,632 }}633 >634 {seg.word.slice(-1)}635 </span>636 ) : null}637 </>638 );639640 return (641 <AbsoluteFill style={{ background: stage, overflow: "hidden" }}>642 <ScaleLayer scale={scale}>643 <div644 style={{645 position: "absolute",646 left: 0,647 top,648 width,649 height: blockH,650 }}651 >652 {lines.map((line, i) => {653 const r = rise(i * 4);654 const isFocus = i === seg.line;655 return (656 <div657 key={`${i}-${line}`}658 style={{659 position: "absolute",660 left: 0,661 top: i * lineH,662 width,663 height: lineH,664 display: "flex",665 justifyContent: "center",666 color: fg,667 opacity: r,668 transform: `translateY(${(1 - r) * 26 * u}px)`,669 }}670 >671 {isFocus ? (672 <>673 <span674 style={{675 ...textStyle,676 transform: `translateX(${shiftLine - room}px)`,677 }}678 >679 {seg.before}680 </span>681 <span682 style={{683 position: "relative",684 zIndex: 1,685 height: lineH,686 transform: `translateX(${shiftLine}px)`,687 }}688 >689 <span style={wordStyle}>{wordNode}</span>690 <Capsule691 fg={fg}692 inner={inner}693 t={t}694 seg={seg}695 lw={lw}696 lh={lh}697 lineH={lineH}698 offset={offset}699 mag={mag}700 disp={disp}701 wordStyle={wordStyle}702 wordNode={wordNode}703 textStyle={textStyle}704 p={p}705 u={u}706 enter={enter}707 room={room}708 beforeW={beforeW}709 wordW={wordW}710 />711 </span>712 <span713 style={{714 ...textStyle,715 transform: `translateX(${shiftLine + room}px)`,716 }}717 >718 {seg.after}719 </span>720 </>721 ) : (722 <span style={textStyle}>{line}</span>723 )}724 </div>725 );726 })}727 </div>728 </ScaleLayer>729 {grain ? <Grain opacity={p.grain} /> : null}730 </AbsoluteFill>731 );732}









