Vibe coding with Claude Code course ยท Module 12: Medium clone

The Chronicle Editor: Plan, Blocks and Autosave

10 min read
In this lesson9

Ahoy! The captain has kept a journal for years, but the pages get soaked and the entries from the voyages vanish into the sea chest. The crew wants to read his stories online, so in this location you build Captain's Chronicle, a Medium clone, a platform for long texts. You start with the editor, because a chronicle is not a note of a few sentences. It has a title, paragraphs, subheadings and quotes, and the captain writes it for hours. If the browser tab closes after an hour of writing, the text must not be lost.

What you will learn

  • order a big feature in plan mode and check the plan before any code exists;
  • read in Cursor the block types and the functions that change a list without guessing;
  • find an autosave that never saves and prove the fix with a test that uses a fake clock;
  • guard new dependencies with one line in CLAUDE.md.

A new port: the captains-chronicle project

The chronicle is a separate app, so you create it with the command from lesson 1_2, changing only the name. Compare the command with this one before you click Yes:

npx create-next-app@latest captains-chronicle --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npm

Then the familiar routine: a claude session in the captains-chronicle folder, a CLAUDE.md that imports @AGENTS.md (lesson 1_7), Vitest with the @types/node fix from lesson 4_1, and a first commit. Add one line to the conventions section of CLAUDE.md, because a text editor is a place where an agent happily reaches for a ready-made package:

- New dependencies only with my consent: ask before you add a package to package.json.

A ready-made editor from npm means hundreds of lines of someone else's code, its own storage format and updates you did not plan for. It can be a good choice, but it should be your decision, not a side effect of one request.

Request for Claude Code

An article is a list of blocks: a paragraph, a heading or a quote. Every block has an id, a type and a text. This step touches types, functions, a component, a page and a hook, which is a React function with its own state, so you start with a plan, as in lesson 1_6. In plan mode Claude reads the project and writes a plan, but does not change files until you approve it. At the end stands the finish line from lesson 10_1.

Request for Claude Code:

/plan Add an article editor to Captain's Chronicle on the /write page.
An article is a list of blocks: paragraph, heading, quote; a block has
an id, a type and a text. Types in types/article.ts, block functions
in lib/blocks.ts, the component in components/ArticleEditor.tsx.
Reading time above the title (200 words per minute). Autosave of the
draft to localStorage every 30 seconds, also while I write without
a pause. No new packages. Propose a split into files and an order of
steps, no code yet.
Done when Vitest tests show: an empty article is 0 minutes, a new block
lands after the chosen block, autosave saves after 30 seconds of
continuous writing. Then npm run lint, npx tsc --noEmit and npm run build.

In the plan check two things: where a block gets its id and what restarts the autosave timer. If the plan is silent about it, press Ctrl+G, which opens the plan in your editor, and add it, or choose "No, keep planning" and ask. When the plan fits, choose "Yes, manually approve edits": you will see every edit before it is saved.

What Claude wrote: the block types

Open types/article.ts in Cursor. The block type is one of three names, so a typo like "qoute" will not get past the compiler:

// types/article.ts
export type BlockType = "paragraph" | "heading" | "quote";

export interface ArticleBlock {
  id: string;
  type: BlockType;
  text: string;
}

Lower in the same file stands Draft, which is an id, a title and a list of blocks. A draft saved in the browser also gets the date of the save:

// types/article.ts
export interface SavedDraft extends Draft {
  savedAt: string; // "2026-11-15T09:30:00.000Z": JSON turns a Date into a string
}

savedAt is a string because, according to MDN, JSON.stringify turns a date into text in the ISO format, and JSON.parse will not turn it back into a date by itself. You know this catch from lesson 2_3: a Date type on data from localStorage lies, and TypeScript will not notice.

What Claude wrote: blocks without guessing

Open lib/blocks.ts. Every new block gets an id from the browser:

// lib/blocks.ts
export function newBlock(type: BlockType = "paragraph"): ArticleBlock {
  return { id: crypto.randomUUID(), type, text: "" };
}

crypto.randomUUID() returns a random identifier 36 characters long. The React docs recommend it for locally created data as a source of list keys. MDN adds a condition: it works only in a secure context, that is over HTTPS or on localhost. Inserting after a chosen block builds a new array out of three pieces:

// lib/blocks.ts
export function addBlockAfter(blocks: ArticleBlock[], afterId: string, block: ArticleBlock): ArticleBlock[] {
  const index = blocks.findIndex((b) => b.id === afterId);
  if (index === -1) return [...blocks, block];
  return [...blocks.slice(0, index + 1), block, ...blocks.slice(index + 1)];
}

