Vibe coding with Claude Code course · Module 8: Slack clone

The Navigation Board: a Crew Dashboard Computed from Messages

10 min read
In this lesson10

The captain wants to know whether Ship's Comms is alive: how many messages flow through the channels, who writes the most and whether this week is quieter than the last. A number without a source is sailing in fog, and a chart with hard-coded data looks great and lies. In this lesson the dashboard computes everything from real messages, and tests make sure the numbers add up.

The problem: three traps in simple addition

The dashboard looks like plain counting, but it has three places where a mistake is easy. The first is the time zone, that is, the clock offset from universal time, UTC. Messages carry an ISO date written in UTC, while the crew lives in Warsaw, which is one hour ahead of UTC, and in summer two. A message written half an hour after midnight belongs to the new day, even though in UTC it is still the previous day. The second place is the percent change when the previous week had nothing. The third is access: a guest must not be able to read off the dashboard how much is going on in a private channel, not even as totals.

Request for Claude Code:

/plan Add a /panel page with the crew activity from the last 7 days:
three cards (messages, active members, thread replies) with the
percent change against the previous 7 days, a bar chart of messages
per day, a ranking of channels and the three most active members.
Compute everything from messages with pure functions in
lib/analytics.ts, tests first. A day is counted in the
Europe/Warsaw time zone. Only channels the logged-in member may see.
The chart without a library, with a short description for screen
readers and a table with the data. Add two weeks of conversations
to the test data. At the end tests, lint, types and build.

The sentence about the library is deliberate. Seven bars are plain HTML elements with a height in percent: they render on the server together with the rest of the page and add no dependency to package.json that you would have to keep updating. Reach for a chart library only when you need axes, zooming or tooltips on hover, and then ask Claude to first show in the documentation that it works with your version of React. In the plan itself, check that the counting goes into lib/analytics.ts and not into components: only pure functions can be tested without a browser.

What the first run showed

Claude started with the tests in lib/analytics.test.ts and then wrote a first version of the functions. It took the day of a message from createdAt.slice(0, 10), that is, from the first ten characters of the ISO date. Four of ten tests failed, and the first of them looked like this:

FAIL  lib/analytics.test.ts > dayKey > counts the day in the Europe/Warsaw zone, not in UTC
AssertionError: expected '2026-11-13' to be '2026-11-14' // Object.is equality

Expected: "2026-11-14"
Received: "2026-11-13"

The test passed a message from the moment 2026-11-13T23:30:00.000Z. In Warsaw that is 00:30 on 14 November, and slice cut the date off in UTC and threw the night watch into the previous day. Nothing on screen would have given it away: the bars would look ordinary, only one message would stand a day too early. A second test caught the same thing in July, when the difference is two hours. The remaining two failures were division by zero, which we will reach in a moment.

What Claude wrote: a day in the Warsaw zone

Open lib/analytics.ts in Cursor. The corrected dayKey function asks for the date directly in the Warsaw zone:

export const TIME_ZONE = "Europe/Warsaw";

const dayParts = new Intl.DateTimeFormat("en-GB", {
  timeZone: TIME_ZONE,
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});

export function dayKey(date: Date | string): string {
  const parts = dayParts.formatToParts(new Date(date));
  const part = (type: Intl.DateTimeFormatPartTypes) =>
    parts.find((p) => p.type === type)?.value;
  return `${part("year")}-${part("month")}-${part("day")}`;
}

Intl.DateTimeFormat with the timeZone field converts the time to the Warsaw clock, daylight saving included, and formatToParts hands back the year, month and day separately instead of a ready-made string with slashes (Intl.DateTimeFormatPartTypes is the type with the names of those parts). The result is a key like "2026-11-14", which you can compare and sort like ordinary text. The data does not change: a message still keeps its time in UTC, and the zone enters the game only when counting. You saw the same rule in lesson 7_2, when formatting the time.

The period and the counting

Next to it stand two small functions. lastDays("2026-11-14", 7) returns seven day keys ending on the given day, and inPeriod keeps only messages from those days. The page app/panel/page.tsx takes fourteen days and splits them into two halves:

const days = lastDays(dayKey(new Date()), 14);
const week = inPeriod(messages, days.slice(7)); // the last 7 days
const before = inPeriod(messages, days.slice(0, 7)); // the 7 days before

messages here are messages filtered earlier by canSeeChannel, the same function that guarded the sidebar and the channel route in lesson 7_1. So the guest merchant sees only general and trade on the dashboard, and the traffic on captains-secrets will not leak to them even as a sum. The ranking of channels and members comes from countBy(week, (m) => m.channelId), which returns a map of "identifier, count". None of these functions stores counters next to the data, so, as in the log from 7_2, nothing can drift apart.

Percent change without dividing by zero

