Blocks

Scroll story

The site's scroll story: a story in chapters told while the reader scrolls. From 1024 the stage pins and the pieces (creatives, a board, chips, a page, a thread, a profile, a result card) move on keyframes in a 1512x982 frame scaled to the content width while each chapter's words rise in; below 1024 or with reduced motion the chapters stack over still arrangements.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add scroll-story
<script type="module" src="/spyglass-ds/elements/scroll-story.js"></script>
A category's hooks

How a creative team reads hooks across a category

A whole category’s ads

Pick a category and get every Meta ad from its 16 daily nutrition brands at once.

Grouped by hook

Ads gather under the hook they open with. The hook most brands use rises to the top.

Take one hook apart

It opens on a question. 16 brands make the same move, and Acme has kept its version live 63 days.

Same hook, other brands

Search the hook in plain words and see it in other brands’ ads and posts, each in its own style.

Watch a hook rise or fade

A daily trend tracker shows which hooks gain brands, and which brands drop them.

Get a free API keySee templates
  1. A whole category’s ads

    Pick a category and get every Meta ad from its 16 daily nutrition brands at once.

  2. Grouped by hook

    Ads gather under the hook they open with. The hook most brands use rises to the top.

  3. Take one hook apart

    It opens on a question. 16 brands make the same move, and Acme has kept its version live 63 days.

  4. Same hook, other brands

    Search the hook in plain words and see it in other brands’ ads and posts, each in its own style.

  5. Watch a hook rise or fade

    A daily trend tracker shows which hooks gain brands, and which brands drop them.

    Get a free API keySee templates
A brand's comments

How a brand team reads its comments

Every post, every comment

Acme’s Instagram and TikTok posts, each one with its views and the whole thread under it.

Where people ask the most

Rank posts by the questions in their comments. A teaser for a new flavor drew the most.

What the thread is about

Thousands of comments, read for you: what people ask, what they guess and how warm they are.

The conversation, word for word

Who said it and how many agreed, with asks, guesses and complaints on their own tabs.

Know when the talk shifts

Each day, count which themes grow in your comments and in your competitors’, with the posts behind them.

Get a free API keySee templates
  1. Every post, every comment

    Acme’s Instagram and TikTok posts, each one with its views and the whole thread under it.

  2. Where people ask the most

    Rank posts by the questions in their comments. A teaser for a new flavor drew the most.

  3. What the thread is about

    Thousands of comments, read for you: what people ask, what they guess and how warm they are.

  4. The conversation, word for word

    Who said it and how many agreed, with asks, guesses and complaints on their own tabs.

  5. Know when the talk shifts

    Each day, count which themes grow in your comments and in your competitors’, with the posts behind them.

    Get a free API keySee templates
The pages behind ads

How a growth team studies the pages behind ads

The pages behind the ads

Ask which product pages get the most Meta ads and see each one as a shopper does, above the fold.

Ranked by ads pointing there

A page with 519 ads behind it is a page the brand trusts. That one is Acme’s Black Edition.

Read the page itself

Its offer, its headline and what sits above the fold, as Spyglass captured it.

A second page, same product

Acme sends its new ads to a page of their own. Open it, and the ads that lead there.

Hear about new pages first

When a brand starts sending ads to a new page, you hear that week, with the first ads that lead there.

Get a free API keySee templates
  1. The pages behind the ads

    Ask which product pages get the most Meta ads and see each one as a shopper does, above the fold.

  2. Ranked by ads pointing there

    A page with 519 ads behind it is a page the brand trusts. That one is Acme’s Black Edition.

  3. Read the page itself

    Its offer, its headline and what sits above the fold, as Spyglass captured it.

  4. A second page, same product

    Acme sends its new ads to a page of their own. Open it, and the ads that lead there.

  5. Hear about new pages first

    When a brand starts sending ads to a new page, you hear that week, with the first ads that lead there.

    Get a free API keySee templates
One brand, every channel

How a strategist reads one brand across every channel

Acme, on every channel

One name pulls up its Meta ads, its Instagram and TikTok posts and what creators post about it.

Each channel by its own measure

Ads by days run, posts and creator posts by views. Each channel’s best in one view.

One record holds it all

Ads, posts, creators, landing pages and comments, linked to the same brand. Nothing counted twice.

Open the brand’s record

Its profile and latest work, with every ad, post, creator and page tied to it a click away.

One brand’s week, every channel

Once a week, what the brand did on each channel, in one note your team can forward.

Get a free API keySee templates
  1. Acme, on every channel

    One name pulls up its Meta ads, its Instagram and TikTok posts and what creators post about it.

  2. Each channel by its own measure

    Ads by days run, posts and creator posts by views. Each channel’s best in one view.

  3. One record holds it all

    Ads, posts, creators, landing pages and comments, linked to the same brand. Nothing counted twice.

  4. Open the brand’s record

    Its profile and latest work, with every ad, post, creator and page tied to it a click away.

  5. One brand’s week, every channel

    Once a week, what the brand did on each channel, in one note your team can forward.

    Get a free API keySee templates

Usage

