9 November 2026

Review mode

Reviewing a page on a phone takes screenshots, notes, and many trips between the page and the chat. A review mode for nimib pages: select text, comment on it, go through the comments with a bar, and export them all in one text to paste in the chat, where an agent makes the changes. This post is reviewed with its own review mode, round by round.

New in this version
  1. The review mode is on every page of the site, and its version comes from git: a commit that changes a page is its next version, and the export names it
  2. the post is one notebook, and versions 1 to 8 are linked as they were, in git
  3. History lists only the versions with comments in this browser
  4. the export is nimib-review/4

What the review asked for is in Versions and rounds.

You are reviewing this page

Select a few words and tap Comment ✓ in the bar at the bottom, then write what should change (paste a screenshot in it if it helps): it is kept as you type. With nothing selected, the same button is Page note, a note on the whole page. ‹ and › open your comments one by one; Export gives the text to copy into the chat. Close review, above, goes back to reading.

The problem

More and more pages are written by coding agents: a notebook, a report, the docs of a library. Someone has to read them and say what to change. Pietro has Claude Code write his pages, and he reviews them mostly from his phone. Today a comment goes like this: take a screenshot of the page, paste it in the chat, write what to change, then go back to the page, which in a claude.ai artifact takes a few seconds to load again. A page merged and served by GitHub Pages opens faster, but every comment is still a trip from the page to the chat and back. Ten comments are ten round trips.

The idea

A review mode keeps the whole review on the page and makes one trip at the end. Open it with a button, select some words, comment on them, paste a screenshot where words are not enough, and go on reading; when the reading is done, export everything at once. The agent gets one text that says which page, which version, and what to change where, in the order of the page, and then the screenshots. Closed, the review mode leaves the page as it was.

The simplest review: one comment

Tap ✎ Review, beside the version under the lede: a bar appears at the bottom of the screen. Select ten round trips in the first section and tap Comment ✓: the words are marked, and a comment box opens at the top. Write Replace with: ten trips, a minute each. There is nothing to save: the note is kept as it is typed. Tap Export, and the text reads

## 1. In “The problem” (#the-problem)

> ten round trips

Around it: “…chat and back. Ten comments are ⟦ten round trips⟧. The idea A review mode kee…”

Replace with: ten trips, a minute each

A comment is three things: the words selected, the place they are in (the heading above them), and a note. Everything else is there to make many of these quick to write, to find again, and to hand over. When the review is done, Close review goes back to reading: the same button that opened it, or the one in the export, so a long page need not be scrolled back to its top.

The pieces of the screen

Four screens of this page on a phone, one card each: reading, reviewing with a comment open, the export, and History. Each card numbers its pieces from 1 and says what they do, and what is still open about them.

Reading

The page as it is, with one button
The page as it is, with one button
  1. ✎ Review, under the lede, beside the version and the day of its last update: opens the review mode. Every page of this site has it.

Reviewing

A comment open in the comment box, its words under it
A comment open in the comment box, its words under it
  1. Close review: the same button, closes the review mode.
  2. Marks: the words of each comment, in the soft colour of notes; the open one, darker. A tap opens it. A note on the whole page has no mark: its box says On the whole page.
  3. ‹ › and the count: the previous and next comment, in the order of the page (notes on the whole page first), each opened in the comment box; 2/5 says which.
  4. Delete deletes the comment that is open.
  5. Comment ✓ on the words selected; Page note on the whole page, when nothing is selected.
  6. Export opens the export.
  7. The comment box: the comment that is open, kept as it is typed. Empty, it says how to ask for new words (Replace with:) or none (Remove). A tap on the page closes it; left empty, the comment is dropped. Still open: is a tap on the page the best way to close it?
  8. Screenshots, pasted in the note: small under it, × removes one, a tap shows it large.

Export

The text of every comment, and each screenshot
The text of every comment, and each screenshot
  1. The text of every comment, Markdown after a block of YAML, to edit before it goes.
  2. Each screenshot, named as the text names it, with Copy image, to paste after the text.
  3. History opens the versions of the page.
  4. Close review ends the review, back to reading.
  5. Copy copies the text only.

History

The versions of the page, and the comments kept on each
The versions of the page, and the comments kept on each
  1. A version with comments in this browser, this one first, then the others, newest first.
  2. Bring here moves the comments of an older version to this one, those whose words this version still has; Export exports them, with the commit they were written on.
  3. Clear deletes the comments of that version (a second tap confirms).
  4. Export everything exports the comments of every version, each saying where it is from; Export goes back to the export.

The modes, and how to move between them

A page with the review mode is read in one of two modes, and the review mode has three places of its own: the comment box, the export and History. The drawing has them all, and the buttons that take you from one to the next.

What it lets you do

The review mode is for two readers: the reviewer on the page, and the agent that gets the export. Each row is something one of them wants to do, why, and how the review mode does it.

I want toso thatHow
The reviewer
read the page with nothing in the wayreviewing is a choice, not the defaultthe page opens in reading mode; ✎ Review opens the review
comment on a few wordsthe agent knows whereselect them, Comment ✓
say something about the whole pagenot every note is about some wordsPage note, with nothing selected
ask for new words, or for nonethe agent changes exactly those wordsReplace with: and the new text, or Remove, in the note
show what words can'ta layout or a colour is clear at a glancepaste a screenshot in the note
look at a screenshot closelycheck it before it goesa tap on it shows it large
go through my comments againread them over, change one‹ and ›, or a tap on marked words
drop a commentI changed my mindDelete, or empty the note
stop, and go on tomorrowa review takes timethe comments stay in the browser
send the whole review at onceone trip to the chatExport, Copy, then each screenshot
start again from nothinga version reviewed is doneHistory: clear one version, or everything
The agent
know which file and version to changethe page's address is not its sourcethe YAML block: source and version
find each comment's words in the sourcethe same words may be in many placesthe quote, and the words around it
know that nothing was lost in the pastea long paste can be cut shortthe YAML block says how many comments there are

The decisions behind it

