Vibe coding with Claude Code course Β· Module 13: Twitch clone

The Archive of Best Moments: Categories, Clips and Videos

9 min read
In this lesson9

The channel has a business card but a new viewer does not yet know what to look for. They need a page where they browse categories, see who is broadcasting now, and watch short clips with the best moments. The streamer, in turn, wants the voyage not to vanish after the broadcast: the recording stays in the archive, split into chapters, and a viewer can cut a clip out of it. In this lesson Claude builds a Browse page with three tabs, a video page and clip creation. You check where a clip is really made.

What you will learn

  • order a big feature in plan mode and at once use the tabs convention from CLAUDE.md without another copy of the code;
  • read covers with fixed proportions that do not jump while loading;
  • understand that a clip is a time range in a recording, and that the server guards it;
  • check every tab in the browser, with Claude in Chrome or by hand.

Request for Claude Code

This step touches data, three card components, two pages, an API route and the player, so you start with a plan, as in lesson 1_6:

Request for Claude Code:

/plan Add a page /browse with tabs Categories, Live and Clips
(through Tabs, as in CLAUDE.md). Categories: a grid of 3:4 covers
with the number of viewers, covers from images.unsplash.com through
next/image. Live: channels from lib/channels.ts that are broadcasting.
Clips: a clip is a time range in a recording (vodId, start, end), no
video cutting. A page /videos/[id] with a recording player, a list
of chapters and a button Create clip. A clip is saved by the route
POST /api/clips: the server itself computes 30 seconds around the
given moment and rejects a moment outside the recording. Vitest tests
for chapters and the clip range. At the end npm run test -- --run,
npm run lint, npx tsc --noEmit and npm run build.

In the plan check one thing: whether Claude intends to cut video in the browser. If the plan talks about "trimming the file" in a component, answer "No, keep planning" and remind it that a clip is a range.

What Claude wrote: tabs from the convention

Open app/browse/page.tsx. The page has no tab code of its own, only a list and the shared component from lesson 12_2:

// app/browse/page.tsx
const BROWSE_TABS = [
  { key: "categories", label: "Categories" },
  { key: "live", label: "Live" },
  { key: "clips", label: "Clips" },
] as const;

The page starts with a Browse heading, under it stands <Tabs tabs={BROWSE_TABS} active={active} basePath="/browse" />, and below are three sections, each drawn only for its own tab. The categories section is one expression: categories.map((c) => <CategoryCard key={c.slug} category={c} />). That is proof the line in CLAUDE.md worked: Claude did not write a sixth copy.

What Claude wrote: covers that do not jump

Open components/CategoryCard.tsx. A category cover is taller than it is wide, like a game box:

// components/CategoryCard.tsx
<div className="relative aspect-3/4 overflow-hidden rounded-lg bg-zinc-800">
  <Image src={category.cover} alt="" fill sizes="(min-width: 1024px) 20vw, 45vw" className="object-cover" />
</div>

Under the cover stand the category name in an h3 and the number of viewers. aspect-3/4 reserves space with proportions 3 to 4 before the picture downloads, so the text under the card does not jump. fill stretches the picture over the parent with relative, sizes tells the browser what part of the screen the card will take, and object-cover crops the photo to the shape. You know all of this from lesson 3_1. The remotePatterns entry for images.unsplash.com in next.config.ts comes from there too. Without it next build passes, and a picture from another server knocks the page over only in the browser. The live channel card, components/LiveCard.tsx, works the same way, only with aspect-video and a LIVE badge, and leads to the channel page. There the Videos tab from lesson 12_2 got a list of links to /videos/[id].

A clip is a range, not a new file

Cutting a piece out of a film is heavy work: you have to read the file, encode a piece anew and save it as a new video. It is done on a server, with a program such as ffmpeg, which you used in lesson 12_1 to make the test file. A React component in the viewer's browser is a bad place for such work: a phone would have to download the whole recording and re-encode a piece of it. Our clone takes a simpler road: it saves only a time range in an existing recording. Open components/ClipPlayer.tsx:

// components/ClipPlayer.tsx
<video
  src={`${vod.src}#t=${clip.start},${clip.end}`}
  controls
  preload="metadata"
  className="aspect-video w-full rounded-lg bg-black"
/>

#t=40,55 at the end of the address is a media fragment. MDN describes it as a way to play only a part of a file: from the first number of seconds to the second. Under the player stand the clip title in an h3 and the recording name with the range, for example 0:40-0:55. In our run Chrome set the clip to 0:40 and, after playback started, stopped by itself at 55.1 seconds. Remember that this is not protection: the controls show the whole recording (0:40 / 1:00), and scrolling to the 5th second worked without resistance.

