Mohammad Savarmand
  • Projects
  • CV
Biology Dashboard
  • Animal cell
  • DNA mutations
  • Skin zoom
Click a numbered point on the cell
viewof organelle = hotspotFigure("images/animal-cell.svg", cellSpots)
Organelle
md`### ${organelle.n}. ${organelle.title}

${organelle.text}

**Main functions**

${organelle.functions.map(f => `- ${f}`).join("\n")}

<small>Thumbnail icon from [Magnific from Flaticon](https://www.flaticon.com/free-icon/dna_9803045?term=dna&related_id=9803045)</small>`
Related organelles and functions
{
  const box = document.createElement("div");
  organelle.related.forEach(r => {
    const k = cellSpots.findIndex(s => s.title === r.to);
    const row = document.createElement("div");
    row.className = "rel";
    row.innerHTML = `<button class="rel-dot" title="Show on the cell">${k + 1}</button><span><b>${r.to}.</b> ${r.why}</span>`;
    row.firstChild.onclick = () => viewof organelle.querySelectorAll(".hs-dot")[k].click();
    box.append(row);
  });
  return box;
}
// x and y are percentages of the image. `to` in related must match another title.
cellSpots = [
  {x: 89.2, y: 21.3, title: "Cell membrane",
   text: "A double layer of phospholipids (the orange heads and pale tails in the magnified view) with proteins set into it. At normal scale it is only a thin line around the cell.",
   functions: ["Controls what enters and leaves the cell", "Receives signals from outside through receptor proteins", "Anchors the cytoskeleton and joins the cell to its neighbors"],
   related: [{to: "Golgi apparatus", why: "Its vesicles fuse with the membrane to deliver new proteins and lipids."}, {to: "Cytoskeleton", why: "Attached to the inside of the membrane, it holds the cell's shape."}, {to: "Lysosome", why: "Digests material the membrane has taken into the cell."}]},
  {x: 28.9, y: 37.4, title: "Nucleus",
   text: "The double outline is the nuclear envelope, and the gaps in it are pores that let molecules pass in and out.",
   functions: ["Stores the cell's DNA", "Copies DNA into RNA (transcription)", "Duplicates the DNA before the cell divides"],
   related: [{to: "Nucleolus", why: "Sits inside the nucleus and builds ribosome parts."}, {to: "Ribosomes", why: "Read the messenger RNA that the nucleus sends out."}, {to: "Rough endoplasmic reticulum", why: "Its membrane is continuous with the nuclear envelope."}]},
  {x: 36.4, y: 48.8, title: "Nucleolus",
   text: "A dense region inside the nucleus with no membrane of its own.",
   functions: ["Makes ribosomal RNA", "Assembles the two halves of each ribosome"],
   related: [{to: "Nucleus", why: "The nucleolus forms around genes inside it."}, {to: "Ribosomes", why: "Their parts are made here, then exported through the nuclear pores."}]},
  {x: 49.0, y: 50.2, title: "Rough endoplasmic reticulum",
   text: "Folded membranes studded with ribosomes (the dark dots).",
   functions: ["Makes proteins destined for membranes or for export", "Folds new proteins and checks their quality", "Attaches sugar chains to proteins"],
   related: [{to: "Ribosomes", why: "The dots on its surface, which feed new proteins into it."}, {to: "Golgi apparatus", why: "Receives its proteins in vesicles for finishing and sorting."}, {to: "Nucleus", why: "Its membrane is continuous with the nuclear envelope."}]},
  {x: 25.6, y: 74.2, title: "Smooth endoplasmic reticulum",
   text: "Membrane tubes with no ribosomes.",
   functions: ["Makes lipids and steroid hormones", "Stores and releases calcium", "Breaks down drugs and toxins, mainly in liver cells"],
   related: [{to: "Rough endoplasmic reticulum", why: "The two are one connected membrane system."}, {to: "Golgi apparatus", why: "Receives the lipids it makes."}, {to: "Peroxisome", why: "Shares the work of lipid metabolism."}]},
  {x: 60.2, y: 55.4, title: "Golgi apparatus",
   text: "A stack of flattened sacs with vesicles (the small circles) budding from it.",
   functions: ["Modifies proteins and lipids, for example by trimming sugar chains", "Sorts them and packages them into vesicles", "Produces lysosomes"],
   related: [{to: "Rough endoplasmic reticulum", why: "Supplies the proteins it processes."}, {to: "Lysosome", why: "Buds off from the Golgi already loaded with enzymes."}, {to: "Cell membrane", why: "Where many of its vesicles are sent."}]},
  {x: 18.2, y: 31.2, title: "Mitochondrion",
   text: "The folded inner membrane increases the surface where energy is released.",
   functions: ["Makes most of the cell's ATP through cellular respiration", "Helps trigger programmed cell death", "Carries its own small DNA and ribosomes"],
   related: [{to: "Peroxisome", why: "Shares the breakdown of fatty acids."}, {to: "Smooth endoplasmic reticulum", why: "Exchanges lipids and calcium with it at contact points."}, {to: "Cytoskeleton", why: "Moves mitochondria to where energy is needed."}]},
  {x: 64.4, y: 75.2, title: "Lysosome",
   text: "A small sac of digestive enzymes kept at acidic pH.",
   functions: ["Digests worn-out organelles (autophagy)", "Breaks down material the cell has taken in", "Recycles the building blocks back to the cell"],
   related: [{to: "Golgi apparatus", why: "Makes lysosomes and fills them with enzymes."}, {to: "Cell membrane", why: "Brings in the outside material that lysosomes digest."}, {to: "Mitochondrion", why: "Damaged ones are removed by lysosomes."}]},
  {x: 40.9, y: 15.0, title: "Peroxisome",
   text: "A small sac of oxidative enzymes.",
   functions: ["Breaks down very long fatty acids", "Neutralizes hydrogen peroxide, a harmful by-product", "Helps make certain membrane lipids"],
   related: [{to: "Mitochondrion", why: "Finishes the fatty acid breakdown that peroxisomes start."}, {to: "Smooth endoplasmic reticulum", why: "Works with it on lipid production."}]},
  {x: 16.2, y: 58.4, title: "Centrosome",
   text: "Two short cylinders called centrioles, set at right angles.",
   functions: ["Organizes the cell's microtubules", "Forms the two poles of the spindle when the cell divides", "Its centrioles anchor cilia and flagella"],
   related: [{to: "Cytoskeleton", why: "The microtubules grow outward from it."}, {to: "Nucleus", why: "The spindle it builds pulls the chromosomes apart."}]},
  {x: 57.4, y: 32.2, title: "Ribosomes",
   text: "Small particles made of RNA and protein. Some float free, as here, and others sit on the rough endoplasmic reticulum.",
   functions: ["Build proteins from amino acids (translation)", "Read the code carried by messenger RNA, three bases at a time", "Free ribosomes make proteins for the cytoplasm; bound ones make proteins for export"],
   related: [{to: "Nucleolus", why: "Where ribosome parts are made."}, {to: "Nucleus", why: "Supplies the messenger RNA they read."}, {to: "Rough endoplasmic reticulum", why: "Where bound ribosomes work."}]},
  {x: 15.5, y: 44.3, title: "Cytoskeleton",
   text: "A network of protein filaments. The lines radiating from the centrosome are microtubules.",
   functions: ["Gives the cell its shape and strength", "Acts as tracks for moving vesicles and organelles", "Moves the cell and pulls it in two during division"],
   related: [{to: "Centrosome", why: "Organizes the microtubules."}, {to: "Cell membrane", why: "Anchored to it from the inside."}, {to: "Mitochondrion", why: "Carried along its tracks."}]}
]
DNA double helix
helix.node
Reading the code three bases at a time
sequenceView(mutation, viewof mutPos, showRna)
Effect on the protein
resultView(mutation, strand)
Choose a DNA strand
viewof strand = strandPicker(strands)
gene = strand.seq
baseColor = {
  return {A: "#1fbf93", T: "#f0703a", G: "#f0e442", C: "#56b4e9"};
}
aminoAcid = {
  return {A: "Ala", R: "Arg", N: "Asn", D: "Asp", C: "Cys", Q: "Gln", E: "Glu", G: "Gly", H: "His", I: "Ile",
          L: "Leu", K: "Lys", M: "Met", F: "Phe", P: "Pro", S: "Ser", T: "Thr", W: "Trp", Y: "Tyr", V: "Val", "*": "Stop"};
}
mutation = mutate(gene, mutType, mutPos, typed || mutBase.repeat(mutLen), mutLen)
typed = mutText.toUpperCase().replace(/[^ATGC]/g, "").slice(0, 6)
helix.update(mutation, spin)
{
  const enable = (view, on) => view.querySelectorAll("input").forEach(el => el.disabled = !on);
  enable(viewof mutPos, mutType !== "None");
  const writes = mutType === "Substitution" || mutType === "Insertion";
  enable(viewof mutText, writes);
  enable(viewof mutBase, writes && !typed);
  enable(viewof mutLen, mutType !== "None" && !(writes && typed));
}
// Splits a DNA string into codons. `read` is false after a stop codon.
function translate(seq) {
  const table = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG";
  const codons = [];
  let read = true;
  for (let i = 0; i < seq.length; i += 3) {
    const bases = seq.slice(i, i + 3);
    const [a, b, c] = [...bases].map(ch => "TCAG".indexOf(ch));
    const aa = bases.length === 3 ? table[16 * a + 4 * b + c] : null;
    codons.push({bases, aa, start: i, read: read && aa !== null});
    if (aa === "*") read = false;
  }
  return codons;
}
// Applies one mutation and works out what it does to the protein.
// `bases` are the letters to write (substitution and insertion). `len` is the base count for the other types.
// Underneath there are only three operations: a duplication is an insertion of a copy, and an
// inversion overwrites a stretch with its reverse complement.
function mutate(gene, type, pos, bases, len) {
  const flip = t => [...t].reverse().map(b => ({A: "T", T: "A", G: "C", C: "G"})[b]).join("");
  const op = type === "Duplication" ? "Insertion" : type === "Inversion" ? "Substitution" : type;
  const first = Math.min(pos - 1, gene.length - len);
  const write = type === "Duplication" ? gene.slice(first, first + len) : type === "Inversion" ? flip(gene.slice(first, first + len)) : bases;
  const n = op === "None" ? 0 : op === "Deletion" ? len : write.length;
  const i = type === "Duplication" ? first + len : op === "Insertion" ? pos - 1 : Math.min(pos - 1, gene.length - n);
  const sub = op === "Substitution";
  const seq = sub ? gene.slice(0, i) + write + gene.slice(i + n)
            : op === "Insertion" ? gene.slice(0, i) + write + gene.slice(i)
            : op === "Deletion" ? gene.slice(0, i) + gene.slice(i + n)
            : gene;
  const before = translate(gene), after = translate(seq);
  const c = Math.floor(i / 3);
  const stop = after.findIndex(d => d.aa === "*");
  const plural = n > 1 ? "s" : "";
  // For a substitution or inversion: the codons whose letters changed.
  const touched = sub ? d3.range(before.length).filter(k => before[k].bases !== after[k].bases) : [];
  const swaps = touched.map(k => `Codon ${k + 1} changes from ${before[k].bases} (${aminoAcid[before[k].aa]}) to ${after[k].bases} (${aminoAcid[after[k].aa]}).`).join(" ");
  const lead = type === "Inversion" ? `Flipping ${n} base${plural} writes the opposite strand's letters in reverse order. ` : "";
  let name = "No mutation", text = "This is the normal sequence. Pick a mutation type to change it.", shifted = false;

  if (op !== "None" && !n) {
    name = "Nothing typed";
    text = "Type one or more of the letters A, T, G and C in the box.";
  } else if (op !== "None" && seq === gene) {
    name = "No change";
    text = type === "Inversion" ? "This stretch reads the same on both strands, so flipping it changes nothing."
         : `${n > 1 ? `Positions ${i + 1} to ${i + n} are` : `Position ${pos} is`} already ${write}. Try something different.`;
  } else if (sub && touched.every(k => before[k].aa === after[k].aa)) {
    name = "Silent mutation";
    text = `${lead}${swaps} The amino acid${touched.length > 1 ? "s are" : " is"} the same, so the protein is unchanged.`;
  } else if (sub && stop >= 0) {
    name = "Nonsense mutation";
    text = `${lead}${swaps} ${after[stop].bases} is a stop signal, so the protein ends after ${stop} amino acids.`;
  } else if (sub) {
    name = "Missense mutation";
    text = `${lead}${swaps} Every other amino acid stays the same.`;
  } else if (n) {
    shifted = n % 3 !== 0;
    const verb = type === "Duplication" ? "Copying" : type === "Insertion" ? "Adding" : "Removing";
    name = shifted ? "Frameshift" : `In-frame ${type.toLowerCase()}`;
    text = shifted
      ? `${verb} ${n} base${plural} shifts the reading frame. From codon ${c + 1} onward, the bases are grouped into different threes.`
      : `${verb} ${n} bases keeps the reading frame, so the codons after the change are read as before.`;
    text += stop >= 0 ? ` A stop signal now appears at codon ${stop + 1}, so the protein is cut short.`
          : shifted ? "" : ` The protein is ${n / 3 === 1 ? "one amino acid" : `${n / 3} amino acids`} ${op === "Insertion" ? "longer" : "shorter"}.`;
  }

  // Where each base of the new sequence came from (-1 = new). A codon is unchanged
  // only if its three bases are an original codon, still in the original frame.
  const from = op === "Insertion" ? [...d3.range(i), ...Array(n).fill(-1), ...d3.range(i, gene.length)]
             : op === "Deletion"  ? [...d3.range(i), ...d3.range(i + n, gene.length)]
             : d3.range(gene.length).map(j => seq[j] !== gene[j] ? -1 : j);
  const intact = d => d.aa !== null && from[d.start] % 3 === 0 && from[d.start + 1] === from[d.start] + 1 && from[d.start + 2] === from[d.start] + 2;
  const kept = new Set(after.filter(intact).map(d => from[d.start] / 3));
  after.forEach((d, k) => d.diff = d.aa !== null && !intact(d) && !(sub && before[k].aa === d.aa));
  before.forEach((d, j) => d.diff = !kept.has(j) && !(sub && after[j].aa === d.aa));

  const hot = new Set(d3.range(i, i + n).filter(j => !sub || seq[j] !== gene[j]));
  // One entry per base pair for the 3D model: the 30 original pairs, then 6 spares for insertions.
  const items = [...gene].map((b, j) =>
      sub ? {base: seq[j], slot: j, on: 1, hot: seq[j] !== b}
    : op === "Insertion" ? {base: b, slot: j < i ? j : j + n, on: 1, hot: false}
    : op === "Deletion" && j >= i ? (j < i + n ? {base: b, slot: i - 0.5, on: 0, hot: true} : {base: b, slot: j - n, on: 1, hot: false})
    : {base: b, slot: j, on: 1, hot: false});
  const spares = d3.range(6).map(k => ({base: write[k] || "A", slot: i + Math.min(k, Math.max(n - 1, 0)), on: +(op === "Insertion" && k < n), hot: true}));
  const old = gene.slice(i, i + n);

  return {
    type, seq, before, after, name, text, shifted, items: [...items, ...spares],
    changed: seq !== gene,
    hotBefore: op === "Insertion" ? new Set() : hot,
    hotAfter: op === "Deletion" ? new Set() : hot,
    gone: op === "Deletion",
    marks: seq === gene ? [] : op === "Deletion" ? [i - 0.5] : d3.range(i, i + n),
    tag: seq === gene ? "" : type === "Inversion" ? `${old} ⇄ ${write}` : type === "Duplication" ? `${write} × 2`
       : sub ? `${old} → ${write}` : op === "Insertion" ? `+ ${write}` : `− ${old}`
  };
}
function sequenceView(m, posInput, rna) {
  const row = (label, codons, hot, hotClass, clickable, asRna) => `<div class="seq-row"><span class="seq-label">${label}</span>${
    codons.map(c => {
      const cls = ["codon", c.diff && "diff", c.aa === "*" && c.read && "stop", !c.read && "unread"].filter(Boolean).join(" ");
      const letters = [...c.bases].map((b, j) => {
        const p = c.start + j;
        return `<b style="color:${baseColor[b]}" class="${hot.has(p) ? hotClass : ""}" ${clickable ? `data-pos="${p + 1}"` : ""}>${asRna && b === "T" ? "U" : b}</b>`;
      }).join("");
      return `<span class="${cls}"><span>${letters}</span>${asRna ? "" : `<small>${c.aa ? aminoAcid[c.aa] : "–"}</small>`}</span>`;
    }).join("")}</div>`;
  const box = document.createElement("div");
  box.className = "seq";
  box.innerHTML = row("Original", m.before, m.hotBefore, m.gone ? "gone" : "hot", true, false)
                + row("Mutated", m.after, m.hotAfter, "hot", false, false)
                + (rna ? row("mRNA", m.after, m.hotAfter, "hot", false, true) : "");
  box.onclick = e => {
    const b = e.target.closest("[data-pos]");
    if (b) setInput(posInput, Math.max(4, +b.dataset.pos));
  };
  return box;
}
// The start of three human genes (first 30 bases of the coding sequence).
// `known` lists named variants: a setting of the controls and what it does to a person.
strands = [
  {name: "Hemoglobin (HBB)", seq: "ATGGTGCATCTGACTCCTGAGGAGAAGTCT", source: "https://databases.lovd.nl/shared/refseq/HBB_NM_000518.4_codingDNA.html", protein: "beta-globin",
   makes: "beta-globin, half of the hemoglobin that carries oxygen in red blood cells",
   loss: "With one working copy a person is usually a healthy carrier. With none, the result is beta-thalassemia major, a severe anemia.",
   known: [
     ["Substitution", 20, "T", 1, "This is the sickle cell change (Hb S). With it in both copies of the gene, red blood cells bend into a sickle shape and block small vessels. One copy usually causes no illness."],
     ["Substitution", 19, "A", 1, "This is hemoglobin C. Two copies cause hemoglobin C disease, usually a mild anemia."],
     ["Substitution", 20, "C", 1, "This is Hb G-Makassar, a rare variant at the same base as sickle cell."],
     ["Deletion", 20, "A", 1, "This is a known beta-thalassemia change, called codon 6 (−A). This copy of the gene makes no working beta-globin."],
     ["Deletion", 17, "A", 2, "This is a known beta-thalassemia change, called codon 5 (−CT). This copy of the gene makes no working beta-globin."],
     ["Deletion", 25, "A", 2, "This is a known beta-thalassemia change, called codon 8 (−AA). This copy of the gene makes no working beta-globin."],
     ["Insertion", 28, "G", 1, "This is a known beta-thalassemia change, called codons 8/9 (+G). This copy of the gene makes no working beta-globin."]
   ]},
  {name: "Insulin (INS)", seq: "ATGGCCCTGTGGATGCGCCTCCTGCCCCTG", source: "https://databases.lovd.nl/shared/refseq/INS_NM_000207.2_codingDNA.html", protein: "insulin",
   makes: "the hormone that lets cells take up sugar from the blood",
   loss: "One working copy is usually enough. With none, a baby cannot make insulin and has diabetes from birth.", known: []},
  {name: "Growth hormone (GH1)", seq: "ATGGCTACAGGCTCCCGGACGTCCCTGCTC", source: "https://databases.lovd.nl/shared/refseq/GH1_NM_000515.3_codingDNA.html", protein: "growth hormone",
   makes: "the hormone that tells a child's body to grow",
   loss: "One working copy is usually enough. With none, a child makes no growth hormone and grows very slowly unless treated.", known: []}
]
function strandPicker(list) {
  const box = document.createElement("div");
  box.className = "strands";
  box.innerHTML = list.map((d, k) => `<button data-k="${k}" title="${d.name}"><b>${d.name.replace(/ \(.*/, "")}</b></button>`).join("")
    + `<p></p><small>Drag the helix to turn it, scroll to zoom, click a base pair to move the mutation there.</small>`;
  const pick = k => {
    box.querySelectorAll("button").forEach((b, j) => b.classList.toggle("on", j === k));
    box.querySelector("p").innerHTML = `${list[k].name}: makes ${list[k].makes}. Shown: its first 30 bases (<a href="${list[k].source}" target="_blank" rel="noopener">source: LOVD reference sequence</a>).`;
    box.value = list[k];
  };
  box.onclick = e => {
    const b = e.target.closest("button");
    if (!b) return;
    pick(+b.dataset.k);
    box.dispatchEvent(new CustomEvent("input", {bubbles: true}));
  };
  pick(0);
  return box;
}
// What the change could mean for a person. Simplified: real effects depend on the exact change.
function humanEffect(m, strand) {
  const hit = strand.known.find(d => mutate(strand.seq, d[0], d[1], d[2].repeat(d[3]), d[3]).seq === m.seq);
  return hit ? hit[4]
    : !m.changed ? ""
    : m.name === "Silent mutation" ? `The ${strand.protein} made is identical, so no effect on the person is expected.`
    : m.name === "Missense mutation" ? `One or two building blocks of ${strand.protein} differ. Many such changes are harmless, but some stop the protein working. If this one did: ${strand.loss}`
    : m.name === "Nonsense mutation" || m.name === "Frameshift" ? `This copy of the gene would no longer make working ${strand.protein}. ${strand.loss}`
    : `The ${strand.protein} made is slightly longer or shorter. It may still work. If it does not: ${strand.loss}`;
}
function resultView(m, strand) {
  const person = humanEffect(m, strand);
  const box = document.createElement("div");
  box.className = "verdict";
  box.innerHTML = `<div class="big-number">${m.name}</div>
    ${m.changed ? `<span class="status ${m.shifted ? "shifted" : "kept"}">Reading frame ${m.shifted ? "shifted" : "kept"}</span>` : ""}
    <p><b>In the DNA.</b> ${m.text}</p>${person ? `<p><b>In the person.</b> ${person}</p>` : ""}`;
  return box;
}
THREE = require("three@0.149.0/build/three.min.js")
// Built once. helix.update() only moves and recolors what is already there.
helix = {
  const N = gene.length + 6;
  const RISE = 0.34, TURN = 2 * Math.PI / 10.5, R = 1;
  const GROOVE = 2.45;         // strand 2 leads strand 1 by this angle, which makes the two grooves unequal
  const SEG = 8 * (N - 1);     // backbone pieces per strand
  const pair = {A: "T", T: "A", G: "C", C: "G"};

  const wrap = document.createElement("div");
  wrap.className = "fill dna";
  wrap.innerHTML = `<div class="dna-tag" hidden></div><div class="dna-legend">${
    Object.entries(baseColor).map(([b, c]) => `<span style="background:${c}">${b}</span>`).join("")}</div>`;
  const tag = wrap.querySelector(".dna-tag");

  const renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  const canvas = renderer.domElement;
  wrap.prepend(canvas);

  const scene = new THREE.Scene();
  scene.fog = new THREE.Fog(0x141a22, 10, 30);
  const camera = new THREE.PerspectiveCamera(30, 2, 0.1, 100);
  scene.add(new THREE.HemisphereLight(0xffffff, 0x2c3648, 0.75));
  const sun = new THREE.DirectionalLight(0xffffff, 0.55);
  sun.position.set(2, 4, 6);
  scene.add(sun);
  const group = new THREE.Group();
  group.rotation.order = "YXZ";
  scene.add(group);

  // Three instanced meshes: all rung halves are one draw call, all beads another, all backbone pieces a third.
  const material = () => new THREE.MeshStandardMaterial({roughness: 0.5, metalness: 0.05});
  const cylinder = new THREE.CylinderGeometry(1, 1, 1, 12);
  const rungs = new THREE.InstancedMesh(cylinder, material(), 2 * N);
  const beads = new THREE.InstancedMesh(new THREE.SphereGeometry(1, 14, 10), material(), 2 * N);
  const links = new THREE.InstancedMesh(cylinder, material(), 2 * SEG);
  const strandColor = [new THREE.Color("#c3ccdd"), new THREE.Color("#7383a3")];
  for (let k = 0; k < 2 * SEG; k++) links.setColorAt(k, strandColor[k < SEG ? 0 : 1]);
  for (let k = 0; k < 2 * N; k++) {
    beads.setColorAt(k, strandColor[k % 2]);
    rungs.setColorAt(k, strandColor[0]);
  }
  const ring = new THREE.Mesh(new THREE.TorusGeometry(1.32, 0.035, 8, 60),
                              new THREE.MeshBasicMaterial({color: 0xff8c42, transparent: true, depthWrite: false}));
  ring.rotation.y = Math.PI / 2;
  group.add(rungs, beads, links, ring);

  const state = d3.range(N).map(() => ({slot: 0, on: 0, hot: 0, split: 0.5, c1: new THREE.Color(), c2: new THREE.Color()}));
  let goal = null, marks = [], center = 0;
  let spinning = true, turn = 0, yaw = -0.3, zoom = 1, settle = 0;
  let visible = true, running = false, drag = null, last = 0;

  const a = new THREE.Vector3(), b = new THREE.Vector3(), m = new THREE.Vector3(), mid = new THREE.Vector3(), dir = new THREE.Vector3();
  const size = new THREE.Vector3(), quat = new THREE.Quaternion(), still = new THREE.Quaternion(), matrix = new THREE.Matrix4();
  const up = new THREE.Vector3(0, 1, 0);

  // Right-handed helix along x. strand is 0 or 1.
  const point = (v, slot, strand) => {
    const angle = slot * TURN + strand * GROOVE;
    return v.set((slot - center) * RISE, R * Math.cos(angle), R * Math.sin(angle));
  };
  const stick = (mesh, k, p, q, radius, stretch) => {
    dir.subVectors(q, p);
    const length = dir.length() || 1e-6;
    quat.setFromUnitVectors(up, dir.divideScalar(length));
    mesh.setMatrixAt(k, matrix.compose(mid.addVectors(p, q).multiplyScalar(0.5), quat, size.set(radius, length * stretch, radius)));
  };

  function layout() {
    const live = state.filter((d, k) => goal[k].on);
    const lo = d3.min(live, d => d.slot), hi = d3.max(live, d => d.slot);
    center = (lo + hi) / 2;
    state.forEach((d, k) => {
      point(a, d.slot, 0);
      point(b, d.slot, 1);
      m.lerpVectors(a, b, d.split);
      const radius = 0.085 * d.on * (1 + 0.8 * d.hot);
      stick(rungs, 2 * k, a, m, radius, 1);
      stick(rungs, 2 * k + 1, m, b, radius, 1);
      rungs.setColorAt(2 * k, d.c1);
      rungs.setColorAt(2 * k + 1, d.c2);
      beads.setMatrixAt(2 * k, matrix.compose(a, still, size.setScalar(0.17 * d.on)));
      beads.setMatrixAt(2 * k + 1, matrix.compose(b, still, size.setScalar(0.17 * d.on)));
    });
    for (let strand = 0; strand < 2; strand++) {
      for (let k = 0; k < SEG; k++) {
        point(a, lo + (hi - lo) * k / SEG, strand);
        point(b, lo + (hi - lo) * (k + 1) / SEG, strand);
        stick(links, strand * SEG + k, a, b, 0.12, 1.2);
      }
    }
    // One hoop marks the change. Over several bases it stretches into a see-through sleeve.
    ring.visible = marks.length > 0;
    if (ring.visible) {
      ring.position.x = (d3.mean(marks) - center) * RISE;
      ring.scale.z = 1 + (marks.length - 1) * RISE / 0.07;
      ring.material.opacity = marks.length > 1 ? 0.4 : 0.95;
    }
    rungs.instanceMatrix.needsUpdate = beads.instanceMatrix.needsUpdate = links.instanceMatrix.needsUpdate = true;
    rungs.instanceColor.needsUpdate = true;
  }

  function tick(time) {
    const dt = Math.min(0.05, (time - last) / 1000 || 0);
    last = time;
    if (settle > 0) {
      settle -= dt;
      const ease = settle > 0 ? 1 - Math.exp(-dt / 0.13) : 1;
      state.forEach((d, k) => {
        const g = goal[k];
        if (d.on < 0.02 && g.on) d.slot = g.slot;
        for (const key of ["slot", "on", "hot", "split"]) d[key] += (g[key] - d[key]) * ease;
        d.c1.lerp(g.c1, ease);
        d.c2.lerp(g.c2, ease);
      });
      layout();
    }
    if (spinning && !drag) turn += dt * 0.45;
    draw();
    running = visible && (spinning || drag || settle > 0);
    if (running) requestAnimationFrame(tick);
  }
  function draw() {
    group.rotation.set(turn, yaw, 0);
    if (marks.length) {
      m.set((d3.mean(marks) - center) * RISE, R + 0.55, 0).applyAxisAngle(up, yaw).project(camera);
      tag.style.left = `${(m.x + 1) * 50}%`;
      tag.style.top = `${(1 - m.y) * 50}%`;
    }
    renderer.render(scene, camera);
  }
  // Render only while something is changing and the page is on screen.
  const wake = () => {
    if (!running && visible && goal) {
      running = true;
      last = performance.now();
      requestAnimationFrame(tick);
    }
  };

  function resize() {
    const w = wrap.clientWidth, h = wrap.clientHeight;
    if (!w || !h) return;
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    const half = Math.tan(camera.fov * Math.PI / 360);
    const distance = zoom * Math.max((N * RISE / 2 + 0.6) / (half * camera.aspect), 2.2 / half);
    camera.position.set(0, 0.25, distance);
    camera.lookAt(0, 0.15, 0);
    camera.updateProjectionMatrix();
    scene.fog.near = distance - 1.5;
    scene.fog.far = distance + 9;
    if (goal) draw();
    wake();
  }
  const sizeWatch = new ResizeObserver(resize);
  sizeWatch.observe(wrap);
  const viewWatch = new IntersectionObserver(([entry]) => {
    visible = entry.isIntersecting;
    wake();
  });
  viewWatch.observe(wrap);

  const ray = new THREE.Raycaster(), pointer = new THREE.Vector2();
  canvas.addEventListener("pointerdown", e => {
    drag = {x: e.clientX, y: e.clientY, moved: 0};
    canvas.setPointerCapture(e.pointerId);
    wake();
  });
  canvas.addEventListener("pointermove", e => {
    if (!drag) return;
    const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
    drag = {x: e.clientX, y: e.clientY, moved: drag.moved + Math.abs(dx) + Math.abs(dy)};
    yaw = Math.max(-1, Math.min(1, yaw + dx * 0.006));
    turn += dy * 0.01;
  });
  canvas.addEventListener("pointerup", e => {
    const click = drag && drag.moved < 5;
    drag = null;
    if (!click) return;
    const box = canvas.getBoundingClientRect();
    pointer.set((e.clientX - box.left) / box.width * 2 - 1, 1 - (e.clientY - box.top) / box.height * 2);
    ray.setFromCamera(pointer, camera);
    const hit = ray.intersectObjects([rungs, beads])[0];
    if (hit && hit.instanceId >> 1 < gene.length) setInput(viewof mutPos, Math.max(4, (hit.instanceId >> 1) + 1));
  });
  canvas.addEventListener("wheel", e => {
    e.preventDefault();
    zoom = Math.max(0.5, Math.min(1.6, zoom * Math.exp(e.deltaY * 0.001)));
    resize();
  }, {passive: false});

  invalidation.then(() => {
    visible = false;
    sizeWatch.disconnect();
    viewWatch.disconnect();
    renderer.dispose();
  });

  function update(mutation, spin) {
    const first = !goal;
    goal = mutation.items.map(d => ({
      slot: d.slot, on: d.on, hot: +d.hot, split: "AG".includes(d.base) ? 0.57 : 0.43,
      c1: new THREE.Color(baseColor[d.base]), c2: new THREE.Color(baseColor[pair[d.base]])
    }));
    marks = mutation.marks;
    tag.hidden = !mutation.tag;
    tag.textContent = mutation.tag;
    spinning = spin;
    if (first) state.forEach((d, k) => Object.assign(d, goal[k], {c1: goal[k].c1.clone(), c2: goal[k].c2.clone()}));
    settle = first ? 0.01 : 1.2;
    wake();
  }

  return {node: wrap, update};
}
viewof mutType = Inputs.radio(["Substitution", "Insertion", "Deletion", "Duplication", "Inversion", "None"], {value: "Substitution", label: "Mutation"})
viewof mutPos  = Inputs.range([4, gene.length], {value: 20, step: 1, label: "Position"})
viewof mutText = Inputs.text({value: "", label: "Bases to write", placeholder: "type up to 6, e.g. TAG", maxlength: 6})
viewof mutBase = Inputs.radio(["A", "T", "G", "C"], {value: "T", label: "Or repeat one base"})
viewof mutLen  = Inputs.radio([1, 2, 3, 4, 5, 6], {value: 1, label: "Base count"})
viewof spin    = Inputs.toggle({label: "Auto-rotate", value: true})
viewof showRna = Inputs.toggle({label: "Show mRNA", value: false})
From arm’s length to a single cell
skin.node
// portal = [x, y, width] of the next level inside this one (each drawing is 1200 x 800).
// width = real width of the first frame in meters. The rest follow from the portals.
skinLevels = [
  {src: "images/skin-1-forearm.svg", title: "Forearm", width: 0.3, portal: [559.6, 468.1, 120],
   text: "What the eye sees at arm's length: an even surface with fine hairs and the odd freckle. The frame is about 30 cm wide."},
  {src: "images/skin-2-surface.svg", title: "Skin surface", portal: [610, 410, 120],
   text: "Ten times closer, as through a strong magnifying glass. The surface is a mesh of fine furrows around small raised plateaus. Each hair leaves through its own opening, the small dots are sweat pores, and the darker patches are freckles."},
  {src: "images/skin-3-layers.svg", title: "Layers of the skin", portal: [600, 145.3, 80],
   text: "A slice through the skin. The thin band on top is the epidermis. Under it lies the dermis, with hair follicles, a coiled sweat gland, blood vessels (red and blue) and nerves (yellow). The yellow layer at the bottom is fat."},
  {src: "images/skin-4-epidermis.svg", title: "Epidermis", portal: [610, 324.3, 170],
   text: "The epidermis is built from stacked cells called keratinocytes. New ones are made in the bottom row. They flatten as they are pushed upward and end as the dead scales of the surface. The pale branching cells make the pigment melanin (brown dots). Below, red blood cells pass through a capillary in single file."},
  {src: "images/skin-5-cell.svg", title: "A single skin cell",
   text: "One keratinocyte, about 12 micrometers across. The purple nucleus holds its DNA. Dark melanin granules sit over the nucleus like a cap and shield it from ultraviolet light. The paired dark bars are desmosomes, which rivet the cell to its neighbors, and the fine lines are keratin filaments."}
]
skin = zoomFigure(skinLevels, viewof depth)
skin.update(depth)
// The level currently in view. Only changes when a whole level is crossed.
stage = Generators.observe(notify => {
  let shown;
  const read = () => {
    const s = Math.round(viewof depth.value);
    if (s !== shown) notify(shown = s);
  };
  viewof depth.addEventListener("input", read);
  read();
  return () => viewof depth.removeEventListener("input", read);
})
// Nested images with a camera that flies from each level into the next.
function zoomFigure(levels, input) {
  const W = 1200, H = 800, last = levels.length - 1;
  const lensId = "lens-" + Math.random().toString(36).slice(2);
  const wrap = document.createElement("div");
  wrap.className = "fill zoom";
  const svg = d3.select(wrap).append("svg").attr("viewBox", `0 0 ${W} ${H}`);
  const lens = svg.append("clipPath").attr("id", lensId).append("rect").attr("width", W).attr("height", H);
  const layers = levels.map(() => {
    const g = svg.append("g").style("display", "none");
    g.append("image").attr("class", "full").attr("width", W).attr("height", H).attr("preserveAspectRatio", "none");
    g.append("image").attr("class", "proxy").attr("width", W).attr("height", H).attr("preserveAspectRatio", "none");
    g.append("rect").attr("class", "zoom-ring under").attr("width", W).attr("height", H);
    g.append("rect").attr("class", "zoom-ring").attr("width", W).attr("height", H);
    return g;
  });
  const bar = svg.append("g").attr("class", "zoom-bar");
  const barLine = bar.selectAll("path").data(["under", null]).join("path").attr("class", d => d);
  const barText = bar.append("text").attr("x", 40).attr("y", H - 64);
  const zoomText = bar.append("text").attr("x", W - 40).attr("y", H - 40).attr("text-anchor", "end");

  const paths = levels.slice(0, last).map(level => d3.interpolateZoom([W / 2, H / 2, W], level.portal));
  const widths = [levels[0].width];
  levels.slice(0, last).forEach((level, i) => widths.push(widths[i] * level.portal[2] / W));
  const smooth = t => (t = Math.max(0, Math.min(1, t)), t * t * (3 - 2 * t));
  const units = m => m >= 0.01 ? [100, "cm"] : m >= 1e-3 ? [1e3, "mm"] : m >= 1e-6 ? [1e6, "µm"] : [1e9, "nm"];
  // Loads a level, and makes a small bitmap copy that stands in for it while it is still small on screen.
  const load = j => {
    if (!layers[j] || layers[j].select(".full").attr("href")) return;
    layers[j].select(".full").attr("href", levels[j].src);
    const picture = new Image();
    picture.onload = () => {
      const canvas = document.createElement("canvas");
      canvas.width = W / 2;
      canvas.height = H / 2;
      canvas.getContext("2d").drawImage(picture, 0, 0, W / 2, H / 2);
      try {
        layers[j].select(".proxy").attr("href", canvas.toDataURL());
      } catch (error) {
        // No stand-in for this level: the full drawing is used at every size.
      }
    };
    picture.src = levels[j].src;
  };
  const show = (g, opacity, small) => {
    const proxy = small && g.select(".proxy").attr("href");
    g.select(".full").attr("opacity", opacity).style("display", opacity && !proxy ? null : "none");
    g.select(".proxy").attr("opacity", opacity).style("display", opacity && proxy ? null : "none");
  };

  function update(depth) {
    const i = Math.min(Math.floor(depth + 1e-6), last);
    const s = i === last ? 0 : Math.max(0, depth - i);
    const [vx, vy, vw] = i === last ? [W / 2, H / 2, W] : paths[i](s);
    const k = W / vw, tx = W / 2 - vx * k, ty = H / 2 - vy * k;

    // Only the level in view and the one inside it are drawn. One more is loaded ahead.
    layers.forEach((g, j) => g.style("display", j === i || j === i + 1 ? null : "none"));
    [i, i + 1, i + 2].forEach(load);
    layers[i].attr("transform", `translate(${tx},${ty}) scale(${k})`).attr("clip-path", null);
    show(layers[i], 1, false);
    layers[i].selectAll("rect").style("display", "none");
    if (i < last) {
      const [px, py, pw] = levels[i].portal;
      const corner = (1 - s) * H / 2;
      lens.attr("rx", corner);
      layers[i + 1]
        .attr("transform", `translate(${tx + (px - pw / 2) * k},${ty + (py - pw * H / W / 2) * k}) scale(${k * pw / W})`)
        .attr("clip-path", `url(#${lensId})`);
      show(layers[i + 1], smooth((s - 0.15) / 0.4), k * pw / W < 0.5);
      layers[i + 1].selectAll("rect").style("display", null).attr("rx", corner).attr("opacity", 1 - smooth((s - 0.6) / 0.35));
    }

    const real = widths[i] * vw / W;
    const power = Math.pow(10, Math.floor(Math.log10(real / 4)));
    const nice = [5, 2, 1].find(n => n * power <= real / 4) * power;
    const [factor, unit] = units(nice);
    barLine.attr("d", `M40,${H - 52}v12h${nice / real * W}v-12`);
    barText.text(`${+(nice * factor).toPrecision(1)} ${unit}`);
    zoomText.text(`×${d3.format(",")(+(widths[0] / real).toPrecision(2))}`);
  }

  let frame;
  const set = value => setInput(input, Math.max(0, Math.min(last, value)));
  function flyTo(target) {
    cancelAnimationFrame(frame);
    const from = +input.value, start = performance.now();
    const duration = 900 + 2100 * Math.abs(target - from);
    const step = time => {
      const t = Math.min(1, (time - start) / duration);
      set(from + (target - from) * d3.easeCubicInOut(t));
      if (t < 1) frame = requestAnimationFrame(step);
    };
    frame = requestAnimationFrame(step);
  }
  wrap.addEventListener("wheel", e => {
    e.preventDefault();
    cancelAnimationFrame(frame);
    set(+input.value - e.deltaY * 0.0012);
  }, {passive: false});
  wrap.addEventListener("click", e => {
    const level = Math.floor(+input.value + 0.001);
    flyTo(e.shiftKey ? Math.max(0, Math.ceil(+input.value - 0.001) - 1) : Math.min(last, level + 1));
  });

  return {node: wrap, update, flyTo, play: () => (set(0), flyTo(last))};
}
// Sets an input's value from code so that every cell reading it updates.
function setInput(view, value) {
  view.value = value;
  view.dispatchEvent(new Event("input", {bubbles: true}));
}
// An image with numbered, clickable dots. Its value is the selected hotspot.
function hotspotFigure(src, spots) {
  const wrap = document.createElement("div");
  wrap.className = "hs-wrap";
  const img = document.createElement("img");
  img.src = src;
  img.alt = "Figure with clickable hotspots";
  wrap.append(img);

  const buttons = spots.map((s, i) => {
    const b = document.createElement("button");
    b.className = "hs-dot";
    b.textContent = i + 1;
    b.title = s.title;
    b.style.left = s.x + "%";
    b.style.top = s.y + "%";
    b.onclick = () => select(i);
    wrap.append(b);
    return b;
  });

  function select(i) {
    buttons.forEach((b, j) => b.classList.toggle("active", i === j));
    wrap.value = {...spots[i], n: i + 1};
    wrap.dispatchEvent(new CustomEvent("input", {bubbles: true}));
  }

  const fit = () => {
    if (img.clientWidth) wrap.style.setProperty("--dot", Math.max(16, Math.min(30, img.clientWidth * 0.032)) + "px");
  };
  new ResizeObserver(fit).observe(img);
  img.addEventListener("load", fit);

  img.addEventListener("click", e => {
    if (!e.altKey) return;
    const box = img.getBoundingClientRect();
    const x = (100 * (e.clientX - box.left) / box.width).toFixed(1);
    const y = (100 * (e.clientY - box.top) / box.height).toFixed(1);
    wrap.dataset.pick = `x: ${x}, y: ${y}`;
  });

  buttons[0].classList.add("active");
  wrap.value = {...spots[0], n: 1};
  return wrap;
}
viewof depth = Inputs.range([0, skinLevels.length - 1], {value: 0, step: 0.01, label: "Zoom"})
viewof jump  = Inputs.button([...skinLevels.map((d, i) => [`${i + 1}`, () => skin.flyTo(i)]), ["▶ Play", () => skin.play()]], {label: "Jump to"})
md`### ${stage + 1}. ${skinLevels[stage].title}

${skinLevels[stage].text}`

Click the picture to dive in one level, and Shift-click to come back. You can also scroll over it or drag the slider. The scale bar keeps track of the real size.

Each level is its own vector drawing, nested inside the one before, so nothing blurs however far in you go.

Mohammad Savarmand