The review mode rests on the ten decisions below. They are like the decision records of a project: each says what was chosen and why, and stays until a review changes it. Versions and rounds has what each round asked.

  1. Reading first. The review mode opens with a button and closes with the same one; closed, it leaves nothing on the page but that button. Added in round 6.
  2. One reviewer, one browser. The comments are kept in the browser's localStorage, and nothing is sent anywhere. Another phone, or clearing the site's data, starts with no comments: the export is the way out.
  3. Comments belong to a version. Version 2 of a page starts with no comments; the ones on version 1 stay with version 1. A version is a commit that changed the page's source: git counts them, so a page needs no number of its own. Changed in version 9.
  4. A comment points at text, the words selected and a few around them, not at a place in the HTML. When the words are no longer on the page, the comment is kept and the export says so.
  5. One kind of comment. A comment is a note on the words selected, or on the whole page when nothing is selected (Page note). To ask for new words, the note says Replace with: and the new text; to drop them, Remove. Changed in rounds 3, 4 and 6.
  6. Nothing to save. What is typed is kept as it is typed, and a comment left empty is dropped. The comment the arrows stop on is the one open: there is no Edit, Save or Cancel. Added in round 6.
  7. The export goes through the clipboard. The text can be edited before it goes. Copy copies the text only: a chat message has a limit, and screenshots written into the text go past it. Each screenshot has a Copy image of its own, to paste in the chat after the text; or attach them from the phone's photos. Where the clipboard is blocked (inside an artifact it can be), select the text in its box and copy by hand. There is no Share: on a phone, sharing to Claude opens a new session, outside the project the page belongs to. Changed in rounds 1, 2, 3 and 6.
  8. The bar is at the bottom, the comment box at the top. The thumb reaches the bottom of a phone; the box to write in is at the top, where the keyboard does not cover it, and is kept small, so the words it is about stay in view under it. Changed in rounds 2 and 6.
  9. A screenshot is pasted in the note, like text: no button to press. It is kept in the browser too, made smaller (900 pixels wide, JPEG), next to the comments; a tap shows it large. A browser keeps about 5 MB for a site, some twenty screenshots: when it is full, the bar says so, and exporting and clearing makes room. Added in round 1, changed in rounds 3 and 6.
  10. Git keeps the versions. A page is one notebook, and its old versions are its commits: the export names the commit it was made on, so the agent sees what changed since with git diff. Versions 1 to 8 of this post were a notebook each, built as pages of their own; that was part of the experiment, and ended when the review mode went on every page. Changed in version 9.

The bar and the comment box

While reviewing, a bar stays at the bottom of the screen:

The comment box at the top holds the comment that is open, and nothing else: no buttons. The bar keeps working while it is open, so › takes the box to the next comment. Every button is at least 44 pixels high, the size a finger hits. On a phone, tapping a button can clear the selection before the button sees it, so the page keeps the selection as soon as it is made.

The export

The export is for two readers, the reviewer who checks it before pasting it, and the agent that applies it. JSON would be easy for the second and tiring for the first. Markdown is easy for both, and a chat shows it well: a title, a block of YAML that holds what a program needs (which page, which source file, which version and commit, how many comments), and each comment a short section with its place, the heading it is under, the words as a quote, and the note.

# Review of “Review mode”, version 9

```yaml
format: nimib-review/4
title: "Review mode"
page: "https://pietroppeter.github.io/tabelline/devlog/review-mode/"
source: "docs/devlog/review_mode.nim"
version: "9"
commit: "1a2b3c4"
exported: "2026-11-10T06:40:00.000Z"
comments: 2
```

## 1. On the whole page

Shorter: half the sections could be one paragraph.

## 2. In “The bar and the comment box” (#the-bar-and-the-comment-box)

> Every button is at least 44 pixels high, the size a finger hits.

Around it: “…s the box to the next comment. ⟦Every button is at least 44 pixels high, the size a finger hits.⟧ On a phone, tapping a button ca…”

Remove

Screenshots: review-v9-2-1.jpg

The quote is the text as the page shows it, so the agent searches the source for it (without the Markdown marks) and uses the words around it when it appears more than once. A comment with screenshots adds a line that names them (Screenshots: review-v9-2-1.jpg). Copy copies the text alone, and each screenshot is copied by its own button, under the text.

Where a comment points

A page is rebuilt from its source every time it changes, so a path in the HTML (the third paragraph of the second section) breaks as soon as a paragraph is added above it. What stays is the text. A comment keeps the words selected, the 32 characters before and after them, and the heading they are under: the same idea as the text quote selector of the W3C Web Annotation model.

To find a comment again, the page looks for every place the words appear, and keeps the one whose surroundings match best: the is everywhere, the followed by page and preceded by opens is in one place.

Keeping the comments

The comments of a page are kept in the browser, under one key per page and version (nimib-review:devlog/review-mode@v9 for this one). Reload the page, close the browser, come back tomorrow: they are still there, marked on the text. Nothing leaves the phone until the export. To start from nothing, open History from the export: it clears the comments of one version, or every comment of the review mode in this browser.

Processing an export: a skill

An export pasted in the chat should be enough: no instructions around it. A skill teaches the agent what to do with one. The five steps below are a summary; the whole skill is .claude/skills/nimib-review/SKILL.md, in this repository for now (it can move elsewhere once it works).

  1. read the YAML block, and check that the number of comments matches the sections: a long paste can arrive cut short, and the count is how the agent notices;
  2. see what changed since the review, git diff <commit> -- <source>, and find each quote in the source, knowing that it is rendered text (no Markdown marks, and the text of a table is made by code, not written in the notebook);
  3. make the changes in the page's source: the commit that holds them is the next version;
  4. rebuild and check the page on a phone;
  5. answer by theme, not in the order of the comments: each theme says what was asked and what changed, or the question it raises; comments that only say something works go in a section of their own.

Saving each round's export with the page, and adding the round to a record, is something this post does (below), not a step of the skill.

Versions and rounds

This post changes in rounds: a review of a version makes the next one. A card for each version says what it changed and what its review found, and links the export of the round, saved beside the post's data (round-1.md, round-2.md). Versions 1 to 8 were a notebook each, and their cards link it as it was; since version 9 the post is one notebook, and its versions are the commits that changed it, so their card links the history of the file.

9 Nov 2026 · 09:37Version 1

What it changed: The first draft: the review mode and this post, before any review.

What its review found: Round 1: a section on the pieces of the screen is missing; typing a comment zooms the page; a comment should take screenshots; what Edit opens was unclear; the export should be editable. (3 comments)

9 Nov 2026 · 11:36Version 2

What it changed: a section on the pieces of the screen, no zoom while typing, screenshots in a comment, an export to edit before copying or sharing, Edit explained.

What its review found: Round 2: no zoom works; tapping an older version should open it; a screenshot should be pasted, not picked; the comment sheet hides the words it is about and takes too much room; the pieces of the screen should start from an annotated screenshot. (4 comments)

9 Nov 2026 · 11:56Version 3

What it changed: a compact comment sheet that slides down from the top and leaves the words in view, screenshots pasted, the whole version box a link, an annotated screenshot of the pieces of the screen.

What its review found: Round 3: the strip should show only the newest version and the one before, with a short animation; the compact sheet is better; pasting an image should just work, with no buttons; Delete belongs at the top; Cut is not clear. And the copy with screenshots inside was too long for the chat, where the front matter of the text showed as loose lines. (2 comments)

9 Nov 2026 · 13:17Version 4

What it changed: an image pasted in the note just works, no buttons; Delete in the top row; no Cut (an empty replacement removes the words); Copy copies the text only, and each screenshot has its own Copy image; the export opens with a YAML block, not a front matter, so it reads well in a chat; the strip shows only the newest version and the one before it, and moving between them is a short slide.

What its review found: Round 4: pasting an image works on an iPhone; how to write a note on the whole page; number the changes of a version, without Round 3; a heading for the idea, with screenshots in it; the assumptions read like decision records, and their opening assumed the reader knew the rounds. (6 comments)