The first version counted the change with the textbook formula. For an empty previous week it returned Infinity, and for two empty weeks NaN, so the cards would show "up Infinity%" and "down NaN%". The fix:

export function percentChange(
  current: number,
  previous: number,
): number | null {
  if (previous === 0) return null; // nothing to compare with
  return Math.round(((current - previous) / previous) * 100);
}

null means "no comparison", not zero: a jump from nothing to five messages is not a growth by any specific number of percent. The formatChange function turns the result into words: "up 25%", "down 10%", "no change" or "no data to compare". The color is chosen only later, by the component.

Cards: numbers, not strings

Open components/StatsGrid.tsx. A card gets three fields: label with the name, value with the number from the last 7 days and previous with the number from the week before. The values are numbers, not ready-made strings like "12.5K", because nothing can be computed from a string anymore. Here is one card:

<div className="rounded-lg border border-gray-200 bg-white p-4">
  <dt className="text-sm text-gray-600">{stat.label}</dt>
  <dd className="text-3xl font-bold">{stat.value}</dd>
  <dd className={`text-sm ${tone[direction]}`}>{formatChange(change)}</dd>
</div>

The grid of cards is a description list <dl>: <dt> is the name of the number and <dd> its value, so "Messages" and "19" form a pair in the page code too, not only to the eye. tone is a small dictionary of classes: text-green-700 for growth, text-red-700 for a drop and gray when there is no change or no comparison. The color only underlines a direction that the word already gives, just as the presence dot in 7_1 had hidden text next to it. The same card shows any number: in a shop it would be views, clicks and conversions.

A chart from HTML and CSS

Open components/ActivityChart.tsx. The height of a bar is computed by the pure function barPercent:

export function barPercent(count: number, max: number): number {
  return max === 0 ? 0 : (count / max) * 100;
}

The tallest bar gets 100%, the others proportionally less. That was the fourth red test: in a week without messages max is 0, and 0 / 0 gives NaN. The chart itself is a row of columns, one per day:

<div role="img" aria-label={summary} className="mt-4 flex gap-2">
  {data.map((d) => (
    <div key={d.day} className="flex flex-1 flex-col items-center">
      <span className="text-xs font-semibold">{d.count}</span>
      <div className="flex h-32 w-full items-end">
        <div
          className="w-full rounded-t bg-blue-600"
          style={{ height: `${barPercent(d.count, max)}%` }}
        />
      </div>
      <span className="mt-1 text-xs text-gray-600">{formatDay(d.day)}</span>
    </div>
  ))}
</div>

The bar stands in its own box of fixed height h-32, with the number above it and the date below. In the first version the bar shared a column with the labels and flexbox squeezed the tallest one to fit everything: the seven came out less than twice as tall as the three, though it should be two and a third times taller. A test will not catch that, which is why you also have to look at the dashboard. The chart has no "use client", because it does not react to clicks: the browser receives ready HTML.

A chart for those who cannot see it