Showing how a use case works, step by step, on a use-case or product page. story takes the data (storyFromShape in lib/scroll-story.ts builds the site's five-chapter shape from its parts), or preset names an Acme story; actions are the last chapter's buttons.

Never

  • Motion with reduced motion: the chapters stack and hold still
  • Another brand's ads, logos or channel marks shipped in the data: pass your own src, mark and logos, or keep the placeholders
  • More than one White button: the first action is White, the rest secondary
  • Easing or timers on top of the scroll: the scroll position is the clock

The story data is plain JSON: chapters (heading, text, side, mode, when they come in and leave, and the still arrangement used when stacked) and pieces (a kind, a size in frame px and keyframes: at in chapters, x, y, scale, opacity, badge and mark opacity, an ease). storyFromShape makes the site's shape from a board, a hero and five ranked creatives, five chips, a focal piece (board, thread, page or profile), four creatives around it and a result card. Creatives without src draw the neutral placeholder. Each picture is an image slot (src, alt, fit, position); without src it keeps its placeholder, which carries data-ds-placeholder.

Adds with it: browser-frame, button, creative-card

Props

The web component takes the same as attributes or properties (<spyglass-scroll-story>); title is heading there.

<ScrollStory>

PropTypeDefault
storyScrollStoryData
presetScrollStoryPreset

One of the Acme stories (research, sentiment, landing, channels), when `story` is not given.

'research'
actionsStoryAction[]

Buttons under the last chapter: the first White, the rest secondary.

classNamestring

Examples

The same example in React and as web components; both render identically.

react/examples/scroll-story/Research.tsx
'use client'
import { ScrollStory } from '@/react/components/blocks/ScrollStory'
import { storyActions } from '@/lib/pages/scroll-stories'
// The scroll story as the site's use-case pages set it, with Acme's copy: a category's ads grouped by hook, one taken apart, the trend tracker. Pinned from 1024; stacked below it or with reduced motion.

export default function Research() {
  return <ScrollStory preset="research" actions={storyActions} />
}
elements/examples/scroll-story/Research.html
<!-- The scroll story as the site's use-case pages set it, with Acme's copy: a category's ads grouped by hook, one taken apart, the trend tracker. Pinned from 1024; stacked below it or with reduced motion. -->
<spyglass-scroll-story preset="research" actions='[{"label":"Get a free API key","href":"/sign-up"},{"label":"See templates","href":"/templates"}]'></spyglass-scroll-story>
react/examples/scroll-story/Sentiment.tsx
'use client'
import { ScrollStory } from '@/react/components/blocks/ScrollStory'
import { storyActions } from '@/lib/pages/scroll-stories'
// The scroll story as the site's use-case pages set it, with Acme's copy: a brand's comments ranked and read, the thread word for word. Pinned from 1024; stacked below it or with reduced motion.

export default function Sentiment() {
  return <ScrollStory preset="sentiment" actions={storyActions} />
}
elements/examples/scroll-story/Sentiment.html
<!-- The scroll story as the site's use-case pages set it, with Acme's copy: a brand's comments ranked and read, the thread word for word. Pinned from 1024; stacked below it or with reduced motion. -->
<spyglass-scroll-story preset="sentiment" actions='[{"label":"Get a free API key","href":"/sign-up"},{"label":"See templates","href":"/templates"}]'></spyglass-scroll-story>
react/examples/scroll-story/Landing.tsx
'use client'
import { ScrollStory } from '@/react/components/blocks/ScrollStory'
import { storyActions } from '@/lib/pages/scroll-stories'
// The scroll story as the site's use-case pages set it, with Acme's copy: the pages behind the ads, a browser window as the focal piece. Pinned from 1024; stacked below it or with reduced motion.

export default function Landing() {
  return <ScrollStory preset="landing" actions={storyActions} />
}
elements/examples/scroll-story/Landing.html
<!-- The scroll story as the site's use-case pages set it, with Acme's copy: the pages behind the ads, a browser window as the focal piece. Pinned from 1024; stacked below it or with reduced motion. -->
<spyglass-scroll-story preset="landing" actions='[{"label":"Get a free API key","href":"/sign-up"},{"label":"See templates","href":"/templates"}]'></spyglass-scroll-story>
react/examples/scroll-story/Channels.tsx
'use client'
import { ScrollStory } from '@/react/components/blocks/ScrollStory'
import { storyActions } from '@/lib/pages/scroll-stories'
// The scroll story as the site's use-case pages set it, with Acme's copy: one brand across every channel, its profile as the focal piece. Pinned from 1024; stacked below it or with reduced motion.

export default function Channels() {
  return <ScrollStory preset="channels" actions={storyActions} />
}
elements/examples/scroll-story/Channels.html
<!-- The scroll story as the site's use-case pages set it, with Acme's copy: one brand across every channel, its profile as the focal piece. Pinned from 1024; stacked below it or with reduced motion. -->
<spyglass-scroll-story preset="channels" actions='[{"label":"Get a free API key","href":"/sign-up"},{"label":"See templates","href":"/templates"}]'></spyglass-scroll-story>

Source

react/components/blocks/ScrollStory.tsx
'use client'
import { useEffect, useRef, type CSSProperties } from 'react'
import { Button } from '@/react/components/ui/Button'
import { BrowserFrame } from '@/react/components/site/BrowserFrame'
import { CreativeCard } from '@/react/components/site/CreativeCard'
import { pieceStartStyle, runScrollStory, stillRatio, trackHeight, type ScrollStoryData, type StoryAction, type StoryImage, type StoryLogo, type StoryPiece } from '@/lib/scroll-story'
import { scrollStories, type ScrollStoryPreset } from '@/lib/pages/scroll-stories'
import { cn } from '@/react/lib/cn'
import { imageFit } from '@/lib/image'

// The site's scroll story (story/ScrollStory): a story in chapters told while the reader scrolls. From 1024 with motion
// allowed the stage pins for the story's length; its pieces (creatives, a board, chips, a page, a thread of comments, a
// profile, a result card) move on keyframes in a 1512x982 frame scaled to the content width, the first chapter's words
// sit at the top and the others rise in from below, left and right in turn, the last with the buttons. Below 1024, or
// with reduced motion, the chapters stack: words over a still arrangement of the same pieces, nothing moves. The
// motion is the scroll itself (transform and opacity only). `story` is the data (lib/scroll-story.ts; `storyFromShape`
// builds the site's five-chapter shape), or `preset` names one of the Acme stories; `actions` are the last chapter's
// buttons, the first White. Creatives without `src` are neutral placeholders.
export interface ScrollStoryProps {
  story?: ScrollStoryData
  /** One of the Acme stories (research, sentiment, landing, channels), when `story` is not given. */
  preset?: ScrollStoryPreset
  /** Buttons under the last chapter: the first White, the rest secondary. */
  actions?: StoryAction[]
  className?: string
}

function Shot({ image }: { image: StoryImage }) {
  // The placeholder shows its headline only: the advertiser line would sit under the badge.
  return image.src
    ? <img src={image.src} alt="" loading="lazy" decoding="async" style={imageFit(image)} />
    : <span className="ds-story-fill"><CreativeCard ratio="fill" caption={image.caption} tone={image.tone} /></span>
}

function Logo({ logo }: { logo: StoryLogo }) {
  return <span className="ds-story-logo">{logo.src ? <img src={logo.src} alt="" /> : logo.name.charAt(0).toUpperCase()}</span>
}

function SearchIcon() {
  return (
    <svg className="ds-story-search-icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
      <circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.5" />
      <path d="M10.5 10.5 14 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  )
}

type Piece<K extends StoryPiece['kind']> = Extract<StoryPiece, { kind: K }>

function Board({ piece }: { piece: Piece<'board'> }) {
  return (
    <span className="ds-story-board" data-compact={piece.compact ? '' : undefined}>
      {piece.query ? (
        <>
          <span className="ds-story-search"><SearchIcon /><span className="ds-story-search-text">{piece.query}</span></span>
          {piece.filters && (
            <span className="ds-story-filters">
              {piece.filters.map((f) => {
                const [label, value] = f.split(': ')
                return <span key={f} className="ds-story-filter"><span className="ds-story-muted">{label}:</span> {value}</span>
              })}
            </span>
          )}
        </>
      ) : (
        <>
          <span className="ds-story-board-name">
            {piece.logo && <Logo logo={piece.logo} />}
            {piece.logos && (
              <span className="ds-story-board-stack">
                {piece.logos.map((l) => <Logo key={l.name} logo={l} />)}
                {piece.more ? <span className="ds-story-more">+{piece.more}</span> : null}
              </span>
            )}
            <span className="ds-story-board-title">{piece.title}</span>
          </span>
          <span className="ds-story-board-meta">{piece.meta}</span>
          {piece.action && <span className="ds-story-action">{piece.action}</span>}
        </>
      )}
    </span>
  )
}

function Body({ piece, still = false }: { piece: StoryPiece; still?: boolean }) {
  switch (piece.kind) {
    case 'image':
      return (
        <span className="ds-story-shot">
          <Shot image={piece.image} />
          {piece.badge && <span className="ds-story-badge">{piece.badge}</span>}
          {piece.image.mark && <span className="ds-story-mark"><img src={piece.image.mark} alt="" /></span>}
        </span>
      )
    case 'board':
      return <Board piece={piece} />
    case 'chip':
      return <span className="ds-story-chip"><span className="ds-story-muted">{piece.label}</span><span>{piece.value}</span></span>
    case 'page':
      return (
        <span className="ds-story-page">
          <BrowserFrame url={piece.url} footer={piece.meta}>
            <span className="ds-story-page-fill"><Shot image={piece.image} /></span>
          </BrowserFrame>
        </span>
      )
    case 'thread':
      return (
        <span className="ds-story-card">
          <span className="ds-story-card-head"><span className="ds-story-card-title">{piece.title}</span><span className="ds-story-small">{piece.meta}</span></span>
          {piece.tabs && <span className="ds-story-tabs">{piece.tabs.map((t, i) => <span key={t} className="ds-story-tab" data-on={i === 0 ? '' : undefined}>{t}</span>)}</span>}
          {piece.rows.map((row) => (
            <span key={row.who + row.text} className="ds-story-message">
              <span className="ds-story-initial">{row.avatar ? <img src={row.avatar} alt="" /> : row.who.charAt(0).toUpperCase()}</span>
              <span className="ds-story-message-words"><span className="ds-story-small">{row.who}</span><span className="ds-story-message-text">{row.text}</span></span>
              {row.likes && <span className="ds-story-likes">{row.likes}</span>}
            </span>
          ))}
        </span>
      )
    case 'profile':
      return (
        <span className="ds-story-profile">
          <span className="ds-story-profile-head">
            <Logo logo={piece.logo} />
            <span className="ds-story-profile-words">
              <span className="ds-story-card-title">{piece.name}</span>
              <span className="ds-story-handle">{piece.mark && <img className="ds-story-inline-mark" src={piece.mark} alt="" />}{piece.handle}</span>
            </span>
            <span className="ds-story-action">{piece.action}</span>
          </span>
          <span className="ds-story-profile-meta">{piece.meta}</span>
          <span className="ds-story-grid">{piece.posts.map((p, i) => <span key={i} className="ds-story-post"><Shot image={p} /></span>)}</span>
          <span className="ds-story-profile-foot">{piece.footer}</span>
        </span>
      )
    case 'result':
      return (
        <span className="ds-story-card">
          <span className="ds-story-card-head"><span className="ds-story-card-title">{piece.title}</span><span className="ds-story-small">{piece.meta}</span></span>
          {piece.rows.map((row) => (
            <span key={row.title} className="ds-story-row">
              <span className="ds-story-thumb">{still ? <Shot image={row.image} /> : null}</span>
              <span className="ds-story-row-words">
                <span className="ds-story-body">{row.title}</span>
                <span className="ds-story-detail">{row.logo && <Logo logo={row.logo} />}{row.detail}</span>
              </span>
              <span className="ds-story-figure">{row.mark && <img className="ds-story-inline-mark" src={row.mark} alt="" />}{row.figure}</span>
            </span>
          ))}
        </span>
      )
  }
}

function Actions({ actions }: { actions: StoryAction[] }) {
  return (
    <div className="ds-story-actions">
      {actions.map((a, i) => <Button key={a.href} href={a.href} variant={i === 0 ? 'primary' : 'secondary'} className="max-md:w-full">{a.label}</Button>)}
    </div>
  )
}

export function ScrollStory({ story: given, preset = 'research', actions, className }: ScrollStoryProps) {
  const story = given ?? scrollStories[preset] ?? scrollStories.research
  const { chapters, pieces } = story
  const track = useRef<HTMLDivElement>(null)
  const frame = useRef<HTMLDivElement>(null)
  const words = useRef<HTMLDivElement>(null)
  const pieceEls = useRef<(HTMLSpanElement | null)[]>([])
  const textEls = useRef<(HTMLDivElement | null)[]>([])
  const titleId = `${story.id}-story-title`
  const byId = new Map(pieces.map((p) => [p.id, p]))

  useEffect(() => runScrollStory(() => {
    if (!track.current || !frame.current || !words.current) return null
    return { track: track.current, frame: frame.current, words: words.current, pieces: pieceEls.current.filter((e): e is HTMLSpanElement => !!e), texts: textEls.current.filter((e): e is HTMLDivElement => !!e) }
  }, story), [story])

  return (
    <section data-ds="scroll-story" aria-labelledby={titleId} className={cn('ds-story', className)}>
      <style href="ds-scroll-story" precedence="ds">{css}</style>
      <h2 id={titleId} className="sr-only">{story.title}</h2>
      <div ref={track} className="ds-story-track" style={{ height: trackHeight(chapters.length) }}>
        <div className="ds-story-stage">
          <div ref={frame} className="ds-story-frame" aria-hidden="true">
            {pieces.map((piece, i) => (
              <span key={piece.id} ref={(el) => { pieceEls.current[i] = el }} className="ds-story-piece" data-kind={piece.kind} style={pieceStartStyle(piece, chapters.length) as CSSProperties}>
                <Body piece={piece} />
              </span>
            ))}
          </div>
          <div ref={words} className="ds-story-container ds-story-words">
            {chapters.map((c, i) => (
              <div key={c.id} className="ds-story-slot" data-side={c.side}>
                <div ref={(el) => { textEls.current[i] = el }} className="ds-story-text" data-mode={c.mode ?? 'scroll'}>
                  <h3 className="ds-story-heading">{c.heading}</h3>
                  <p className="ds-story-lead">{c.text}</p>
                  {actions && i === chapters.length - 1 ? <Actions actions={actions} /> : null}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <ol className="ds-story-container ds-story-stack" role="list">
        {chapters.map((c, i) => (
          <li key={c.id} className="ds-story-stack-item">
            <div className="ds-story-stack-text">
              <h3 className="ds-story-heading">{c.heading}</h3>
              <p className="ds-story-lead">{c.text}</p>
              {actions && i === chapters.length - 1 ? <Actions actions={actions} /> : null}
            </div>
            <div className="ds-story-still" data-layout={c.still.layout} aria-hidden="true">
              {c.still.pieces.map((id) => {
                const piece = byId.get(id)
                if (!piece) return null
                const ratio = stillRatio(piece)
                return (
                  <span key={id} className="ds-story-still-piece" data-kind={piece.kind} style={ratio ? { aspectRatio: ratio } : undefined}>
                    <Body piece={piece} still />
                  </span>
                )
              })}
            </div>
          </li>
        ))}
      </ol>
    </section>
  )
}

export default ScrollStory

const css = `
.ds-story { position: relative; display: block; color: var(--ds-color-fg); }
.ds-story-container { width: 100%; max-width: calc(var(--ds-layout-content) + 2 * var(--ds-layout-gutter)); margin-inline: auto; padding-inline: var(--ds-layout-gutter); }
.ds-story-track { display: none; position: relative; margin-top: calc(-1 * var(--story-settle-d, 0px)); margin-bottom: calc(var(--ds-layout-section) - var(--story-foot, var(--ds-layout-section))); }
.ds-story-stage { position: sticky; top: 0; height: 100vh; overflow: clip; pointer-events: none; }
.ds-story-frame { position: absolute; left: 50%; top: 50%; width: calc(var(--ds-story-frame-w) * 1px); height: calc(var(--ds-story-frame-h) * 1px); transform: translate(-50%, -50%); pointer-events: none; }
.ds-story-piece { position: absolute; left: 0; top: 0; display: block; transform-origin: 0 0; will-change: transform, opacity; }
.ds-story-piece[data-kind="chip"] { width: max-content; }
.ds-story-words { position: absolute; inset: 0; pointer-events: none; }
.ds-story-slot { position: absolute; inset: 0 var(--ds-layout-gutter); display: flex; align-items: center; }
.ds-story-slot[data-side="right"] { justify-content: flex-end; }
.ds-story-slot[data-side="top"] { align-items: flex-start; justify-content: center; padding-top: var(--ds-layout-section); text-align: center; }
.ds-story-text { width: var(--ds-story-text-w); will-change: transform; }
.ds-story-slot[data-side="top"] .ds-story-text { width: auto; max-width: var(--ds-layout-measure); display: flex; flex-direction: column; align-items: center; }
.ds-story-slot[data-side="top"] .ds-story-text > :first-child, .ds-story-stack-item:first-child .ds-story-stack-text > :first-child { text-box: trim-start cap alphabetic; }
.ds-story-text[data-mode="scroll"] { transform: translate3d(0, 100vh, 0); }
.ds-story-text[data-mode="reveal"] > * { opacity: 0; transform: translate3d(0, var(--ds-story-text-rise), 0); }
.ds-story-heading { margin: 0; font-family: var(--ds-font-heading); font-weight: var(--ds-font-weight-heading); font-size: var(--ds-text-heading-3); line-height: var(--ds-text-heading-3-leading); letter-spacing: 0; text-wrap: balance; }
.ds-story-lead { margin: var(--ds-space-lg) 0 0; max-width: var(--ds-layout-measure); color: var(--ds-color-fg-soft); font-family: var(--ds-font-text); font-size: var(--ds-text-body-lg); line-height: var(--ds-text-body-lg-leading); text-wrap: pretty; }
.ds-story-actions { display: flex; flex-wrap: wrap; gap: var(--ds-space-md); margin-top: var(--ds-space-2xl); pointer-events: auto; }
.ds-story-shot { position: relative; display: block; width: 100%; height: 100%; overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-raised); }
.ds-story-shot > img, .ds-story-fill { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-badge { position: absolute; left: var(--ds-space-sm); bottom: var(--ds-space-sm); padding: var(--ds-space-xs) var(--ds-space-sm); border-radius: var(--ds-radius-sm); background: var(--ds-color-black); color: var(--ds-color-fg); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); font-variant-numeric: tabular-nums; opacity: var(--b, 0); white-space: nowrap; }
.ds-story-mark { position: absolute; right: var(--ds-space-sm); bottom: var(--ds-space-sm); display: grid; place-items: center; width: var(--ds-space-xl); height: var(--ds-space-xl); border-radius: var(--ds-radius-sm); background: var(--ds-color-black); opacity: var(--m, 1); }
.ds-story-mark img { width: var(--ds-space-md); height: var(--ds-space-md); }
.ds-story-piece .ds-story-shot { container-type: inline-size; }
.ds-story-piece .ds-story-mark { right: 3.36cqi; bottom: 3.36cqi; width: 10.08cqi; height: 10.08cqi; }
.ds-story-piece .ds-story-mark img { width: 5.04cqi; height: 5.04cqi; }
.ds-story-board { display: flex; flex-direction: column; align-items: center; width: 100%; height: 100%; padding-top: calc(var(--ds-space-2xl) + var(--ds-space-sm)); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); text-align: center; }
.ds-story-board-name { display: flex; gap: var(--ds-space-md); align-items: center; }
.ds-story-logo { position: relative; display: grid; place-items: center; flex: none; overflow: hidden; border-radius: var(--ds-radius-full); background: var(--ds-color-white); color: var(--ds-color-black); font-family: var(--ds-font-heading); }
.ds-story-logo img { position: absolute; inset: 0; width: 100%; height: 100%; border-radius: var(--ds-radius-full); object-fit: cover; }
.ds-story-board .ds-story-logo, .ds-story-more { width: var(--ds-space-2xl); height: var(--ds-space-2xl); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-board-title { font-family: var(--ds-font-heading); font-size: var(--ds-text-heading-2); line-height: var(--ds-text-heading-2-leading); }
.ds-story-board-meta { margin-top: var(--ds-space-xs); color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-board[data-compact] { justify-content: center; padding: var(--ds-space-xl); }
.ds-story-board[data-compact] .ds-story-board-name { flex-direction: column; }
.ds-story-board[data-compact] .ds-story-board-title { font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); text-wrap: balance; }
.ds-story-action { display: inline-flex; align-items: center; height: var(--ds-space-2xl); margin-top: var(--ds-space-lg); padding-inline: var(--ds-space-lg); border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-panel); color: var(--ds-color-fg); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); white-space: nowrap; }
.ds-story-search { display: flex; gap: var(--ds-space-md); align-items: center; width: min(100%, var(--ds-story-search-w)); height: var(--ds-space-3xl); padding-inline: var(--ds-space-lg); border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-inset); text-align: left; }
.ds-story-search-icon { width: var(--ds-space-lg); height: var(--ds-space-lg); flex: none; color: var(--ds-color-fg-muted); }
.ds-story-search-text { overflow: hidden; font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); text-overflow: ellipsis; white-space: nowrap; }
.ds-story-filters { display: flex; flex-wrap: wrap; gap: var(--ds-space-sm); justify-content: center; margin-top: var(--ds-space-lg); }
.ds-story-filter { padding: var(--ds-space-xs) var(--ds-space-sm); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-sm); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); white-space: nowrap; }
.ds-story-muted { color: var(--ds-color-fg-muted); }
.ds-story-chip { display: inline-flex; gap: var(--ds-space-sm); align-items: baseline; padding: var(--ds-space-sm) var(--ds-space-md); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); white-space: nowrap; }
.ds-story-card { display: flex; flex-direction: column; width: 100%; height: 100%; border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); }
.ds-story-card-head { display: flex; flex-direction: column; gap: var(--ds-space-xs); padding: var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-card-title { font-family: var(--ds-font-heading); font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); }
.ds-story-small { color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-row { display: grid; grid-template-columns: var(--ds-space-4xl) minmax(0, 1fr) auto; gap: var(--ds-space-lg); align-items: center; padding: var(--ds-space-sm) var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-row:last-child { border-bottom: 0; }
.ds-story-thumb { position: relative; display: block; width: var(--ds-space-4xl); height: var(--ds-space-5xl); overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-inset); }
.ds-story-thumb > * { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-row-words { display: flex; flex-direction: column; min-width: 0; }
.ds-story-body { font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); }
.ds-story-detail { display: flex; gap: var(--ds-space-sm); align-items: center; color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-detail .ds-story-logo { width: var(--ds-space-lg); height: var(--ds-space-lg); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); }
.ds-story-figure { display: flex; gap: var(--ds-space-sm); align-items: center; font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); font-variant-numeric: tabular-nums; }
.ds-story-inline-mark { width: var(--ds-space-md); height: var(--ds-space-md); flex: none; }
.ds-story-tabs { display: flex; gap: var(--ds-space-xs); padding: var(--ds-space-md) var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-tab { padding: var(--ds-space-xs) var(--ds-space-sm); border-radius: var(--ds-radius-sm); color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); white-space: nowrap; }
.ds-story-tab[data-on] { background: var(--ds-color-surface-inset); color: var(--ds-color-fg); }
.ds-story-message { display: grid; grid-template-columns: var(--ds-space-2xl) minmax(0, 1fr) auto; column-gap: var(--ds-space-md); align-items: start; padding: var(--ds-space-lg) var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-message:last-child { border-bottom: 0; }
.ds-story-initial { position: relative; display: grid; place-items: center; width: var(--ds-space-2xl); height: var(--ds-space-2xl); overflow: hidden; border-radius: var(--ds-radius-full); background: var(--ds-color-surface-inset); color: var(--ds-color-fg-soft); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); }
.ds-story-initial img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.ds-story-message-words { display: flex; flex-direction: column; gap: var(--ds-space-xs); min-width: 0; }
.ds-story-message-text { overflow: hidden; font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); text-overflow: ellipsis; white-space: nowrap; }
.ds-story-likes { color: var(--ds-color-fg-muted); font-size: var(--ds-text-caption); line-height: var(--ds-text-ui-leading); font-variant-numeric: tabular-nums; white-space: nowrap; }
.ds-story-profile { display: flex; flex-direction: column; width: 100%; height: 100%; overflow: hidden; border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); }
.ds-story-profile-head { display: flex; gap: var(--ds-space-md); align-items: center; padding: var(--ds-space-xl) var(--ds-space-xl) 0; }
.ds-story-profile-head .ds-story-action { margin: 0; }
.ds-story-profile-head .ds-story-logo { width: var(--ds-space-3xl); height: var(--ds-space-3xl); font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); }
.ds-story-profile-words { display: flex; flex: 1; flex-direction: column; min-width: 0; }
.ds-story-handle { display: flex; gap: var(--ds-space-xs); align-items: center; color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-profile-meta { padding: var(--ds-space-md) var(--ds-space-xl) var(--ds-space-lg); color: var(--ds-color-fg-soft); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-grid { display: grid; flex: 1; grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-rows: 1fr; gap: var(--ds-space-xs); min-height: 0; padding-inline: var(--ds-space-xs); }
.ds-story-post { position: relative; display: block; min-height: 0; overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-inset); }
.ds-story-post > * { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-profile-foot { margin-top: var(--ds-space-xs); padding: var(--ds-space-sm) var(--ds-space-md); border-top: var(--ds-border-hairline) solid var(--ds-color-edge-surface); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-page { display: block; width: 100%; height: 100%; }
.ds-story-page-fill { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-board-stack { display: flex; align-items: center; }
.ds-story-board-stack > * + * { margin-left: calc(var(--ds-space-sm) * -1); }
.ds-story-board-stack > .ds-story-logo, .ds-story-more { outline: calc(var(--ds-border-hairline) * 2) solid var(--ds-color-surface-raised); }
.ds-story-more { display: grid; place-items: center; flex: none; border-radius: var(--ds-radius-full); background: var(--ds-color-surface-subtle); color: var(--ds-color-fg-soft); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); font-weight: var(--ds-font-weight-medium); }
.ds-story-stack { display: grid; row-gap: var(--ds-space-5xl); margin: 0; padding-block: var(--ds-layout-section); list-style: none; }
.ds-story-stack-item { display: grid; row-gap: var(--ds-space-2xl); }
.ds-story-still { display: grid; gap: var(--ds-space-md); max-width: var(--ds-layout-measure); }
.ds-story-still-piece { position: relative; display: block; min-width: 0; }
.ds-story-still-piece[data-kind="chip"] .ds-story-chip { white-space: normal; }
.ds-story-still-piece .ds-story-message-text { white-space: normal; }
.ds-story-still[data-layout="board"] { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: var(--ds-space-lg); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); }
.ds-story-still[data-layout="board"] .ds-story-still-piece[data-kind="board"] { grid-column: 1 / -1; }
.ds-story-still[data-layout="board"] .ds-story-board { padding: 0 0 var(--ds-space-sm); border: 0; }
.ds-story-still[data-layout="board"] .ds-story-search { height: auto; padding-block: var(--ds-space-sm); }
.ds-story-still[data-layout="board"] .ds-story-search-text { white-space: normal; font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-still-piece[data-kind="profile"] .ds-story-grid { grid-auto-rows: auto; }
.ds-story-still-piece[data-kind="profile"] .ds-story-post { aspect-ratio: 1; }
.ds-story-still-piece[data-kind="profile"] { max-width: var(--ds-story-profile-w); }
.ds-story-still[data-layout="rank"] { grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: end; }
.ds-story-still[data-layout="rank"] .ds-story-badge, .ds-story-still[data-layout="focus"] .ds-story-badge { opacity: 1; }
.ds-story-still[data-layout="rank"] .ds-story-mark { display: none; }
.ds-story-still[data-layout="focus"] { display: flex; flex-wrap: wrap; gap: var(--ds-space-sm); }
.ds-story-still[data-layout="focus"] .ds-story-still-piece[data-kind="image"] { flex: 0 0 100%; max-width: var(--ds-layout-measure-sm); }
.ds-story-still[data-layout="page"] { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.ds-story-still[data-layout="page"] .ds-story-still-piece:first-child { grid-column: 1 / -1; }
@media (min-width: 768px) {
  .ds-story-heading { font-size: var(--ds-text-heading-2); line-height: var(--ds-text-heading-2-leading); }
}
@media (min-width: 1024px) {
  .ds-story-stack-item { grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); column-gap: var(--ds-space-4xl); align-items: center; }
  .ds-story-still { max-width: none; }
  .ds-story-still[data-layout="board"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
@media (min-width: 1280px) {
  .ds-story-heading { font-size: var(--ds-text-figure); line-height: var(--ds-text-figure-leading); }
}
@media (min-width: 1024px) and (prefers-reduced-motion: no-preference) {
  .ds-story-track { display: block; }
  .ds-story-stack { display: none; }
}
@media (width < 768px) {
  .ds-story-actions { flex-direction: column; align-self: stretch; }
  .ds-story-still[data-layout="board"] .ds-story-board { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: var(--ds-space-md); align-items: center; text-align: left; }
  .ds-story-still[data-layout="board"] .ds-story-board-name { min-width: 0; }
  .ds-story-still[data-layout="board"] .ds-story-logo, .ds-story-still[data-layout="board"] .ds-story-more { width: var(--ds-space-xl); height: var(--ds-space-xl); }
  .ds-story-still[data-layout="board"] .ds-story-more { position: relative; }
  .ds-story-still[data-layout="board"] .ds-story-board-title { min-width: 0; font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); }
  .ds-story-still[data-layout="board"] .ds-story-board-meta, .ds-story-still[data-layout="board"] .ds-story-search, .ds-story-still[data-layout="board"] .ds-story-filters { grid-column: 1 / -1; }
  .ds-story-still[data-layout="board"] .ds-story-filters { justify-content: flex-start; }
  .ds-story-still[data-layout="board"] .ds-story-action { grid-column: 1 / -1; justify-self: start; margin-top: var(--ds-space-md); }
  .ds-story-still[data-layout="page"] .ds-story-board { padding: var(--ds-space-xl) var(--ds-space-lg); }
  .ds-story-still[data-layout="page"] .ds-story-board-title { font-size: var(--ds-text-heading-3); line-height: var(--ds-text-heading-3-leading); text-wrap: balance; }
}
`
lib/scroll-story.ts
// The scroll story (site story/ScrollStory): a story told in chapters while the reader scrolls. From 1024 with motion
// allowed, a stage pins for the story's length and its pieces (creatives, a board, chips, a page, a thread, a profile,
// a result card) move on keyframes in a 1512x982 design frame scaled to the content width, while each chapter's words
// rise in from below or reveal in place. Below 1024, or with reduced motion, the same chapters stack: words over a still
// arrangement of the pieces, no motion. Shared by both flavors: the data shapes, the timeline, `storyFromShape` (the
// site's five-chapter story built from a few named parts) and `runScrollStory` (the pinned engine on plain DOM nodes).

import type { ImageSlot } from '@/lib/image'

export type StoryEase = 'linear' | 'in' | 'out' | 'inOut'

/** One keyframe: `at` in chapters (1.5 is half through chapter 2), x and y in frame px, scale, opacity, badge and mark opacity. */
export interface StoryKey {
	at: number
	x: number
	y: number
	s?: number
	o?: number
	b?: number
	m?: number
	e?: StoryEase
}

/** A creative: the image as posted (`src`), or the neutral placeholder named by `brand` and `caption`. */
export interface StoryImage extends ImageSlot {
	alt: string
	brand?: string
	caption?: string
	tone?: 1 | 2 | 3 | 4
	/** The channel's mark (an image) in the corner; none by default (no third-party marks shipped). */
	mark?: string
}

/** A brand's round mark: `src`, or the first letter of `name` on White. */
export interface StoryLogo {
	name: string
	src?: string
}

interface PieceBase {
	id: string
	w: number
	h: number
	keys: StoryKey[]
	/** The chapter whose words this piece rides with. */
	withText?: number
	/** Blend into riding with the words between two moments. */
	withTextFrom?: { from: number; to: number }
}

export type StoryPiece = PieceBase &
	(
		| { kind: 'image'; image: StoryImage; badge?: string }
		| { kind: 'board'; title: string; meta: string; logo?: StoryLogo; logos?: StoryLogo[]; more?: number; action?: string; query?: string; filters?: string[]; compact?: boolean }
		| { kind: 'chip'; label: string; value: string }
		| { kind: 'page'; image: StoryImage; url: string; meta: string }
		| { kind: 'thread'; title: string; meta: string; tabs?: string[]; rows: { who: string; text: string; likes?: string; avatar?: string }[] }
		| { kind: 'profile'; logo: StoryLogo; name: string; handle: string; meta: string; action: string; mark?: string; posts: StoryImage[]; footer: string }
		| { kind: 'result'; title: string; meta: string; rows: { title: string; detail: string; figure: string; image: StoryImage; logo?: StoryLogo; mark?: string }[] }
	)

export type StoryLayout = 'board' | 'rank' | 'focus' | 'page' | 'result'

export interface StoryChapter {
	id: string
	heading: string
	text: string
	side: 'top' | 'left' | 'right'
	mode?: 'static' | 'reveal' | 'scroll'
	in: number
	out?: number
	outRate?: 'exit'
	/** The still arrangement shown under the words when the story stacks. */
	still: { layout: StoryLayout; pieces: string[] }
}

export interface ScrollStoryData {
	id: string
	/** The section's name for assistive tech (visually hidden). */
	title: string
	chapters: StoryChapter[]
	pieces: StoryPiece[]
}

/** A button under the last chapter: the first is White, the rest secondary. */
export interface StoryAction {
	label: string
	href: string
}

// ----- Timeline -----

export interface Clock {
	starts: number[]
	lengths: number[]
	total: number
}

export function makeClock(lengths: number[]): Clock {
	const starts: number[] = []
	let t = 0
	for (const l of lengths) {
		starts.push(t)
		t += l
	}
	return { starts, lengths, total: t }
}

export function toScreens(clock: Clock, at: number): number {
	const last = clock.lengths.length - 1
	const i = Math.max(0, Math.min(last, Math.floor(at)))
	return clock.starts[i] + (at - i) * clock.lengths[i]
}

const EASES: Record<StoryEase, (p: number) => number> = {
	linear: (p) => p,
	in: (p) => p * p * p,
	out: (p) => 1 - (1 - p) ** 3,
	inOut: (p) => (p < 0.5 ? 2 * p * p : 1 - (-2 * p + 2) ** 2 / 2),
}

export const ease = (name: StoryEase, p: number) => EASES[name](Math.max(0, Math.min(1, p)))

export interface Frame {
	x: number
	y: number
	s: number
	o: number
	b: number
	m: number
}

type Track = (Required<Omit<StoryKey, 'e'>> & { e: StoryEase; t: number })[]

function makeTrack(clock: Clock, keys: StoryKey[]): Track {
	let prev = { s: 1, o: 1, b: 0, m: 1 }
	return keys.map((k) => {
		const full = { ...k, s: k.s ?? prev.s, o: k.o ?? prev.o, b: k.b ?? prev.b, m: k.m ?? prev.m, e: k.e ?? 'linear', t: toScreens(clock, k.at) }
		prev = full
		return full
	})
}

const lerp = (a: number, b: number, p: number) => a + (b - a) * p

function sample(track: Track, t: number): Frame {
	const first = track[0]
	if (t <= first.t) return first
	for (let i = 1; i < track.length; i++) {
		const k = track[i]
		if (t <= k.t) {
			const a = track[i - 1]
			const p = ease(k.e, k.t === a.t ? 1 : (t - a.t) / (k.t - a.t))
			return { x: lerp(a.x, k.x, p), y: lerp(a.y, k.y, p), s: lerp(a.s, k.s, p), o: lerp(a.o, k.o, p), b: lerp(a.b, k.b, p), m: lerp(a.m, k.m, p) }
		}
	}
	return track[track.length - 1]
}

const frameTransform = (f: Frame) => `translate3d(${f.x.toFixed(2)}px, ${f.y.toFixed(2)}px, 0) scale(${f.s.toFixed(4)})`

/** The style a piece starts with before the engine runs (server render and first paint), as properties for both flavors. */
export function pieceStartStyle(piece: StoryPiece, chapters: number): Record<string, string> {
	const clock = makeClock(Array.from({ length: chapters + 1 }, () => 1))
	const f = sample(makeTrack(clock, piece.keys), 0)
	const size: Record<string, string> = piece.kind === 'chip' ? {} : { width: `${piece.w}px`, height: `${piece.h}px` }
	return { ...size, transform: frameTransform(f), opacity: f.o.toFixed(3), visibility: f.o < 0.005 ? 'hidden' : 'visible', '--b': f.b.toFixed(3), '--m': f.m.toFixed(3) }
}

/** The pinned track's height: every chapter's length, the tail and one screen. */
export function trackHeight(chapters: number): string {
	const lens = Array.from({ length: chapters }, (_, i) => `var(--ds-story-len-${i + 1}, 1)`)
	return `calc((${[...lens, 'var(--ds-story-tail)'].join(' + ')} + 1) * 100vh)`
}

/** The still arrangement's aspect for an image or a page. */
export const stillRatio = (piece: StoryPiece) => (piece.kind === 'image' || piece.kind === 'page' ? `${piece.w} / ${piece.h}` : undefined)

// ----- The pinned engine -----

export const PINNED = '(min-width: 1024px) and (prefers-reduced-motion: no-preference)'

export interface StoryNodes {
	track: HTMLElement
	frame: HTMLElement
	words: HTMLElement
	pieces: HTMLElement[]
	texts: HTMLElement[]
}

/**
 * Runs the pinned story on rendered nodes while PINNED matches (it stops and restarts as the media query changes):
 * reads the story tokens from the track, scales the frame to the content width, and on scroll writes each piece's
 * transform and opacity and each chapter's rise. Returns a stop function.
 */
export function runScrollStory(nodes: () => StoryNodes | null, story: ScrollStoryData): () => void {
	if (!('IntersectionObserver' in globalThis)) return () => {}
	const media = window.matchMedia(PINNED)
	let stop = () => {}
	const start = () => {
		const n = nodes()
		if (!n) return
		const { chapters, pieces } = story
		const style = getComputedStyle(n.track)
		const num = (name: string, fallback = 0) => {
			const v = parseFloat(style.getPropertyValue(name))
			return Number.isFinite(v) ? v : fallback
		}
		const px = (name: string) => {
			const probe = document.createElement('div')
			probe.style.cssText = `position:absolute;visibility:hidden;height:var(${name})`
			n.track.appendChild(probe)
			const v = probe.getBoundingClientRect().height
			probe.remove()
			return v
		}
		const clock = makeClock([...chapters.map((_, i) => num(`--ds-story-len-${i + 1}`, 1)), num('--ds-story-tail')])
		const tracks = pieces.map((p) => makeTrack(clock, p.keys))
		const frameW = num('--ds-story-frame-w')
		const frameH = num('--ds-story-frame-h')
		const frameContent = num('--ds-story-frame-content')
		const rise = px('--ds-story-text-rise')
		const exitRate = num('--ds-story-exit-rate')
		const textRate = num('--ds-story-text-rate')
		const follow = num('--ds-story-follow')
		const settle = num('--ds-story-settle')
		const still = window.matchMedia('(prefers-reduced-motion: reduce)').matches

		let vh = window.innerHeight
		let scale = 1
		let settleD = 0
		let rests: { top: number; bottom: number }[] = []

		const measure = () => {
			vh = window.innerHeight
			const cs = getComputedStyle(n.words)
			const content = n.words.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight)
			scale = Math.min(content / frameContent, vh / frameH)
			n.frame.style.width = `${frameW}px`
			n.frame.style.height = `${frameH}px`
			n.frame.style.transform = `translate(-50%, -50%) scale(${scale.toFixed(4)})`
			settleD = still ? 0 : (vh * settle) / 2
			n.track.style.setProperty('--story-settle-d', `${settleD.toFixed(1)}px`)
			rests = n.texts.map((t) => ({ top: t.offsetTop, bottom: t.offsetTop + t.offsetHeight }))
		}

		const textFrame = (c: StoryChapter, i: number, s: number) => {
			const sIn = toScreens(clock, c.in)
			const out = c.out === undefined ? Infinity : toScreens(clock, c.out)
			const rate = c.outRate === 'exit' ? exitRate : textRate
			const leave = s > out ? (s - out) * vh * rate : 0
			if (c.mode === 'static') return [{ y: -leave, o: 1 }]
			if (c.mode === 'reveal') {
				const p = (s - sIn) / Math.max(0.001, toScreens(clock, i + 1) - sIn)
				return [0, 0.12].map((lag) => {
					const e = ease('inOut', (p - lag) / (1 - lag))
					return { y: rise * (1 - e) - leave, o: e * e }
				})
			}
			const y = Math.max(0, vh - rests[i].top - (s - sIn) * vh * textRate) - leave
			return [{ y, o: 1 }]
		}

		const target = () => {
			const box = n.track.getBoundingClientRect()
			return Math.max(-1, Math.min(clock.total, -box.top / vh))
		}
		let shown = target()
		let last = 0
		const update = (at?: number) => {
			const s = at ?? shown
			const u = settle > 0 ? Math.min(1, Math.max(0, s / settle)) : 1
			const glide = settleD * (1 - u) * (1 - u)
			n.frame.style.transform = `translate(-50%, calc(-50% + ${glide.toFixed(2)}px)) scale(${scale.toFixed(4)})`
			n.words.style.transform = glide ? `translate3d(0, ${glide.toFixed(2)}px, 0)` : ''
			tracks.forEach((tr, i) => {
				const el = n.pieces[i]
				if (!el) return
				const f = sample(tr, s)
				const piece = pieces[i]
				let dy = 0
				if (piece.withText !== undefined) {
					const blend = piece.withTextFrom
					const share = blend ? Math.min(1, Math.max(0, (s - toScreens(clock, blend.from)) / Math.max(0.001, toScreens(clock, blend.to) - toScreens(clock, blend.from)))) : 1
					dy = (share * textFrame(chapters[piece.withText], piece.withText, s)[0].y) / scale
				}
				const t = frameTransform(f)
				el.style.transform = dy ? `translate3d(0, ${dy.toFixed(2)}px, 0) ${t}` : t
				el.style.opacity = f.o.toFixed(3)
				el.style.visibility = f.o < 0.005 ? 'hidden' : 'visible'
				el.style.zIndex = piece.kind === 'image' ? (f.o >= 0.999 ? '2' : '1') : piece.id === 'board' || piece.kind === 'result' ? '0' : '3'
				el.style.setProperty('--b', f.b.toFixed(3))
				el.style.setProperty('--m', f.m.toFixed(3))
			})
			chapters.forEach((c, i) => {
				const el = n.texts[i]
				if (!el) return
				const parts = textFrame(c, i, s)
				const kids = parts.length > 1 ? Array.from(el.children as HTMLCollectionOf<HTMLElement>) : [el]
				kids.forEach((kid, j) => {
					const f = parts[Math.min(j, parts.length - 1)]
					kid.style.transform = `translate3d(0, ${f.y.toFixed(2)}px, 0)`
					kid.style.opacity = f.o.toFixed(3)
				})
				const top = rests[i].top + parts[0].y
				const gone = top > vh || rests[i].bottom + parts[parts.length - 1].y < 0
				el.style.visibility = gone ? 'hidden' : 'visible'
			})
		}

		// The room under the last view: the track ends where the lowest visible piece or word ends, so the next section
		// follows at the section spacing instead of a screen of Black.
		const foot = () => {
			const stage = n.track.firstElementChild
			if (!stage) return
			update(clock.total)
			const top = stage.getBoundingClientRect().top
			let low = 0
			const visible = (el: HTMLElement) => el.style.visibility !== 'hidden' && parseFloat(el.style.opacity || '1') > 0.01
			for (const el of n.pieces) if (visible(el)) low = Math.max(low, el.getBoundingClientRect().bottom - top)
			for (const el of n.texts) {
				if (!visible(el)) continue
				for (const kid of Array.from(el.children as HTMLCollectionOf<HTMLElement>)) if (visible(kid)) low = Math.max(low, kid.getBoundingClientRect().bottom - top)
			}
			if (low > 0) n.track.style.setProperty('--story-foot', `${Math.round(Math.max(0, vh - low))}px`)
		}

		let raf = 0
		const tick = (now: number) => {
			raf = 0
			const goal = target()
			const dt = last ? Math.min(now - last, 64) : 16
			last = now
			shown = still || follow <= 0 ? goal : shown + (goal - shown) * (1 - Math.exp(-dt / follow))
			if (Math.abs(goal - shown) < 0.0004) shown = goal
			update()
			if (shown !== goal) raf = requestAnimationFrame(tick)
			else last = 0
		}
		const onScroll = () => {
			if (!raf) raf = requestAnimationFrame(tick)
		}
		const onResize = () => {
			measure()
			foot()
			shown = target()
			update()
		}
		let listening = false
		const io = new IntersectionObserver(
			([entry]) => {
				if (entry.isIntersecting && !listening) {
					listening = true
					window.addEventListener('scroll', onScroll, { passive: true })
					shown = target()
					update()
				} else if (!entry.isIntersecting && listening) {
					listening = false
					window.removeEventListener('scroll', onScroll)
				}
			},
			{ rootMargin: '50% 0px' },
		)
		measure()
		foot()
		update()
		io.observe(n.track)
		window.addEventListener('resize', onResize)
		let live = true
		document.fonts?.ready.then(() => {
			if (live) onResize()
		})
		stop = () => {
			live = false
			io.disconnect()
			window.removeEventListener('scroll', onScroll)
			window.removeEventListener('resize', onResize)
			cancelAnimationFrame(raf)
		}
	}
	const apply = () => {
		stop()
		stop = () => {}
		if (media.matches) start()
	}
	apply()
	media.addEventListener('change', apply)
	return () => {
		media.removeEventListener('change', apply)
		stop()
	}
}

// ----- The five-chapter shape (site content/pages/useCaseStories/shape.ts) -----

type Words = { heading: string; text: string }
type Ranked = { id: string; image: StoryImage; badge: string }
type Chip = { label: string; value: string }
type Row = { title: string; detail: string; figure: string; mark?: string; logo?: StoryLogo }
type FocalPiece =
	| { kind: 'page'; image: StoryImage; url: string; meta: string }
	| { kind: 'thread'; title: string; meta: string; tabs?: string[]; rows: { who: string; text: string; likes?: string; avatar?: string }[] }
	| { kind: 'board'; title: string; meta: string; logo?: StoryLogo; logos?: StoryLogo[]; more?: number }
	| { kind: 'profile'; logo: StoryLogo; name: string; handle: string; meta: string; action: string; mark?: string; posts: StoryImage[]; footer: string }

/** The site's story in five chapters: a board of work, ranked, one taken apart, the same move elsewhere, the result. */
export interface StoryShape {
	id: string
	title: string
	words: [Words, Words, Words, Words, Words]
	board: { title: string; meta: string; logo?: StoryLogo; logos?: StoryLogo[]; more?: number; action?: string; query?: string; filters?: string[] }
	hero: { image: StoryImage; badge: string }
	ranked: [Ranked, Ranked, Ranked, Ranked, Ranked]
	chips: [Chip, Chip, Chip, Chip, Chip]
	focal: FocalPiece
	around: [StoryImage, StoryImage, StoryImage, StoryImage]
	result: { title: string; meta: string; logo?: StoryLogo; rows: [Row, Row, Row, Row] }
}

const BOARD = { x: 154, y: 272, w: 1204, h: 852 }
const ROW = [BOARD.y + 192, BOARD.y + 192 + 298 + 24]
const COL = [245, 506, 767, 1028]
const SLOTS: [number, number][] = [
	[2, 0],
	[1, 1],
	[1, 0],
	[0, 1],
	[0, 0],
]
const RIDE = 140
const RANK = [
	{ x: 700, y: 260, w: 300 },
	{ x: 1036, y: 260, w: 200 },
	{ x: 1252, y: 260, w: 184 },
	{ x: 1036, y: 534, w: 144 },
	{ x: 1196, y: 534, w: 128 },
	{ x: 1340, y: 534, w: 112 },
]
type Place = { x: number; y: number; w: number }

function boardKeys(col: number, row: number, rank: Place, base: number): StoryKey[] {
	const x = COL[col]
	const y = ROW[row]
	return [
		{ at: 0, x, y, s: 238 / base, b: 0 },
		{ at: 1, x, y },
		{ at: 1.3, x, y: y - RIDE, b: 1 },
		{ at: base === 238 ? 1.75 : 1.9, x: rank.x, y: rank.y, s: rank.w / base, e: 'inOut' },
	]
}

function fallKeys(rank: Place): StoryKey[] {
	return [
		{ at: 2.12, x: rank.x, y: rank.y, s: rank.w / 238 },
		{ at: 2.5, x: rank.x + 10, y: rank.y - 369, o: 0.7 },
		{ at: 3, x: rank.x + 24, y: rank.y - 855 },
	]
}

const CHIP_AT = [
	{ x: 596, y: 316 },
	{ x: 232, y: 404 },
	{ x: 604, y: 500 },
	{ x: 256, y: 600 },
	{ x: 560, y: 664 },
]

function chipKeys(x: number, y: number, i: number): StoryKey[] {
	const d = i * 0.05
	return [
		{ at: 2.6 + d, x: x + 36, y: y - 8, s: 0.9, o: 0 },
		{ at: 2.72 + d, x: x + 10, y: y - 2, s: 1, o: 1, e: 'out' },
		{ at: 3, x, y },
		{ at: 3.12, x, y },
		{ at: 3.35, x: x + 90, y: y + 16, s: 0.9, o: 0 },
	]
}

const ARRIVE = 860
const FOCAL = { x: 900, y: 180, w: 380, h: 460 }
const AROUND = [
	{ x: 1300, y: 110, s: 140 / 160 },
	{ x: 1300, y: 590, s: 150 / 160 },
	{ x: 720, y: 650, s: 150 / 160 },
	{ x: 1000, y: 690, s: 140 / 160 },
]

function arriveKeys(at: number, end: { x: number; y: number; s: number }, drift: number, solid = false): StoryKey[] {
	return [
		{ at: 0, x: end.x - drift, y: end.y + ARRIVE, s: end.s, o: 0 },
		{ at: at - 0.01, x: end.x - drift, y: end.y + ARRIVE, o: 0 },
		{ at, x: end.x - drift, y: end.y + ARRIVE, s: end.s, o: solid ? 1 : 0.21 },
		{ at: at + 0.74, x: end.x, y: end.y, o: 1 },
	]
}

const CARD = { x: 116, y: 219, w: 640, h: 488 }
const SLOT = (row: number) => ({ x: CARD.x + 1 + 24, y: CARD.y + 1 + 97 + 8 + 97 * row })

function landKeys(from: { x: number; y: number; s: number }, row: number, at: number, base: number): StoryKey[] {
	const slot = SLOT(row)
	return [
		{ at: 4.12, x: from.x, y: from.y, s: from.s },
		{ at, x: slot.x, y: slot.y, s: 64 / base, b: 0, m: 0, e: 'inOut' },
		{ at: 5, x: slot.x, y: slot.y },
	]
}

const HERO = { w: 352, h: 440 }

const CHAPTERS: Omit<StoryChapter, 'heading' | 'text' | 'still'>[] = [
	{ id: '1', side: 'top', mode: 'static', in: -1, out: 1, outRate: 'exit' },
	{ id: '2', side: 'left', in: 1.38, out: 2.15 },
	{ id: '3', side: 'right', in: 2.25, out: 3.15 },
	{ id: '4', side: 'left', in: 3.25, out: 4.15 },
	{ id: '5', side: 'right', in: 4.2 },
]

/** Builds the site's five-chapter story (pieces, keyframes, chapters and stills) from its named parts. */
export function storyFromShape(shape: StoryShape): ScrollStoryData {
	const { id, hero, ranked, chips, focal, around, result } = shape
	const chipIds = chips.map((_, i) => `chip-${i + 1}`)
	const focalH = focal.kind === 'page' ? FOCAL.h : focal.kind === 'profile' ? 416 : focal.kind === 'thread' ? 97 + (focal.tabs ? 53 : 0) + 81 * focal.rows.length : 168
	const focalY = FOCAL.y + (FOCAL.h - focalH) / 2
	const stills: StoryChapter['still'][] = [
		{ layout: 'board', pieces: ['board', ranked[4].id, ranked[2].id, ranked[0].id, 'hero'] },
		{ layout: 'rank', pieces: ['hero', ranked[0].id, ranked[1].id] },
		{ layout: 'focus', pieces: ['hero', ...chipIds] },
		{ layout: 'page', pieces: ['focal', 'around-1', 'around-2', 'around-3'] },
		{ layout: 'result', pieces: ['result'] },
	]
	const pieces: StoryPiece[] = [
		{
			id: 'board',
			kind: 'board',
			...shape.board,
			w: BOARD.w,
			h: BOARD.h,
			keys: [
				{ at: 0, x: BOARD.x, y: BOARD.y },
				{ at: 1, x: BOARD.x, y: BOARD.y },
				{ at: 1.3, x: BOARD.x, y: BOARD.y - RIDE, o: 1 },
				{ at: 1.5, x: BOARD.x, y: BOARD.y - 294, o: 0 },
			],
		},
		{
			id: 'focal',
			...focal,
			...(focal.kind === 'board' ? { compact: true } : {}),
			w: FOCAL.w,
			h: focalH,
			keys: [...arriveKeys(3.15, { x: FOCAL.x, y: focalY, s: 1 }, 0, true), { at: 4.12, x: FOCAL.x, y: focalY }, { at: 4.6, x: FOCAL.x, y: -focalH - 120 }],
		} as StoryPiece,
		{
			id: 'result',
			kind: 'result',
			title: result.title,
			meta: result.meta,
			rows: result.rows.map((row, i) => ({ ...row, logo: row.logo ?? result.logo, image: i === 0 ? hero.image : around[i - 1] })),
			w: CARD.w,
			h: CARD.h,
			keys: [{ at: 0, x: CARD.x, y: CARD.y, o: 1 }],
			withText: 4,
		},
		...ranked.map((r, i): StoryPiece => {
			const [col, row] = SLOTS[i]
			const rank = RANK[i + 1]
			return { id: r.id, kind: 'image', image: r.image, badge: r.badge, w: 238, h: 298, keys: [...boardKeys(col, row, rank, 238), ...fallKeys(rank)] }
		}),
		...around.map((image, i): StoryPiece => {
			const end = AROUND[i]
			const drift = end.x > 900 ? -60 : 50
			return {
				id: `around-${i + 1}`,
				kind: 'image',
				image,
				w: 160,
				h: 200,
				keys: [
					...arriveKeys(3.15 + i * 0.02, end, drift),
					...(i === 3
						? [
								{ at: 4.12, x: end.x, y: end.y },
								{ at: 4.6, x: end.x + 40, y: end.y - 390, o: 0 },
							]
						: landKeys(end, i + 1, 4.9 + (i + 1) * 0.03, 160)),
				],
				...(i === 3 ? {} : { withText: 4, withTextFrom: { from: 4.5, to: 4.9 } }),
			}
		}),
		{
			id: 'hero',
			kind: 'image',
			image: hero.image,
			badge: hero.badge,
			w: HERO.w,
			h: HERO.h,
			keys: [
				...boardKeys(3, 0, RANK[0], HERO.w),
				{ at: 2.12, x: 700, y: 260, m: 1 },
				{ at: 2.55, x: 548, y: 244, s: 0.93, m: 0, e: 'in' },
				{ at: 3, x: 336, y: 271, s: 1, e: 'out' },
				{ at: 3.12, x: 336, y: 271 },
				{ at: 3.85, x: 700, y: 330, s: 220 / HERO.w, e: 'inOut' },
				{ at: 4.12, x: 700, y: 330, b: 1 },
				{ at: 4.5, x: 520, y: 300, s: 0.4, b: 0.4, e: 'in' },
				...landKeys({ x: 520, y: 300, s: 0.4 }, 0, 4.9, HERO.w).slice(1),
			],
			withText: 4,
			withTextFrom: { from: 4.5, to: 4.9 },
		},
		...chips.map((c, i): StoryPiece => ({ id: chipIds[i], kind: 'chip', ...c, w: 0, h: 0, keys: chipKeys(CHIP_AT[i].x, CHIP_AT[i].y, i) })),
	]
	return { id, title: shape.title, chapters: CHAPTERS.map((c, i) => ({ ...c, id: `${id}-${c.id}`, ...shape.words[i], still: stills[i] })), pieces }
}
lib/pages/scroll-stories.ts
import { storyFromShape, type ScrollStoryData, type StoryAction, type StoryImage, type StoryLogo } from '@/lib/scroll-story'

// The scroll stories' copy, Acme only: one story for each focal piece the site's five-chapter shape uses (a board, a
// thread of comments, a landing page, a brand's profile). Creatives are neutral placeholders named by advertiser and
// headline; pass `src` for real images.

const ACME: StoryLogo = { name: 'Acme' }
const NORTHWIND: StoryLogo = { name: 'Northwind' }

const ad = (brand: string, caption: string, tone: 1 | 2 | 3 | 4 = 2): StoryImage => ({ brand, caption, tone, alt: `${brand} ad: ${caption}` })
const brands = (n: number) => `${n} brands`
const days = (n: number) => `${n} days`

export const researchStory: ScrollStoryData = storyFromShape({
	id: 'creative-research',
	title: 'How a creative team reads hooks across a category',
	words: [
		{ heading: 'A whole category’s ads', text: 'Pick a category and get every Meta ad from its 16 daily nutrition brands at once.' },
		{ heading: 'Grouped by hook', text: 'Ads gather under the hook they open with. The hook most brands use rises to the top.' },
		{ heading: 'Take one hook apart', text: 'It opens on a question. 16 brands make the same move, and Acme has kept its version live 63 days.' },
		{ heading: 'Same hook, other brands', text: 'Search the hook in plain words and see it in other brands’ ads and posts, each in its own style.' },
		{ heading: 'Watch a hook rise or fade', text: 'A daily trend tracker shows which hooks gain brands, and which brands drop them.' },
	],
	board: { title: 'Daily nutrition', meta: 'Meta ads from 16 brands, last 30 days', logos: [ACME, NORTHWIND], more: 14, action: 'Save' },
	hero: { image: ad('Acme', 'Does it actually work?', 3), badge: brands(16) },
	ranked: [
		{ id: 'hook-welcome-kit', image: ad('Acme', 'Free welcome kit', 4), badge: brands(12) },
		{ id: 'hook-billboard', image: ad('Northwind', 'This is a meal', 2), badge: brands(9) },
		{ id: 'hook-customer-quote', image: ad('Acme', 'Lost 80lbs so far', 1), badge: brands(8) },
		{ id: 'hook-ingredients', image: ad('Northwind', '75 ingredients', 3), badge: brands(6) },
		{ id: 'hook-big-sale', image: ad('Acme', 'Up to 60% off', 2), badge: brands(5) },
	],
	chips: [
		{ label: 'Hook', value: 'A question headline' },
		{ label: 'Used by', value: '16 brands' },
		{ label: 'Kept longest', value: 'Acme, 63 days' },
		{ label: 'First seen', value: 'Aug 12' },
		{ label: 'Format', value: 'Single image' },
	],
	focal: { kind: 'board', title: '“a question as the headline”', meta: 'Daily nutrition, 212 ads and 47 posts' },
	around: [ad('Northwind', 'Tired by noon?', 4), ad('Acme', 'Is it healthy?', 2), ad('Acme', 'What is it?', 1), ad('Northwind', 'Why fiber?', 3)],
	result: {
		title: 'Build your own trend tracker',
		meta: 'Every day at 7:00. Question headlines, by days kept.',
		rows: [
			{ title: 'Does it actually work?', detail: 'Acme', figure: days(63), logo: ACME },
			{ title: 'Tired by noon?', detail: 'Northwind', figure: days(41), logo: NORTHWIND },
			{ title: 'Is it healthy?', detail: 'Acme', figure: days(34), logo: ACME },
			{ title: 'What is it?', detail: 'Acme', figure: days(12), logo: ACME },
		],
	},
})

const asks = (n: string) => `${n} asks`
const post = (caption: string, tone: 1 | 2 | 3 | 4 = 2): StoryImage => ({ brand: 'Acme', caption, tone, alt: `Acme post: ${caption}` })

export const sentimentStory: ScrollStoryData = storyFromShape({
	id: 'consumer-sentiment',
	title: 'How a brand team reads its comments',
	words: [
		{ heading: 'Every post, every comment', text: 'Acme’s Instagram and TikTok posts, each one with its views and the whole thread under it.' },
		{ heading: 'Where people ask the most', text: 'Rank posts by the questions in their comments. A teaser for a new flavor drew the most.' },
		{ heading: 'What the thread is about', text: 'Thousands of comments, read for you: what people ask, what they guess and how warm they are.' },
		{ heading: 'The conversation, word for word', text: 'Who said it and how many agreed, with asks, guesses and complaints on their own tabs.' },
		{ heading: 'Know when the talk shifts', text: 'Each day, count which themes grow in your comments and in your competitors’, with the posts behind them.' },
	],
	board: { title: 'Acme', meta: '@acme on Instagram, 48K comments this month', logo: ACME, action: 'Follow' },
	hero: { image: post('Something saucy is coming', 4), badge: asks('1,168') },
	ranked: [
		{ id: 'post-sherbet', image: post('Sherbet is back', 3), badge: asks('742') },
		{ id: 'post-snow', image: post('Snow day flavors', 1), badge: asks('516') },
		{ id: 'post-giveaway', image: post('Giveaway', 2), badge: asks('388') },
		{ id: 'post-ranch', image: post('Ranch, really?', 4), badge: asks('204') },
		{ id: 'post-arch', image: post('Six packs', 3), badge: asks('96') },
	],
	chips: [
		{ label: 'Comments', value: '2,431' },
		{ label: 'Top ask', value: 'When does it drop?' },
		{ label: 'Top guess', value: 'A hot sauce collab' },
		{ label: 'Mood', value: '78% warm' },
		{ label: 'Asked again', value: 'Bigger packs' },
	],
	focal: {
		kind: 'thread',
		title: '2,431 comments',
		meta: 'Asks 48%, guesses 33%, complaints 7%',
		tabs: ['Asks', 'Guesses', 'Complaints', 'Love'],
		rows: [
			{ who: 'maya.eats', text: 'Is it a sauce or a soda??', likes: '512 likes' },
			{ who: 'jordan_k', text: 'When can I buy it in Chicago?', likes: '344 likes' },
			{ who: 'sam.sips', text: 'Please sell it in 12-packs', likes: '98 likes' },
		],
	},
	around: [post('Tag a teacher', 2), post('Behind the bar', 1), post('The stack', 3), post('Woe is me', 4)],
	result: {
		title: 'Build your own trend tracker',
		meta: 'Every day at 7:00. Themes gaining ground in the comments.',
		logo: ACME,
		rows: [
			{ title: 'When does it drop?', detail: 'Teasers, 1,168 asks', figure: '+41%' },
			{ title: 'Tagging their teachers', detail: 'Friends tagging friends', figure: '+26%' },
			{ title: 'Mocktail recipes', detail: 'Asks for the recipe', figure: '+14%' },
			{ title: 'Bigger packs', detail: 'Asked under 31 posts', figure: '+9%' },
		],
	},
})

const page = (caption: string, tone: 1 | 2 | 3 | 4 = 2): StoryImage => ({ brand: 'Acme', caption, tone, alt: `Acme product page: ${caption}`, position: '50% 0%' })
const ads = (n: number) => `${n} ads`

export const landingStory: ScrollStoryData = storyFromShape({
	id: 'landing-page-development',
	title: 'How a growth team studies the pages behind ads',
	words: [
		{ heading: 'The pages behind the ads', text: 'Ask which product pages get the most Meta ads and see each one as a shopper does, above the fold.' },
		{ heading: 'Ranked by ads pointing there', text: 'A page with 519 ads behind it is a page the brand trusts. That one is Acme’s Black Edition.' },
		{ heading: 'Read the page itself', text: 'Its offer, its headline and what sits above the fold, as Spyglass captured it.' },
		{ heading: 'A second page, same product', text: 'Acme sends its new ads to a page of their own. Open it, and the ads that lead there.' },
		{ heading: 'Hear about new pages first', text: 'When a brand starts sending ads to a new page, you hear that week, with the first ads that lead there.' },
	],
	board: {
		title: 'Product pages',
		meta: 'Most Meta ads behind them, last 30 days',
		query: 'Which product pages get the most Meta ads?',
		filters: ['Channel: Meta ads', 'Page: Product', 'Last: 30 days'],
	},
	hero: { image: page('Black Edition', 3), badge: ads(519) },
	ranked: [
		{ id: 'page-oven', image: page('Countertop oven', 2), badge: ads(212) },
		{ id: 'page-sos', image: page('Rescue spray', 4), badge: ads(164) },
		{ id: 'page-cooker', image: page('Pressure cooker', 1), badge: ads(118) },
		{ id: 'page-shineon', image: page('Lip jelly', 3), badge: ads(87) },
		{ id: 'page-titanium', image: page('Pro pan set', 2), badge: ads(52) },
	],
	chips: [
		{ label: 'Ads behind it', value: '519' },
		{ label: 'Offer', value: 'Free shaker and tee' },
		{ label: 'Headline', value: 'High-protein, high in fiber' },
		{ label: 'Above the fold', value: 'Price and Add to cart' },
		{ label: 'Other pages', value: '5 more from Acme' },
	],
	focal: { kind: 'page', image: { brand: 'Acme', caption: 'Three reasons people love it', tone: 3, alt: 'Acme’s new product page' }, url: 'acme.com/black-edition', meta: '35 ads point here' },
	around: [ad('Acme', 'Not your appetite', 4), ad('Acme', 'You know what’s wild?', 2), ad('Acme', 'Pouch to camera', 1), ad('Acme', '40g protein', 3)],
	result: {
		title: 'Build your own competitor monitor',
		meta: 'Every Monday at 8:00. New pages and the ads behind them.',
		logo: ACME,
		rows: [
			{ title: 'Black Edition', detail: 'acme.com, 519 ads', figure: '+38' },
			{ title: 'Not your appetite', detail: 'To the new page', figure: 'New' },
			{ title: 'You know what’s wild?', detail: 'To the new page', figure: 'New' },
			{ title: 'Pouch to camera', detail: 'To the new page', figure: 'New' },
		],
	},
})

const pic = (caption: string, tone: 1 | 2 | 3 | 4 = 2): StoryImage => ({ brand: 'Acme', caption, tone, alt: `Acme: ${caption}` })

export const channelsStory: ScrollStoryData = storyFromShape({
	id: '360-degree-research',
	title: 'How a strategist reads one brand across every channel',
	words: [
		{ heading: 'Acme, on every channel', text: 'One name pulls up its Meta ads, its Instagram and TikTok posts and what creators post about it.' },
		{ heading: 'Each channel by its own measure', text: 'Ads by days run, posts and creator posts by views. Each channel’s best in one view.' },
		{ heading: 'One record holds it all', text: 'Ads, posts, creators, landing pages and comments, linked to the same brand. Nothing counted twice.' },
		{ heading: 'Open the brand’s record', text: 'Its profile and latest work, with every ad, post, creator and page tied to it a click away.' },
		{ heading: 'One brand’s week, every channel', text: 'Once a week, what the brand did on each channel, in one note your team can forward.' },
	],
	board: { title: 'Acme', meta: 'Meta ads, Instagram, TikTok and creators', logo: ACME, action: 'Follow' },
	hero: { image: pic('Lip and cheek', 3), badge: 'Post, 1.4M views' },
	ranked: [
		{ id: 'pic-pearl-hand', image: pic('Meet pocket pearl', 2), badge: 'Post, 1.1M views' },
		{ id: 'pic-lip-shape', image: pic('Lip shape', 4), badge: 'Ad, 88 days' },
		{ id: 'pic-new-from', image: pic('New from Acme', 1), badge: 'Post, 920K views' },
		{ id: 'pic-highlight', image: pic('Highlight milk', 3), badge: 'Creator, 410K views' },
		{ id: 'pic-blush', image: pic('Blush', 2), badge: 'Ad, 34 days' },
	],
	chips: [
		{ label: 'Ads', value: '214 live' },
		{ label: 'Posts', value: '96' },
		{ label: 'Creators', value: '38' },
		{ label: 'Pages', value: '12' },
		{ label: 'Comments', value: '18.2K' },
	],
	focal: {
		kind: 'profile',
		logo: ACME,
		name: 'Acme',
		handle: '@acme',
		meta: 'Skincare and makeup, 214 live Meta ads',
		action: 'Follow',
		posts: [pic('Kit', 2), pic('Lip tint', 3), pic('Glazing milk', 1), pic('Swatches', 4), pic('Pocket blush', 2), pic('Travel', 3)],
		footer: '38 creators and 12 pages on the same record',
	},
	around: [pic('Travel case', 4), pic('The bottle', 2), pic('Tube close-up', 1), pic('Pocket pearls', 3)],
	result: {
		title: 'Build your own competitor monitor',
		meta: 'Every Monday at 8:00. One brand, every channel.',
		logo: ACME,
		rows: [
			{ title: 'Instagram', detail: 'Lip and cheek, 1.4M views', figure: '+22%' },
			{ title: 'Meta ads', detail: '214 live, 18 new this week', figure: '+18' },
			{ title: 'Landing pages', detail: '12 live, 1 new', figure: '+1' },
			{ title: 'Creators', detail: '38 posted, 5 for the first time', figure: '+5' },
		],
	},
})

/** The stories by name, for the `preset` prop and attribute. */
export const scrollStories = { research: researchStory, sentiment: sentimentStory, landing: landingStory, channels: channelsStory }
export type ScrollStoryPreset = keyof typeof scrollStories

/** The buttons under the last chapter on the site's use-case pages. */
export const storyActions: StoryAction[] = [
	{ label: 'Get a free API key', href: '/sign-up' },
	{ label: 'See templates', href: '/templates' },
]
react/lib/cn.ts
// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]

export function cn(...values: ClassValue[]): string {
	const out: string[] = []
	for (const v of values) {
		if (!v) continue
		if (Array.isArray(v)) {
			const s = cn(...v)
			if (s) out.push(s)
		}
		else out.push(v)
	}
	return out.join(' ')
}
elements/components/blocks/scroll-story.ts
import { html, nothing, type PropertyValues } from 'lit'
import { styleMap } from 'lit/directives/style-map.js'
import { DsElement, define, HostLayoutController } from '@/elements/lib/element'
import { pieceStartStyle, runScrollStory, stillRatio, trackHeight, type ScrollStoryData, type StoryAction, type StoryImage, type StoryLogo, type StoryPiece } from '@/lib/scroll-story'
import { scrollStories, type ScrollStoryPreset } from '@/lib/pages/scroll-stories'
import '@/elements/components/ui/button'
import '@/elements/components/site/browser-frame'
import '@/elements/components/site/creative-card'
import styles from 'virtual:tw'
import { imageFit } from '@/lib/image'

// ScrollStory.tsx as <spyglass-scroll-story>: the site's scroll story. From 1024 with motion allowed the stage pins and
// the pieces move on keyframes as the reader scrolls, the chapters' words rising in turn; below 1024 or with reduced
// motion the chapters stack over still arrangements. `story` (JSON, lib/scroll-story.ts) or `preset` (research,
// sentiment, landing, channels: the Acme stories), and `actions` (JSON [{ label, href }]) under the last chapter.

type Piece<K extends StoryPiece['kind']> = Extract<StoryPiece, { kind: K }>

const shot = (image: StoryImage) =>
	image.src
		? html`<img src=${image.src} alt="" loading="lazy" decoding="async" style=${styleMap(imageFit(image) ?? {})}>`
		: html`<span class="ds-story-fill"><spyglass-creative-card ratio="fill" caption=${image.caption ?? nothing} tone=${image.tone ?? 2}></spyglass-creative-card></span>`

const logo = (l: StoryLogo) => html`<span class="ds-story-logo">${l.src ? html`<img src=${l.src} alt="">` : l.name.charAt(0).toUpperCase()}</span>`

const searchIcon = html`<svg class="ds-story-search-icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"></circle><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>`

const board = (p: Piece<'board'>) =>
	html`<span class="ds-story-board" ?data-compact=${!!p.compact}>${p.query
		? html`<span class="ds-story-search">${searchIcon}<span class="ds-story-search-text">${p.query}</span></span>${p.filters ? html`<span class="ds-story-filters">${p.filters.map((f) => {
				const [label, value] = f.split(': ')
				return html`<span class="ds-story-filter"><span class="ds-story-muted">${label}:</span> ${value}</span>`
			})}</span>` : nothing}`
		: html`<span class="ds-story-board-name">${p.logo ? logo(p.logo) : nothing}${p.logos ? html`<span class="ds-story-board-stack">${p.logos.map(logo)}${p.more ? html`<span class="ds-story-more">+${p.more}</span>` : nothing}</span>` : nothing}<span class="ds-story-board-title">${p.title}</span></span><span class="ds-story-board-meta">${p.meta}</span>${p.action ? html`<span class="ds-story-action">${p.action}</span>` : nothing}`}</span>`

const head = (title: string, meta: string) => html`<span class="ds-story-card-head"><span class="ds-story-card-title">${title}</span><span class="ds-story-small">${meta}</span></span>`

function body(piece: StoryPiece, still = false) {
	switch (piece.kind) {
		case 'image':
			return html`<span class="ds-story-shot">${shot(piece.image)}${piece.badge ? html`<span class="ds-story-badge">${piece.badge}</span>` : nothing}${piece.image.mark ? html`<span class="ds-story-mark"><img src=${piece.image.mark} alt=""></span>` : nothing}</span>`
		case 'board':
			return board(piece)
		case 'chip':
			return html`<span class="ds-story-chip"><span class="ds-story-muted">${piece.label}</span><span>${piece.value}</span></span>`
		case 'page':
			return html`<span class="ds-story-page"><spyglass-browser-frame url=${piece.url}><span class="ds-story-page-fill">${shot(piece.image)}</span><span slot="footer">${piece.meta}</span></spyglass-browser-frame></span>`
		case 'thread':
			return html`<span class="ds-story-card">${head(piece.title, piece.meta)}${piece.tabs ? html`<span class="ds-story-tabs">${piece.tabs.map((t, i) => html`<span class="ds-story-tab" ?data-on=${i === 0}>${t}</span>`)}</span>` : nothing}${piece.rows.map((row) => html`<span class="ds-story-message"><span class="ds-story-initial">${row.avatar ? html`<img src=${row.avatar} alt="">` : row.who.charAt(0).toUpperCase()}</span><span class="ds-story-message-words"><span class="ds-story-small">${row.who}</span><span class="ds-story-message-text">${row.text}</span></span>${row.likes ? html`<span class="ds-story-likes">${row.likes}</span>` : nothing}</span>`)}</span>`
		case 'profile':
			return html`<span class="ds-story-profile"><span class="ds-story-profile-head">${logo(piece.logo)}<span class="ds-story-profile-words"><span class="ds-story-card-title">${piece.name}</span><span class="ds-story-handle">${piece.mark ? html`<img class="ds-story-inline-mark" src=${piece.mark} alt="">` : nothing}${piece.handle}</span></span><span class="ds-story-action">${piece.action}</span></span><span class="ds-story-profile-meta">${piece.meta}</span><span class="ds-story-grid">${piece.posts.map((p) => html`<span class="ds-story-post">${shot(p)}</span>`)}</span><span class="ds-story-profile-foot">${piece.footer}</span></span>`
		case 'result':
			return html`<span class="ds-story-card">${head(piece.title, piece.meta)}${piece.rows.map((row) => html`<span class="ds-story-row"><span class="ds-story-thumb">${still ? shot(row.image) : nothing}</span><span class="ds-story-row-words"><span class="ds-story-body">${row.title}</span><span class="ds-story-detail">${row.logo ? logo(row.logo) : nothing}${row.detail}</span></span><span class="ds-story-figure">${row.mark ? html`<img class="ds-story-inline-mark" src=${row.mark} alt="">` : nothing}${row.figure}</span></span>`)}</span>`
	}
}

const actionsRow = (actions: StoryAction[]) => html`<div class="ds-story-actions">${actions.map((a, i) => html`<spyglass-button href=${a.href} variant=${i === 0 ? 'primary' : 'secondary'} class="max-md:w-full">${a.label}</spyglass-button>`)}</div>`

/**
 * @summary A story told in chapters while the reader scrolls, pinned from 1024.
 */
export class ScrollStory extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="scroll-story"]'))
	static properties = { story: { type: Object }, preset: {}, actions: { type: Array } }
	/** The story (lib/scroll-story.ts). */
	story?: ScrollStoryData
	/** One of the Acme stories when `story` is not set: research, sentiment, landing or channels. */
	preset: ScrollStoryPreset = 'research'
	/** Buttons under the last chapter: [{ label, href }], the first White. */
	actions?: StoryAction[]
	#stop = () => {}

	get #data(): ScrollStoryData {
		return (this.story && typeof this.story === 'object' ? this.story : undefined) ?? scrollStories[this.preset] ?? scrollStories.research
	}

	protected updated(changed: PropertyValues) {
		super.updated?.(changed)
		if (changed.has('story') || changed.has('preset')) {
			this.#stop()
			const root = this.renderRoot
			this.#stop = runScrollStory(() => {
				const track = root.querySelector<HTMLElement>('.ds-story-track')
				const frame = root.querySelector<HTMLElement>('.ds-story-frame')
				const words = root.querySelector<HTMLElement>('.ds-story-words')
				if (!track || !frame || !words) return null
				return { track, frame, words, pieces: [...root.querySelectorAll<HTMLElement>('.ds-story-piece')], texts: [...root.querySelectorAll<HTMLElement>('.ds-story-text')] }
			}, this.#data)
		}
	}

	connectedCallback() {
		super.connectedCallback()
		if (this.hasUpdated) this.requestUpdate('preset')
	}

	disconnectedCallback() {
		super.disconnectedCallback()
		this.#stop()
		this.#stop = () => {}
	}

	render() {
		const story = this.#data
		const { chapters, pieces } = story
		const actions = Array.isArray(this.actions) ? this.actions : undefined
		const byId = new Map(pieces.map((p) => [p.id, p]))
		const titleId = `${story.id}-story-title`
		return html`<section data-ds="scroll-story" aria-labelledby=${titleId} class="ds-story"><h2 id=${titleId} class="sr-only">${story.title}</h2><div class="ds-story-track" style=${styleMap({ height: trackHeight(chapters.length) })}><div class="ds-story-stage"><div class="ds-story-frame" aria-hidden="true">${pieces.map((piece) => html`<span class="ds-story-piece" data-kind=${piece.kind} style=${styleMap(pieceStartStyle(piece, chapters.length))}>${body(piece)}</span>`)}</div><div class="ds-story-container ds-story-words">${chapters.map((c, i) => html`<div class="ds-story-slot" data-side=${c.side}><div class="ds-story-text" data-mode=${c.mode ?? 'scroll'}><h3 class="ds-story-heading">${c.heading}</h3><p class="ds-story-lead">${c.text}</p>${actions && i === chapters.length - 1 ? actionsRow(actions) : nothing}</div></div>`)}</div></div></div><ol class="ds-story-container ds-story-stack" role="list">${chapters.map((c, i) => html`<li class="ds-story-stack-item"><div class="ds-story-stack-text"><h3 class="ds-story-heading">${c.heading}</h3><p class="ds-story-lead">${c.text}</p>${actions && i === chapters.length - 1 ? actionsRow(actions) : nothing}</div><div class="ds-story-still" data-layout=${c.still.layout} aria-hidden="true">${c.still.pieces.map((id) => {
			const piece = byId.get(id)
			if (!piece) return nothing
			const ratio = stillRatio(piece)
			return html`<span class="ds-story-still-piece" data-kind=${piece.kind} style=${styleMap(ratio ? { aspectRatio: ratio } : {})}>${body(piece, true)}</span>`
		})}</div></li>`)}</ol></section>`
	}
}