9 Nov 2026 · 14:54Version 5

What it changed: With nothing selected, the comment button says Page note: a note on the whole page; the changes of a version are a numbered list; the idea has a heading of its own, The idea, and mentions screenshots; the assumptions are now The decisions behind it, each saying which round changed it.

What its review found: Round 5: every heading of the site should lead back to the contents; the problem assumed the reader knew these threads; the versions should say the time, and how long after the one before. (3 comments)

9 Nov 2026 · 16:04Version 6

What it changed: Every heading of the site has an arrow back to the contents; the problem says who makes the pages (coding agents, Claude Code from a phone); the table of versions gives the day and time of the first of each day, then how long after the one before.

What its review found: Round 6: no kinds, a replacement is said in the note; rethink the post from scratch, with a diagram of the modes and the stories the review mode serves; a Review button that opens and closes the mode, and no review UI without it; a sheet with no buttons that saves by itself; screenshots that open large; History instead of Clear all; Share opens a new session, outside the project; How it is built from zero, starting from nimib. (27 comments)

10 Nov 2026 · 06:35Version 7

What it changed: reading is the default, and a Review button beside the version opens and closes the review mode; outside it, no bar and no marks; no kinds: a replacement is written in the note; the comment the arrows stop on is open in a sheet with no buttons, which saves as you type; a screenshot opens large with a tap; History lists the versions and clears their comments; no Share, since it opens a new session; the post rethought from scratch, with a diagram of the modes and the stories they serve; How it is built starts from nimib.

What its review found: Round 7: the date above the title reads badly; the pieces of the screen should come before the modes, one card per screen, History too; Close review in the export; sheet is not a clear name; the table of versions is unreadable; the folded code looks like headings; the review mode deserves a module of its own, in English, and a simpler call; the skill keeps versions and rounds that only this post needs, and its answers should be grouped. (22 comments)

10 Nov 2026 · 06:35Version 8

What it changed: the date the post was written above the title, the last update beside the version; the pieces of the screen before the modes, one card per screen, History included; Close review in the export too; the sheet is now the comment box; the versions are cards; folded code reads show code; the review mode is a module of its own, review.nim, in English, and nbReview() needs no arguments; the skill keeps versions and rounds only for pages that ask for them, and answers by theme.

What its review found: No round on the page: the API was discussed in the chat, and became the change review-mode-api, now in the specs of the review mode: the newest version by default, or only the newest; the version from git; the review mode on every page; devlog posts take edits.

10 Nov 2026Version 9

What it changed: The review mode is on every page of the site, and its version comes from git: a commit that changes a page is its next version, and the export names it; the post is one notebook, and versions 1 to 8 are linked as they were, in git; History lists only the versions with comments in this browser; the export is nimib-review/4.

What its review found: Waiting for the ninth round.

How it is built

The review mode exists because the page is a nimib notebook. A nimib notebook is a Nim program that writes its page from blocks: text, code, tables, and any block a project adds of its own. So the review mode is a block: one line in the notebook puts a script, its settings and its styles in the page. And a notebook knows its own source file, which is how an export can tell the agent which file to change. Another framework could do the same; this one is done with nimib. Three parts: where it lives, how a page turns it on, and the script.

Where it lives

FileWhat it holds
docs/review.nimA module of its own, with English names, that can move to nimib: the blocks (nbReview turns the review mode on, nbVersion puts the version line somewhere else, nbInReview holds blocks shown only while reviewing), the version from git, and their styles, reviewCss, from the page's colours or plain ones.
docs/blocks.nimuseTabelline, which every page of this site calls, turns the review mode on with the shared script.
docs/assets/review.jsThe script, in nine parts (below).
.claude/skills/nimib-review/SKILL.mdThe skill that turns an export into changes.
docs/devlog/review_mode/This post's data: storia.nim, the versions and rounds; the post is docs/devlog/review_mode.nim.

A page with the review mode

A plain nimib page:

import nimib

nbInit
nbText: "# Notes\n\nSome text to review."
nbSave

The same page with the review mode is one import and one line:

import nimib
import review

nbInit
nbReview()
nbText: "# Notes\n\nSome text to review."
nbSave

nbReview() finds what it needs by itself. The source is the notebook's own file, from the root of its repository (docs/notes.nim); it goes in the export, so the agent knows which file to change. The page, which names the key the comments are kept under, is the source too. The title, also in the export, is the page's title.

The version comes from git when the page is built: the number of commits that changed the source, the last one's short hash and its day. Commit a change, build again, and the page is at the next version, with no comments yet. A page built from changes not yet committed shows the number with a + (Version 12+); a notebook outside git gets 7 characters of a hash of its source, which changes when the source does. The page shows Version 9 · updated 10 Nov 2026 under its lede, or under its title when it has none, with ✎ Review beside it; nbVersion() puts that line where it is called instead. Blocks inside nbInReview: show only while reviewing, as New in this version does on this page.

By default the script is inlined, so a page stays one file that works anywhere, even as a claude.ai artifact. The pages of a site share one copy instead: nbReview(tscript = "../assets/review.js") writes a link to the script, and the browser loads it once for all of them.

Every page of this site has the review mode without asking for it: useTabelline, the line each page calls after nbInit for its look, calls nbReview with the shared script, and its style is in the site's shared style sheet. A page that should not have it passes review = false. This post passes reviewPage = "devlog/review-mode", so its comments keep the key they had when it was a notebook per version. The blocks, in full:

docs/review.nim 108 lines
type ReviewVersion* = object
  ## The version of a page: `number` (the commits that touched its source, `+` when the page was
  ## built from uncommitted changes; outside git, a hash of the source), the last `commit`'s short
  ## hash and its date, `updated` (both empty outside git).
  number*, commit*, updated*: string

proc reviewVersion*(commits: openArray[string], dirty = false, source = ""): ReviewVersion =
  ## The version from `git log --format=%h|%cs -- <source>`, newest first: one line per commit.
  ## No commits (outside git): the first 7 characters of a hash of the `source` text.
  if commits.len == 0:
    return ReviewVersion(number: toHex(hash(source)).toLowerAscii[^7 .. ^1])
  let last = commits[0].split('|')
  ReviewVersion(number: $commits.len & (if dirty: "+" else: ""), commit: last[0],
                updated: (if last.len > 1: parse(last[1], "yyyy-MM-dd", utc()).format("d MMM yyyy") else: ""))

proc repoRoot(file: string): string =
  var dir = file.parentDir
  while dir.len > 1 and not dirExists(dir / ".git") and not fileExists(dir / ".git"): dir = dir.parentDir
  if dirExists(dir / ".git") or fileExists(dir / ".git"): dir else: ""

