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

The Ship's Logbook: Messages, Reactions and Threads

9 min read
In this lesson10

A channel without messages is an empty cabin. In Slack a conversation is more than text: under a message people leave reactions instead of writing "agreed", the author fixes a typo, and a longer discussion moves to a thread, a separate panel with replies under one message. This keeps the channel readable, and whoever wants the details opens the panel on the side.

The problem: who may change an entry in the log

Only the author may edit and delete a message. The browser will hide the buttons on other people's messages, but the Next.js documentation warns that Server Actions can be called by a direct POST request, bypassing the interface. So the decision belongs to the server. The second trap is numbers: it is easy to store the reaction counter and the reply counter next to the data and then forget to update them.

Request for Claude Code:

/plan Add messages to Ship's Comms. A Message type in types/chat.ts:
author, text, ISO date, editedAt, parentId for thread replies
and reactions (a short name like "+1" plus a list of members). Do not
store counters, compute them from the data. Data in data/messages.json
through lib/store.ts. First tests of the pure function toggleReaction
in lib/reactions.ts: a new reaction, a second member, removing your
own, an empty reaction disappears, input unchanged. Then Server
Actions: send, react, edit and delete; the author always comes from
getCurrentMember(), editing and deleting only your own. Components: a
message list, MessageItem with actions on hover (also reachable from
the keyboard and on touch), MessageInput (Enter sends, Shift+Enter
breaks the line) and a thread panel at the address ?thread=<id>. At
the end tests, lint, types and build.

You do not say a word about formatting: the hook from the previous lesson will tidy every file Claude changes.

What Claude wrote: the message in types

Open types/chat.ts in Cursor. Two types were added below the channel model:

export interface Reaction {
  name: string; // a short name as in Slack: "+1", "eyes", "tada"
  memberIds: string[];
}

export interface Message {
  id: string;
  channelId: string;
  authorId: string;
  text: string;
  createdAt: string; // ISO text
  editedAt?: string;
  parentId?: string; // a thread reply: the id of the message it hangs under
  reactions: Reaction[];
}

A message points to its channel and author by identifiers. A thread reply is an ordinary message with a parentId field, so the thread panel is simply a filter of the list. There are no count and replyCount fields: the number of reactions comes from memberIds.length, and the number of replies from counting messages with a given parentId. A number you do not store cannot drift away from the data. Reactions are short names in colons, :+1:, the kind you type in Slack; images can be added later as a layer of looks.

Where messages live and how time is counted

Messages go to the file data/messages.json through lib/store.ts, like the profiles in Crew Connections. The file begins with import "server-only", so an accidental import in a browser component ends the build with a readable error, and Claude added the data directory to .gitignore. The list in components/MessageList.tsx shows only messages without a parentId, and for each one counts the replies by filtering the whole channel list. An empty channel gets the sentence "It's quiet on this channel so far" instead of a white blank. The message time is formatted by lib/format.ts:

const timeFormat = new Intl.DateTimeFormat("en-GB", {
  day: "numeric",
  month: "short",
  hour: "2-digit",
  minute: "2-digit",
  timeZone: "Europe/Warsaw",
});

From an ISO text this produces a string such as "14 Nov, 09:00". The time zone is given explicitly, because a server on a host often counts time in a different zone than your computer. The formatting happens on the server, and the browser component receives a ready string, so the time does not depend on where the code happens to run. The edit date lands in editedAt, and next to such a message stands the note "(edited)".

Test first: the reaction toggle

Open lib/reactions.test.ts. The names of the cases are the fastest way to judge whether Claude understood the rules:

it("a second click removes your own reaction and drops an empty one from the list", () => {
  const before: Reaction[] = [{ name: "+1", memberIds: ["u1"] }];
  expect(toggleReaction(before, "+1", "u1")).toEqual([]);
});

Next to it stand three more cases: a new reaction, a second crew member and "does not change the input array". The last one makes sure the function returns a new list instead of rearranging the old one, because React notices a change by a new object. The function itself in lib/reactions.ts:

