DEV Community

Daniel Pertu
Daniel Pertu

Posted on

Two code paths build the same 50 strings, so I replaced navigator.clipboard to find out whether they agree

Content pages on Nakodo are arrays of typed blocks, and one of those block types is a copyable template: a label, an optional subject line and a body. I have written about the 50 of them as rows in an array, with the unit test that proofreads them. To be clear about what they are, these are templates we publish for readers to copy and send themselves. What the product sends on a customer's behalf is a different system that stays out of these posts.

That post ended with a loose thread. The same block is rendered three times by three different pieces of code:

// src/components/content/blocks.tsx
case "template": {
  const copy = block.subject ? `Subject: ${block.subject}\n\n${block.body}` : block.body;
  return (
    <figure className="rounded-lg border bg-card">
      <figcaption ...><span className="font-semibold">{block.label}</span><CopyButton text={copy} /></figcaption>
      <div className="space-y-3 px-5 py-4 text-[15px] leading-7">
        {block.subject && <p><span className="text-muted-foreground">Subject: </span>{block.subject}</p>}
        <p className="whitespace-pre-line">{block.body}</p>
      </div>
    </figure>
  );
}
Enter fullscreen mode Exit fullscreen mode
// src/content/markdown.ts
case "template":
  return `**${b.label}**\n\n\`\`\`\n${b.subject ? `Subject: ${b.subject}\n\n` : ""}${b.body}\n\`\`\``;
Enter fullscreen mode Exit fullscreen mode

Three renderings. The paragraphs you read on the page, the string the Copy button puts on your clipboard, and the fenced block inside llms-full.txt. Subject: plus the subject plus a blank line is written out twice, in two files, by hand, and nothing in the test suite compares them. So I compared them from the outside, on the live site.

Replacing the clipboard instead of reading it

The obvious approach is to click Copy and read the clipboard back. That needs a permission grant, needs the document focused, and tells you nothing about which button produced which string if anything goes wrong. The cheaper approach is to replace the API before clicking:

window.__caught = [];
Object.defineProperty(navigator, "clipboard", {
  value: { ...navigator.clipboard, writeText: (t) => { window.__caught.push(t); return Promise.resolve(); } },
  configurable: true,
});
Enter fullscreen mode Exit fullscreen mode

Then click every button whose text is exactly Copy, and read window.__caught in order. No permissions, no focus rules, and the strings arrive in document order so each one can be matched to the figure above it.

Our copy helper is a one liner around that API, which is why the swap is enough:

export async function copyText(text: string, done?: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    if (done) notify({ message: done });
    return true;
  } catch {
    notify({ error: "Couldn't copy. Select the text and copy it yourself." });
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

What came back

pages with template blocks          16
Copy buttons found                  50
clipboard strings captured          50
total characters on the clipboard   30,903
total lines                            770
longest block                           46 lines
shortest                                 1 line

visible block text == clipboard string          50 of 50
clipboard string == llms-full.txt fenced block  50 of 50
Enter fullscreen mode Exit fullscreen mode

No drift. Three renderings of 30,903 characters, built by two hand-written concatenations and one CSS box, and they agree on every byte.

The llms-full comparison is the easy half: both strings come from the same two fields, and a === against the 50 fenced blocks in an 865 KB text file found all 50 verbatim.

The page comparison is the interesting half, because the page is not a string at all.

Why the page agreeing is not trivial

To compare the rendered block with the copied string I took the figure's innerText, stripped the caption label and the word Copy, and compared what was left. Three separate things have to line up for that to match.

The blank line. In the string it is a literal \n\n between the subject and the body. On the page it is two sibling paragraphs, and innerText inserts a blank line between block level boxes. Those two mechanisms have nothing to do with each other, and they produce the same two newlines.

The label. <span className="text-muted-foreground">Subject: </span> carries a trailing space inside the span, and the copied string has the space in the template literal. Move that space outside the JSX span and the rendered text keeps it anyway, because HTML collapses it against the following text node. Move it the other way and the string loses it. Only one of those two systems cares where you put it.

The body. whitespace-pre-line keeps newlines and collapses runs of spaces and tabs. That is the one place this comparison could have failed silently: a template body with two spaces after a full stop, or a trailing space before a newline, would render as one space but copy as two, and nobody would ever notice by looking. So I counted, across all 50 captured strings:

tabs                              0
carriage returns                  0
runs of two or more spaces        0
lines with trailing whitespace    0
runs of three or more newlines    0
Enter fullscreen mode Exit fullscreen mode

30,903 characters of hand-written template, and not one of them has whitespace that pre-line would have eaten. That is the proofreading test doing its job, but no assertion actually says so, which is the second loose thread from the earlier post now measured instead of assumed.

The split that falls out for free

41 of the 50 blocks carry a subject and 9 do not, and the 9 are exactly the blocks that are not emails. Their captions say so:

The note to put in the parcel
Campaign brief
Creator brief
Creator agreement outline
Direct message on Instagram or X, when there's no email
Short DM asking for the best contact
Creator brief
Plain-words clause for paid usage (a starting point, not legal advice)
DM asking where to send a proposal
Enter fullscreen mode Exit fullscreen mode

41 <span>Subject: </span> labels on the page, 41 clipboard strings beginning Subject:, 41 fenced blocks beginning Subject:. The optional field is optional in all three renderings and in the same nine places. You can see the dense version of this on the outreach template page, which carries seven blocks, and the single block version on the contract outline, which is the 46 line one.

What I am changing anyway

A passing comparison is not a reason to leave two copies of a format string in two files. The fix is one exported helper that both call:

export function templateText(b: { subject?: string; body: string }) {
  return b.subject ? `Subject: ${b.subject}\n\n${b.body}` : b.body;
}
Enter fullscreen mode Exit fullscreen mode

Then the unit test can assert what this sweep proved by hand: for every template block, the markdown rendering contains templateText(block) and nothing else between the fences, and no body contains a tab, a carriage return, a double space, a trailing space or three consecutive newlines.

What a unit test still cannot see is the page, because the page's blank line comes out of CSS and innerText. That part stays a browser check, and this is the whole of it: visit the 16 pages, swap navigator.clipboard, click everything named Copy, compare three strings. About thirty lines, and it is now the only thing standing between a tidy template and a subject line that silently stops being copied.

The honest caveat: by replacing writeText I proved what the application hands to the clipboard, not what the clipboard received. A real end to end check needs the permission grant and a focused document. For a bug where one of two hand-written prefixes drifts from the other, the string the app produced is the string that matters.

Top comments (0)