A check on the server: the clip range

The Create clip button sends only vodId and the current second. The length of the clip and its limits are computed by the server, like the lock from lesson 8_3, because a request can be sent bypassing the button. Open lib/clipRange.ts:

// lib/clipRange.ts
export const CLIP_SECONDS = 30; // a rule of our clone

export function clipRange(at: number, duration: number): { start: number; end: number } | null {
  if (!Number.isFinite(at) || at < 0 || at > duration) return null;
  const start = Math.max(0, Math.min(Math.round(at) - CLIP_SECONDS / 2, duration - CLIP_SECONDS));
  return { start, end: Math.min(duration, start + CLIP_SECONDS) };
}

Thirty seconds is our rule, not a Twitch rule. Number.isFinite rejects NaN, which is the result of Number("abc"). Math.min and Math.max shift the clip so that it does not stick out before the start or after the end of the recording. The test checks a clip at the 3rd second (0-30) and at the 58th (30-60). The route app/api/clips/route.ts first reads the request body with request.json().catch(() => null), then looks up the recording by vodId (missing is 404). Next it computes const range = clipRange(Number(body.at), vod.duration) and answers 400 when it gets null. At the end it saves the clip and answers 201. Check it with npm run dev running:

curl -s -w ' %{http_code}\n' -X POST -H 'Content-Type: application/json' -d '{"vodId":"voyage-1","at":9999}' localhost:3000/api/clips

-w appends the response code at the end of the line. For us it came out as {"error":"That moment is outside the recording"} 400, and 404 for an unknown recording. The clips are kept in an array on globalThis, for the reason from lesson 11_2: the route and the page would otherwise see separate copies.

What Claude wrote: chapters from a sorted copy

A streamer adds chapters during editing, in any order, so the data may not stand in sequence. Open lib/chapters.ts:

// lib/chapters.ts
export function sortChapters(chapters: readonly Chapter[]): Chapter[] {
  return [...chapters].sort((a, b) => a.start - b.start);
}

export function currentChapter(chapters: readonly Chapter[], time: number): Chapter | undefined {
  return sortChapters(chapters).findLast((chapter) => chapter.start <= time);
}

The same rule as in the emote parser: a copy before sorting and readonly in the type. findLast searches from the end, so it returns the last chapter that started before the current second. formatTime from the same file turns seconds into m:ss or h:mm:ss (65.9 seconds is "1:05"), and the chapter list shows formatTime(ch.start) before the title. VodPlayer computes the chapter during render from time, which is set by onTimeUpdate of the <video> element. MDN says this event arrives roughly 4 to 66 times a second, depending on the load, so it is enough to display a chapter.

Captain's review

  1. Invented helpers. A typical agent mistake is a createClip in the browser that calls generateId(), getCurrentUser() and getCurrentStream(), although nobody wrote them. In our run npm run lint stayed silent on such a file, and npx tsc --noEmit reported Cannot find name 'generateId' and two similar errors. The same version computed currentTimestamp - duration / 2, a negative start at the third second of the recording.
  2. Dead state. Search for isPlaying. The agent likes const [isPlaying, setIsPlaying] = useState(false) and autoPlay={isPlaying}, although nothing changes that state. Lint showed us only the warning 'setIsPlaying' is assigned a value but never used and finished with success, so read warnings, do not scroll past them.
  3. Covers. Every Image with fill has a parent with relative and proportions.
  4. The browser. This is the step no test replaces. With Claude in Chrome from lesson 3_8 one request is enough:
Open localhost:3000/browse and go through the tabs Categories,
Live and Clips. On each one check that the cards display, and look
into the console for errors. On /videos/voyage-1 click the chapter
Player, then Create clip, and check that the clip appears in the Clips
tab. Report what you see.

Without the extension do the same by hand. For us all three tabs showed cards, the console was empty, the chapter switched to "Player", and POST /api/clips answered 201.

Next step

When the review passes, ask for a commit "Browse, clips and recording chapters". Then a small step: "On a category page show the live channels from that category, plan first". The clone already has something to boast about, but the port is still far: in the next lessons you will close it in a container and set up a pipeline that checks every change. In the editor below waits a miniature Browse page: switch the tabs and create clips from a pretend recording.