export function toggleReaction(
  reactions: Reaction[],
  name: string,
  memberId: string,
): Reaction[] {
  const current = reactions.find((reaction) => reaction.name === name);
  if (!current) {
    return [...reactions, { name, memberIds: [memberId] }];
  }
  const memberIds = current.memberIds.includes(memberId)
    ? current.memberIds.filter((id) => id !== memberId)
    : [...current.memberIds, memberId];
  return reactions
    .map((reaction) => (reaction === current ? { name, memberIds } : reaction))
    .filter((reaction) => reaction.memberIds.length > 0);
}

A new reaction starts with one member, and clicking an existing one adds you or takes you off the list. The last filter removes a reaction nobody is left on, so :+1: 0 never hangs under a message.

The server guards the author

Open app/c/[channel]/actions.ts. Every action starts from the logged-in crew member, never from a form field:

export async function deleteMessage(messageId: string) {
  const me = await getCurrentMember();
  const messages = await readMessages();
  const message = messages.find((m) => m.id === messageId);
  if (!message) return;
  if (message.authorId !== me.id) {
    throw new Error("You can only delete your own message.");
  }
  await writeMessages(
    messages.filter((m) => m.id !== messageId && m.parentId !== messageId),
  );
  revalidatePath("/c/[channel]", "page");
}

editMessage has the same check, and reactToMessage rejects a name outside the REACTIONS list, so a reaction with an empty name cannot appear. Deleting a message also takes the replies of its thread. revalidatePath gets a route pattern and the type "page", because the Next.js documentation requires the type when the path has a dynamic segment; this is how all channel pages refresh.

Actions on hover, from the keyboard and on touch

Open components/MessageItem.tsx. A message has a header with the author and time on top, then the content, the reactions and a link with the number of replies. In the top right corner lies an action bar (three reactions, Reply, and on your own message Edit and Delete). It is always in the page code, and the classes decide whether you see it:

<div className="absolute right-4 top-1 flex gap-1 rounded-md border border-gray-200 bg-white p-1 text-xs opacity-0 shadow-sm group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100">

group-hover shows the bar when the cursor is over the message, and group-focus-within when a button inside gets focus with the Tab key. pointer-coarse is a Tailwind variant for an imprecise pointer, that is a finger on a touch screen: there the bar is always visible, because hover: in Tailwind 4 works only on devices with a cursor. The old version with an onMouseEnter event did not show the actions on a phone at all. Edit mode keeps an editing state in the component, and saving calls editMessage. A reaction you have already given has aria-pressed="true": a screen reader says the button is pressed, and the classes aria-pressed:border-blue-600 and aria-pressed:bg-blue-50 highlight it in blue.

The message field: Enter and Shift+Enter

Open components/MessageInput.tsx. The form sends the text through a Server Action, and the keyboard shortcut is handled by a small function:

function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
  if (
    event.key === "Enter" &&
    !event.shiftKey &&
    !event.nativeEvent.isComposing
  ) {
    event.preventDefault();
    event.currentTarget.form?.requestSubmit();
  }
}

Enter alone blocks the new line and submits the form through requestSubmit(), that is, as if someone clicked "Send". Shift+Enter does not meet the condition, so the field gets a new line. isComposing protects people who type with an input method in which Enter confirms a character, not a message. After sending, the field clears, and on an error, for example text made only of spaces, it keeps its content with a message underneath. Above the field stands a <label> with the sr-only class, because a placeholder alone vanishes after the first letter and does not replace a description for a screen reader.

A thread at an address

The "Reply" link leads to an address such as /c/general?thread=m1. The channel page reads searchParams, finds the parent message and passes its replies to components/ThreadPanel.tsx. At the bottom of the panel stands the same field as in the channel:

<MessageInput
  key={parent.id}
  channelId={channel.id}
  parentId={parent.id}
  placeholder="Reply in the thread"
/>