define('scroll-story', ScrollStory)
elements/components/blocks/scroll-story.css
.ds-story { position: relative; display: block; color: var(--ds-color-fg); }
.ds-story-container { width: 100%; max-width: calc(var(--ds-layout-content) + 2 * var(--ds-layout-gutter)); margin-inline: auto; padding-inline: var(--ds-layout-gutter); }
.ds-story-track { display: none; position: relative; margin-top: calc(-1 * var(--story-settle-d, 0px)); margin-bottom: calc(var(--ds-layout-section) - var(--story-foot, var(--ds-layout-section))); }
.ds-story-stage { position: sticky; top: 0; height: 100vh; overflow: clip; pointer-events: none; }
.ds-story-frame { position: absolute; left: 50%; top: 50%; width: calc(var(--ds-story-frame-w) * 1px); height: calc(var(--ds-story-frame-h) * 1px); transform: translate(-50%, -50%); pointer-events: none; }
.ds-story-piece { position: absolute; left: 0; top: 0; display: block; transform-origin: 0 0; will-change: transform, opacity; }
.ds-story-piece[data-kind="chip"] { width: max-content; }
.ds-story-words { position: absolute; inset: 0; pointer-events: none; }
.ds-story-slot { position: absolute; inset: 0 var(--ds-layout-gutter); display: flex; align-items: center; }
.ds-story-slot[data-side="right"] { justify-content: flex-end; }
.ds-story-slot[data-side="top"] { align-items: flex-start; justify-content: center; padding-top: var(--ds-layout-section); text-align: center; }
.ds-story-text { width: var(--ds-story-text-w); will-change: transform; }
.ds-story-slot[data-side="top"] .ds-story-text { width: auto; max-width: var(--ds-layout-measure); display: flex; flex-direction: column; align-items: center; }
.ds-story-slot[data-side="top"] .ds-story-text > :first-child, .ds-story-stack-item:first-child .ds-story-stack-text > :first-child { text-box: trim-start cap alphabetic; }
.ds-story-text[data-mode="scroll"] { transform: translate3d(0, 100vh, 0); }
.ds-story-text[data-mode="reveal"] > * { opacity: 0; transform: translate3d(0, var(--ds-story-text-rise), 0); }
.ds-story-heading { margin: 0; font-family: var(--ds-font-heading); font-weight: var(--ds-font-weight-heading); font-size: var(--ds-text-heading-3); line-height: var(--ds-text-heading-3-leading); letter-spacing: 0; text-wrap: balance; }
.ds-story-lead { margin: var(--ds-space-lg) 0 0; max-width: var(--ds-layout-measure); color: var(--ds-color-fg-soft); font-family: var(--ds-font-text); font-size: var(--ds-text-body-lg); line-height: var(--ds-text-body-lg-leading); text-wrap: pretty; }
.ds-story-actions { display: flex; flex-wrap: wrap; gap: var(--ds-space-md); margin-top: var(--ds-space-2xl); pointer-events: auto; }
.ds-story-shot { position: relative; display: block; width: 100%; height: 100%; overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-raised); }
.ds-story-shot > img, .ds-story-fill { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-badge { position: absolute; left: var(--ds-space-sm); bottom: var(--ds-space-sm); padding: var(--ds-space-xs) var(--ds-space-sm); border-radius: var(--ds-radius-sm); background: var(--ds-color-black); color: var(--ds-color-fg); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); font-variant-numeric: tabular-nums; opacity: var(--b, 0); white-space: nowrap; }
.ds-story-mark { position: absolute; right: var(--ds-space-sm); bottom: var(--ds-space-sm); display: grid; place-items: center; width: var(--ds-space-xl); height: var(--ds-space-xl); border-radius: var(--ds-radius-sm); background: var(--ds-color-black); opacity: var(--m, 1); }
.ds-story-mark img { width: var(--ds-space-md); height: var(--ds-space-md); }
.ds-story-piece .ds-story-shot { container-type: inline-size; }
.ds-story-piece .ds-story-mark { right: 3.36cqi; bottom: 3.36cqi; width: 10.08cqi; height: 10.08cqi; }
.ds-story-piece .ds-story-mark img { width: 5.04cqi; height: 5.04cqi; }
.ds-story-board { display: flex; flex-direction: column; align-items: center; width: 100%; height: 100%; padding-top: calc(var(--ds-space-2xl) + var(--ds-space-sm)); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); text-align: center; }
.ds-story-board-name { display: flex; gap: var(--ds-space-md); align-items: center; }
.ds-story-logo { position: relative; display: grid; place-items: center; flex: none; overflow: hidden; border-radius: var(--ds-radius-full); background: var(--ds-color-white); color: var(--ds-color-black); font-family: var(--ds-font-heading); }
.ds-story-logo img { position: absolute; inset: 0; width: 100%; height: 100%; border-radius: var(--ds-radius-full); object-fit: cover; }
.ds-story-board .ds-story-logo, .ds-story-more { width: var(--ds-space-2xl); height: var(--ds-space-2xl); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-board-title { font-family: var(--ds-font-heading); font-size: var(--ds-text-heading-2); line-height: var(--ds-text-heading-2-leading); }
.ds-story-board-meta { margin-top: var(--ds-space-xs); color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-board[data-compact] { justify-content: center; padding: var(--ds-space-xl); }
.ds-story-board[data-compact] .ds-story-board-name { flex-direction: column; }
.ds-story-board[data-compact] .ds-story-board-title { font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); text-wrap: balance; }
.ds-story-action { display: inline-flex; align-items: center; height: var(--ds-space-2xl); margin-top: var(--ds-space-lg); padding-inline: var(--ds-space-lg); border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-panel); color: var(--ds-color-fg); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); white-space: nowrap; }
.ds-story-search { display: flex; gap: var(--ds-space-md); align-items: center; width: min(100%, var(--ds-story-search-w)); height: var(--ds-space-3xl); padding-inline: var(--ds-space-lg); border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-inset); text-align: left; }
.ds-story-search-icon { width: var(--ds-space-lg); height: var(--ds-space-lg); flex: none; color: var(--ds-color-fg-muted); }
.ds-story-search-text { overflow: hidden; font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); text-overflow: ellipsis; white-space: nowrap; }
.ds-story-filters { display: flex; flex-wrap: wrap; gap: var(--ds-space-sm); justify-content: center; margin-top: var(--ds-space-lg); }
.ds-story-filter { padding: var(--ds-space-xs) var(--ds-space-sm); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-sm); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); white-space: nowrap; }
.ds-story-muted { color: var(--ds-color-fg-muted); }
.ds-story-chip { display: inline-flex; gap: var(--ds-space-sm); align-items: baseline; padding: var(--ds-space-sm) var(--ds-space-md); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); white-space: nowrap; }
.ds-story-card { display: flex; flex-direction: column; width: 100%; height: 100%; border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); }
.ds-story-card-head { display: flex; flex-direction: column; gap: var(--ds-space-xs); padding: var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-card-title { font-family: var(--ds-font-heading); font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); }
.ds-story-small { color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-row { display: grid; grid-template-columns: var(--ds-space-4xl) minmax(0, 1fr) auto; gap: var(--ds-space-lg); align-items: center; padding: var(--ds-space-sm) var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-row:last-child { border-bottom: 0; }
.ds-story-thumb { position: relative; display: block; width: var(--ds-space-4xl); height: var(--ds-space-5xl); overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-inset); }
.ds-story-thumb > * { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-row-words { display: flex; flex-direction: column; min-width: 0; }
.ds-story-body { font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); }
.ds-story-detail { display: flex; gap: var(--ds-space-sm); align-items: center; color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-detail .ds-story-logo { width: var(--ds-space-lg); height: var(--ds-space-lg); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); }
.ds-story-figure { display: flex; gap: var(--ds-space-sm); align-items: center; font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); font-variant-numeric: tabular-nums; }
.ds-story-inline-mark { width: var(--ds-space-md); height: var(--ds-space-md); flex: none; }
.ds-story-tabs { display: flex; gap: var(--ds-space-xs); padding: var(--ds-space-md) var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-tab { padding: var(--ds-space-xs) var(--ds-space-sm); border-radius: var(--ds-radius-sm); color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); white-space: nowrap; }
.ds-story-tab[data-on] { background: var(--ds-color-surface-inset); color: var(--ds-color-fg); }
.ds-story-message { display: grid; grid-template-columns: var(--ds-space-2xl) minmax(0, 1fr) auto; column-gap: var(--ds-space-md); align-items: start; padding: var(--ds-space-lg) var(--ds-space-xl); border-bottom: var(--ds-border-hairline) solid var(--ds-color-edge-surface); }
.ds-story-message:last-child { border-bottom: 0; }
.ds-story-initial { position: relative; display: grid; place-items: center; width: var(--ds-space-2xl); height: var(--ds-space-2xl); overflow: hidden; border-radius: var(--ds-radius-full); background: var(--ds-color-surface-inset); color: var(--ds-color-fg-soft); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); }
.ds-story-initial img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.ds-story-message-words { display: flex; flex-direction: column; gap: var(--ds-space-xs); min-width: 0; }
.ds-story-message-text { overflow: hidden; font-size: var(--ds-text-body); line-height: var(--ds-text-body-leading); text-overflow: ellipsis; white-space: nowrap; }
.ds-story-likes { color: var(--ds-color-fg-muted); font-size: var(--ds-text-caption); line-height: var(--ds-text-ui-leading); font-variant-numeric: tabular-nums; white-space: nowrap; }
.ds-story-profile { display: flex; flex-direction: column; width: 100%; height: 100%; overflow: hidden; border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); }
.ds-story-profile-head { display: flex; gap: var(--ds-space-md); align-items: center; padding: var(--ds-space-xl) var(--ds-space-xl) 0; }
.ds-story-profile-head .ds-story-action { margin: 0; }
.ds-story-profile-head .ds-story-logo { width: var(--ds-space-3xl); height: var(--ds-space-3xl); font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); }
.ds-story-profile-words { display: flex; flex: 1; flex-direction: column; min-width: 0; }
.ds-story-handle { display: flex; gap: var(--ds-space-xs); align-items: center; color: var(--ds-color-fg-muted); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-profile-meta { padding: var(--ds-space-md) var(--ds-space-xl) var(--ds-space-lg); color: var(--ds-color-fg-soft); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-grid { display: grid; flex: 1; grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-rows: 1fr; gap: var(--ds-space-xs); min-height: 0; padding-inline: var(--ds-space-xs); }
.ds-story-post { position: relative; display: block; min-height: 0; overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-surface-inset); }
.ds-story-post > * { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-profile-foot { margin-top: var(--ds-space-xs); padding: var(--ds-space-sm) var(--ds-space-md); border-top: var(--ds-border-hairline) solid var(--ds-color-edge-surface); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-page { display: block; width: 100%; height: 100%; }
.ds-story-page-fill { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
.ds-story-board-stack { display: flex; align-items: center; }
.ds-story-board-stack > * + * { margin-left: calc(var(--ds-space-sm) * -1); }
.ds-story-board-stack > .ds-story-logo, .ds-story-more { outline: calc(var(--ds-border-hairline) * 2) solid var(--ds-color-surface-raised); }
.ds-story-more { display: grid; place-items: center; flex: none; border-radius: var(--ds-radius-full); background: var(--ds-color-surface-subtle); color: var(--ds-color-fg-soft); font-size: var(--ds-text-caption); line-height: var(--ds-text-caption-leading); font-weight: var(--ds-font-weight-medium); }
.ds-story-stack { display: grid; row-gap: var(--ds-space-5xl); margin: 0; padding-block: var(--ds-layout-section); list-style: none; }
.ds-story-stack-item { display: grid; row-gap: var(--ds-space-2xl); }
.ds-story-still { display: grid; gap: var(--ds-space-md); max-width: var(--ds-layout-measure); }
.ds-story-still-piece { position: relative; display: block; min-width: 0; }
.ds-story-still-piece[data-kind="chip"] .ds-story-chip { white-space: normal; }
.ds-story-still-piece .ds-story-message-text { white-space: normal; }
.ds-story-still[data-layout="board"] { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: var(--ds-space-lg); border: var(--ds-border-hairline) solid var(--ds-color-edge-surface); border-radius: var(--ds-radius-panel); background: var(--ds-color-surface-raised); }
.ds-story-still[data-layout="board"] .ds-story-still-piece[data-kind="board"] { grid-column: 1 / -1; }
.ds-story-still[data-layout="board"] .ds-story-board { padding: 0 0 var(--ds-space-sm); border: 0; }
.ds-story-still[data-layout="board"] .ds-story-search { height: auto; padding-block: var(--ds-space-sm); }
.ds-story-still[data-layout="board"] .ds-story-search-text { white-space: normal; font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); }
.ds-story-still-piece[data-kind="profile"] .ds-story-grid { grid-auto-rows: auto; }
.ds-story-still-piece[data-kind="profile"] .ds-story-post { aspect-ratio: 1; }
.ds-story-still-piece[data-kind="profile"] { max-width: var(--ds-story-profile-w); }
.ds-story-still[data-layout="rank"] { grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: end; }
.ds-story-still[data-layout="rank"] .ds-story-badge, .ds-story-still[data-layout="focus"] .ds-story-badge { opacity: 1; }
.ds-story-still[data-layout="rank"] .ds-story-mark { display: none; }
.ds-story-still[data-layout="focus"] { display: flex; flex-wrap: wrap; gap: var(--ds-space-sm); }
.ds-story-still[data-layout="focus"] .ds-story-still-piece[data-kind="image"] { flex: 0 0 100%; max-width: var(--ds-layout-measure-sm); }
.ds-story-still[data-layout="page"] { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.ds-story-still[data-layout="page"] .ds-story-still-piece:first-child { grid-column: 1 / -1; }
@media (min-width: 768px) {
  .ds-story-heading { font-size: var(--ds-text-heading-2); line-height: var(--ds-text-heading-2-leading); }
}
@media (min-width: 1024px) {
  .ds-story-stack-item { grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); column-gap: var(--ds-space-4xl); align-items: center; }
  .ds-story-still { max-width: none; }
  .ds-story-still[data-layout="board"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
@media (min-width: 1280px) {
  .ds-story-heading { font-size: var(--ds-text-figure); line-height: var(--ds-text-figure-leading); }
}
@media (min-width: 1024px) and (prefers-reduced-motion: no-preference) {
  .ds-story-track { display: block; }
  .ds-story-stack { display: none; }
}
@media (width < 768px) {
  .ds-story-actions { flex-direction: column; align-self: stretch; }
  .ds-story-still[data-layout="board"] .ds-story-board { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: var(--ds-space-md); align-items: center; text-align: left; }
  .ds-story-still[data-layout="board"] .ds-story-board-name { min-width: 0; }
  .ds-story-still[data-layout="board"] .ds-story-logo, .ds-story-still[data-layout="board"] .ds-story-more { width: var(--ds-space-xl); height: var(--ds-space-xl); }
  .ds-story-still[data-layout="board"] .ds-story-more { position: relative; }
  .ds-story-still[data-layout="board"] .ds-story-board-title { min-width: 0; font-size: var(--ds-text-heading-4); line-height: var(--ds-text-heading-4-leading); }
  .ds-story-still[data-layout="board"] .ds-story-board-meta, .ds-story-still[data-layout="board"] .ds-story-search, .ds-story-still[data-layout="board"] .ds-story-filters { grid-column: 1 / -1; }
  .ds-story-still[data-layout="board"] .ds-story-filters { justify-content: flex-start; }
  .ds-story-still[data-layout="board"] .ds-story-action { grid-column: 1 / -1; justify-self: start; margin-top: var(--ds-space-md); }
  .ds-story-still[data-layout="page"] .ds-story-board { padding: var(--ds-space-xl) var(--ds-space-lg); }
  .ds-story-still[data-layout="page"] .ds-story-board-title { font-size: var(--ds-text-heading-3); line-height: var(--ds-text-heading-3-leading); text-wrap: balance; }
}

Reference: Site story/ScrollStory (ScrollStory.tsx, pieces.tsx, timeline.ts, types.ts, ScrollStory.module.css) and content/pages/useCaseStories (shape.ts and the stories): the --story-* tokens (tokens.css 820-836), pinned at (min-width: 1024px) and (prefers-reduced-motion: no-preference), the frame scaled to min(content / 1280, height / 982), chapter words at 41.6% wide, 24/32/40 Funnel Display 450 headings with the 20/28 lead.