slice copies the part of the list before the insertion point and the part after it, so the old array stays untouched and React gets a new one. When there is no block with that id, the new one goes to the end instead of vanishing. Reading time counts the words of all blocks:

// lib/blocks.ts
export function readingTime(blocks: ArticleBlock[]): number {
  const words = blocks.flatMap((b) => b.text.split(/\s+/)).filter(Boolean).length;
  return Math.ceil(words / WORDS_PER_MINUTE);
}

split(/\s+/) cuts the text at spaces and line ends, and filter(Boolean) throws out the empty pieces. Without that filter an empty block counts as one word, because "".split(" ") gives an array with one empty string, and a new article shows "1 min read". Math.ceil rounds up, so 201 words is 2 minutes.

What Claude wrote: the editor

components/ArticleEditor.tsx holds state, so it starts with the directive from lesson 2_3:

// components/ArticleEditor.tsx
"use client";

import { useState } from "react";

The React docs say that 'use client' must stand at the very top of the file, above the imports; only comments may come before it. Changing the text of one block looks like this:

// components/ArticleEditor.tsx
function updateText(id: string, text: string) {
  setBlocks((prev) => prev.map((b) => (b.id === id ? { ...b, text } : b)));
}

prev => ... is an updater function: it receives the freshest list of blocks, not the one remembered at the last render. The React docs show the difference on a counter: three calls of setAge(age + 1) in one function give 43, not 45, because every call sees the same old state. The text field of a block has these classes:

// components/ArticleEditor.tsx
className={`w-full resize-none rounded outline-hidden focus:bg-amber-50 ${BLOCK_STYLES[block.type]}`}

outline-hidden is the successor of the old outline-none in Tailwind 4: it hides the focus outline but keeps it in the system's forced colors mode. The Tailwind docs then recommend a custom focus style, hence focus:bg-amber-50. In version 4 outline-none sets outline-style: none and takes the outline away from everyone.

An autosave that never saves

The first autosave from the agent looks innocent. Open hooks/useAutosave.ts:

// hooks/useAutosave.ts (the agent's version)
useEffect(() => {
  const id = setTimeout(() => {
    setSavedAt(saveDraft(draft).savedAt);
  }, AUTOSAVE_MS);
  return () => clearTimeout(id);
}, [draft]);

Every key changes draft, so React cleans up the old timer and sets a new one for a full 30 seconds. That is the debounce from lesson 3_5: good for a search box that waits for silence, and bad for an autosave, because during continuous writing the silence never comes. In our run this version passed lint and tsc. Only a test with a fake clock caught it, in which the function draft(text) builds a draft with one block:

// hooks/useAutosave.test.ts
test("saves after 30 s although the captain writes without a pause", () => {
  const { rerender } = renderHook(({ d }) => useAutosave(d), { initialProps: { d: draft("A") } });
  let text = "A";
  for (let second = 1; second <= 31; second++) {
    text += "h";
    rerender({ d: draft(text) });
    act(() => vi.advanceTimersByTime(1000));
  }
  expect(loadDrafts()).toHaveLength(1);
  expect(loadDrafts()[0].blocks[0].text).toBe("A" + "h".repeat(30));
});

vi.useFakeTimers() in beforeEach replaces the clocks, and according to the Vitest docs vi.advanceTimersByTime(1000) runs every timer whose time has come within the given milliseconds. The loop is 31 seconds of writing, one letter per second. The agent's version failed with the message expected [] to have a length of 1 but got +0. The tempting "fix", a setInterval with an empty dependency array, failed the second line with a message starting with expected 'A' to be 'Ahhh: the timer remembered the draft from the first render, and lint gave only the warning react-hooks/exhaustive-deps. This version passed:

// hooks/useAutosave.ts
const saveIfChanged = useEffectEvent(() => {
  const json = JSON.stringify(draft);
  if (json === lastSaved.current) return;
  lastSaved.current = json;
  setSavedAt(saveDraft(draft).savedAt);
});

useEffect(() => {
  const id = setInterval(() => saveIfChanged(), AUTOSAVE_MS);
  return () => clearInterval(id);
}, []);

useEffectEvent is a React hook for logic that must see the latest props and state but must not restart the effect. The docs show it with setInterval in particular. The timer starts once, and every 30 seconds it saves the current draft if it changed since the last save; lastSaved is a useRef with the text of the previous save. localStorage appears only in this timer, never during rendering, because it does not exist when rendering on the server.