proc gitVersion*(file: string): ReviewVersion =
  ## The version of `file` (a notebook) from git, at build time; see `reviewVersion`.
  let root = repoRoot(file)
  if root.len > 0:
    let rel = file.relativePath(root)
    let (log, code) = execCmdEx("git log --format=%h%x7C%cs -- " & quoteShell(rel), workingDir = root)
    if code == 0 and log.strip.len > 0:
      let (status, _) = execCmdEx("git status --porcelain -- " & quoteShell(rel), workingDir = root)
      return reviewVersion(log.strip.splitLines, dirty = status.strip.len > 0)
  reviewVersion([], source = (if fileExists(file): readFile(file) else: file))

func reviewTag*(page, title, source: string, v: ReviewVersion): string =
  ## The settings the script reads: an empty `<div id="review">` with them as data attributes.
  &"""<div id="review" hidden data-page="{esc(page)}" data-title="{esc(title)}" data-source="{esc(source)}" """ &
    &"""data-version="{esc(v.number)}" data-commit="{esc(v.commit)}" data-updated="{esc(v.updated)}"></div>"""

newNbBlock(NbReview):
  page: string
  title: string
  source: string
  number: string
  commit: string
  updated: string
  script: string     ## the script's address, or "" to inline it
  toHtml:
    reviewTag(blk.page, blk.title, blk.source, ReviewVersion(number: blk.number, commit: blk.commit, updated: blk.updated)) &
      (if blk.script.len > 0: &"""<script src="{esc(blk.script)}" defer></script>"""
       else: "<script>\ndocument.addEventListener('DOMContentLoaded', function () {\n" & reviewJs & "});\n</script>")

func `$`*(v: ReviewVersion): string =
  &"version: {v.number}, commit: {v.commit}, updated: {v.updated}"

type ReviewSettings* = object
  ## What the export names: `page` (the key the comments are kept under), `source` and `title`.
  page*, source*, title*: string

func `$`*(s: ReviewSettings): string =
  &"page: {s.page}\nsource: {s.source}\ntitle: {s.title}"

proc reviewSettings*(file, root: string, title: string, page = "", source = ""): ReviewSettings =
  ## The settings `nbReview` writes for the notebook `file` in the repository at `root` ("" outside
  ## git): the source is the file from the root, the page is the source; either can be given.
  let source = if source.len > 0: source
               elif root.len > 0: file.relativePath(root).replace('\\', '/')
               else: file.extractFilename
  ReviewSettings(page: (if page.len > 0: page else: source), source: source, title: title)

proc review*(nb: var Nb, page = "", title = "", source = "", script = "", css = true) =
  ## See `nbReview`. `css = false` leaves the styles out, for a site that puts `reviewCss` in
  ## its shared style sheet.
  let file = nb.doc.thisFile.string
  let s = reviewSettings(file, repoRoot(file), (if title.len > 0: title else: nb.doc.context{"title"}.getStr),
                         page, source)
  let v = gitVersion(file)
  if css:
    nb.doc.context["stylesheet"] = %(nb.doc.context["stylesheet"].getStr & "\n<style>\n" & reviewCss & "</style>")
  nb.add newNbReview(page = s.page, title = s.title, source = s.source,
                     number = v.number, commit = v.commit, updated = v.updated, script = script)

template nbReview*(tpage = "", ttitle = "", tsource = "", tscript = "") =
  ## The review mode on this page. Reading is the default: the page shows its version, from git
  ## (*Version 12 · updated 10 Nov 2026*), under its lede or title, and **✎ Review** beside it,
  ## which opens and closes the review mode. With no arguments, everything comes from the
  ## notebook: its source file (named in the export, and the key the comments are kept under in
  ## the browser), its title and its version. `tpage` keeps the key when the file is renamed;
  ## `tscript` is the address of a shared `review.js`: empty, the script is inlined and the page
  ## stays one file.
  nb.review(tpage, ttitle, tsource, tscript)

newNbBlock(NbVersion):
  toHtml:
    """<p class="rv-enter"></p>"""

template nbVersion*() =
  ## Where the version line and **✎ Review** go, when not under the lede or the title: the
  ## script writes them here.
  nb.add newNbVersion()

newNbBlock(NbInReview of NbContainer):
  toHtml:
    """<div class="rv-only">""" & nbContainerToHtml(blk, nb) & "</div>"

template nbInReview*(body: untyped) =
  ## Blocks shown only while the review mode is open, such as what is new in this version.
  let only = newNbInReview()
  nb.withContainer(only):
    body
  nb.add only

The script

docs/assets/review.js is plain JavaScript with no dependencies, in nine parts. It could be written in Nim and compiled to JavaScript; for now plain JavaScript is shorter, both to read and to load. What each part does, and its code, folded:

PartWhat it doesLines
Where a comment pointsFinds the words selected in the text of the page, with the words around them and the heading above, and finds them again later.69
Marking the textWraps the words of each comment in a mark, and puts the comments in the order of the page.42
Keeping the commentsKeeps the comments, and the mode, in the browser's localStorage, one key per page and version.24
Reading and reviewingAdds ✎ Review beside the version, and opens and closes the review mode.33
The barThe bar at the bottom: the arrows, Delete, a new comment, Export; it keeps a selection as soon as it is made.59
The comment boxOpens the comment the arrows stop on, keeps the note as it is typed, takes pasted screenshots, drops an empty comment.134
A screenshot, largeShows a screenshot as large as the screen allows.8
The exportWrites the text of every comment, and lets the reviewer copy it and each screenshot.134
HistoryLists the versions with the comments kept on each, and clears them.132
Where a comment points 69 lines
// part: anchor
// A comment points at the text it quotes, with a few words around it (as a W3C text quote
// selector does), and the heading it is under. Not at an element: the page is rebuilt from its
// source, and the text is what stays. The text of the page is its text nodes, in order.
var CONTEXT = 32;
var BLOCKS = 'p, li, h1, h2, h3, h4, pre, td, th, caption, blockquote, summary, dt, dd, div, nav';
function textIndex() {
  // a line break between blocks, so the words around a quote read "page Select", not "pageSelect"
  var nodes = [], text = '', last = null;
  var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
    acceptNode: function (n) {
      var p = n.parentNode.closest('script, style, #review');
      return p ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
    }
  });
  for (var n = walker.nextNode(); n; n = walker.nextNode()) {
    var block = n.parentNode.closest(BLOCKS);
    if (nodes.length && block !== last) text += '\n';
    last = block;
    nodes.push({ node: n, start: text.length });
    text += n.data;
  }
  return { nodes: nodes, text: text };
}
function pointToIndex(idx, container, offset) {
  if (container.nodeType === 3) {
    for (var i = 0; i < idx.nodes.length; i++)
      if (idx.nodes[i].node === container) return idx.nodes[i].start + offset;
  }
  var at = document.createRange();
  at.setStart(container, offset);
  for (var j = 0; j < idx.nodes.length; j++)   // the first text node after the point
    if (at.comparePoint(idx.nodes[j].node, 0) >= 0) return idx.nodes[j].start;
  return idx.text.length;
}
function sectionOf(node) {
  var found = { title: '', id: '' };
  root.querySelectorAll('h1, h2, h3').forEach(function (h) {
    if (h.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)
      found = { title: h.textContent.trim(), id: h.id || '' };
  });
  return found;
}
function describe(range) {
  var idx = textIndex();
  var s = pointToIndex(idx, range.startContainer, range.startOffset);
  var e = pointToIndex(idx, range.endContainer, range.endOffset);
  var quote = idx.text.slice(s, e);
  if (!quote.trim()) return null;
  return { quote: quote, prefix: idx.text.slice(Math.max(0, s - CONTEXT), s),
           suffix: idx.text.slice(e, e + CONTEXT), section: sectionOf(range.startContainer) };
}
function locate(note, idx) {
  // every place the quote is, scored by how much of its context matches; the best wins
  var best = null, bestScore = -1;
  for (var at = idx.text.indexOf(note.quote); at >= 0; at = idx.text.indexOf(note.quote, at + 1)) {
    var before = idx.text.slice(Math.max(0, at - note.prefix.length), at);
    var after = idx.text.slice(at + note.quote.length, at + note.quote.length + note.suffix.length);
    var score = common(before, note.prefix, true) + common(after, note.suffix, false);
    if (score > bestScore) { best = at; bestScore = score; }
  }
  return best === null ? null : { start: best, end: best + note.quote.length };
}
function common(a, b, fromEnd) {
  var n = 0;
  while (n < a.length && n < b.length &&
         (fromEnd ? a[a.length - 1 - n] === b[b.length - 1 - n] : a[n] === b[n])) n++;
  return n;
}
Marking the text 42 lines
// part: mark
// A located comment is drawn with <mark> around each piece of text it covers (a quote can
// cross a link or a paragraph). Marks only wrap text, so the text of the page stays the same.
function mark(note) {
  if (!note.quote) return;   // a comment on the whole page has nothing to mark
  var idx = textIndex(), at = locate(note, idx);
  note.found = !!at;
  if (!at) return;
  idx.nodes.forEach(function (n) {
    var a = Math.max(at.start, n.start) - n.start;
    var b = Math.min(at.end, n.start + n.node.data.length) - n.start;
    if (b <= a || !n.node.data.slice(a, b).trim()) return;
    if (n.node.parentNode.closest('table') && !n.node.parentNode.closest('td, th, caption')) return;
    var t = n.node;
    if (b < t.data.length) t.splitText(b);
    if (a > 0) t = t.splitText(a);
    var m = document.createElement('mark');
    m.className = 'rv-mark';
    m.dataset.id = note.id;
    t.parentNode.replaceChild(m, t);
    m.appendChild(t);
  });
}
function unmarkAll() {
  root.querySelectorAll('mark.rv-mark').forEach(function (m) {
    var p = m.parentNode;
    while (m.firstChild) p.insertBefore(m.firstChild, m);
    p.removeChild(m);
    p.normalize();
  });
}
function drawAll() {
  unmarkAll();
  notes.forEach(mark);
  var idx = textIndex();
  function place(note) {   // the page's order: a comment on the whole page first, one not found last
    if (!note.quote) return -1;
    var m = root.querySelector('mark.rv-mark[data-id="' + note.id + '"]');
    return m ? pointToIndex(idx, m.firstChild, 0) : Infinity;
  }
  notes.sort(function (a, b) { return place(a) - place(b); });
}
Keeping the comments 24 lines
// part: store
// The comments of a page live in this browser's localStorage, one key per page and version,
// so a new version starts with no comments and the old ones stay with the version they are on.
// Whether the review mode is open is kept too, so a page opens the way it was left.
var PREFIX = 'nimib-review:', KEY = PREFIX + page.page + '@v' + page.version;
var MODE = 'nimib-review-mode:' + page.page;
function read(key) {
  try { return JSON.parse(localStorage.getItem(key)) || []; } catch (e) { return []; }
}
function save() {
  try {
    localStorage.setItem(KEY, JSON.stringify(notes.map(function (n) {
      return { id: n.id, kind: n.kind, quote: n.quote, prefix: n.prefix, suffix: n.suffix,
               section: n.section, text: n.text, replacement: n.replacement, at: n.at, images: n.images,
               commit: n.commit || page.commit || '' };
    })));
    full = false;
  } catch (e) { full = true; }   // the browser's storage is full: screenshots take the most
}
function remember(on) {
  try { if (on) localStorage.setItem(MODE, '1'); else localStorage.removeItem(MODE); } catch (e) {}
}
var notes = read(KEY);
var current = -1, full = false, on = false;
Reading and reviewing 33 lines
// part: mode
// Reading is the default: no bar, no marks, nothing of the review mode but its version line,
// *Version 12 · updated 10 Nov 2026*, and one button beside it, Review, under the lede or the
// title (or where the page put `.rv-enter`). It opens the review mode, and closes it. Blocks
// that only matter while reviewing (`.rv-only`) show only then.
var slot = document.querySelector('.rv-enter');
if (!slot) {
  slot = document.createElement('p');
  slot.className = 'rv-enter';
  var after = root.querySelector('.lede') || root.querySelector('h1');
  if (after) after.insertAdjacentElement('afterend', slot); else root.prepend(slot);
}
if (!slot.querySelector('.rv-version')) {
  var line = document.createElement('span');
  line.className = 'rv-version';
  line.textContent = 'Version ' + page.version + (page.updated ? ' · updated ' + page.updated : '');
  slot.prepend(line);
}
var toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'rv-toggle';
slot.appendChild(toggle);
toggle.addEventListener('click', function () { setMode(!on); });
function setMode(open) {
  on = open;
  remember(on);
  document.body.classList.toggle('rv-on', on);
  toggle.textContent = on ? 'Close review' : '✎ Review';
  toggle.setAttribute('aria-pressed', on ? 'true' : 'false');
  bar.hidden = !on;
  if (on) drawAll(); else { leave(); unmarkAll(); pending = null; }
  show();
}
The bar 59 lines
// part: bar
// While reviewing, a bar stays at the bottom of the screen, where a thumb reaches on a phone:
// the previous and next comment and which one this is, delete it, a new one (*Page note* when
// nothing is selected, a note on the whole page; *Comment ✓* on the words selected), and
// export. A selection is kept as soon as it is made, because tapping a button can clear it.
var bar = document.createElement('div');
bar.className = 'rv-bar';
bar.hidden = true;
bar.setAttribute('role', 'toolbar');
bar.setAttribute('aria-label', 'Review mode');
bar.innerHTML =
  '<button type="button" data-do="prev" aria-label="Previous comment">‹</button>' +
  '<span class="rv-count" aria-live="polite"></span>' +
  '<button type="button" data-do="next" aria-label="Next comment">›</button>' +
  '<button type="button" data-do="delete" aria-label="Delete this comment">Delete</button>' +
  '<button type="button" data-do="add" class="rv-add">Page note</button>' +
  '<button type="button" data-do="export">Export</button>';