A thread in the address can be sent to someone from the crew or opened in a new tab, and "Close" is an ordinary link to the channel. key={parent.id} matters: moving to another thread changes only the address parameter, so React leaves the components in place together with their state. We checked it: without the key a reply draft from one thread stayed in the field after opening another. The name of a reply's author is taken by the panel from authorName(reply.authorId), because a message knows only the author's identifier.

Captain's review

  1. Someone else's message. We asked Claude for a test: it sent the delete form with the identifier of a message by Anne. The server answered with an error, the server terminal showed "You can only delete your own message.", and the message stayed. A typical agent mistake: a check only in JSX (isOwn && <button>), while the action deletes whatever anyone asks.
  2. Counters. Look in the diff for count or replyCount fields. If Claude added them, ask for counting from the data.
  3. Keyboard. Tab through a message: the action bar must appear, and Enter on "Delete" must work like a click.
  4. Proof. Tests, lint, types and build. At the end npx prettier --check . reports "All matched files use Prettier code style!", although the request never mentioned formatting. That is the hook's work.

Next step

When the review passes, ask for a commit, for example "Messages, reactions and threads". Then a small step with a test:

Add a case to lib/reactions.test.ts: the same member reacts with
:+1: and :eyes:, both reactions stay. Show the test result. Then add
a confirmation before deleting a message.

The editor below holds a channel in miniature: reactions with the same toggle, editing only your own messages, and a thread. Try Enter and Shift+Enter, then try to delete someone else's message.

Remember: only the one who made an entry in the ship's logbook corrects it, and the harbour master guards that, which is the server, not the logbook itself.

Code for this lesson: App.jsx
// Channel #general in miniature: reactions, editing, deleting and a thread.
// In the project the rules are enforced by Server Actions in app/c/[channel]/actions.ts;
// here the same set of rules is checked by the "server" functions below.
import { useState } from 'react';

const ME = 'u1';
const REACTIONS = ['+1', 'eyes', 'tada'];
const names = { u1: 'Captain Redbeard', u2: 'Anne Bonny', u3: 'Łukasz Sternik' };

const initialMessages = [
  { id: 'm1', authorId: 'u1', text: 'Ahoy, crew! We weigh anchor at dawn tomorrow.', time: '09:00', reactions: [{ name: '+1', memberIds: ['u2', 'u3'] }] },
  { id: 'm2', authorId: 'u2', text: 'The water barrels are already on deck.', time: '09:05', reactions: [] },
  { id: 'm3', authorId: 'u3', text: 'I will check the ropes before we sail.', time: '09:10', parentId: 'm1', reactions: [] },
];

// The same pure function as in lib/reactions.ts.
function toggleReaction(reactions, name, memberId) {
  const current = reactions.find((reaction) => reaction.name === name);
  if (!current) return [...reactions, { name, memberIds: [memberId] }];
  const memberIds = current.memberIds.includes(memberId)
    ? current.memberIds.filter((id) => id !== memberId)
    : [...current.memberIds, memberId];
  return reactions
    .map((reaction) => (reaction === current ? { name, memberIds } : reaction))
    .filter((reaction) => reaction.memberIds.length > 0);
}

// "Server": the author always comes from the session (ME), never from the form.
function serverEdit(messages, id, text) {
  const message = messages.find((m) => m.id === id);
  if (!message) return { messages, error: '' };
  if (message.authorId !== ME) return { messages, error: 'You can only edit your own message.' };
  const clean = text.trim();
  if (!clean) return { messages, error: 'The message cannot be empty.' };
  return { messages: messages.map((m) => (m.id === id ? { ...m, text: clean, edited: true } : m)), error: '' };
}

function serverDelete(messages, id) {
  const message = messages.find((m) => m.id === id);
  if (!message) return { messages, error: '' };
  if (message.authorId !== ME) return { messages, error: 'You can only delete your own message.' };
  return { messages: messages.filter((m) => m.id !== id && m.parentId !== id), error: '' };
}

