Channel Thread
Slack-style chat animation: team messages arrive with typing dots. A work chat filling itself in, the way the channel actually reads: an avatar, a name in bold, a quiet timestamp and the messages as plain lines under them.
Source
components/kuchi/channel-thread.tsx
1"use client";23import { loadFont as loadSans } from "@remotion/google-fonts/Barlow";4import type { CSSProperties } from "react";5import { 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 resolveFont,19 type KuchiTheme,20 useKuchiTheme,21 withAlpha,22} from "@/lib/kuchi-ui";2324/**25 * A work chat filling itself in, the way the channel actually reads.26 *27 * Not bubbles: a transcript. An avatar, a name in bold, a quiet timestamp, and28 * the messages under them as plain lines — the shape every team tool has29 * settled on. Messages land one at a time; a second message from the same30 * person joins the group without repeating the name; and when somebody new31 * starts typing, three dots hold their line until the words arrive. The32 * transcript never creeps: it sits perfectly still between arrivals and then33 * scrolls, once, by exactly the room the new line needs.34 *35 * ## The layout came off a recording and it closes to the pixel36 *37 * Four numbers describe every vertical position in the scene, measured on a38 * 638 × 354 capture by thresholding the ink of eighty frames:39 *40 * name → its first message 37.5941 * message → message 46.0142 * last message → next name 69.0043 * first message, before any scroll, at 158.9044 *45 * That is not a model fitted to the frames, it is *checked* against them. Take46 * the first message's start, add the two arrivals' scroll (46.01 + 2 × 46.01),47 * and the oldest line lands at 20.87; the recording's last frame has it at 21.48 * Carry the same arithmetic down to the newest name and it predicts 138.9 where49 * the recording measures 139.00. Nine tenths of a pixel over a whole scene.50 *51 * ## The scroll is an event, not a drift52 *53 * Between arrivals the transcript is *byte-identical* frame to frame — the54 * measured movement is 0.00px for twenty-nine frames at the head of the clip and55 * for another eight in the middle. Everything that looks like life comes from56 * the arrivals themselves. `SCROLL` is one of those moves, measured: it57 * accelerates for four frames, peaks at 5.1px, and then spends three quarters of58 * a second arriving.59 *60 * A caveat, because it is measured and it is not reproduced: the recording's61 * two-row scroll runs about 1.6× faster in normalised time than its one-row62 * scroll — a longer move that takes *less* time, which is a browser's native63 * smooth-scroll heuristic and not something a scene should imitate. One curve64 * ships, taken from the one-row move, and a two-row move simply travels twice65 * as far along it.66 */6768const { fontFamily: SANS } = loadSans("normal", {69 weights: ["400", "500", "600", "700"],70 subsets: ["latin"],71});7273/* ─────────────────────────────────────────────────────────────────────────74 The transcript, in the recording's own 638 × 354 pixels75 ───────────────────────────────────────────────────────────────────────── */7677export const REF_W = 638;78export const REF_H = 354;7980/** Baseline of a group's first message, below the name. */81export const NAME_GAP = 37.59;82/** Baseline to baseline, within a group. */83export const MSG_GAP = 46.01;84/** Last message of a group to the next group's name. */85export const GROUP_GAP = 69;86/** Where the oldest message sits before anything has arrived. */87export const START_Y = 158.9;88/**89 * The line the newest message rests on, and the whole reason the transcript is90 * still between arrivals.91 *92 * It does not scroll on every message — the recording's second message lands93 * with the stack measurably motionless, 0.00px for twenty-nine frames. It94 * scrolls only by however far the newest baseline would fall *past* this line,95 * which is zero until the thread is tall enough to reach it. One constant96 * replaces a per-message "does this one scroll" flag, and it is what makes the97 * arithmetic close: 158.90 + 46.01 is above it and moves nothing; the next two98 * rows put the newest baseline at 311.50 and the scroll settles at exactly99 * 92.02, which is what the recording measures.100 */101export const ANCHOR = 219.48;102103/** The avatar is square, and its top sits this far above the name's baseline. */104export const AVATAR = 70;105export const AVATAR_X = 119.5;106export const AVATAR_RISE = 28;107/** Left of the text column's box. Ink starts at 201.1 (name) and 202.4 (body). */108export const TEXT_X = 202;109110/** Body type. Cap height measured at 22.40px. */111export const SIZE = 31.2;112/** The timestamp, measured on its digits: cap 18.09. */113export const TIME_SIZE = 24.9;114/** Box top → baseline at `lineHeight: 1`. A face metric, measured, not guessed. */115export const ASC = 28.95;116117/** Typing dots: on the line the message will take, a little above its baseline. */118export const DOT = 5;119export const DOT_GAP = 8.4;120export const DOT_RISE = 5.7;121/** A dot every this many seconds, then the ellipsis starts over. */122export const DOT_BEAT = 0.1;123/**124 * Frames between a group's row opening and the group appearing in it.125 *126 * The room is made first and the person arrives into it: the recording starts127 * scrolling on frame 37 and does not paint the avatar, the name or the first128 * dot until frame 40. Three frames is nothing to watch and everything to match,129 * and it is also what the dots are timed from — anchor their cycle to the scroll130 * instead and the ellipsis is a step out of phase for its whole life.131 */132export const LEAD = 3;133134/**135 * One arrival's scroll, as (seconds since it started, share of the travel).136 *137 * Recovered by correlating each frame's vertical ink profile against the last —138 * which reads the move off every visible row at once rather than tracking one139 * word — and checked against the absolute baseline of the bold name row, which140 * agrees to a third of a pixel.141 */142export const SCROLL: readonly (readonly [number, number])[] = [143 [0, 0],144 [0.0167, 0.004],145 [0.05, 0.016],146 [0.0833, 0.044],147 [0.1167, 0.093],148 [0.15, 0.178],149 [0.1833, 0.289],150 [0.2167, 0.398],151 [0.25, 0.486],152 [0.2833, 0.557],153 [0.3167, 0.616],154 [0.35, 0.663],155 [0.3833, 0.702],156 [0.4167, 0.737],157 [0.45, 0.767],158 [0.4833, 0.791],159 [0.5167, 0.814],160 [0.55, 0.834],161 [0.5833, 0.852],162 [0.6167, 0.867],163 [0.65, 0.881],164 [0.6917, 0.893],165 [0.7167, 0.903],166 [0.75, 0.912],167 [0.7833, 0.919],168 [1.1, 1],169];170171/**172 * How far a line is faded, by its height in the frame.173 *174 * Read as an envelope over the whole clip: the brightest any pixel of a line175 * ever got at each height. Taking the maximum across every frame is what makes176 * it a property of the *position* — one sample would have read a line with no177 * ascenders as a dip in the gradient.178 *179 * It stops at a tenth rather than at nothing: the oldest line is cut off by the180 * frame, not erased by the fade.181 */182export const FADE: readonly (readonly [number, number])[] = [183 [10, 0.098],184 [25, 0.125],185 [40, 0.149],186 [55, 0.216],187 [70, 0.357],188 [85, 0.518],189 [100, 0.651],190 [115, 0.843],191 [140, 0.98],192 [175, 1],193];194195type Table = readonly (readonly [number, number])[];196197/** Linear read of a rising table, clamped at both ends. */198export function read(table: Table, x: number): number {199 const first = table[0];200 const last = table[table.length - 1];201 if (!first || !last) return 0;202 if (x <= first[0]) return first[1];203 if (x >= last[0]) return last[1];204 for (let i = 1; i < table.length; i++) {205 const hi = table[i];206 const lo = table[i - 1];207 if (hi && lo && x <= hi[0]) {208 return lo[1] + ((hi[1] - lo[1]) * (x - lo[0])) / (hi[0] - lo[0]);209 }210 }211 return last[1];212}213214interface Line {215 /** Baseline in transcript space, before any scroll. */216 y: number;217 /** Baseline of this group's name row, when this line heads a group. */218 nameY: number;219 group: number;220 /** First line of a group, i.e. the one the name and avatar belong to. */221 head: boolean;222 text: string;223 /** Frame the words land on. The row itself opens at `opens`. */224 at: number;225 opens: number;226}227228/**229 * Lay the transcript out once, in transcript space.230 *231 * Positions are absolute and never re-flow: the scroll is a single translate232 * over the top of them. That is what lets every arrival be a number rather than233 * a layout pass, and it is why the stack can be perfectly still between them.234 */235export function layout(236 groups: { person: string; time: string; lines: string[] }[],237): Line[] {238 const out: Line[] = [];239 let last = START_Y - NAME_GAP;240 let first = true;241 for (let g = 0; g < groups.length; g++) {242 const group = groups[g];243 if (!group) continue;244 for (let m = 0; m < group.lines.length; m++) {245 const head = m === 0;246 const nameY = head ? (first ? last : last + GROUP_GAP) : 0;247 const y = head ? nameY + NAME_GAP : last + MSG_GAP;248 out.push({249 y,250 nameY,251 group: g,252 head,253 text: group.lines[m] ?? "",254 at: 0,255 opens: 0,256 });257 last = y;258 first = false;259 }260 }261 return out;262}263264/**265 * One message. A message with the same author, time and avatar as the one266 * above it joins that group, under one name, the way the channel reads.267 */268export interface ThreadMessage {269 text: string;270 author?: string;271 time?: string;272 avatar?: string;273 /** Frame the words land on. Default: the measured 0, 12, 60, 84, then every 24. */274 at?: number;275 /**276 * Frame the row opens on, before the words land — typing dots, if it starts277 * a group. Default: the measured 0, 12, 37, 72, then every 24.278 */279 opens?: number;280}281282export const DEFAULT_MESSAGES: readonly ThreadMessage[] = [283 ["rhea", "9:41 AM", "07", "Launch video by Thursday?"],284 ["rhea", "9:41 AM", "07", "We have nothing shot."],285 ["sam", "9:42 AM", "13", "Already done."],286 ["sam", "9:42 AM", "13", "Built it out of kuchi."],287].map(([author, time, face, text]) => ({288 author,289 time,290 avatar: `https://kuchi-media.kalarislabs.com/components/art/avatar-${face}.svg`,291 text: text ?? "",292}));293294/** The recording's four arrivals; after them, a message every 24 frames. */295const BEATS = [0, 12, 60, 84];296const OPENS = [0, 12, 37, 72];297298/**299 * The string form of `messages`, for the customizer and for quick edits:300 * messages split by `|`, each `avatar > name time > text`. The name runs to301 * the first space. A message that is only text continues the one above it.302 *303 * "/avatars/07.jpg > rhea 9:41 AM > Launch video? | Nothing shot."304 */305export function toMessages(306 input: readonly ThreadMessage[] | string,307): readonly ThreadMessage[] {308 if (typeof input !== "string") return input;309 let head = { author: "", time: "", avatar: "" };310 return input311 .split("|")312 .filter((m) => m.trim())313 .map((m) => {314 const parts = m.split(">").map((v) => v.trim());315 const text = parts.pop() ?? "";316 const who = parts.pop();317 if (who !== undefined) {318 const cut = who.indexOf(" ");319 head = {320 author: cut < 0 ? who : who.slice(0, cut),321 time: cut < 0 ? "" : who.slice(cut + 1),322 avatar: parts.pop() ?? "",323 };324 }325 return { ...head, text };326 });327}328329export interface ChannelThreadProps {330 /** The conversation, in order. Also takes the string form: see `toMessages`. */331 messages?: readonly ThreadMessage[] | string;332 theme?: Partial<KuchiTheme>;333 mode?: "light" | "dark";334 fontFamily?: string;335}336337export function ChannelThread({338 messages = DEFAULT_MESSAGES,339 theme,340 mode = "dark",341 fontFamily = "Default",342}: ChannelThreadProps) {343 const frame = useCurrentFrame();344 const { fps, width, height } = useVideoConfig();345 const t = useKuchiTheme(theme, mode);346 const face = resolveFont(fontFamily) ?? SANS;347348 const u = height / REF_H;349 const ox = (width - REF_W * u) / 2;350 const now = frame / fps;351352 const said = toMessages(messages).filter((m) => m.text.trim());353 const groups: {354 person: string;355 time: string;356 avatar: string;357 lines: string[];358 }[] = [];359 for (const m of said) {360 const [person = "", time = "", avatar = ""] = [m.author, m.time, m.avatar];361 const g = groups[groups.length - 1];362 if (g && g.person === person && g.time === time && g.avatar === avatar) {363 g.lines.push(m.text.trim());364 } else {365 groups.push({ person, time, avatar, lines: [m.text.trim()] });366 }367 }368369 const lines = layout(groups);370 lines.forEach((l, i) => {371 const m = said[i];372 l.at = m?.at ?? BEATS[i] ?? 84 + 24 * (i - 3);373 l.opens =374 i === 0375 ? Number.NEGATIVE_INFINITY376 : (m?.opens ?? OPENS[i] ?? 72 + 24 * (i - 3));377 });378379 // Each opened row moves the target to however far its baseline falls past the380 // anchor. A row that does not reach the anchor moves nothing, which is the381 // stillness in the reference rather than an exception carved out for it.382 let scroll = 0;383 let target = 0;384 for (const l of lines) {385 const want = Math.max(0, l.y - ANCHOR);386 const step = want - target;387 target = want;388 if (step <= 0) continue;389 // A longer move takes *less* time, not more — measured, twice: the two-row390 // scroll runs 1.60× faster in normalised time than the one-row scroll, which391 // is what a browser's native smooth scroll does with distance and what the392 // recording therefore does. One curve, read faster the further it has to go.393 const rate = (step / MSG_GAP) ** 0.68;394 scroll += step * read(SCROLL, (now - l.opens / fps) * rate);395 }396397 const ink = t.foreground;398 const dim = t.mutedForeground;399400 return (401 <AbsoluteFill style={{ backgroundColor: t.background }}>402 <div403 style={{404 position: "absolute",405 left: ox,406 top: 0,407 width: REF_W * u,408 height: REF_H * u,409 fontFamily: face,410 // Hinting re-snaps every stem as a line slides past, and the411 // letterforms boil. This renders the outline as it actually is.412 textRendering: "geometricPrecision",413 whiteSpace: "nowrap",414 overflow: "hidden",415 }}416 >417 {lines.map((l, i) => {418 const y = l.y - scroll;419 if (y < -MSG_GAP || y > REF_H + MSG_GAP) return null;420 const shown = frame >= l.at;421 if (frame < l.opens) return null;422 const arrived = frame >= l.opens + LEAD;423 const g = groups[l.group];424 const nameA = read(FADE, y - NAME_GAP);425 const bodyA = read(FADE, y);426 return (427 <div key={`${l.group}-${i}`}>428 {l.head && g && arrived && (429 <>430 <Avatar431 src={g.avatar}432 name={g.person}433 y={(y - NAME_GAP - AVATAR_RISE) * u}434 u={u}435 t={t}436 alpha={read(FADE, y - NAME_GAP - AVATAR_RISE + AVATAR / 2)}437 />438 <div439 style={{440 position: "absolute",441 left: TEXT_X * u,442 top: (y - NAME_GAP - ASC) * u,443 fontSize: SIZE * u,444 lineHeight: 1,445 fontWeight: 700,446 color: ink,447 // Per row, not per group. The name sits 37.59px above its448 // first message and the gradient moves measurably over449 // that distance — sharing one opacity between them reads450 // as a name that refuses to leave.451 opacity: nameA,452 }}453 >454 {g.person}455 <span456 style={{457 fontSize: TIME_SIZE * u,458 fontWeight: 500,459 color: dim,460 // The timestamp rides the name's baseline, so it is one461 // inline run and not a second absolutely-placed box to462 // keep in step when the name's width changes.463 marginLeft: 13.4 * u,464 }}465 >466 {g.time}467 </span>468 </div>469 </>470 )}471 {shown ? (472 // The message is the object Studio selects: its body line, by473 // its index across the whole conversation.474 <Item index={i}>475 <div476 style={{477 position: "absolute",478 left: TEXT_X * u,479 top: (y - ASC) * u,480 fontSize: SIZE * u,481 lineHeight: 1,482 color: ink,483 opacity: bodyA,484 }}485 >486 {l.text}487 </div>488 </Item>489 ) : (490 l.head &&491 arrived && (492 <Dots493 y={(y - DOT_RISE) * u}494 u={u}495 colour={mixOklch(dim, ink, 0.3)}496 since={now - (l.opens + LEAD) / fps}497 alpha={bodyA}498 />499 )500 )}501 </div>502 );503 })}504 </div>505 </AbsoluteFill>506 );507}508509/** Three dots that arrive one at a time, then start over. */510function Dots({511 y,512 u,513 colour,514 since,515 alpha,516}: {517 y: number;518 u: number;519 colour: string;520 since: number;521 alpha: number;522}) {523 const step = Math.floor((since % (DOT_BEAT * 4)) / DOT_BEAT);524 return (525 <>526 {[0, 1, 2].map((i) => (527 <div528 key={i}529 style={{530 position: "absolute",531 left: (TEXT_X + 3.3 + i * DOT_GAP) * u,532 top: y - (DOT / 2) * u,533 width: DOT * u,534 height: DOT * u,535 borderRadius: "50%",536 background: colour,537 opacity: i < step ? alpha : 0,538 }}539 />540 ))}541 </>542 );543}544545/**546 * A root-relative asset is a `public/` file. Only the site's own Player serves547 * it at that path; Remotion Studio and a render know its URL through548 * `staticFile()` alone — so every environment but the Player rewrites it.549 */550function resolveSrc(src: string): string {551 const isLocal = src.startsWith("/") && !src.startsWith("//");552 if (!isLocal || getRemotionEnvironment().isPlayer) return src;553 // A value that already came out of staticFile() carries the static base554 // (`/static-<hash>/…`); running it through again would prefix it twice.555 const base = staticFile("_").slice(0, -2);556 if (base && src.startsWith(`${base}/`)) return src;557 try {558 return staticFile(src.replace(/^\/+/, ""));559 } catch {560 return src;561 }562}563564/**565 * An avatar that holds the render until it has actually loaded.566 *567 * Without this a frame can be captured before the picture arrives and the568 * square comes out empty — invisible in the Player, where an image simply569 * appears, and silent in an mp4 until somebody watches it. Remotion's own `Img`570 * is avoided for the reason `hero-launch` documents: it awaits `decode()`, which571 * the headless compositor rejects for some progressive JPEGs and hangs the572 * export. `onError` releases too, so a bad source degrades to a missing picture573 * rather than a stuck render.574 */575function Face({ src, style }: { src: string; style: CSSProperties }) {576 const [handle] = useState(() => delayRender(`channel avatar: ${src}`));577 const release = useCallback(() => continueRender(handle), [handle]);578 return (579 // biome-ignore lint/performance/noImgElement: Remotion frame, not a Next route.580 <img // eslint-disable-line @remotion/warn-native-media-tag -- onLoad releases the frame; <Img> hangs on some JPEGs581 src={resolveSrc(src)}582 alt=""583 // Tailwind's preflight sets `img { max-width: 100% }`, which collapses an584 // image inside a shrink-to-fit box to zero pixels wide on the site while585 // rendering perfectly in an mp4. Size it here and say so.586 style={{ ...style, maxWidth: "none" }}587 onLoad={release}588 onError={release}589 />590 );591}592593/** The person's picture, or their initial on a tinted square when there is none. */594function Avatar({595 src,596 name,597 y,598 u,599 t,600 alpha,601}: {602 src: string;603 name: string;604 y: number;605 u: number;606 t: KuchiTheme;607 alpha: number;608}) {609 const box = {610 position: "absolute" as const,611 left: AVATAR_X * u,612 top: y,613 width: AVATAR * u,614 height: AVATAR * u,615 borderRadius: 8 * u,616 overflow: "hidden" as const,617 opacity: alpha,618 };619 if (src) return <Face src={src} style={{ ...box, objectFit: "cover" }} />;620 return (621 <div622 style={{623 ...box,624 // A tinted tile with the accent's own letter on it: legible on either625 // theme, and it moves with a user's palette instead of inventing a grey.626 // An alpha tint rather than a mix — the page is a near-neutral, its hue627 // in oklch is undefined, and interpolating toward the accent through it628 // comes out somewhere else entirely. Measured: a blue accent over the629 // warm off-white page mixed to a pale *green*.630 background: withAlpha(t.primary, 0.16),631 color: t.primary,632 fontSize: AVATAR * 0.45 * u,633 fontWeight: 600,634 display: "flex",635 alignItems: "center",636 justifyContent: "center",637 }}638 >639 {name.slice(0, 1).toUpperCase()}640 </div>641 );642}