Captain's review

  1. Identifiers. Search the project (Cmd+Shift+F) for Date.now. The agent likes id: Date.now().toString(): in our run five calls in one loop gave the same number five times. Two blocks with one id are changed at once by updateText.
  2. Functional updates. Every setBlocks( in the editor has prev => inside.
  3. An empty chronicle. A new article shows "0 min read", not "1 min".
  4. The directive. When Claude puts "use client" below the imports, the build fails with the error The "use client" directive must be placed before other expressions.
  5. Dependencies. In the Source Control panel open package.json. An editor package added without asking breaks the rule from CLAUDE.md: ask Claude why it needs it, or undo it with /rewind from lesson 0_6.

You collect the last proof in the browser: npm run dev, the /write page, write without a pause, and after half a minute "saved at" with a time appears under the title. That is what happened for us, and localStorage held a draft with savedAt as a string.

Next step

When the tests and the browser agree, ask for a commit "Block editor with autosave". Then a small request, again with a plan: "Enter at the end of a block creates a new paragraph below it. Plan first." A list of saved drafts that reads localStorage with the pattern from lesson 2_3 waits in the practice task. The editor below is a miniature editor with a fake clock: write without a pause and switch the agent's version on, and you will see its countdown keep jumping back to 30.

Remember: a captain does not drive in planks without a ship's plan, and the logbook must be saved in the middle of the storm, not only once the wind drops.

Code for this lesson: App.jsx
// Chronicle editor in miniature: blocks, reading time and autosave with a fake clock
import { useEffect, useReducer } from 'react';

const AUTOSAVE_S = 30;
const WORDS_PER_MINUTE = 200;
const LABELS = { paragraph: 'Paragraph', heading: 'Heading', quote: 'Quote' };
const STYLES = {
  paragraph: 'text-base',
  heading: 'text-xl font-bold',
  quote: 'border-l-4 border-gray-300 pl-3 italic',
};

let nextId = 1;
function newBlock(type = 'paragraph') {
  return { id: 'b' + nextId++, type, text: '' };
}

function addBlockAfter(blocks, afterId, block) {
  const index = blocks.findIndex((b) => b.id === afterId);
  if (index === -1) return [...blocks, block];
  return [...blocks.slice(0, index + 1), block, ...blocks.slice(index + 1)];
}

function countWords(blocks) {
  return blocks.flatMap((b) => b.text.split(/\s+/)).filter(Boolean).length;
}

function readingTime(blocks) {
  return Math.ceil(countWords(blocks) / WORDS_PER_MINUTE);
}

function formatClock(s) {
  return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
}

const initialState = {
  title: '',
  blocks: [newBlock()],
  now: 0, // seconds of the fake clock
  lastChange: null, // second of the last text change
  savedJson: null,
  saves: [],
  agentBug: false,
  typing: false,
};

function snapshot(state) {
  return JSON.stringify({ title: state.title, blocks: state.blocks });
}

function changeText(state, blocks, title) {
  return { ...state, blocks, title, lastChange: state.now };
}

// The reducer always sees the latest state, so the clock never remembers an old draft
function reducer(state, action) {
  switch (action.type) {
    case 'title':
      return changeText(state, state.blocks, action.value);
    case 'text':
      return changeText(state, state.blocks.map((b) => (b.id === action.id ? { ...b, text: action.value } : b)), state.title);
    case 'type':
      return changeText(state, state.blocks.map((b) => (b.id === action.id ? { ...b, type: action.value } : b)), state.title);
    case 'add':
      return changeText(state, addBlockAfter(state.blocks, action.id, newBlock()), state.title);
    case 'agentBug':
      return { ...state, agentBug: action.value };
    case 'typing':
      return { ...state, typing: action.value };
    case 'tick': {
      let next = { ...state, now: state.now + 1 };
      if (state.typing) {
        const last = next.blocks[next.blocks.length - 1];
        next = changeText(next, next.blocks.map((b) => (b.id === last.id ? { ...b, text: b.text + (b.text ? ' ' : '') + 'wave' } : b)), next.title);
      }
      const changed = next.lastChange !== null && snapshot(next) !== next.savedJson;
      // The agent's version: the clock counts from the last key (debounce). The fix: every 30 s from the start.
      const due = next.agentBug ? next.now - next.lastChange >= AUTOSAVE_S : next.now % AUTOSAVE_S === 0;
      if (changed && due) {
        return {
          ...next,
          savedJson: snapshot(next),
          saves: [{ at: next.now, words: countWords(next.blocks) }, ...next.saves].slice(0, 4),
        };
      }
      return next;
    }
    default:
      return state;
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const [fast, setFast] = useReducer((v) => !v, false);

  useEffect(() => {
    const id = setInterval(() => dispatch({ type: 'tick' }), fast ? 200 : 1000);
    return () => clearInterval(id);
  }, [fast]);

  const minutes = readingTime(state.blocks);
  const secondsLeft = state.agentBug
    ? state.lastChange === null
      ? AUTOSAVE_S
      : AUTOSAVE_S - (state.now - state.lastChange)
    : AUTOSAVE_S - (state.now % AUTOSAVE_S);

  return (
    <div className="min-h-screen bg-gray-50 p-4 text-gray-900">
      <div className="mx-auto max-w-xl space-y-3 rounded-xl bg-white p-4 shadow-sm">
        <p className="text-sm text-gray-500">{minutes} min read ยท {countWords(state.blocks)} words</p>
        <input
          aria-label="Title"
          value={state.title}
          onChange={(e) => dispatch({ type: 'title', value: e.target.value })}
          placeholder="Chronicle title"
          className="w-full rounded text-2xl font-bold outline-hidden focus:bg-amber-50"
        />
        {state.blocks.map((block) => (
          <div key={block.id} className="space-y-1">
            <div className="flex gap-2 text-sm">
              <select
                aria-label="Block type"
                value={block.type}
                onChange={(e) => dispatch({ type: 'type', id: block.id, value: e.target.value })}
                className="rounded border border-gray-300 px-1"
              >
                {Object.entries(LABELS).map(([type, label]) => (
                  <option key={type} value={type}>{label}</option>
                ))}
              </select>
              <button type="button" onClick={() => dispatch({ type: 'add', id: block.id })} className="text-gray-600">
                + block
              </button>
            </div>
            <textarea
              aria-label={LABELS[block.type]}
              value={block.text}
              onChange={(e) => dispatch({ type: 'text', id: block.id, value: e.target.value })}
              rows={block.type === 'heading' ? 1 : 2}
              placeholder="Write here..."
              className={'w-full resize-none rounded outline-hidden focus:bg-amber-50 ' + STYLES[block.type]}
            />
          </div>
        ))}
      </div>

      <div className="mx-auto mt-3 max-w-xl space-y-2 rounded-xl bg-gray-900 p-4 text-sm text-white">
        <p>Fake clock: <strong>{formatClock(state.now)}</strong></p>
        <p>
          Next save in: <strong>{secondsLeft} s</strong>{' '}
          ({state.agentBug ? "agent's version: counts from the last key" : 'the fix: every 30 s from the start'})
        </p>
        <p>
          Last save:{' '}
          {state.saves.length ? formatClock(state.saves[0].at) + ' (' + state.saves[0].words + ' words)' : 'nothing saved yet'}
        </p>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={state.typing} onChange={(e) => dispatch({ type: 'typing', value: e.target.checked })} />
          The captain writes without a pause (a word every second)
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={state.agentBug} onChange={(e) => dispatch({ type: 'agentBug', value: e.target.checked })} />
          Agent's bug: setTimeout with [draft] in the dependencies
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={fast} onChange={setFast} />
          Fast clock (5 times faster)
        </label>
      </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. Why does newBlock in the chronicle editor give a block an id from crypto.randomUUID() and not from Date.now().toString()?

  2. 2. Why does the SavedDraft type give the savedAt field the type string and not Date?

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

Hands-on tasks in the game

  • Click in order

    Click the elements to build the word count of one block, in which an empty block gives 0 words:

  • Horizontal ordering

    Put in order, in one line, a change of a block's text through an updater function:

  • Vertical ordering

    Put the work on the chronicle editor in plan mode in order:

  • Code editor

    Rich text editor component

  • Click in order

    Click the elements to build the return of an array with a new block inserted after the block with the number index:

  • Horizontal ordering

    Put in order, in one line, the start of a timer that calls the save of the current draft every 30 seconds:

  • Code editor

    Draft system interface

  • Vertical ordering

    The agent's version has a setTimeout in a useEffect with the dependency [draft]. Put in order what happens when the captain writes without a pause:

  1. QuestionBlock identifiers
  2. QuestionThe save date of a draft as a string
  3. Click in orderWords without empty pieces
  4. Put in orderChanging the text of one block
  5. Put in orderThe editor through plan mode
  6. Coding taskPractice: Article editor
  7. QuestionReading time of an empty chronicle
  8. QuestionA new package in the diff
  9. Click in orderInserting after a chosen block
  10. Put in orderThe autosave timer
  11. Coding taskPractice: Draft management
  12. QuestionWhere the use client directive goes
  13. Put in orderWhy the agent's autosave stays silent
  14. QuestionThe autosave that passed the test

Useful articles