function MessageInput({ id, placeholder, onSend }) {
  const [text, setText] = useState('');
  const [error, setError] = useState('');

  function send() {
    if (!text.trim()) {
      setError('Write something before sending.');
      return;
    }
    onSend(text.trim());
    setText('');
    setError('');
  }

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        send();
      }}
      className="border-t border-gray-200 p-2"
    >
      <label className="sr-only" htmlFor={id}>Message</label>
      <textarea
        id={id}
        rows={2}
        value={text}
        placeholder={placeholder}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
            e.preventDefault();
            send();
          }
        }}
        className="w-full resize-none rounded-md border border-gray-300 p-2 text-sm"
      />
      <div className="flex items-center justify-between">
        <p className="text-xs text-gray-500">Enter sends, Shift+Enter breaks the line</p>
        <button className="rounded-md bg-green-700 px-3 py-1 text-sm font-semibold text-white">Send</button>
      </div>
      {error && <p role="alert" className="text-sm text-red-700">{error}</p>}
    </form>
  );
}

function MessageItem({ message, replyCount, onReact, onEdit, onDelete, onOpenThread }) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(message.text);
  const isOwn = message.authorId === ME;

  return (
    <article className="group relative px-3 py-2 hover:bg-gray-50 focus-within:bg-gray-50">
      <p className="text-sm">
        <span className="font-bold">{names[message.authorId]}</span>{' '}
        <span className="text-xs text-gray-500">{message.time}</span>
        {message.edited && <span className="text-xs text-gray-500"> (edited)</span>}
      </p>
      {editing ? (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            onEdit(message.id, draft);
            setEditing(false);
          }}
          className="space-y-1"
        >
          <textarea value={draft} onChange={(e) => setDraft(e.target.value)} aria-label="Message text" className="w-full rounded-md border border-gray-300 p-1 text-sm" />
          <button className="rounded-md bg-green-700 px-2 py-0.5 text-xs text-white">Save</button>
        </form>
      ) : (
        <p className="whitespace-pre-wrap text-sm">{message.text}</p>
      )}
      {message.reactions.length > 0 && (
        <div className="mt-1 flex gap-1">
          {message.reactions.map((reaction) => (
            <button
              key={reaction.name}
              onClick={() => onReact(message.id, reaction.name)}
              aria-pressed={reaction.memberIds.includes(ME)}
              className="rounded-full border border-gray-300 px-2 text-xs aria-pressed:border-blue-600 aria-pressed:bg-blue-50"
            >
              :{reaction.name}: {reaction.memberIds.length}
            </button>
          ))}
        </div>
      )}
      {onOpenThread && replyCount > 0 && (
        <button onClick={() => onOpenThread(message.id)} className="text-xs font-semibold text-blue-700 hover:underline">
          Replies: {replyCount}
        </button>
      )}
      <div className="absolute right-2 top-1 flex gap-1 rounded-md border border-gray-200 bg-white p-0.5 text-xs opacity-0 shadow-sm group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100">
        {REACTIONS.map((name) => (
          <button key={name} onClick={() => onReact(message.id, name)} className="rounded px-1 hover:bg-gray-100">:{name}:</button>
        ))}
        {onOpenThread && <button onClick={() => onOpenThread(message.id)} className="rounded px-1 hover:bg-gray-100">Reply</button>}
        {isOwn && !editing && (
          <>
            <button onClick={() => setEditing(true)} className="rounded px-1 hover:bg-gray-100">Edit</button>
            <button onClick={() => onDelete(message.id)} className="rounded px-1 text-red-700 hover:bg-red-50">Delete</button>
          </>
        )}
      </div>
    </article>
  );
}