document.body.appendChild(bar);
var pending = null;
document.addEventListener('selectionchange', function () {
  if (!on) return;
  var sel = document.getSelection();
  if (sel.rangeCount && !sel.isCollapsed && root.contains(sel.getRangeAt(0).commonAncestorContainer)) {
    pending = describe(sel.getRangeAt(0));
  } else {
    setTimeout(function () { if (document.getSelection().isCollapsed) { pending = null; show(); } }, 400);
  }
  show();
});
bar.addEventListener('pointerdown', function (e) { e.preventDefault(); });   // keep the selection
bar.addEventListener('click', function (e) {
  var b = e.target.closest('button');
  if (!b) return;
  var act = b.dataset.do;
  if (act === 'prev' || act === 'next') step(act === 'next' ? 1 : -1);
  if (act === 'delete' && notes[current]) remove(notes[current]);
  if (act === 'add') add();
  if (act === 'export') openExport();
});
root.addEventListener('click', function (e) {   // a tap on marked words opens them, anywhere else closes
  if (!on || !document.getSelection().isCollapsed) return;
  var m = e.target.closest('mark.rv-mark');
  if (m) {
    var n = notes.find(function (x) { return x.id === m.dataset.id; });
    if (n) select(n);
  } else if (current >= 0 && !e.target.closest('a, button')) leave();
});
function show() {
  var c = bar.querySelector('.rv-count');
  c.textContent = full ? 'storage full: export'
                : notes.length ? (current >= 0 ? (current + 1) + '/' : '') + notes.length : 'none';
  bar.querySelector('[data-do="prev"]').disabled = !notes.length;
  bar.querySelector('[data-do="next"]').disabled = !notes.length;
  bar.querySelector('[data-do="delete"]').disabled = current < 0;
  var add = bar.querySelector('.rv-add');
  add.textContent = pending ? 'Comment ✓' : 'Page note';   // says what it will do: on the words, or on the page
  add.classList.toggle('rv-selected', !!pending);
  add.setAttribute('aria-label', pending ? 'Comment on the selected text' : 'Comment on the whole page');
}
The comment box 134 lines
// part: sheet
// The comment that ‹ and › stop on is open in a sheet at the top of the screen: there is no
// Edit, no Save and no Cancel. What is typed is kept as it is typed; ‹ and › keep working and
// take the sheet to the next comment; a tap on the page closes it. A comment left empty is
// dropped. The sheet is small, so the words it is about stay in view under it, marked. There
// are no kinds: to replace the words, the note says so ("Replace with: ..."), or "Remove". A
// screenshot is pasted in the note, like text: the note is an editable box, so a phone offers
// to paste an image there. While the sheet is open the page may not zoom.
var viewport = document.querySelector('meta[name="viewport"]');
var looseViewport = viewport ? viewport.content : '';
function noZoom(yes) {
  if (viewport) viewport.content = yes ? looseViewport + ', maximum-scale=1' : looseViewport;
}
var sheet = document.createElement('div');
sheet.className = 'rv-panel';
sheet.hidden = true;
sheet.innerHTML =
  '<p class="rv-whole">On the whole page</p>' +
  '<div class="rv-note" contenteditable="true" role="textbox" aria-multiline="true" aria-label="Comment"' +
  ' data-placeholder="What should change, and why. To replace the words: Replace with: and the new text; ' +
  'to drop them: Remove. Paste a screenshot here too."></div>' +
  '<div class="rv-thumbs"></div>';