Bars are a picture, and a picture needs a description. The W3C tutorial on complex images (https://www.w3.org/WAI/tutorials/images/complex/) says that a chart needs a description in two parts: a short one that says what the image shows, and a longer one with the most important data. The short one is carried by role="img" with an aria-label, for example "Bar chart of messages per day. Most: 14 Nov, 7. Exact numbers in the table below the chart.". role="img" tells a screen reader to treat the whole box as one image, so it will not read out fourteen loose numbers without context. The longer part is a table inside <details> with the caption "Chart data in a table" and the columns "Day" and "Messages". It will also help anyone who wants to copy the numbers into a report.

Captain's review

  1. The zone in the test, not only in the code. Look in the test diff for a time just after midnight in Warsaw. A typical agent mistake: slice(0, 10) or getDate() without a zone and a test with the time 12:00, which passes in every zone and checks nothing.
  2. The guest. In lib/session.ts change the logged-in member to merchant and open /panel. For us the ranking showed only #general and #trade, and the "Messages" card dropped from 19 to 10.
  3. An empty week. The "Thread replies" card showed "no data to compare", because in the test data the previous week had no replies at all. That is right, instead of "Infinity%".
  4. Proof. Tests (33 green for us), npm run lint, npx tsc --noEmit and npm run build. All new files arrived already formatted, because the hook from lesson 7_1 is at work.

Next step

Ask for a commit, for example "Crew dashboard with tests". Then a small step with the same rhythm:

Add a period choice in the dashboard address: ?days=7 or ?days=30,
7 by default. Any other value falls back to 7. Tests first for the
function that reads the parameter. Show the test result and build.

In the editor below waits the dashboard in miniature: switch the zone from Warsaw to UTC and watch the night watch jump to the previous day, and then log in as the guest.

Remember: a navigation board is worth as much as the measurements it was made from, and a test with a time zone checks that the clock on the bridge runs the way it does in port.

Code for this lesson: App.jsx
// The crew dashboard in miniature: a day in a time zone, cards with a change and a chart made of HTML.
// In the project the functions live in lib/analytics.ts (with tests), and the /panel page computes them on the server.
import { useState } from 'react';

const REPORT_DAY = '2026-11-14'; // report day hard-coded so the example never changes

const members = [
  { id: 'u1', name: 'Captain Redbeard', role: 'owner' },
  { id: 'u2', name: 'Anne Bonny', role: 'admin' },
  { id: 'u3', name: 'Łukasz Sternik', role: 'member' },
  { id: 'u4', name: 'Jack Rackham', role: 'member' },
  { id: 'u5', name: 'Merchant from Tortuga', role: 'guest' },
];

const channels = [
  { id: 'c1', name: 'general', isPrivate: false, memberIds: ['u1', 'u2', 'u3', 'u4', 'u5'] },
  { id: 'c2', name: 'treasure-hunts', isPrivate: false, memberIds: ['u1', 'u2', 'u3', 'u4'] },
  { id: 'c4', name: 'trade', isPrivate: false, memberIds: ['u1', 'u2', 'u5'] },
  { id: 'c5', name: 'captains-secrets', isPrivate: true, memberIds: ['u1', 'u2'] },
];

// [channel, author, time in UTC]
const rows = [
  ['c1', 'u1', '2026-11-14T09:00:00.000Z'],
  ['c1', 'u2', '2026-11-14T09:05:00.000Z'],
  ['c2', 'u2', '2026-11-14T10:15:00.000Z'],
  ['c5', 'u1', '2026-11-14T12:05:00.000Z'],
  ['c1', 'u3', '2026-11-13T23:30:00.000Z'], // night watch: 00:30 in Warsaw
  ['c4', 'u5', '2026-11-13T09:20:00.000Z'],
  ['c4', 'u2', '2026-11-13T09:45:00.000Z'],
  ['c1', 'u1', '2026-11-12T08:30:00.000Z'],
  ['c2', 'u4', '2026-11-12T16:45:00.000Z'],
  ['c1', 'u2', '2026-11-11T07:55:00.000Z'],
  ['c2', 'u1', '2026-11-11T13:30:00.000Z'],
  ['c1', 'u4', '2026-11-10T18:20:00.000Z'],
  ['c1', 'u1', '2026-11-08T10:30:00.000Z'],
  ['c1', 'u1', '2026-11-06T09:15:00.000Z'],
  ['c2', 'u2', '2026-11-06T12:40:00.000Z'],
  ['c1', 'u2', '2026-11-04T08:10:00.000Z'],
  ['c5', 'u2', '2026-11-03T17:25:00.000Z'],
];
const messages = rows.map(([channelId, authorId, createdAt], i) => ({ id: 'm' + i, channelId, authorId, createdAt }));

function canSeeChannel(channel, member) {
  if (channel.isPrivate || member.role === 'guest') return channel.memberIds.includes(member.id);
  return true;
}

function dayKey(iso, timeZone) {
  const parts = new Intl.DateTimeFormat('en-GB', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date(iso));
  const part = (type) => parts.find((p) => p.type === type).value;
  return part('year') + '-' + part('month') + '-' + part('day');
}

function lastDays(endDay, count) {
  const end = Date.parse(endDay + 'T00:00:00.000Z');
  return Array.from({ length: count }, (_, i) => new Date(end - (count - 1 - i) * 86400000).toISOString().slice(0, 10));
}

function percentChange(current, previous) {
  if (previous === 0) return null;
  return Math.round(((current - previous) / previous) * 100);
}

function formatChange(change) {
  if (change === null) return 'no data to compare';
  if (change === 0) return 'no change';
  return change > 0 ? 'up ' + change + '%' : 'down ' + -change + '%';
}

function barPercent(count, max) {
  return max === 0 ? 0 : (count / max) * 100;
}

function formatDay(day) {
  return new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' }).format(new Date(day + 'T00:00:00.000Z'));
}

const tone = { up: 'text-green-700', down: 'text-red-700', none: 'text-gray-600' };

export default function App() {
  const [timeZone, setTimeZone] = useState('Europe/Warsaw');
  const [meId, setMeId] = useState('u1');

  const me = members.find((m) => m.id === meId);
  const visible = channels.filter((c) => canSeeChannel(c, me));
  const mine = messages.filter((m) => visible.some((c) => c.id === m.channelId));
  const days = lastDays(REPORT_DAY, 14);
  const inPeriod = (period) => mine.filter((m) => period.includes(dayKey(m.createdAt, timeZone)));
  const week = inPeriod(days.slice(7));
  const before = inPeriod(days.slice(0, 7));
  const authors = (list) => new Set(list.map((m) => m.authorId)).size;
  const stats = [
    { label: 'Messages', value: week.length, previous: before.length },
    { label: 'Active members', value: authors(week), previous: authors(before) },
  ];
  const data = days.slice(7).map((day) => ({ day, count: week.filter((m) => dayKey(m.createdAt, timeZone) === day).length }));
  const max = Math.max(0, ...data.map((d) => d.count));
  const peak = data.find((d) => d.count === max);
  const summary = max === 0
    ? 'Bar chart: there were no messages in this period.'
    : 'Bar chart of messages per day. Most: ' + formatDay(peak.day) + ', ' + max + '. Exact numbers in the table below the chart.';
  const watch = messages.find((m) => m.createdAt === '2026-11-13T23:30:00.000Z');

  return (
    <div className="min-h-screen bg-gray-50 p-4 text-gray-900">
      <div className="mb-4 flex flex-wrap items-center gap-3 text-sm">
        <label htmlFor="tz">Time zone for counting days:</label>
        <select id="tz" value={timeZone} onChange={(e) => setTimeZone(e.target.value)} className="rounded-md border border-gray-300 bg-white px-2 py-1">
          <option value="Europe/Warsaw">Europe/Warsaw (correct)</option>
          <option value="UTC">UTC (like createdAt.slice(0, 10))</option>
        </select>
        <label htmlFor="me">Logged in:</label>
        <select id="me" value={meId} onChange={(e) => setMeId(e.target.value)} className="rounded-md border border-gray-300 bg-white px-2 py-1">
          <option value="u1">Captain Redbeard (owner)</option>
          <option value="u5">Merchant from Tortuga (guest)</option>
        </select>
      </div>
      <p className="mb-4 text-sm text-gray-700">
        The night watch (23:30 UTC, 13 November) counts toward the day: <strong>{formatDay(dayKey(watch.createdAt, timeZone))}</strong>
      </p>

      <dl className="mb-4 grid gap-3 sm:grid-cols-2">
        {stats.map((stat) => {
          const change = percentChange(stat.value, stat.previous);
          const direction = change === null || change === 0 ? 'none' : change > 0 ? 'up' : 'down';
          return (
            <div key={stat.label} className="rounded-lg border border-gray-200 bg-white p-4">
              <dt className="text-sm text-gray-600">{stat.label}</dt>
              <dd className="text-3xl font-bold">{stat.value}</dd>
              <dd className={'text-sm ' + tone[direction]}>{formatChange(change)}</dd>
            </div>
          );
        })}
      </dl>

      <figure className="rounded-lg border border-gray-200 bg-white p-4">
        <figcaption className="font-semibold">Messages per day, 8-14 November</figcaption>
        <div role="img" aria-label={summary} className="mt-4 flex gap-2">
          {data.map((d) => (
            <div key={d.day} className="flex flex-1 flex-col items-center">
              <span className="text-xs font-semibold">{d.count}</span>
              <div className="flex h-32 w-full items-end">
                <div className="w-full rounded-t bg-blue-600" style={{ height: barPercent(d.count, max) + '%' }} />
              </div>
              <span className="mt-1 text-xs text-gray-600">{formatDay(d.day)}</span>
            </div>
          ))}
        </div>
        <details className="mt-3 text-sm">
          <summary className="cursor-pointer text-blue-700">Chart data in a table</summary>
          <table className="mt-2 w-full text-left">
            <thead>
              <tr className="border-b border-gray-200">
                <th scope="col" className="py-1">Day</th>
                <th scope="col" className="py-1">Messages</th>
              </tr>
            </thead>
            <tbody>
              {data.map((d) => (
                <tr key={d.day} className="border-b border-gray-100">
                  <td className="py-1">{formatDay(d.day)}</td>
                  <td className="py-1">{d.count}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </details>
      </figure>
      <p className="mt-3 text-xs text-gray-600">Channels on the dashboard: {visible.map((c) => '#' + c.name).join(', ')}</p>
    </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. A message has createdAt "2026-11-13T23:30:00.000Z". Which day should the Ship's Comms dashboard count it in?

  2. 2. What does percentChange(5, 0) return when the previous week had no messages at all?

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

Hands-on tasks in the game

  • Code editor

    Analytics dashboard with cards and a chart

  • Horizontal ordering

    Arrange on one line the return from barPercent that gives 0 when there were no messages in the whole period:

  1. QuestionQuiz: A day in a time zone
  2. QuestionQuiz: Change without a previous period
  3. Coding taskPractice: Analytics dashboard
  4. Put in orderSorting: Height of a bar
  5. QuestionQuiz: Direction of change in words

Useful articles