export default function App() {
  const [messages, setMessages] = useState(initialMessages);
  const [threadId, setThreadId] = useState(null);
  const [serverError, setServerError] = useState('');
  const topLevel = messages.filter((m) => !m.parentId);
  const parent = topLevel.find((m) => m.id === threadId);

  function react(id, name) {
    setMessages(messages.map((m) => (m.id === id ? { ...m, reactions: toggleReaction(m.reactions, name, ME) } : m)));
  }

  function apply(result) {
    setMessages(result.messages);
    setServerError(result.error);
  }

  function send(text, parentId) {
    const id = 'm' + Date.now();
    setMessages([...messages, { id, authorId: ME, text, time: 'now', parentId, reactions: [] }]);
  }

  const itemProps = {
    onReact: react,
    onEdit: (id, text) => apply(serverEdit(messages, id, text)),
    onDelete: (id) => apply(serverDelete(messages, id)),
  };

  return (
    <div className="min-h-screen bg-gray-100 p-3 text-gray-900">
      <div className="mb-2 flex flex-wrap items-center gap-2 text-sm">
        <span>You are: {names[ME]}</span>
        <button onClick={() => apply(serverDelete(messages, 'm2'))} className="rounded-md border border-red-600 px-2 py-0.5 text-red-700">
          Send a request to delete Anne's message, bypassing the button
        </button>
      </div>
      {serverError && <p role="alert" className="mb-2 rounded-md bg-red-50 p-2 text-sm text-red-800">Server: {serverError}</p>}
      <div className="flex overflow-hidden rounded-lg border border-gray-200 bg-white">
        <section className="flex min-w-0 flex-1 flex-col">
          <h1 className="border-b border-gray-200 px-3 py-2 font-bold"># general</h1>
          <div className="flex-1">
            {topLevel.map((m) => (
              <MessageItem key={m.id} message={m} replyCount={messages.filter((r) => r.parentId === m.id).length} onOpenThread={setThreadId} {...itemProps} />
            ))}
          </div>
          <MessageInput id="message" placeholder="Write in #general" onSend={(text) => send(text)} />
        </section>
        {parent && (
          <aside aria-label="Thread" className="flex w-64 shrink-0 flex-col border-l border-gray-200">
            <div className="flex items-center justify-between border-b border-gray-200 px-3 py-2">
              <h2 className="font-bold">Thread</h2>
              <button onClick={() => setThreadId(null)} className="text-sm hover:underline">Close</button>
            </div>
            <div className="flex-1">
              <MessageItem message={parent} replyCount={0} {...itemProps} />
              {messages.filter((r) => r.parentId === parent.id).map((r) => (
                <MessageItem key={r.id} message={r} replyCount={0} {...itemProps} />
              ))}
            </div>
            <MessageInput key={parent.id} id="reply" placeholder="Reply in the thread" onSend={(text) => send(text, parent.id)} />
          </aside>
        )}
      </div>
    </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. Which fields does the Message type have in Ship's Comms?

  2. 2. What is the editedAt field in Message for?

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

Hands-on tasks in the game

  • Horizontal ordering

    Arrange on one line the address under which the thread of message m1 in the general channel opens:

  • Code editor

    Chat message component

  • Vertical ordering

    Order the sending of a message in MessageInput:

  • Code editor

    Chat message input

  • Vertical ordering

    Arrange the elements of a message in MessageItem from top to bottom:

  • Horizontal ordering

    Arrange on one line the call that refreshes all channel pages after a change:

  • Vertical ordering

    Order the steps of editing your own message:

  • Horizontal ordering

    Arrange the buttons of the action bar of your own message (one row, from the left):

  1. QuestionQuiz: Fields of the Message type
  2. QuestionQuiz: The editedAt field
  3. Put in orderSorting: Thread address
  4. Coding taskPractice: Message item
  5. QuestionQuiz: Reactions under a message
  6. QuestionQuiz: The action bar without a mouse
  7. Put in orderSorting: Sending a message
  8. Coding taskPractice: Message input
  9. QuestionQuiz: Enter and Shift+Enter
  10. QuestionQuiz: isComposing in the message field
  11. Put in orderSorting: Message layout
  12. QuestionQuiz: Number of replies
  13. Put in orderSorting: Refreshing channel pages
  14. Put in orderSorting: Editing a message
  15. QuestionQuiz: The key of the thread field
  16. Put in orderSorting: Message action bar

Useful articles