document.body.appendChild(sheet);
var noteBox = sheet.querySelector('.rv-note');
function add() {
  var n = Object.assign({ text: '', quote: '', prefix: '', suffix: '', section: { title: '', id: '' } }, pending || {});
  n.id = 'c' + Date.now().toString(36);
  n.at = new Date().toISOString();
  notes.push(n);
  document.getSelection().removeAllRanges();
  pending = null;
  select(n);
  noteBox.focus();
}
function select(n) {
  var was = notes[current];
  if (was && was !== n) drop(was);
  drawAll();
  current = notes.indexOf(n);
  root.querySelectorAll('mark.rv-current').forEach(function (m) { m.classList.remove('rv-current'); });
  var ms = root.querySelectorAll('mark.rv-mark[data-id="' + n.id + '"]');
  ms.forEach(function (m) { m.classList.add('rv-current'); });
  sheet.querySelector('.rv-whole').hidden = !!n.quote;
  noteBox.textContent = n.text || '';
  thumbs();
  sheet.hidden = false;
  noZoom(true);
  keepInView();
  show();
}
function step(d) {
  if (!notes.length) return;
  var target = notes[((current < 0 ? (d > 0 ? -1 : 0) : current) + d + notes.length) % notes.length];
  if (target !== notes[current]) select(target);
}
function leave() {   // close the sheet; an empty comment goes
  var n = notes[current];
  current = -1;
  sheet.hidden = true;
  noZoom(false);
  if (n) drop(n);
  root.querySelectorAll('mark.rv-current').forEach(function (m) { m.classList.remove('rv-current'); });
  show();
}
function empty(n) { return !(n.text || '').trim() && !(n.images || []).length && n.replacement == null; }
function drop(n) { if (empty(n)) { notes = notes.filter(function (x) { return x !== n; }); save(); drawAll(); } }
function remove(n) {
  notes = notes.filter(function (x) { return x !== n; });
  save();
  current = -1;
  sheet.hidden = true;
  noZoom(false);
  drawAll();
  show();
}
function keepInView() {   // the marked words, just under the sheet
  var m = root.querySelector('mark.rv-current');
  if (!m) return;
  var under = sheet.offsetHeight + 24;
  window.scrollBy({ top: m.getBoundingClientRect().top - under, behavior: 'smooth' });
}
noteBox.addEventListener('input', function () {
  var n = notes[current];
  if (!n) return;
  n.text = noteBox.innerText.trim();
  save();
  show();
});
function thumbs() {
  var n = notes[current], shots = (n && n.images) || [];
  var box = sheet.querySelector('.rv-thumbs');
  box.innerHTML = '';
  box.hidden = !shots.length;
  shots.forEach(function (src, i) {
    var t = document.createElement('div');
    t.className = 'rv-thumb';
    t.innerHTML = '<img alt="screenshot ' + (i + 1) + '"><button type="button" aria-label="Remove screenshot ' + (i + 1) + '">×</button>';
    t.querySelector('img').src = src;
    t.querySelector('img').addEventListener('click', function () { zoom(src); });
    t.querySelector('button').addEventListener('click', function () {
      shots.splice(i, 1);
      n.images = shots.length ? shots : undefined;
      save(); thumbs();
    });
    box.appendChild(t);
  });
}
function shrink(blob, width, quality) {   // an image as a JPEG at most `width` pixels wide
  return new Promise(function (ok, ko) {
    var img = new Image(), url = URL.createObjectURL(blob);
    img.onload = function () {
      var k = Math.min(1, width / img.naturalWidth), c = document.createElement('canvas');
      c.width = Math.round(img.naturalWidth * k); c.height = Math.round(img.naturalHeight * k);
      c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
      URL.revokeObjectURL(url);
      ok(c.toDataURL('image/jpeg', quality));
    };
    img.onerror = ko;
    img.src = url;
  });
}
noteBox.addEventListener('paste', function (e) {   // an image goes to the screenshots, text stays plain text
  e.preventDefault();
  var n = notes[current];
  var files = [].filter.call(e.clipboardData.files || [], function (f) { return /^image\//.test(f.type); });
  Promise.all(files.map(function (b) { return shrink(b, 900, 0.72); })).then(function (srcs) {
    if (!srcs.length || !n) return;
    n.images = (n.images || []).concat(srcs);
    save(); thumbs(); keepInView(); show();
  });
  var text = e.clipboardData.getData('text/plain');
  if (text) document.execCommand('insertText', false, text);
});
noteBox.addEventListener('drop', function (e) { e.preventDefault(); });   // no images inside the text
A screenshot, large 8 lines
// part: zoom
// A tap on a screenshot, in the sheet or in the export, shows it as large as the screen allows.
var lens = document.createElement('dialog');
lens.className = 'rv-zoom';
lens.innerHTML = '<button type="button" aria-label="Close">×</button><img alt="screenshot">';
document.body.appendChild(lens);
lens.addEventListener('click', function () { lens.close(); });
function zoom(src) { lens.querySelector('img').src = src; lens.showModal(); }
The export 134 lines
// part: export
// The comments as one text, for a person and for an agent: a title, a YAML block that says which
// page, version and source they are on, then one Markdown section per comment, in page order.
// The text can be edited before it is copied. Copy copies the text only, short enough for a
// chat message; each screenshot has a Copy of its own, to paste after it. Close review ends the
// review here too, so a long page need not be scrolled back to its top.
function yaml(s) { return JSON.stringify(String(s)); }   // a JSON string is a YAML string
function flat(s) { return s.replace(/\s+/g, ' '); }
function quoted(s) { return flat(s).trim(); }
function fence(s) {
  var f = '~~~';
  while (s.indexOf(f) >= 0) f += '~';
  return f + 'text\n' + s.trim() + '\n' + f;
}
var exportVersion = '';   // the version being exported, when it is not this one
function shotName(i, k) { return 'review-v' + (exportVersion || page.version) + '-' + (i + 1) + '-' + (k + 1) + '.jpg'; }
function exportText(list, version, commit) {
  // a chat shows a pasted text as Markdown: a yaml fence is a tidy box under the title.
  // By default the comments of this version; History exports those of an older one, with the
  // commit they were written on, and says which of them this version no longer has.
  list = list || notes; version = version || page.version;
  commit = commit === undefined ? page.commit || '' : commit;
  var out = ['# Review of “' + page.title + '”, version ' + version, '',
    '```yaml',
    'format: nimib-review/5',
    'title: ' + yaml(page.title),
    'page: ' + yaml(location.origin + location.pathname),
    'source: ' + yaml(page.source),
    'version: ' + yaml(version),
    'commit: ' + yaml(commit),
    'exported: ' + yaml(new Date().toISOString()),
    'comments: ' + list.length,
    '```', ''];
  list.forEach(function (n, i) {
    var where = !n.quote ? 'On the whole page'
              : n.section && n.section.title ? 'In “' + n.section.title + '”' + (n.section.id ? ' (#' + n.section.id + ')' : '')
              : 'At the top';
    out.push('## ' + (i + 1) + '. ' + where, '');
    if (n.from && n.from !== version) out.push('From version ' + n.from + (n.commit ? ' (commit ' + n.commit + ')' : '') + '.', '');
    if (n.quote) {
      out.push('> ' + quoted(n.quote), '');
      out.push('Around it: “…' + flat(n.prefix) + '⟦' + flat(n.quote) + '⟧' + flat(n.suffix) + '…”', '');
      if (n.found === false) out.push('(Not found on the page any more.)', '');
    }
    // a comment kept from version 6 or before may still have a kind of its own
    if (n.kind === 'cut' || (n.kind === 'replace' && !(n.replacement || '').trim())) out.push('Remove these words.', '');
    else if (n.kind === 'replace') out.push('Replace with:', '', fence(n.replacement), '');
    if (n.text) out.push(n.text, '');
    if (n.images) out.push('Screenshots: ' + n.images.map(function (src, k) { return shotName(i, k); }).join(', '), '');
  });
  return out.join('\n');
}
var box = document.createElement('dialog');
box.className = 'rv-sheet rv-export';
box.innerHTML =
  '<form method="dialog"><p class="rv-where">Export: edit it if you like, then copy it</p>' +
  '<textarea rows="12" spellcheck="false"></textarea><div class="rv-shotlist"></div>' +
  '<div class="rv-actions"><button value="history" class="rv-left">History</button>' +
  '<button value="leave">Close review</button><button value="close">Close</button>' +
  '<button value="copy" class="rv-save" autofocus>Copy</button></div></form>';
document.body.appendChild(box);
var area = box.querySelector('textarea');
var exportList = null;
function openExport(list, version, commit) {
  if (current >= 0) leave();
  exportList = list || null; exportVersion = list ? version : '';
  area.value = exportText(list, version, commit);
  shotList();
  noZoom(true);
  box.showModal();
}
box.addEventListener('close', function () { noZoom(false); });
function allShots() {
  var all = [];
  (exportList || notes).forEach(function (n, i) { (n.images || []).forEach(function (src, k) { all.push({ name: shotName(i, k), src: src }); }); });
  return all;
}
function shotList() {   // each screenshot, with its own Copy: paste it in the chat after the text
  var list = box.querySelector('.rv-shotlist');
  var canCopy = !!(navigator.clipboard && window.ClipboardItem);
  list.innerHTML = '';
  var all = allShots();
  list.hidden = !all.length;
  all.forEach(function (shot) {
    var row = document.createElement('div');
    row.className = 'rv-shot';
    row.innerHTML = '<img alt=""><span></span><button type="button">Copy image</button>';
    row.querySelector('img').src = shot.src;
    row.querySelector('img').addEventListener('click', function () { zoom(shot.src); });
    row.querySelector('span').textContent = shot.name;
    var b = row.querySelector('button');
    b.hidden = !canCopy;
    b.addEventListener('click', function () {
      copied(b, navigator.clipboard.write([new ClipboardItem({ 'image/png': png(shot.src) })]));
    });
    list.appendChild(row);
  });
}
function png(src) {   // the clipboard takes PNG images everywhere, JPEG not always
  return new Promise(function (ok, ko) {
    var img = new Image();
    img.onload = function () {
      var c = document.createElement('canvas');
      c.width = img.naturalWidth; c.height = img.naturalHeight;
      c.getContext('2d').drawImage(img, 0, 0);
      c.toBlob(ok, 'image/png');
    };
    img.onerror = ko;
    img.src = src;
  });
}
function copied(button, promise) {
  var label = button.textContent;
  return promise.then(function () {
    button.textContent = 'Copied ✓';
    setTimeout(function () { button.textContent = label; }, 1500);
  }, function () { button.textContent = 'Blocked'; });
}
box.querySelector('form').addEventListener('submit', function (e) {
  var act = e.submitter && e.submitter.value;
  if (act === 'copy') {
    e.preventDefault();
    var button = e.submitter;
    var fallback = function () { area.select(); document.execCommand('copy'); };
    copied(button, navigator.clipboard ? navigator.clipboard.writeText(area.value).catch(fallback)
                                       : Promise.resolve().then(fallback));
  } else if (act === 'history') {
    e.preventDefault();
    box.close();
    openHistory();
  } else if (act === 'leave') {   // the end of a review: back to reading, from the bottom of the page too
    setMode(false);
  }
});
History 131 lines
// part: history
// The versions of the page that have comments in this browser, this one first. The comments
// of an older version can be brought here (those whose words this version still has) or
// exported, with the commit they were written on; Export everything exports the comments of
// every version. Old versions are not pages: git keeps them. Clearing the comments of a
// version asks twice, with a second tap (confirm() is blocked inside an artifact).
var hist = document.createElement('dialog');
hist.className = 'rv-sheet rv-history';
hist.innerHTML =
  '<form method="dialog"><p class="rv-where">History: the versions of this page</p>' +
  '<ol class="rv-versions"></ol>' +
  '<div class="rv-actions"><button value="all" class="rv-left">Export everything</button>' +
  '<button value="export">Export</button><button value="close" class="rv-save" autofocus>Close</button></div></form>';
document.body.appendChild(hist);
function stored() {   // the versions of this page that have comments in this browser
  var found = {};
  try {
    for (var i = 0; i < localStorage.length; i++) {
      var k = localStorage.key(i), m = k.match(/@v([^@]+)$/);
      if (m && k.indexOf(PREFIX + page.page + '@v') === 0) found[m[1]] = read(k).length;
    }
  } catch (e) {}
  return found;
}
function twice(button, label, act) {   // the first tap asks, the second does
  if (button.dataset.sure === 'yes') { act(); return; }
  button.dataset.sure = 'yes';
  button.textContent = label;
}
function bringHere(version) {
  // the comments of an old version that this version still has (their words, found with their
  // context, or a comment on the whole page) move here; the others stay where they were
  var key = PREFIX + page.page + '@v' + version, old = read(key), stay = [], moved = 0;
  unmarkAll();
  var idx = textIndex(), ids = notes.map(function (n) { return n.id; });
  old.forEach(function (n) {
    if (n.quote && !locate(n, idx)) { stay.push(n); return; }
    while (ids.indexOf(n.id) >= 0) n.id = n.id + 'x';   // two ids made in the same millisecond
    ids.push(n.id);
    notes.push(n); moved++;
  });
  save();
  try {
    if (stay.length) localStorage.setItem(key, JSON.stringify(stay)); else localStorage.removeItem(key);
  } catch (e) {}
  drawAll(); show();
  return { moved: moved, left: stay.length };
}
function exportAll() {
  // every comment of this page in this browser, this version's first, then the older ones,
  // newest first, each saying the version it was written on and whether it is still found
  var counts = stored(), idx = textIndex(), list = [];
  var versions = Object.keys(counts).filter(function (v) { return v !== page.version; })
    .sort(function (a, b) { return (parseInt(b, 10) || 0) - (parseInt(a, 10) || 0); });
  notes.forEach(function (n) { list.push(n); });
  versions.forEach(function (v) {
    read(PREFIX + page.page + '@v' + v).forEach(function (n) {
      n.from = v;
      if (n.quote) n.found = !!locate(n, idx);
      list.push(n);
    });
  });
  hist.close();
  openExport(list, page.version, page.commit || '');
}
function exportOld(version) {
  var list = read(PREFIX + page.page + '@v' + version);
  var idx = textIndex();
  list.forEach(function (n) { n.from = version; if (n.quote) n.found = !!locate(n, idx); });
  var commits = list.map(function (n) { return n.commit || ''; }).filter(function (c) { return c; });
  hist.close();
  openExport(list, version, commits.length ? commits[commits.length - 1] : '');
}
function openHistory() {
  var list = hist.querySelector('.rv-versions'), counts = stored();
  var all = [{ n: page.version }];
  Object.keys(counts).forEach(function (n) { if (n !== page.version) all.push({ n: n }); });
  // this one first, then the others, newest first (a number from git, `12+` for a local build)
  all.sort(function (a, b) {
    if (a.n === page.version) return -1;
    if (b.n === page.version) return 1;
    return (parseInt(b.n, 10) || 0) - (parseInt(a.n, 10) || 0);
  });
  list.innerHTML = '';
  all.forEach(function (v) {
    var li = document.createElement('li'), n = counts[v.n] || 0, here = v.n === page.version;
    li.innerHTML = '<b></b> <span class="rv-date"></span> <span class="rv-n"></span>' +
      '<span class="rv-old"><button type="button" value="bring">Bring here</button>' +
      '<button type="button" value="export">Export</button></span>' +
      '<button type="button" class="rv-danger">Clear</button>';
    var old = li.querySelector('.rv-old');
    old.hidden = here || !n;
    old.querySelector('[value="bring"]').addEventListener('click', function (e) {
      var r = bringHere(v.n);
      openHistory();
      var said = r.moved + ' brought here' + (r.left ? ', ' + r.left + ' not found: they stay on v' + v.n : '');
      hist.querySelector('.rv-where').textContent = 'History: ' + said;
    });
    old.querySelector('[value="export"]').addEventListener('click', function () { exportOld(v.n); });
    li.querySelector('b').textContent = 'v' + v.n;
    li.querySelector('.rv-date').textContent = here ? (page.updated || '') + ' · this one' : '';
    li.querySelector('.rv-n').textContent = n ? n + (n === 1 ? ' comment' : ' comments') : '';
    var b = li.querySelector('.rv-danger');
    b.hidden = !n;
    b.addEventListener('click', function () {
      twice(b, 'Delete ' + n + '?', function () {
        try { localStorage.removeItem(PREFIX + page.page + '@v' + v.n); } catch (e) {}
        if (here) { notes = []; leave(); drawAll(); show(); }
        openHistory();
      });
    });
    list.appendChild(li);
  });
  hist.querySelector('.rv-where').textContent = 'History: the versions of this page';
  if (!hist.open) hist.showModal();
}
hist.querySelector('form').addEventListener('submit', function (e) {
  var act = e.submitter && e.submitter.value;
  if (act === 'all') {
    e.preventDefault();
    exportAll();
  } else if (act === 'export') {
    e.preventDefault();
    hist.close();
    openExport();
  }
});

var wasOn = false;
try { wasOn = localStorage.getItem(MODE) === '1'; } catch (e) {}
setMode(wasOn);