Remember: an archive is worth as much as the map that leads to it, and the shears for the tape are held by the bosun in the hold, not by a viewer on the deck.

Code for this lesson: App.tsx
// Browse in miniature: tabs, 3:4 covers, a clip as a range computed by a pretend server, and chapters
import { useState } from 'react';

interface Chapter {
  start: number;
  title: string;
}

interface Clip {
  id: string;
  start: number;
  end: number;
}

const DURATION = 60; // the recording lasts a minute
const CLIP_SECONDS = 30; // a rule of our clone
const CHAPTERS: readonly Chapter[] = Object.freeze([
  { start: 40, title: 'Chat and emotes' },
  { start: 0, title: 'Welcome aboard' },
  { start: 15, title: 'Player' },
]);
const CATEGORIES = [
  { slug: 'programming', name: 'Programming', viewers: 1247, colors: 'from-sky-600 to-indigo-900' },
  { slug: 'shanties', name: 'Sea shanties', viewers: 310, colors: 'from-amber-500 to-rose-800' },
  { slug: 'navigation', name: 'Navigation', viewers: 88, colors: 'from-emerald-500 to-teal-900' },
];
const TABS = [
  { key: 'categories', label: 'Categories' },
  { key: 'live', label: 'Live' },
  { key: 'clips', label: 'Clips' },
] as const;
type BrowseTab = (typeof TABS)[number]['key'];

function sortChapters(chapters: readonly Chapter[]): Chapter[] {
  return [...chapters].sort((a, b) => a.start - b.start);
}

function currentChapter(chapters: readonly Chapter[], time: number): Chapter | undefined {
  return sortChapters(chapters).findLast((chapter) => chapter.start <= time);
}

function clipRange(at: number, duration: number): { start: number; end: number } | null {
  if (!Number.isFinite(at) || at < 0 || at > duration) return null;
  const start = Math.max(0, Math.min(Math.round(at) - CLIP_SECONDS / 2, duration - CLIP_SECONDS));
  return { start, end: Math.min(duration, start + CLIP_SECONDS) };
}

function formatTime(seconds: number): string {
  const s = Math.floor(seconds);
  return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
}

// In the project the id comes from crypto.randomUUID(); here a counter is enough
let nextId = 1;

// Pretend server: it computes the range itself; the agent's version accepts what the browser computed
function fakeServer(body: { at: number; start?: number; end?: number }, trustClient: boolean) {
  if (trustClient && body.start !== undefined && body.end !== undefined) {
    return { status: 201, clip: { id: 'c' + nextId++, start: body.start, end: body.end } };
  }
  const range = clipRange(body.at, DURATION);
  if (!range) return { status: 400, clip: null };
  return { status: 201, clip: { id: 'c' + nextId++, ...range } };
}

