Code diff

A code change you can watch happen, on a sheet set into a soft frame. Switch between before, the diff and after: removed lines fold away, new ones open up, the changed words light up and the line numbers roll to their new places.

src/cart/total.ts +4−3
  1. import { rates } from "./rates";
  2. export function total(items: Item[]) {
  3. export function total(items: Item[], region = "GB") {
  4. let sum = 0;
  5. for (const item of items) {
  6. sum += item.price;
  7. sum += item.price * item.count;
  8. }
  9. return sum;
  10. const tax = rates[region] ?? 0;
  11. return sum * (1 + tax);
  12. }
Charge tax by regiona1f93c2

Options

Screen
Colour

Code

import { useEffect, useRef, useState } from "react";
import "./code-diff.css";

const views = ["before", "diff", "after"];
const words = /("[^"]*")|\b(import|from|export|function|let|const|for|of|return)\b|\b(\d+(?:\.\d+)?)\b/g;

/* Colours the words of the language, text in quotes and numbers. */
function paint(text, key) {
  const parts = [];
  let at = 0;
  for (const found of text.matchAll(words)) {
    parts.push(text.slice(at, found.index));
    parts.push(
      <span key={key + found.index} data-is={found[1] ? "text" : found[2] ? "word" : "number"}>
        {found[0]}
      </span>,
    );
    at = found.index + found[0].length;
  }
  parts.push(text.slice(at));
  return parts;
}

/* lines is a list of { type, text, mark }. type is "same", "del" or "add"; mark is the
   part of a changed line that is different, and is optional. logo is your own
   mark, as an element; note and commit are the line under the code.

   <CodeDiff folder="src/cart/" file="total.ts" logo={<Logo className="dh-diff-logo" />} note="Charge tax by region" lines={[
     { type: "del", text: "return sum;" },
     { type: "add", text: "return sum * 1.2;", mark: "* 1.2;" },
   ]} /> */
export function CodeDiff({ file, folder, logo, lines, note, commit, opens = true }) {
  const [view, setView] = useState("before");
  const touched = useRef(false);
  const waiting = useRef();
  const card = useRef(null);
  const buttons = useRef([]);

  const pick = (next) => {
    touched.current = true;
    clearTimeout(waiting.current);
    setView(next);
  };

  /* Replay goes back to the start, then opens the diff again. */
  const replay = () => {
    pick("before");
    waiting.current = setTimeout(() => setView("diff"), 750);
  };

  /* The first time it is seen, it opens the diff by itself. */
  useEffect(() => {
    if (!opens) return;
    const watcher = new IntersectionObserver(([seen]) => {
      if (!seen.isIntersecting) return;
      watcher.disconnect();
      waiting.current = setTimeout(() => touched.current || setView("diff"), 900);
    }, { threshold: 0.6 });
    watcher.observe(card.current);
    return () => {
      watcher.disconnect();
      clearTimeout(waiting.current);
    };
  }, [opens]);

  const onKeyDown = (event) => {
    const step = { ArrowRight: 1, ArrowLeft: -1 }[event.key];
    const from = buttons.current.indexOf(event.target);
    if (!step || from < 0) return;
    const next = (from + step + views.length) % views.length;
    pick(views[next]);
    buttons.current[next].focus();
  };

  const added = lines.filter((line) => line.type === "add").length;
  const removed = lines.filter((line) => line.type === "del").length;
  const share = Math.round((5 * added) / (added + removed || 1));
  const changed = (line) => line && line.type !== "same";
  let [before, after, turn] = [0, 0, 0];

  return (
    <figure className="dh-diff" data-view={view} ref={card}>
      <figcaption>
        <span className="dh-diff-file">
          {logo}
          {folder && <span>{folder}</span>}
          {file}
        </span>
        <span className="dh-diff-count">
          <b>+{added}</b>
          <s>−{removed}</s>
          <span>
            {[0, 1, 2, 3, 4].map((i) => (
              <i key={i} data-del={i < share ? undefined : ""} style={{ "--dh-diff-turn": i }} />
            ))}
          </span>
        </span>
        <span className="dh-diff-views" role="radiogroup" aria-label="Show" onKeyDown={onKeyDown}>
          {views.map((name, i) => (
            <button
              key={name}
              type="button"
              role="radio"
              aria-checked={view === name}
              ref={(button) => (buttons.current[i] = button)}
              onClick={() => pick(name)}
            >
              {name[0].toUpperCase() + name.slice(1)}
            </button>
          ))}
        </span>
      </figcaption>
      <ol>
        {lines.map((line, i) => {
          const { type, text, mark } = line;
          if (type !== "add") before++;
          if (type !== "del") after++;
          const at = mark ? text.lastIndexOf(mark) : -1;
          const edge = changed(line) && [!changed(lines[i - 1]) && "top", !changed(lines[i + 1]) && "bottom"].filter(Boolean).join(" ");
          return (
            <li key={i} data-line={type} data-edge={edge || undefined} style={type === "same" ? undefined : { "--dh-diff-turn": turn++ }}>
              <div>
                <i data-before={type === "add" ? undefined : before} data-after={type === "del" ? undefined : after} />
                <code>
                  {at < 0 ? paint(text || " ", "a") : [paint(text.slice(0, at), "a"), <mark key="mark">{paint(mark, "m")}</mark>, paint(text.slice(at + mark.length), "z")]}
                </code>
              </div>
            </li>
          );
        })}
      </ol>
      <footer>
        <span className="dh-diff-note">
          {note}
          <code>{commit}</code>
        </span>
        <button type="button" className="dh-diff-replay" onClick={replay}>
          <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M2.750 8a5.250 5.250 0 1 0 1.700-3.870" />
            <path d="M2.500 2.250v2.500H5" />
          </svg>
          Replay
        </button>
      </footer>
    </figure>
  );
}
src/cart/total.ts +4−3
  1. import { rates } from "./rates";
  2. export function total(items: Item[]) {
  3. export function total(items: Item[], region = "GB") {
  4. let sum = 0;
  5. for (const item of items) {
  6. sum += item.price;
  7. sum += item.price * item.count;
  8. }
  9. return sum;
  10. const tax = rates[region] ?? 0;
  11. return sum * (1 + tax);
  12. }
Charge tax by regiona1f93c2