export default function App() {
  const [active, setActive] = useState<BrowseTab>('categories');
  const [time, setTime] = useState(3);
  const [clips, setClips] = useState<Clip[]>([]);
  const [trustClient, setTrustClient] = useState(false);
  const [status, setStatus] = useState('');
  const chapter = currentChapter(CHAPTERS, time);

  function createClip() {
    // The agent's version computes the range in the browser: at - 15, with no recording limits
    const body = trustClient ? { at: time, start: time - CLIP_SECONDS / 2, end: time + CLIP_SECONDS / 2 } : { at: time };
    const res = fakeServer(body, trustClient);
    if (res.clip) {
      const clip = res.clip;
      setClips((prev) => [clip, ...prev]);
    }
    setStatus('The server answered ' + res.status);
  }

  return (
    <div className="min-h-screen space-y-4 bg-zinc-950 p-4 text-zinc-100">
      <h1 className="text-2xl font-bold">Browse</h1>
      <nav aria-label="Tabs" className="flex gap-1 border-b border-zinc-800">
        {TABS.map((tab) => (
          <button
            key={tab.key}
            type="button"
            onClick={() => setActive(tab.key)}
            aria-current={tab.key === active ? 'page' : undefined}
            className={tab.key === active ? 'border-b-2 border-purple-500 px-4 py-2 font-semibold' : 'border-b-2 border-transparent px-4 py-2 text-zinc-400'}
          >
            {tab.label}
          </button>
        ))}
      </nav>

      {active === 'categories' && (
        <section className="grid max-w-md grid-cols-3 gap-3">
          {CATEGORIES.map((c) => (
            <article key={c.slug}>
              <div className={'aspect-3/4 rounded-lg bg-linear-to-b ' + c.colors} />
              <h2 className="mt-2 font-semibold">{c.name}</h2>
              <p className="text-sm text-zinc-400">{c.viewers} viewers</p>
            </article>
          ))}
        </section>
      )}

      {active === 'live' && <p>Captain Redbeard is live: Voyage across the Sea of Code (1247 viewers)</p>}

      {active === 'clips' && (
        <section className="space-y-3">
          <label className="block text-sm">
            Pretend recording, second {formatTime(time)} of {formatTime(DURATION)}
            <input type="range" min={0} max={DURATION} value={time} onChange={(e) => setTime(Number(e.target.value))} className="block w-full" aria-label="Recording second" />
          </label>
          <p>Chapter: <strong>{chapter?.title ?? 'none'}</strong></p>
          <ol className="text-sm text-zinc-400">
            {sortChapters(CHAPTERS).map((ch) => (
              <li key={ch.start}>{formatTime(ch.start)} {ch.title}</li>
            ))}
          </ol>
          <button type="button" onClick={createClip} className="rounded bg-purple-600 px-4 py-2 font-semibold">
            Create clip
          </button>
          <p role="status">{status}</p>
          <ul className="space-y-1">
            {clips.map((clip) => (
              <li key={clip.id} className={clip.start < 0 || clip.end > DURATION ? 'text-red-400' : ''}>
                Clip {formatTime(Math.max(0, clip.start))}-{formatTime(clip.end)} (start {clip.start}, end {clip.end})
              </li>
            ))}
          </ul>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={trustClient} onChange={(e) => setTrustClient(e.target.checked)} />
            The agent's version: the browser computes the range, the server accepts it
          </label>
        </section>
      )}
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is a clip in Live from the Deck?

  2. 2. Who in Live from the Deck computes the start and end of a new clip?

These are 2 of 10 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the address that plays a clip from the 40th to the 55th second of a recording (one line):

  • Code editor

    Build a category browsing page

  • Horizontal ordering

    Arrange the inside of sortChapters that sorts a copy of the chapters (one line):

  • Vertical ordering

    Arrange the steps of the route that saves a clip:

  • Code editor

    Create a clip player

  • Vertical ordering

    Arrange the elements of CategoryCard from the top:

  • Click in order

    Build the call that shows the start of a chapter as m:ss

  • Vertical ordering

    The chapters stand in the data as 0:40, 0:00, 0:15. Arrange them as the list from sortChapters will show them:

  • Vertical ordering

    Arrange the path of a clip from the click to the Clips tab:

  • Click in order

    Build the line of the route POST /api/clips that computes the clip range

  • Vertical ordering

    Arrange the viewer's path from the Browse page to a recording:

  • Horizontal ordering

    Arrange the body of the pickTab function (one line):

  • Vertical ordering

    Arrange the elements of ClipPlayer from the top:

  • Horizontal ordering

    Arrange the expression that draws the cards in the Categories tab (one line):

  • Horizontal ordering

    Arrange the body of the currentChapter function (one line):

  • Vertical ordering

    Arrange the elements of the Browse page from the top:

  • Horizontal ordering

    Arrange the result of formatTime(65.9) for a recording shorter than an hour (one line): 1:05

  1. QuestionQuiz: what a clip is
  2. QuestionQuiz: who computes the clip range
  3. Put in orderOrder: a clip address
  4. Coding taskPractice: Browse categories
  5. QuestionQuiz: a media fragment is not a lock
  6. Put in orderOrder: chapters from a copy
  7. Put in orderOrder: the route POST /api/clips
  8. Coding taskPractice: Clip player
  9. QuestionQuiz: the current chapter
  10. Put in orderOrder: the category card
  11. Click in orderBuild: chapter time
  12. QuestionQuiz: clipRange at the start of a recording
  13. Put in orderOrder: the chapter list
  14. Put in orderOrder: the path of a clip
  15. Click in orderBuild: the clip range on the server
  16. Put in orderOrder: the viewer's path
  17. Put in orderOrder: pickTab in one line
  18. QuestionQuiz: how the player knows the chapter
  19. Put in orderOrder: the clip player
  20. Put in orderOrder: the category grid
  21. QuestionQuiz: the dead isPlaying state
  22. Put in orderOrder: the current chapter
  23. QuestionQuiz: invented helpers
  24. Put in orderOrder: the Browse page from the top
  25. QuestionQuiz: aria-pressed on the Follow button
  26. Put in orderOrder: the result of formatTime
  27. QuestionQuiz: what you check in the browser

Useful articles