UI without documents: every page a node, the library root the first; moving, copying, exporting and importing any node

The page has one head for whatever node is the page (crumbs from the library's title, a byline of
sections and nodes, its flags and ⋯); in panes the first pane is the page and every other pane has
a section's head, whatever node it shows. A prompt (a node whose sections cite its sentences) is
folded wherever it shows. The library root's sections open in place like any others; an address
outside the hoisted node un-hoists to the library, and Esc at a hoisted page's top steps out to its
parent's.

What acts on a node and everything under it acts on the node the reader is on (the focused
section, or the one a focused note or selection is in): M moves it under any node (the jump box as
a picker, the root offered too), /duplicate copies it just after itself, /export saves it, /import
reads a file in as its last child (place() prefixes the titles down to the parent), /linkhere scans
it, S lists its links (on the root, the whole library's), history's f filters to it and r reverts
it. Every node's ⋯ offers them.

The documents menu, its mode and keys, /new, /open, /rename and /linkdoc are gone; m is free and
the top bar's left is a plain label with the library's name. Addresses are /n/<node id>, and / the
root; an old /doc/ address shows the library.

Server: /api/docs gives way to /api/nodes/<id>/{tree,export,import}; link jobs take scope "node" or
"library" and pending lists ?node=<id>&subtree=1. Step-1 shims removed: docOf/documents, all of
core/library.ts (IMPORT_MAX and importTree move to seed.ts, address and resolve to address.ts),
docArg, and the old single-document replica check. revertDocTo is revertSubtreeTo.

The page scrolls the focus into view only when the focus, the page or the mode changed, not on a
render for something that arrived in the background; row flags give way on a narrow screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 01:49:12 -05:00
1 parent e6e4ad8d26
commit bed47c0c7a
31 files changed
+789 -1153

No files matched your search

+62 -63
View File
@@ -5,10 +5,11 @@ phrase and word can be opened further. The first levels are written ahead of tim
instantly; past them, a model writes the expansion on request. Everything is editable, by you or
by a model, and the tree is versioned like git.
All documents live in one library: a single versioned tree whose root is the library and whose
sections are the documents, so a node can move from one document to another and reading goes from
one to the next without closing anything. The first document is this project describing itself,
grown from the prompt that started it; a set of starter documents (`library/*.md`) comes with it.
Everything is a node of one library: a single versioned tree whose root is the library itself.
Any node, with everything under it, can be moved under any other, copied, saved to a file, or
given a file's tree under it, and reading goes from one place to the next without closing
anything. The first tree is this project describing itself, grown from the prompt that started it;
a set of starter trees (`library/*.md`) comes with it.
## Run it
@@ -32,8 +33,8 @@ use on their own machine.
| `CLAUDE_CODE_OAUTH_TOKEN` | unset | A subscription token, used when no API key is set. A token put in `ANTHROPIC_API_KEY` by mistake is moved here. |
| `IE_MODEL` | `claude-opus-5-5` | Model for every call. |
| `IE_LLM` | `claude` with a key, `subscription` with a token, else `off` | `mock`: a deterministic stand-in (the tests). |
| `IE_DATA` | `.data` | Where the library and its caches are kept. Delete it to start again from the seed and the starter documents. |
| `IE_LIBRARY` | `library` | Starter documents, each imported once. |
| `IE_DATA` | `.data` | Where the library and its caches are kept. Delete it to start again from the seed and the starter trees. |
| `IE_LIBRARY` | `library` | Starter trees (`.md` files in the text format), each imported once. |
| `IE_USER` | your login name | The name on commits the server makes for you (the page lets you change yours with `/user`). |
| `IE_WIKI` | `live` | `mock`: built-in test articles, no network (the browser tests); `off`: every `/api/wiki/*` route answers 503. |
| `IE_HOSTS` | (none) | Extra host names the dev server answers to, comma-separated. `localhost` and `*.ts.net` (Tailscale) are always allowed. |
@@ -41,7 +42,7 @@ use on their own machine.
| `IE_WIKI_CONTACT` | unset | An email address, an `https://` URL or `User:Name` for the User-Agent of Wikipedia requests. Without it requests are spaced 6.5 s apart (the page says so once, the first time it is slow); with it, 1 s. Nothing else about you is sent. |
| `IE_WEB` | `on` when a model is configured | `off` takes web search and fetch away from the editor agent, whatever the page asks. |
| `IE_WEB_SEARCHES`, `IE_WEB_FETCHES` | `5`, `5` | Searches and page reads one request to the editor may make. |
| `IE_REVIEW_CALLS` | `50` | Model calls the link reviewer may make in one `/linkdoc` or `/linkall` (each call judges up to 60 links). What is left past the cap waits for you. |
| `IE_REVIEW_CALLS` | `50` | Model calls the link reviewer may make in one `/linkhere` or `/linkall` (each call judges up to 60 links). What is left past the cap waits for you. |
| `IE_EMBED` | on | Local embeddings for link discovery (bge-small, loaded on first use in a worker thread, about 560 MB of memory). `off`: links are found by text alone. `fake`: hashed words, no download (the tests). |
| `IE_EMBED_MODEL` | `Xenova/bge-small-en-v1.5` | Downloaded once into `IE_DATA/models/`. `Snowflake/snowflake-arctic-embed-xs` is a drop-in alternative. |
| `IE_EMBED_THREADS` | `4` | ONNX threads for the embedding model. |
@@ -66,15 +67,18 @@ Press `?` for every key. The short version:
- `c` edits, `r` renames, `a` adds, `D` deletes, `u` undoes (the last edit made in this tab,
wherever it was). `p` locks a node: the model never rewrites a locked node (your own edits lock
it). Locking is not pinning: a pin (`P`) keeps a pane open in the panes view. On a node, `:` hands an instruction to the editor agent; `Esc` stops it.
- `g` opens history: commits, branches, conflicts. `f` shows only what touched the current
document; `r` reverts the current document to a commit, leaving the rest of the library alone.
- The library is the first page. `l` or `Enter` opens a document in place; `h` or `Esc` at its top
steps back out. `/` jumps to any section in any document.
- `m` (or a click on the title) opens the documents menu: type to filter, `Enter` opens. `Esc`
moves to the list, where `n` makes a document, `r` renames, `s` duplicates, `D` deletes (`u`
brings it back), `x` saves it as a `.md` file and `i` imports one (dropping a file on the menu
works too). From the command bar: `/new`, `/open`, `/rename`, `/duplicate`, `/export`,
`/import`. All of these are ordinary edits of the library, made in the browser's replica.
- `g` opens history: commits, branches, conflicts. `f` shows only what touched the node you are on
and what is under it; `r` reverts that node and what is under it to a commit, leaving the rest of
the library alone (on the library root, the whole library goes back).
- The library root is the first page, a node like any other: `l` or `Enter` opens one of its
sections in place, `a` adds one, `z` makes a node the whole page and `h` or `Esc` at its top steps
out to its parent's page. `/` jumps to any section anywhere in the library.
- What acts on a node and everything under it acts on the node you are on (the focused section,
or the one a focused note or selection is in), anywhere in the tree: `M` moves it under any other
node (a picker like the jump box; the library root is offered too), `/duplicate [title]` copies
it just after itself, `/export` saves it as a `.md` file, `/import` reads a `.md` file into it as
its last child, `/linkhere` looks for links in it. Each is in the `⋯` menu of any node, and each
is an ordinary edit of the library, made in the browser's replica (`u` undoes it).
- Edits are saved as they are made; the top bar says `saved` once the server has them all.
- **With a mouse or a finger.** Everything a reader needs is reachable without the keys, and each
control names its key, so the mouse teaches the keyboard. A click on a sentence selects it and a
@@ -84,8 +88,8 @@ Press `?` for every key. The short version:
on words, a row, a link, a note or a pane opens what can be done with it, Copy first (Shift+right-
click is the browser's own menu); so does the `⋯` beside a row, a pane's pin, a page's byline or a
note, shown only when pointed at, and a stale flag. The top bar, which stays at the top, has
`undo`, `redo` when there is something to redo, and `menu` (documents, jump, history, links,
layout and settings). Keys named in the status line or a panel's head are buttons. On a phone the
`undo`, `redo` when there is something to redo, and `menu` (jump, history, links, layout and
settings); on its left, the library's name. Keys named in the status line or a panel's head are buttons. On a phone the
bar sits at the foot of the screen and menus rise from it. Every item acts by pressing its key
(`src/ui/press.ts`), so a click and a key cannot do different things. The first visit says, once,
in the status line, that a click on a sentence offers actions and `?` lists the keys. Left to the
@@ -94,15 +98,16 @@ Press `?` for every key. The short version:
that no menu lists (`/branch`, `/switch`, `/merge`, `/user`, `/link`, …), which the menu's
Command line… opens for typing.
- On a window 900 px wide or more, a laptop's too, the page opens as panes side by side, after
Andy Matuschak's notes: the library, the open document, its open sections. `v` switches between
Andy Matuschak's notes: the library, then each open node in a pane of its own. `v` switches between
panes and the single column, `/view auto|column|panes` sets it.
- **Opening.** `Enter`, `l` or a click on a row, a link, a link in an article, or a "Linked from",
"Mentioned in" or Related row opens its target in the next column, beside what is already open
there (so do Ctrl-, Cmd- and middle clicks); `Shift+Enter` or a Shift-click opens it in place of
the focused branch's pane there, closing that pane and what was opened from it. Opening what is
open already focuses it; a second `Enter` on an open row keeps it (closing is `q`'s or the x's).
A document chosen in the menu, or by `/open`, opens in place of the one open. Moving back left
with `h` closes nothing.
The first pane is the page, headed with its crumbs and byline; every other pane has a section's
head, whatever node it shows, and one opened by a jump names the titles above it. Moving back
left with `h` closes nothing.
- **Columns.** Column d holds every pane at depth d, top to bottom, in the order of what they were
opened from: by where their parents stand, then by where in the parent each was opened from, so a
pane opened from higher up stands higher (and curves cross as little as they can). A column divides
@@ -176,7 +181,7 @@ Press `?` for every key. The short version:
write a note on the words, which is a note like any other (`Enter` steps into it; `c`, `D`, `f`,
`u`, `:` the editor). Wikipedia's text itself cannot be edited: keys that would edit it say why not. The notes
belong to the article, so they show wherever it is opened. The library keeps a node per annotated
article in a container that is not a document (not listed, never scanned for links, never
article in a container that is not one of the root's sections (not listed, never scanned for links, never
reconciled); the article text stays in the server's cache. Each note records its section, its
words, a little text either side and the revision; in a later revision it is found again (its
section first, then anywhere, then ignoring case and punctuation), and if its words are gone it
@@ -185,13 +190,13 @@ Press `?` for every key. The short version:
- To link by hand, select words (`i`, widen with `H` `L`) and press `w`: the picker offers library
sections and notes, Wikipedia articles and, for a pasted address, the web page. `w` on a link
retargets it, `D` removes it (for good: see below); `:/link target` and `:/unlink` do the same.
- A link to a deleted node stays in the text, marked broken, with the document and section titles
it pointed to, so undoing the delete finds it again.
- A link to a deleted node stays in the text, marked broken, with the titles down to it from the
library root, so undoing the delete finds it again.
### Links found for you
- Whenever text is written (an edit saved, text a model wrote, a file imported) the server scans it
in the background: phrases that are another section's title, sections of other documents close in
in the background: phrases that are another section's title, sections in other top-level trees close in
meaning, and Wikipedia articles, each checked against the text. These scans ask Wikipedia only
after anything a person is waiting for.
- What is found is **reviewed by the model** (`/autolink review`, the default when a model is
@@ -207,7 +212,8 @@ Press `?` for every key. The short version:
declines it (remembered in the node, on every replica). `/autolink suggest` leaves every
candidate to you; `/autolink on` makes the scanner's surest links unreviewed (they measured 0.84
precision on unseen documents); `/autolink off` scans nothing by itself.
- `S` opens the **links list** of the document, beside the text: every link found or made, what
- `S` opens the **links list** of the node you are on and everything under it (on the library
root, of the whole library), beside the text: every link found or made, what
was rejected and what waits, each with who decided (the reviewer or you) and the reviewer's
reason. `1` `2` `3` (or a click) show or hide linked · rejected · pending, with their counts;
rejected is hidden at first. `j` `k` move, and the row's words are selected in the text; `y`
@@ -219,9 +225,10 @@ Press `?` for every key. The short version:
note that also links keeps the note's text).
- In the body editor `[[` opens a completer (library titles, then Wikipedia). A bare `[[term]]`
left in the text is looked up on save.
- Under the node being read, **Related** lists sections of other documents close in meaning.
- Under the node being read, **Related** lists sections elsewhere in the library close in meaning.
`1`–`5` with words selected links them to that row; on the node, goes there.
- `/linkdoc` and `/linkall` scan the document or the library in the background, with progress in
- `/linkhere` and `/linkall` scan the node you are on with everything under it, or the whole
library (as `/linkhere` does on the library root), in the background, with progress in
the status line, the reviewer's calls counted against the cap (`/linkcancel` stops; what was
reviewed is kept, and what was approved is linked).
- A model writing a note or sections is given a few nearby library nodes and may mark phrases
@@ -248,7 +255,7 @@ What is sent where:
- **With an API key**, searches and fetches are Anthropic's server tools, run by Anthropic during
the call (pages are fetched from Anthropic's servers). Fetch may only read addresses from the
request, the document sent with it, or an earlier search or fetch of the run; dynamic filtering
request, the outline sent with it, or an earlier search or fetch of the run; dynamic filtering
(which runs code) is off.
- **On a subscription**, Claude Code is given exactly WebSearch and WebFetch. WebFetch fetches the
page **from this machine** and a small model summarises it. A guard in the server refuses every
@@ -266,7 +273,7 @@ What is sent where:
parent text it was last reconciled with; a mismatch makes it stale in that direction. A person's
edits lock a node: flagged when stale (LOCKED beside it), never rewritten. `p` locks or unlocks
one by hand; the flag keeps its old name, `pinned`, in the data and the op API, so existing
libraries keep their locks. The library and its documents are not reconciled with each other.
libraries keep their locks. The library root and its sections are not reconciled with each other.
- **Snapshots are patched, not rebuilt**: a change re-reads only the nodes it wrote, so an edit
costs what it touches, whatever the size of the library.
- **`src/core/repo.ts`** Every commit records the SHA-256 of the tree, so any checkout can be
@@ -274,14 +281,14 @@ What is sent where:
node by node and what a character merge cannot see becomes a conflict record.
- **`src/llm/`** Prompts and the tasks built on them: expand a selection, deepen a leaf, cascade
after an edit (a resolver decides how far up), resolve conflicts, and the editor agent, which
works on a fork and merges back. A prompt carries the focused node's document only.
works on a fork and merges back. A prompt carries the outline of the focused node's top-level tree only.
- **`src/core/ref.ts`, `src/core/links.ts`** Targets, the backlinks index, finding a node target
again, `applyLinks`, which links a batch of spans in one commit, and the phrase key a decline
records.
- **`src/core/article.ts`, `src/ui/articleText.ts`** Notes on Wikipedia articles: the article
nodes, anchors and finding them again in a new revision; an article's HTML as text to select in.
- **`src/core/format.ts`, `seed.ts`, `library.ts`** The text format, writing a parsed tree into the
library, and the document operations and addresses.
- **`src/core/format.ts`, `seed.ts`, `address.ts`** The text format, writing a parsed tree into the
library under any node (an import), and a node's address.
- **`server/`** Relays updates between replicas and persists them (`library.ts`), proxies model
calls (`claude.ts`, `subscription.ts`, `usage.ts`, `web.ts`), Wikipedia (`wiki.ts`, `wikiHtml.ts`,
`wikiRoutes.ts`, `wikiMock.ts`), local embeddings (`embed.ts`), link discovery and its model reviewer (`links/`), and
@@ -299,28 +306,24 @@ On disk:
```
IE_DATA/library/<branch>.loro the library, one Loro snapshot per branch
IE_DATA/library.json starter documents already imported
IE_DATA/library.json starter files already imported
IE_DATA/links/pending.json link suggestions, the reviewer's verdicts and your decisions (derived)
IE_DATA/vectors/nodes.* the library's sections as vectors (derived)
IE_DATA/wiki-cache/ Wikipedia answers (derived)
IE_DATA/models/ the embedding model
```
A document is a section of the library root; nothing else marks it. Its name in an address is
made from its title (so it changes with it); nothing of it is stored.
| | |
|---|---|
| `/` | the library |
| `/doc/<name>` | a document |
| `/doc/<name>/<node id>` | a node in it (the id is what counts: a moved node is still found) |
| `/n/<node id>` | any node |
| `/` | the library root |
| `/n/<node id>` | any other node (by its id alone, so a moved or renamed node is still found) |
| `/w/<lang>/<title>` | a Wikipedia article as a page of its own (the column) |
The address follows the focus; opening a document or jumping makes a history entry.
The address follows the focus; changing the page (hoisting, stepping out) or jumping makes a
history entry. An address that names nothing, or one from before (`/doc/…`), shows the library.
On startup every `library/*.md` whose file name has not been imported before is
imported at the end of the library, so a starter document you delete stays deleted. A file that
imported at the end of the library, so a starter tree you delete stays deleted. A file that
does not parse is logged and skipped.
A data directory from an older layout (one database per document under `IE_DATA/docs/`, or a
@@ -334,7 +337,7 @@ saves each as a `.md` file.
Used for the starter library and for export and import.
```
# Document title
# Title of the tree's top
Root text: paragraphs separated by blank lines. Inline markup is only *emphasis* and `code`.
@@ -368,7 +371,8 @@ titles from the library root (`./Section` below the top of the file, `^"quote"`
or an `http(s)` address with an optional title. A target containing `: ` is quoted; in a path `\/`,
`\^` and `\\` escape a slash, a caret and a backslash. Wrapped lines join with a space; a line
ending in `\` keeps its break; a text line starting with `#`, `^` or `\` is written with a `\` in
front. Imported documents are written as the model, all reconciled, so nothing starts stale.
front. Imported trees are written as the model, all reconciled, so nothing starts stale; an import
goes under any node, and a path below the file's top (`./…`) is stored from the library root.
Export writes each note with the current text of its anchor; orphaned notes and sections under a
note have no place in the format and are left out and counted. Export then import gives back the
@@ -376,38 +380,34 @@ same tree.
### HTTP API
`<branch>` defaults to `main`. Node ids are the library's, so one batch of ops can span documents.
`<branch>` defaults to `main`. Node ids are the library's, so one batch of ops can work anywhere in it.
| | |
|---|---|
| `GET /api/tree[/<branch>]` | the whole library as JSON, with conflicts and recent history |
| `POST /api/ops[/<branch>]` | `{ ops, message?, author?, actor? }`, applied as one commit. `create` and `update` take `ref`: `{ "kind": "wiki", "title", "lang" }`, `{ "kind": "node", "id", "doc", "path" }` or `{ "kind": "url", "url", "title" }`; `"ref": null` removes it |
| `GET /api/docs` | the documents, in library order: `{ node, slug, title, excerpt }` (`slug`: the name made from the title) |
| `POST /api/docs` `{ title }` | a new blank document |
| `POST /api/docs/import?name=file.md` | body: the file (2 MB at most); 422 with `problems` if it does not parse |
| `GET` / `PATCH {title}` / `DELETE /api/docs/<name or node id>` | read, rename, delete (undoable) |
| `POST /api/docs/<name or node id>/duplicate` `{ title }` | a copy of the document |
| `GET /api/docs/<name or node id>/export[/<branch>]` | the text format; header `x-skipped` counts what was left out |
| `GET /api/docs/<name or node id>/tree[/<branch>]`, `POST /api/docs/<name or node id>/ops[/<branch>]` | one document's subtree with its conflicts; ops as above |
| `GET /api/nodes/<id>/tree[/<branch>]` | one node and everything under it, with their conflicts |
| `GET /api/nodes/<id>/export[/<branch>]` | the same in the text format; header `x-skipped` counts what was left out |
| `POST /api/nodes/<id>/import?name=file.md` | body: the file (2 MB at most), read in as the node's last child on main; 422 with `problems` if it does not parse |
| `GET /api/wiki/…` | Wikipedia through the server's cache: `summary`, `article` (`&full=1` for every section), `section`, `senses`, `suggest`, `search`, `lookup` (server/wikiRoutes.ts) |
| `POST /api/links/scan` `{ node, review? }` | scan a node and record what is found as pending; with `review`, the model reviewer judges what is new, and the approved links are handed back to be made |
| `GET /api/links/pending?doc=<name or node id>&tier=auto\|suggest&all=1&claim=1` | pending suggestions with the context a reviewer needs; `all` with every determination; `claim` hands out the approved links no page has made |
| `GET /api/links/pending?node=<id>&subtree=1&tier=auto\|suggest&all=1&claim=1` | pending suggestions with the context a reviewer needs; `all` with every determination; `claim` hands out the approved links no page has made |
| `POST /api/links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined |
| `POST /api/links/decide` `{ ids, link, by }` | record a person's decision made in their own replica |
| `POST` / `GET` / `DELETE /api/links/jobs` `{ scope: "doc" \| "library", doc?, review? }` | a background scan (reviewed, with `review`): start, progress, cancel |
| `POST` / `GET` / `DELETE /api/links/jobs` `{ scope: "node" \| "library", node?, review? }` | a background scan (reviewed, with `review`): start, progress, cancel |
| `GET /api/links/related?node=`, `/nearby?node=`, `/status` | the Related list, the nearby list a model is given, the scanner's state |
| `GET /api/state`, `/api/usage`, `/api/events`, `/api/branch/<b>`, `POST /api/sync/<b>`, `POST /api/llm/…` | what the page uses |
An outside agent reads and writes with the same ops the keyboard uses:
```sh
curl localhost:4747/api/docs/the-tides/tree
curl localhost:4747/api/nodes/<node id>/tree
curl localhost:4747/api/ops -H 'content-type: application/json' -d '{
"author": "my-agent", "message": "Add a remark",
"ops": [{ "op": "create", "parent": "<node id>", "title": "A remark", "body": "Text." }]
}'
curl localhost:4747/api/links/jobs -H 'content-type: application/json' -d '{"scope":"library"}'
curl 'localhost:4747/api/links/pending?doc=tides'
curl 'localhost:4747/api/links/pending?node=<node id>&subtree=1'
curl localhost:4747/api/links/accept -H 'content-type: application/json' -d '{"ids":["…"],"author":"reviewer"}'
```
@@ -430,16 +430,15 @@ npm run fixtures render DIR && npm run fixtures check DIR
- Undoing or reverting a deletion re-creates nodes under new ids: content, anchors and links that
carry a path are restored; anything else that referred to the old ids is not.
- Semantic conflicts are detected on every sync but resolved by a model only after an explicit
merge, and only within a document. Two replicas resolving one conflict at once conflict again.
merge, and only within one top-level tree. Two replicas resolving one conflict at once conflict again.
Two replicas pointing one link at different targets is left to a person (`1` `2` in history).
- Export cannot hold a note's title, sections under a note, or the prompt sentences the first
document's sections cite.
- Two documents with the same title share a name; the first in the library has the short address.
Two replicas linking the same words both keep their link.
- In history, the documents a commit touched are placed by where its nodes are now: a commit that
tree's sections cite.
- Two replicas linking the same words both keep their link.
- In history, the top-level nodes a commit touched are placed by where its nodes are now: a commit that
only deleted names none.
- Articles are shown without images, references or infoboxes.
- Web research: that queries never carry the document's text rests on the agent's instructions,
- Web research: that queries never carry the library's text rests on the agent's instructions,
not a check, and a cited source is checked to have been retrieved, not to say what was written.
## Third-party material
+1 -1
View File
@@ -344,7 +344,7 @@ sense or the wrong person of the same name, a library section matched on its tit
document's own quoted prompt. That reviewer is now built in (`server/links/review.ts`), and
**`/autolink review`** is the default whenever a model is configured.
**Flow.** After a scan (an edit saved, `/linkdoc`, `/linkall`) the candidates nobody has judged
**Flow.** After a scan (an edit saved, `/linkhere`, `/linkall`) the candidates nobody has judged
go to the configured model in batches of up to 60, grouped by document and section. Each proposal
carries its sentence, the section's title and path, the target's title and short description (and
the first sentence of its summary when the cache has one, never a new request), and for a library
+2 -2
View File
@@ -16,7 +16,7 @@
*/
import { readFileSync, readdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { importDoc } from "../src/core/library";
import { importTree } from "../src/core/seed";
import { Doc, ancestorsBelowRoot, sections, type NodeId, type Snap } from "../src/core/model";
import { embedder } from "../server/embed";
import { extract } from "../server/links/extract";
@@ -35,7 +35,7 @@ const LABELS = resolve("tests/fixtures/link-labels.json");
// The whole starter library, so that titles under other tops can be matched as they would be.
const doc = Doc.library("eval");
const byFile = new Map<string, NodeId>();
for (const f of readdirSync("library").filter((x) => x.endsWith(".md")).sort()) byFile.set(f.replace(/\.md$/, ""), importDoc(doc, readFileSync(join("library", f), "utf8"), f, { creator: "eval" }));
for (const f of readdirSync("library").filter((x) => x.endsWith(".md")).sort()) byFile.set(f.replace(/\.md$/, ""), importTree(doc, readFileSync(join("library", f), "utf8"), f, { creator: "eval" }));
const snap = doc.snap();
const words = (s: string) => s.split(/\s+/).filter(Boolean).length;
+39 -80
View File
@@ -6,18 +6,18 @@
* In development it also hosts Vite; in production it serves the built files.
*
* The whole library is one database: /api/tree, /api/ops, /api/sync… act on all of it, and
* /api/docs lists the root's children, with a few routes scoped to one. See README.md for the list.
* /api/nodes/<id>/… on one node and what is under it. See README.md for the list.
*/
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { userInfo } from "node:os";
import { extname, join, resolve } from "node:path";
import { VersionVector } from "loro-crdt";
import { IMPORT_MAX, createDoc, deleteDoc, duplicateDoc, findTop, importDoc, listDocs, renameDoc, topName } from "../src/core/library";
import { Doc, OpError, descendants, topOf, type NodeId, type Op, type Snap } from "../src/core/model";
import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model";
import { encodeVV, history } from "../src/core/repo";
import { FormatError, serializeDoc } from "../src/core/format";
import { writeSeed } from "../src/core/seed";
import { IMPORT_MAX, importTree, writeSeed } from "../src/core/seed";
import { slugify } from "../src/core/text";
import { mockLLM } from "../src/llm/mock";
import { LLMUnavailable, type JsonReq, type LLM, type Req, type TurnReq } from "../src/llm/types";
import { seed } from "../src/seed/tree";
@@ -159,7 +159,6 @@ function needLLM(): LLM {
if (!llm) throw new LLMUnavailable();
return llm;
}
const titleOf = (v: unknown) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, 200) : "");
/** A server-side write to a branch: saved shortly and announced to every replica. */
function wrote(branch: string) {
@@ -167,15 +166,6 @@ function wrote(branch: string) {
announce({ branch, from: "api" });
}
/** One document's entry in the listing. */
const entry = (snap: Snap, id: NodeId) => listDocs(snap).find((d) => d.node === id)!;
/** A subtree on its own, as the tree route returns the library. */
function subtree(snap: Snap, id: NodeId) {
const ids = new Set([id, ...descendants(snap, id)]);
return { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])) };
}
async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
const parts = url.pathname.split("/").slice(2).map(decodeURIComponent); // after /api/
const [a, b] = parts;
@@ -188,7 +178,6 @@ async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
model: llm?.model ?? null,
library: store.id,
branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })),
docs: store.list(),
migrated: store.migrated(),
wiki: wikiState,
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off",
@@ -238,7 +227,7 @@ async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
}
}
if (a === "docs") return docsApi(req, res, url, parts.slice(1));
if (a === "nodes") return nodeApi(req, res, url, parts.slice(1));
if (["events", "branch", "sync", "tree", "ops"].includes(a)) return libraryApi(req, res, url, a, b);
if (await handleWiki(req, res, url)) return;
if (url.pathname.startsWith("/api/links/")) nodeIndex.activate();
@@ -331,27 +320,38 @@ async function opsApi(req: IncomingMessage, res: ServerResponse, name: string) {
}
/**
* /api/docs: the root's children, by node id or name (TEMPORARY: step 3 removes it). Creating,
* renaming, copying and deleting one are ordinary commits on main; the browser makes the
* same commits in its own replica.
* One node and everything under it, by its id: the subtree as JSON with its conflicts, the text
* format as a download, or a file in the text format imported under it. An import is an ordinary
* commit on main; the browser makes the same commits in its own replica.
*/
async function docsApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) {
async function nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) {
const method = req.method ?? "GET";
const [slug, action, branch] = parts;
const main = store.main;
if (!slug) {
if (method === "GET") return json(res, 200, store.list());
if (method === "POST") {
const title = titleOf((await readJson<{ title?: string }>(req)).title);
if (!title) return json(res, 400, { error: "a new document needs a title" });
const id = createDoc(main, title, USER);
wrote("main");
return json(res, 201, entry(main.snap(), id));
}
const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined];
const name = branch || "main";
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
const doc = store.branches.get(name);
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
const snap = doc.snap();
if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` });
// GET /api/nodes/<id>/tree[/<branch>]: the subtree, as /api/tree returns the library.
if (action === "tree" && method === "GET") {
const ids = new Set([id, ...descendants(snap, id)]);
return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) });
}
// POST /api/docs/import?name=file.md, with the file as the body.
if (slug === "import" && !action && method === "POST") {
const name = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md";
// GET /api/nodes/<id>/export[/<branch>]: the text format, as a download.
if (action === "export" && method === "GET") {
const { text, skipped } = serializeDoc(snap, id);
res.writeHead(200, {
"content-type": "text/markdown; charset=utf-8",
"content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`,
"x-skipped": JSON.stringify(skipped),
});
return res.end(text);
}
// POST /api/nodes/<id>/import?name=file.md, with the file as the body: a new last child of the node (on main).
if (action === "import" && !branch && method === "POST") {
const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md";
let text: string;
try {
text = (await readBody(req, IMPORT_MAX)).toString("utf8");
@@ -359,58 +359,17 @@ async function docsApi(req: IncomingMessage, res: ServerResponse, url: URL, part
if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` });
throw err;
}
const main = store.main;
if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` });
try {
const id = importDoc(main, text, name, { creator: USER });
const top = importTree(main, text, file, { creator: USER, parent: id });
wrote("main");
return json(res, 201, entry(main.snap(), id));
return json(res, 201, { node: top, title: main.snap().nodes[top].title });
} catch (err) {
if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems });
throw err;
}
}
const name = branch || "main";
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
const doc = store.branches.get(name);
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
const id = findTop(doc.snap(), slug);
if (!id) return json(res, 404, { error: `no such document: ${slug}`, missing: "document" });
if (!action) {
if (method === "GET") return json(res, 200, entry(doc.snap(), id));
if (method === "PATCH") {
const title = titleOf((await readJson<{ title?: string }>(req)).title);
if (!title) return json(res, 400, { error: "a title is needed" });
renameDoc(main, id, title, USER);
wrote("main");
return json(res, 200, entry(main.snap(), id));
}
if (method === "DELETE") {
deleteDoc(main, id, USER);
wrote("main");
return json(res, 200, { deleted: slug });
}
}
if (action === "duplicate" && method === "POST") {
const title = titleOf((await readJson<{ title?: string }>(req)).title) || `${main.snap().nodes[id].title} (copy)`;
const copy = duplicateDoc(main, id, title, USER);
wrote("main");
return json(res, 201, entry(main.snap(), copy));
}
// GET /api/docs/<slug>/export[/<branch>]: the text format, as a download.
if (action === "export" && method === "GET") {
const { text, skipped } = serializeDoc(doc.snap(), id);
res.writeHead(200, {
"content-type": "text/markdown; charset=utf-8",
"content-disposition": `attachment; filename="${topName(doc.snap().nodes[id].title)}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`,
"x-skipped": JSON.stringify(skipped),
});
return res.end(text);
}
if (action === "tree" && method === "GET") {
const snap = doc.snap();
return json(res, 200, { ...subtree(snap, id), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && snap.nodes[x] && topOf(snap, x) === id)) });
}
if (action === "ops" && method === "POST") return opsApi(req, res, name);
json(res, 404, { error: "not found" });
}
@@ -481,7 +440,7 @@ createServer(async (req, res) => {
}).listen(PORT, "127.0.0.1", () => {
const nodes = Object.keys(store.main.snap().nodes).length;
console.log(`Infinispand http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`);
console.log(`library: ${store.list().length} top-level sections, ${nodes} nodes, opened in ${startMs} ms`);
console.log(`library: ${store.titles().length} top-level sections, ${nodes} nodes, opened in ${startMs} ms`);
console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`);
console.log(
`wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`,
+6 -5
View File
@@ -6,15 +6,14 @@
* <data>/library.json starter files already imported (by file name), so a deleted one stays deleted
*
* Branch names are percent-encoded into file names, so no request can name a file outside it.
* Writes are gathered for a moment before they go to disk: with every document in one file, a
* Writes are gathered for a moment before they go to disk: with the whole library in one file, a
* save per keystroke would rewrite the whole library each time. Replicas keep what has not been
* saved and send it again, so a crash loses nothing that a browser still holds.
*/
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { FormatError } from "../src/core/format";
import { listDocs } from "../src/core/library";
import { Doc } from "../src/core/model";
import { Doc, tops } from "../src/core/model";
import { writeText } from "../src/core/seed";
import { slugify } from "../src/core/text";
import { SEED_KEY, migrate } from "./migrate";
@@ -56,8 +55,10 @@ export class LibraryStore {
return this.main.libraryId ?? "";
}
list() {
return listDocs(this.main.snap());
/** The titles of the root's children on main, in order. */
titles(): string[] {
const snap = this.main.snap();
return tops(snap).map((id) => snap.nodes[id].title);
}
/** What the migration recorded, for browsers that still hold replicas of the old documents. */
+6 -6
View File
@@ -1,5 +1,5 @@
/**
* Scanning a document or the whole library in the background: one job at a time, a node at a
* Scanning a node and everything under it, or the whole library, in the background: one job at a time, a node at a
* time, at bulk priority (a person's own requests to Wikipedia go first), with progress announced
* and a cancel. Lookups are gathered across the next few nodes and asked together, 50 phrases a
* request, which is most of what keeps a bulk pass affordable. A job started with `review` also has
@@ -18,9 +18,9 @@ import type { Linker, Suggestion } from "./scan";
export interface JobState {
id: string;
scope: "doc" | "library";
/** The document scanned, for a document job. */
doc?: NodeId;
scope: "node" | "library";
/** The node scanned (with everything under it), for a node job. */
node?: NodeId;
title: string;
state: "running" | "done" | "cancelled" | "failed";
done: number;
@@ -61,14 +61,14 @@ export class Jobs {
) {}
/** Start a job over these nodes (in reading order). A running job is cancelled first. */
start(scope: "doc" | "library", nodes: NodeId[], title: string, doc?: NodeId, review = false): JobState {
start(scope: "node" | "library", nodes: NodeId[], title: string, node?: NodeId, review = false): JobState {
this.cancel();
const wiki = this.o.wiki();
const spacing = wiki?.spacingMs ?? 0;
const state: JobState = {
id: Math.random().toString(36).slice(2, 10),
scope,
...(doc ? { doc } : {}),
...(node ? { node } : {}),
title,
state: "running",
done: 0,
+24 -21
View File
@@ -7,8 +7,9 @@
* stored for it, with determinations. review ("all", or "unmarked" to leave out [[marks]],
* which a person typed) has the model reviewer judge what is undecided; `apply` is then the
* approved links handed to the caller to make, and `review` the reviewer's report
* GET /api/links/pending ?doc=<top's id or name>&node=<id>&tier=auto|suggest&limit=&offset=&all=1&claim=1
* → { total, suggestions: [{ …, nodeTitle, top, path, sentence }], apply? };
* GET /api/links/pending ?node=<id>&subtree=1&tier=auto|suggest&limit=&offset=&all=1&claim=1
* → { total, suggestions: [{ …, nodeTitle, top, path, sentence }], apply? }; node alone is
* that node, with subtree=1 everything under it too, and without node the whole library;
* all=1 lists every entry whatever was decided, with its determinations; claim=1 hands
* out the approved links no page has made yet (in `apply`), to be made by the caller
* POST /api/links/accept { ids, author? } → applied with applyLinks as one commit by "linker"
@@ -17,7 +18,8 @@
* GET /api/links/related ?node=<id> → { related, degraded }; or POST { node, text, title, top, topTitle, ancestors }
* GET /api/links/nearby ?node=<id>&k=5 → { nearby: [{ handle, title, top }] } (hybrid search on the node);
* or POST { node, text, title, ancestors }
* POST /api/links/jobs { scope: "doc" | "library", doc?, review? } → the job's state (doc: a top's id or name); it runs in the background
* POST /api/links/jobs { scope: "node" | "library", node?, review? } → the job's state (node: a node's id, scanned with
* everything under it; on the library root, the whole library); it runs in the background
* (with review, the model reviewer judges what it finds, within IE_REVIEW_CALLS calls)
* GET /api/links/jobs → { job } (the current or last one)
* DELETE /api/links/jobs → cancel the running job
@@ -27,8 +29,7 @@
*/
import type { IncomingMessage, ServerResponse } from "node:http";
import { applyLinks, type LinkSpec } from "../../src/core/links";
import { findTop } from "../../src/core/library";
import { descendants, isLibraryRoot, tops, type Doc, type NodeId, type Op, type Snap } from "../../src/core/model";
import { descendants, isLibraryRoot, label, tops, type Doc, type NodeId, type Op, type Snap } from "../../src/core/model";
import type { Embedder } from "../embed";
import { HttpError, abortOnClose, readJson as readBody, sendJson as send } from "../util";
import type { Jobs } from "./jobs";
@@ -57,12 +58,12 @@ class Bad extends HttpError {
const readJson = <T>(req: IncomingMessage) => readBody<T>(req, 4 * 1024 * 1024);
/** A child of the root by its node id or name (TEMPORARY: step 2 scopes by any node). */
const docArg = (snap: Snap, v: string | null): NodeId | null => (v ? (findTop(snap, v) ?? null) : null);
/** The nodes of a top's tree (or of the library), in reading order: sections and notes with text. */
export function scopeNodes(snap: Snap, doc: NodeId | null): NodeId[] {
const roots = doc ? [doc] : tops(snap);
/**
* A node and everything under it (or, for none or the library root, the whole library but the
* Wikipedia container), in reading order: the sections and notes with text.
*/
export function scopeNodes(snap: Snap, node: NodeId | null): NodeId[] {
const roots = node && !isLibraryRoot(snap, node) ? [node] : tops(snap);
const out: NodeId[] = [];
for (const r of roots) for (const id of [r, ...descendants(snap, r)]) if (snap.nodes[id].body.trim() && !isLibraryRoot(snap, id)) out.push(id);
return out;
@@ -99,10 +100,10 @@ export function linkRoutes(deps: LinkDeps) {
return send(res, 200, { ...r, entries: deps.pending.of(input.node), apply, review: report }), true;
}
if (route === "pending" && method === "GET") {
const docId = docArg(snap, url.searchParams.get("doc"));
if (url.searchParams.get("doc") && !docId) throw new Bad(`no document ${url.searchParams.get("doc")}`);
const node = url.searchParams.get("node") as NodeId | null;
const scope = node ? new Set([node]) : docId ? new Set(scopeNodes(snap, docId)) : undefined;
const subtree = url.searchParams.get("subtree") === "1";
if (node && subtree && !snap.nodes[node]) throw new Bad(`no node ${node}`);
const scope = node ? new Set(subtree ? scopeNodes(snap, node) : [node]) : undefined;
const tier = url.searchParams.get("tier");
const all = url.searchParams.get("all") === "1";
const apply = url.searchParams.get("claim") === "1" ? deps.pending.claim(snap, scope ?? scopeNodes(snap, null)) : undefined;
@@ -160,13 +161,15 @@ export function linkRoutes(deps: LinkDeps) {
if (method === "GET") return send(res, 200, { job: deps.jobs.current }), true;
if (method === "DELETE") return send(res, 200, { cancelled: deps.jobs.cancel(), job: deps.jobs.current }), true;
if (method === "POST") {
const input = await readJson<{ scope?: string; doc?: string; review?: boolean }>(req);
if (input.scope !== "doc" && input.scope !== "library") throw new Bad('scope is "doc" or "library"');
const docId = input.scope === "doc" ? docArg(snap, input.doc ?? null) : null;
if (input.scope === "doc" && !docId) throw new Bad(`no document ${input.doc ?? ""}`);
const nodes = scopeNodes(snap, docId);
const title = docId ? snap.nodes[docId].title : "the library";
return send(res, 202, { job: deps.jobs.start(input.scope, nodes, title, docId ?? undefined, input.review === true) }), true;
const input = await readJson<{ scope?: string; node?: string; review?: boolean }>(req);
if (input.scope !== "node" && input.scope !== "library") throw new Bad('scope is "node" or "library"');
const id = input.scope === "node" ? ((input.node ?? "") as NodeId) : null;
if (id !== null && !snap.nodes[id]) throw new Bad(`no node ${input.node ?? ""}`);
// The library root is the whole library, as a library job.
const at = id && !isLibraryRoot(snap, id) ? id : null;
const nodes = scopeNodes(snap, at);
const title = at ? label(snap, at) : "the library";
return send(res, 202, { job: deps.jobs.start(at ? "node" : "library", nodes, title, at ?? undefined, input.review === true) }), true;
}
}
if (route === "status" && method === "GET") {
+24
View File
@@ -0,0 +1,24 @@
/**
* Where a node is, as the page's address: `/` is the library root, `/n/<node id>` any other node.
* The id is all there is to it, so an address survives renames and moves.
*/
import type { NodeId, Snap } from "./model";
export function address(snap: Snap, id: NodeId): string {
if (!snap.nodes[id] || id === snap.root) return "/";
return `/n/${encodeURIComponent(id)}`;
}
/** The node a path names, or why there is none. */
export function resolve(snap: Snap, path: string): { node: NodeId } | { missing: string } {
let parts: string[];
try {
parts = path.split("/").filter(Boolean).map(decodeURIComponent);
} catch {
return { missing: `no page ${path}` };
}
if (!parts.length) return { node: snap.root };
const [kind, id] = parts;
if (kind === "n" && parts.length === 2) return snap.nodes[id as NodeId] ? { node: id as NodeId } : { missing: `no node ${id}` };
return { missing: `no page ${path}` };
}
-107
View File
@@ -1,107 +0,0 @@
/**
* Importing a file into the library, and (until step 2 of the move to nodes only removes them) the
* UI's document features: the root's children listed, created, renamed, copied, deleted and
* addressed. Each is an ordinary op on that subtree, so the server and the browser share this file
* and every one of them is a commit that syncs, versions and undoes like any other edit.
*
* TEMPORARY (step 2 deletes everything here but IMPORT_MAX and importDoc): `DocInfo`, `listDocs`,
* `createDoc`, `renameDoc`, `duplicateDoc`, `deleteDoc`, `topName`, `findTop`, `address`, `resolve`.
* Nothing is stored for them: a top's name in an address is made from its title.
*/
import { Doc, retitleOps, topOf, tops, type NodeId, type Snap } from "./model";
import { writeText, type BuildOptions } from "./seed";
import { clip, paragraphs, plain, slugify } from "./text";
/** Largest .md file an import accepts. */
export const IMPORT_MAX = 2 * 1024 * 1024;
/** A child of the root, as the documents menu lists it. */
export interface DocInfo {
/** Its node. */
node: NodeId;
/** Its name in an address (`topName`), not stored. */
slug: string;
title: string;
/** The first paragraph of its text, plain and clipped. */
excerpt: string;
}
function excerpt(body: string): string {
const first = paragraphs(body)[0];
return first ? clip(plain(body.slice(first[0], first[1])), 160) : "";
}
/** A top's name in an address: made from its title, so it changes with it. */
export const topName = (title: string) => slugify(title) || "untitled";
/** The root's children, in library order. */
export function listDocs(snap: Snap): DocInfo[] {
return tops(snap).map((id) => {
const n = snap.nodes[id];
return { node: id, slug: topName(n.title), title: n.title, excerpt: excerpt(n.body) };
});
}
/** A child of the root by its node id, or else by its name (the first with that name). */
export function findTop(snap: Snap, name: string): NodeId | undefined {
const all = tops(snap);
return all.find((d) => d === name) ?? all.find((d) => topName(snap.nodes[d].title) === name);
}
/** A new, empty child of the root at its end (or at `index`). */
export function createDoc(doc: Doc, title: string, author: string, index?: number): NodeId {
const snap = doc.snap();
return doc.as(author, () => doc.apply([{ op: "create", parent: snap.root, index, title, body: "" }], `New “${clip(title, 60)}”`).created[0]);
}
export function renameDoc(doc: Doc, id: NodeId, title: string, author: string) {
doc.as(author, () => doc.apply(retitleOps(doc.snap(), id, title), `Rename to “${clip(title, 60)}”`));
}
/** Save as: a copy of the whole subtree, placed after the original, under a new title. */
export function duplicateDoc(doc: Doc, id: NodeId, title: string, author: string): NodeId {
const snap = doc.snap();
const index = snap.nodes[snap.root].children.indexOf(id) + 1;
return doc.as(author, () =>
doc.apply([{ op: "copy", id, parent: snap.root, index, title }], `Duplicate “${clip(snap.nodes[id].title, 40)}” as “${clip(title, 40)}”`).created[0],
);
}
/** An ordinary delete: `u` brings it back. */
export function deleteDoc(doc: Doc, id: NodeId, author: string) {
const snap = doc.snap();
doc.as(author, () => doc.apply([{ op: "delete", id }], `Delete “${clip(snap.nodes[id].title, 60)}”`));
}
/** A model-authored tree from the text format, at the end of the library. Throws FormatError, writing nothing. */
export function importDoc(doc: Doc, text: string, name: string, opts: BuildOptions = {}): NodeId {
return writeText(doc, text, name, { verb: "Import", ...opts });
}
// ---- addresses ----
/**
* Where a node lives, as a path: `/` is the library, `/doc/<name>` a child of the root, and
* `/doc/<name>/<node id>` a node under it (or a child of the root whose name another one has
* too). The node id is what counts; the name, made from the top's title, is there to be read.
* `/n/<node id>` names a node with no top to put in front of it.
*/
export function address(snap: Snap, id: NodeId): string {
if (!snap.nodes[id] || (snap.library && id === snap.root)) return "/";
const d = snap.library ? topOf(snap, id) : null;
if (!d) return `/n/${encodeURIComponent(id)}`;
const name = topName(snap.nodes[d].title);
return d === id && findTop(snap, name) === id ? `/doc/${name}` : `/doc/${name}/${encodeURIComponent(id)}`;
}
/** The node a path names, or why there is none. */
export function resolve(snap: Snap, path: string): { node: NodeId } | { missing: string } {
const parts = path.split("/").filter(Boolean).map(decodeURIComponent);
if (!parts.length) return { node: snap.root };
const [kind, a, b] = parts;
const node = (x: string | undefined) => (x && snap.nodes[x as NodeId] ? (x as NodeId) : null);
if (kind === "n") return node(a) ? { node: a as NodeId } : { missing: `no node ${a ?? ""}` };
if (kind !== "doc") return { missing: `no page ${path}` };
const d = a ? findTop(snap, a) : undefined;
return node(b) ? { node: b as NodeId } : d ? { node: d } : { missing: `nothing called “${a ?? ""}”` };
}
-5
View File
@@ -900,11 +900,6 @@ export function topOf(snap: Snap, id: NodeId): NodeId | null {
return n.id;
}
/** @deprecated Temporary, for UI files untouched in step 1 (Panes.tsx, Mouse.tsx and others): step 2 removes it. */
export const docOf = topOf;
/** @deprecated Temporary, for the UI's document features: step 2 removes it. */
export const documents = tops;
// ---- staleness: computed, never stored ----
/** A node's sections, in order. The Wikipedia container (article.ts) is nobody's section. */
+6 -6
View File
@@ -173,7 +173,7 @@ function reanchor(doc: Doc, id: NodeId, was: NodeSnap, now: NodeSnap) {
/** Roll the whole tree back to a commit by writing the inverse as a new commit. History is kept. */
export function revertTo(doc: Doc, commit: Commit) {
const target = at(doc, commit).snap();
if (doc.snap().library && !target.library) throw new OpError("that commit is from before the library existed; revert one document to it instead");
if (doc.snap().library && !target.library) throw new OpError("that commit is from before the library existed; revert one node to it instead");
doc.begin(`Revert to “${clip(commit.message, 60)}”`, "human", "revert");
doc.loro.revertTo(commit.frontiers);
doc.reread();
@@ -192,12 +192,12 @@ export function revertTo(doc: Doc, commit: Commit) {
}
/**
* Roll one subtree (a document) back to how it stood at a commit, leaving the rest of the library
* as it is now. Nodes that still exist keep their ids and are moved, rewritten and re-anchored to
* match; nodes deleted since come back as copies under new ids; nodes added since are deleted.
* The document node itself stays where it is now.
* Roll one node and everything under it back to how it stood at a commit, leaving the rest of the
* library as it is now. Nodes that still exist keep their ids and are moved, rewritten and
* re-anchored to match; nodes deleted since come back as copies under new ids; nodes added since
* are deleted. The node itself stays where it is now.
*/
export function revertDocTo(doc: Doc, commit: Commit, id: NodeId) {
export function revertSubtreeTo(doc: Doc, commit: Commit, id: NodeId) {
const target = at(doc, commit).snap();
const now = doc.snap();
if (!target.nodes[id]) throw new OpError(`“${clip(label(now, id), 40)}” did not exist yet at “${clip(commit.message, 40)}”`);
+31 -11
View File
@@ -1,9 +1,9 @@
/**
* Writes a hand-written tree into the library as a new child of the root: the first one (the
* project describing itself, grown from the verbatim prompt), and every file read from the text
* format (src/core/format.ts).
* Writes a hand-written tree into the library: the first one (the project describing itself, grown
* from the verbatim prompt) as a child of the root, and every file read from the text format
* (src/core/format.ts), under the root or under any node (an import).
*/
import { healLinks } from "./links";
import { healLinks, nodeRef } from "./links";
import { Doc, type Actor, type NodeId, type Op } from "./model";
import type { Ref } from "./ref";
import type { SeedNode, SeedNote } from "../seed/types";
@@ -19,21 +19,30 @@ export interface BuildOptions {
rootActor?: Actor;
/** First word of each commit message: "Pre-generate “Section”". */
verb?: string;
/** The node the tree goes under (the library root by default), and where among its children (the end by default). */
parent?: NodeId;
index?: number;
}
/**
* Write a tree into a library as a new child of the root, at its end, through the op API: one
* commit for the tree's top, one for its notes and one per section under it. Everything was
* written together, so everything is blessed and nothing starts out stale; below the top it is
* authored as the model, so a model may later rewrite it. Returns the top's node.
* Write a tree into a library through the op API, as a new child of the root at its end, or of
* `opts.parent` at `opts.index`: one commit for the tree's top, one for its notes and one per
* section under it. Everything was written together, so everything is blessed and nothing starts
* out stale; below the top it is authored as the model, so a model may later rewrite it. Returns
* the top's node.
*/
export function writeTree(doc: Doc, top: SeedNode, opts: BuildOptions = {}): NodeId {
const verb = opts.verb ?? "Pre-generate";
// A path written relative to the file's top ("./Section") is stored from the library root.
const place = (r: Ref | undefined): Ref | undefined => (r?.kind === "node" && r.rel ? { kind: "node", path: [top.title, ...(r.path ?? [])], ...(r.quote !== undefined ? { quote: r.quote } : {}) } : r);
const snap = doc.snap();
const parent = opts.parent ?? snap.root;
if (!snap.nodes[parent]) throw new Error(`no node ${parent} to write the tree under`);
// A path written relative to the file's top ("./Section") is stored from the library root: the
// titles down to where the tree goes, then the tree's own.
const above = nodeRef(snap, parent).path ?? [];
const place = (r: Ref | undefined): Ref | undefined => (r?.kind === "node" && r.rel ? { kind: "node", path: [...above, top.title, ...(r.path ?? [])], ...(r.quote !== undefined ? { quote: r.quote } : {}) } : r);
const [root] = doc.as(opts.creator ?? "seed", () =>
doc.apply(
[{ op: "create", parent: doc.snap().root, title: top.title, body: top.body, ref: place(top.target) }],
[{ op: "create", parent, index: opts.index, title: top.title, body: top.body, ref: place(top.target) }],
`${verb} “${clip(top.title, 60)}”`,
{ actor: opts.rootActor ?? "llm", tag: "seed" },
).created,
@@ -95,3 +104,14 @@ export function writeSeed(doc: Doc, prompt: string, tree: SeedNode[]): NodeId {
export function writeText(doc: Doc, text: string, name: string, opts: BuildOptions = {}): NodeId {
return writeTree(doc, parseDoc(text, name), opts);
}
/** Largest .md file an import accepts. */
export const IMPORT_MAX = 2 * 1024 * 1024;
/**
* A file in the text format, imported as a model-authored tree under `opts.parent` (the library
* root by default), at its end unless `opts.index` says where. Throws FormatError, writing nothing.
*/
export function importTree(doc: Doc, text: string, name: string, opts: BuildOptions = {}): NodeId {
return writeText(doc, text, name, { verb: "Import", ...opts });
}
+51 -26
View File
@@ -1,11 +1,11 @@
import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "preact/hooks";
import { ancestors, ancestorsBelowRoot, docOf, label, sections, staleness, type Conflict, type NodeId } from "../core/model";
import { ancestors, isLibraryRoot, label, sections, staleness, type Conflict, type NodeId } from "../core/model";
import { verifyHistory, type Commit } from "../core/repo";
import { clip, plain } from "../core/text";
import { hostOf } from "../core/ref";
import { nodeRef } from "../core/links";
import { HELP, handleKey } from "./keys";
import { DocBar, DocsPanel } from "./Menu";
import { DocBar } from "./Menu";
import { LinkCard, LinkPicker, LinksPanel, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
import { Panes } from "./Panes";
@@ -18,15 +18,14 @@ import { press } from "./press";
function Page() {
if (store.colWiki) return <WikiPage />;
const kids = sections(store.snap, store.top);
const listing = store.snap.library && store.top === store.snap.root;
return (
<article class={store.preview ? "preview" : ""}>
<TopMatter id={store.top} />
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={store.top} />
{!listing && (store.articleUnder(store.top) ? <WikiView host={`n${store.top}`} /> : <TargetRow id={store.top} />)}
{!listing && <NodeBacklinks id={store.top} />}
{!listing && <NodeRelated id={store.top} />}
{store.articleUnder(store.top) ? <WikiView host={`n${store.top}`} /> : <TargetRow id={store.top} />}
<NodeBacklinks id={store.top} />
<NodeRelated id={store.top} />
</article>
);
}
@@ -96,12 +95,15 @@ function HistoryPanel({ verdict }: { verdict: string }) {
});
const heads = new Set<string>();
let lastType = "";
const live = store.doc.snap();
const filter = store.historyFilter && live.nodes[store.historyFilter] ? store.historyFilter : null;
const onRoot = isLibraryRoot(live, store.activeNode);
return (
<aside class="panel" ref={ref}>
<div class="panel-head">
<span>History{store.historyFilter && store.currentDoc ? ` · ${clip(store.snap.nodes[store.currentDoc]?.title ?? "", 30)}` : " · the library"}</span>
<span>History{filter ? ` · ${clip(label(store.doc.snap(), filter), 30)}` : " · the library"}</span>
<span class="keys">
<Hints hint={["j k", ["Enter", "view"], ["r", `revert${store.currentDoc ? " this document" : ""}`], ["n", "branch"], ["m", "merge"], ["f", store.historyFilter ? "everything" : "this document"], ["v", "verify"], ["Escape", "close"]]} />
<Hints hint={["j k", ["Enter", "view"], ["r", `revert ${onRoot ? "the library" : "this node"}`], ["n", "branch"], ["m", "merge"], ["f", filter ? "everything" : "this node"], ["v", "verify"], ["Escape", "close"]]} />
</span>
</div>
{verdict && <div class="verdict">{verdict}</div>}
@@ -138,7 +140,7 @@ function HistoryPanel({ verdict }: { verdict: string }) {
function CommitRow({ c, selected }: { c: Commit; selected: boolean }) {
const viewing = store.preview?.commit.id === c.id;
const snap = store.doc.snap();
const docs = store.touchedDocs(c).map((d) => snap.nodes[d]?.title ?? "");
const under = store.touchedTops(c).map((d) => snap.nodes[d]?.title ?? "");
return (
<div class={`item commit${selected ? " selected" : ""}${viewing ? " viewing" : ""}`}>
<div class="line">
@@ -152,9 +154,9 @@ function CommitRow({ c, selected }: { c: Commit; selected: boolean }) {
{c.tag ? ` · ${c.tag}` : ""}
{viewing ? " · viewing" : ""}
</div>
{docs.length > 0 && (
<div class="docs" title={docs.join(", ")}>
{docs.length > 3 ? `${docs.slice(0, 3).map((t) => clip(t, 24)).join(" · ")} · and ${docs.length - 3} more` : docs.map((t) => clip(t, 30)).join(" · ")}
{under.length > 0 && (
<div class="under" title={under.join(", ")}>
under: {under.length > 3 ? `${under.slice(0, 3).map((t) => clip(t, 24)).join(" · ")} · and ${under.length - 3} more` : under.map((t) => clip(t, 30)).join(" · ")}
</div>
)}
</div>
@@ -193,19 +195,26 @@ function Help() {
);
}
function Jump() {
/**
* The jump box (/): sections anywhere in the library, by title and text. The same box is the
* picker of Move under… (M), where it offers the library root too and never the node being moved.
*/
function Jump({ move }: { move?: boolean }) {
const [q, setQ] = useState("");
const [i, setI] = useState(0);
const hits = store.search(q);
const hits = move ? store.moveTargets(q) : store.search(q);
const snap = store.snap;
const close = () => store.setMode("normal");
const close = () => (move ? store.cancelMove() : store.setMode("normal"));
const pick = (id: NodeId) => (move ? store.moveUnder(id) : store.jumpTo(id));
const moving = move && store.moving && snap.nodes[store.moving] ? label(snap, store.moving) : "";
return (
<div class="overlay" onClick={close}>
<div class="jump" onClick={(e) => e.stopPropagation()}>
<div class={`jump${move ? " move" : ""}`} onClick={(e) => e.stopPropagation()}>
{move && <div class="jump-head">Move “{clip(moving, 50)}” and everything under it under…</div>}
<input
autoFocus
ref={(el) => el?.focus()}
placeholder="Jump to a section, in any document…"
placeholder={move ? "The node to move it under…" : "Jump to a section, anywhere in the library…"}
value={q}
onInput={(e) => (setQ((e.target as HTMLInputElement).value), setI(0))}
onKeyDown={(e) => {
@@ -213,19 +222,27 @@ function Jump() {
if (e.key === "Escape") close();
else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) (e.preventDefault(), setI(Math.min(hits.length - 1, i + 1)));
else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) (e.preventDefault(), setI(Math.max(0, i - 1)));
else if (e.key === "Enter" && hits[i]) store.jumpTo(hits[i]);
else if (e.key === "Enter" && hits[i]) pick(hits[i]);
}}
/>
<ul>
{hits.map((id, k) => {
const d = docOf(snap, id);
const within = ancestorsBelowRoot(snap, id).reverse().slice(1);
// Where it is: the titles down to it from the library root, the first of them bold.
const path = ancestors(snap, id).reverse().slice(1);
return (
<li key={id} class={k === i ? "selected" : ""} onClick={() => store.jumpTo(id)}>
<li key={id} class={k === i ? "selected" : ""} data-hit={id} onClick={() => pick(id)}>
<span class="t">{label(snap, id)}</span>
<span class="p">
{d && d !== id ? <b class="in">{snap.nodes[d].title}</b> : <b class="in">document</b>}
{within.length ? ` › ${within.map((a) => snap.nodes[a].title).join(" › ")}` : ""}
{isLibraryRoot(snap, id) ? (
<b class="in">the library root</b>
) : path.length ? (
<>
<b class="in">{snap.nodes[path[0]].title}</b>
{path.length > 1 ? ` › ${path.slice(1).map((a) => snap.nodes[a].title).join(" › ")}` : ""}
</>
) : (
<b class="in">{label(snap, snap.root)}</b>
)}
</span>
</li>
);
@@ -438,6 +455,8 @@ function StatusLine() {
// ---- the app ----
let hover: ReturnType<typeof setTimeout> | undefined;
/** The focus last scrolled into view (App's layout effect). */
let shownFocus = "";
export function App() {
const [, tick] = useReducer((x: number) => x + 1, 0);
@@ -508,8 +527,14 @@ export function App() {
useLayoutEffect(() => {
if (!store.ready) return;
const f = store.focus;
// The panes keep their own focus in view (Panes.tsx).
// Only when the focus, the page or the mode has changed: a render for something that arrived
// in the background (a list fetched, a scan's suggestions) leaves the page where the reader
// scrolled it. The panes keep their own focus in view (Panes.tsx).
const key = JSON.stringify([f, store.aux, store.mode, store.panes, store.top, store.colWiki?.title]);
const moved = key !== shownFocus;
shownFocus = key;
const el =
moved &&
!store.panes &&
((f.grain !== "node" && document.querySelector(".sel")) ||
document.querySelector(`[data-row="${CSS.escape(f.node)}"]`) ||
@@ -705,7 +730,7 @@ export function App() {
};
return (
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "docs" || store.mode === "review" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "review" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
<main
class="page"
onClick={onClick}
@@ -722,10 +747,10 @@ export function App() {
{panes ? <Panes /> : <Page />}
</main>
{store.mode === "history" && <HistoryPanel verdict={verdict} />}
{store.mode === "docs" && <DocsPanel />}
{store.mode === "review" && <LinksPanel />}
{store.mode === "help" && <Help />}
{store.mode === "jump" && <Jump />}
{store.mode === "move" && <Jump move />}
{store.mode === "command" && <CommandBar prefill={prefill} />}
{store.mode === "link" && store.picker && <LinkPicker />}
<Popup />
+34 -21
View File
@@ -6,7 +6,7 @@
import { Fragment, createContext } from "preact";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { ownerSection, resolveNode } from "../core/links";
import { docOf, isLink, label, type NodeId } from "../core/model";
import { isLibraryRoot, isLink, label, topOf, type NodeId, type Snap } from "../core/model";
import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref";
import { clip, plain } from "../core/text";
import { kidClass, sameAux, store, type Aux } from "./store";
@@ -17,15 +17,21 @@ import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion
const MARK: Record<Ref["kind"], string> = { wiki: "W", node: "§", url: "↗" };
/** The document a node target is in, for its mark's tooltip. */
/** Where a node is, in a word: the title of the top-level node it is under, or for a top-level node itself, the library's. */
export function whereIs(s: Snap, id: NodeId): string {
const t = topOf(s, id);
return t && t !== id ? s.nodes[t].title : label(s, s.root);
}
/** Where a node target is, for its mark's tooltip. */
function where(r: Ref): string {
if (r.kind === "wiki") return `Wikipedia: ${r.title}`;
if (r.kind === "url") return hostOf(r.url);
const s = store.snap;
const id = resolveNode(store.snap, r);
if (!id) return "a note that is gone";
const d = docOf(s, id);
return `${label(s, id)}${d && d !== id ? ` · in ${s.nodes[d].title}` : ""}`;
const t = topOf(s, id);
return `${label(s, id)}${t && t !== id ? ` · in ${s.nodes[t].title}` : ""}`;
}
/** The mark set after linked words. Not text of the body: it carries no offset and cannot be selected. */
@@ -56,7 +62,7 @@ export function Attribution({ a }: { a: Attr }) {
);
}
/** What a target is, briefly: an article's summary, a node's title, document and first lines, a page's host. */
/** What a target is, briefly: an article's summary, a node's title, where it is and first lines, a page's host. */
export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
if (r.kind === "url") {
return (
@@ -80,13 +86,13 @@ export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
</div>
);
}
const d = docOf(s, id);
const d = topOf(s, id);
const n = s.nodes[id];
const sec = ownerSection(s, id);
return (
<div class="lcard l-node">
<div class="lhead">
<span class="lmark l-node">§</span> {d ? s.nodes[d].title : "the library"}
<span class="lmark l-node">§</span> {d ? s.nodes[d].title : label(s, s.root)}
{sec !== d && n.kind === "note" ? ` › ${label(s, sec)}` : ""}
</div>
<div class="ltitle">{label(s, id)}</div>
@@ -163,7 +169,7 @@ export function useForkMark(): ((...keys: (string | undefined)[]) => string) | n
}
/**
* "Linked from": the nodes that link here, each as its section's title and its document. Collapsed
* "Linked from": the nodes that link here, each as its section's title and where it is. Collapsed
* to nothing when there are none. The same list, for an article, is "Mentioned in".
*/
export function Backlinks({ ids, title, focusedAt }: { ids: NodeId[]; title: string; focusedAt: (i: number) => boolean }) {
@@ -176,12 +182,11 @@ export function Backlinks({ ids, title, focusedAt }: { ids: NodeId[]; title: str
<ul>
{ids.map((id, i) => {
const sec = ownerSection(s, id);
const d = docOf(s, id);
const n = s.nodes[id];
return (
<li key={id} class={[focusedAt(i) && "focused", forkMark?.(`n:${sec}`)].filter(Boolean).join(" ")} data-linking={id}>
<span class="bl-title">{label(s, sec)}</span>
<span class="bl-doc">{d && d !== sec ? s.nodes[d].title : "document"}</span>
<span class="bl-doc">{whereIs(s, sec)}</span>
{n.kind === "note" && <span class="bl-quote">“{clip(n.anchors[0]?.text ?? "", 60)}”</span>}
</li>
);
@@ -205,7 +210,7 @@ export function SuggestionCard({ sg }: { sg: Sugg }) {
}
/**
* "Related": sections of other documents close in meaning to this one, derived and never stored.
* "Related": sections elsewhere in the library close in meaning to this one, derived and never stored.
* Numbered: with words of this node selected, the number links them to that section; on the node,
* it goes there.
*/
@@ -245,11 +250,10 @@ export interface Choice {
ref: Ref;
}
/** A section of the library as a choice, with the document it is in. */
/** A section of the library as a choice, with where it is. */
export function sectionChoice(id: NodeId): Choice {
const s = store.snap;
const d = docOf(s, id);
return { group: "Library", label: s.nodes[id].title || "(untitled)", sub: d && d !== id ? s.nodes[d].title : "document", ref: { kind: "node", id } };
return { group: "Library", label: s.nodes[id].title || "(untitled)", sub: whereIs(s, id), ref: { kind: "node", id } };
}
/** A Wikipedia title suggestion as a choice. */
@@ -307,8 +311,8 @@ function libraryChoices(q: string, spot: NodeId): Choice[] {
if (n.kind !== "note" || isLink(n) || !n.anchors.length) continue;
const text = (n.anchors[0].text || n.anchors[0].quote).toLowerCase();
if (!terms.every((t) => text.includes(t))) continue;
const d = docOf(s, n.id);
out.push({ group: "Library", label: `“${clip(n.anchors[0].text, 50)}”`, sub: `note in ${d ? s.nodes[d].title : "the library"} › ${label(s, ownerSection(s, n.id))}`, ref: { kind: "node", id: n.id } });
const d = topOf(s, n.id);
out.push({ group: "Library", label: `“${clip(n.anchors[0].text, 50)}”`, sub: `note in ${d ? s.nodes[d].title : label(s, s.root)} › ${label(s, ownerSection(s, n.id))}`, ref: { kind: "node", id: n.id } });
}
return out;
}
@@ -377,6 +381,9 @@ export function LinkPicker() {
// ---- the links list (S) ----
/** Rows of the links list drawn at once, around the selected one. */
const WINDOW = 200;
const FILTERS: [key: string, status: Status, label: string][] = [
["1", "linked", "linked"],
["2", "rejected", "rejected"],
@@ -397,7 +404,8 @@ function verdictLine(r: LinkRow): string {
}
/**
* The links list (S): every link found or made in the current document, as it stands, with who
* The links list (S): every link found or made in a node and everything under it (on the library
* root, the whole library), as it stands, with who
* decided and the reviewer's reason. Quiet toggles filter it by status; the selected row's words
* are selected in the text, and every key it takes is a button in its head.
*/
@@ -412,12 +420,15 @@ export function LinksPanel() {
const rows = all.filter((x) => r.show[x.status]);
const sel = store.reviewRow();
const s = store.snap;
const doc = store.currentDoc;
const count = (st: Status) => all.filter((x) => x.status === st).length;
// A whole library's list can be long: the rows around the selected one are drawn, the rest counted.
const at = Math.max(0, rows.findIndex((x) => x.key === sel?.key));
const from = Math.max(0, Math.min(at - WINDOW / 2, rows.length - WINDOW));
const shown = rows.slice(from, from + WINDOW);
return (
<aside class="panel links" ref={ref} data-links-panel>
<div class="panel-head">
<span>Links{doc ? ` · ${clip(s.nodes[doc]?.title ?? "", 30)}` : ""}</span>
<span>Links · {isLibraryRoot(s, r.node) ? "the library" : clip(label(s, r.node), 30)}</span>
<span class="keys">
<Hints hint={["j k", ...(sel?.status !== "linked" ? [["y", "link"] as [string, string]] : []), ...(sel?.status !== "rejected" ? [["n", sel?.status === "linked" ? "remove" : "decline"] as [string, string]] : []), ["Y", "link all"], ["Enter", "go"], ["Escape", "close"]]} />
</span>
@@ -432,8 +443,9 @@ export function LinksPanel() {
</Fragment>
))}
</div>
{!rows.length && <p class="lempty">{all.length ? "Nothing shown: 1 2 3 show more." : "Nothing linked or found here yet. :/linkdoc looks for links in this document."}</p>}
{rows.map((x) => (
{!rows.length && <p class="lempty">{all.length ? "Nothing shown: 1 2 3 show more." : "Nothing linked or found yet. :/linkall looks for links in the whole library, :/linkhere in the node you are on."}</p>}
{from > 0 && <p class="lmore">{from} more above</p>}
{shown.map((x) => (
<div key={x.key} class={`item lrow ${x.status}${x.key === sel?.key ? " selected" : ""}`} data-row={x.status} onClick={() => store.reviewSelect(x.key)}>
<div class="line">
<span class="lq">“{clip(x.quote, 48)}”</span>
@@ -449,6 +461,7 @@ export function LinksPanel() {
</div>
</div>
))}
{from + shown.length < rows.length && <p class="lmore">{rows.length - from - shown.length} more below</p>}
</aside>
);
}
+7 -174
View File
@@ -1,8 +1,6 @@
/** The top bar (where the reader is, and whether it is saved) and the documents menu it opens (m). */
import { useLayoutEffect, useRef, useState } from "preact/hooks";
import { clip } from "../core/text";
/** The top bar: where the reader is (the library's name) and whether it is saved, with undo and the menu. */
import { topEntries } from "./actions";
import { Hints, act, showMenu } from "./Mouse";
import { act, showMenu } from "./Mouse";
import { press } from "./press";
import { store } from "./store";
@@ -19,22 +17,12 @@ const SAVE_TITLE = {
export function DocBar() {
const state = store.saveState();
const here = store.currentDoc;
const snap = store.snap;
return (
<nav class="docbar">
<button
class="doc-title"
title="Documents (m)"
onClick={(e) => {
e.stopPropagation();
if (store.mode === "docs") store.closeMenu();
else store.openMenu();
}}
>
<span class="name">{here ? snap.nodes[here]?.title || "Untitled" : snap.nodes[snap.root].title}</span>
<span class="chev" />
</button>
<span class="lib-name" title="The library">
{snap.nodes[snap.root].title || "Library"}
</span>
<span class={`save-state ${state}`} title={SAVE_TITLE[state]}>
{SAVE_LABEL[state]}
</span>
@@ -51,12 +39,12 @@ export function DocBar() {
type="button"
class="tool"
aria-haspopup="menu"
title="Documents, history, layout and settings"
title="Jump, history, links, layout and settings"
onMouseDown={keep}
onClick={(e) => {
e.stopPropagation();
const s = store.settings;
showMenu(topEntries({ view: s.view, autolink: s.autolink, auto: s.auto, speculate: s.speculate, curves: s.curves, colors: s.colors, panes: store.panes, doc: !!store.currentDoc, canRedo: store.canRedo() }, act), e.currentTarget as HTMLElement);
showMenu(topEntries({ view: s.view, autolink: s.autolink, auto: s.auto, speculate: s.speculate, curves: s.curves, colors: s.colors, panes: store.panes, canRedo: store.canRedo() }, act), e.currentTarget as HTMLElement);
}}
>
menu<span class="chev" />
@@ -65,158 +53,3 @@ export function DocBar() {
</nav>
);
}
function TitlePrompt() {
const p = store.menu.prompt!;
const label = { new: "New document, titled", rename: "Rename to", duplicate: "Save a copy as" }[p.kind];
return (
<label class="prompt">
<span>{label}</span>
<input
ref={(el) => {
if (el && document.activeElement !== el) (el.focus(), el.select());
}}
defaultValue={p.value}
placeholder="Title"
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
store.menuSubmit((e.target as HTMLInputElement).value);
} else if (e.key === "Escape") {
e.preventDefault();
store.menu.prompt = null;
store.menu.focus = "list";
store.emit();
}
}}
/>
</label>
);
}
export function DocsPanel() {
const m = store.menu;
const items = store.menuItems();
const sel = store.menuSelected();
const current = store.currentDoc;
const ref = useRef<HTMLElement>(null);
const [dropping, setDropping] = useState(false);
useLayoutEffect(() => {
ref.current?.querySelector(".doc.selected")?.scrollIntoView({ block: "nearest" });
});
const typing = m.focus === "filter" && !m.prompt && !m.confirm;
const act = (fn: () => void) => (e: MouseEvent) => {
e.stopPropagation();
fn();
};
return (
<aside
class={`panel docs${dropping ? " dropping" : ""}`}
ref={ref}
onDragOver={(e) => (e.preventDefault(), setDropping(true))}
onDragLeave={() => setDropping(false)}
onDrop={(e) => {
e.preventDefault();
setDropping(false);
const file = e.dataTransfer?.files[0];
if (file) void store.importFile(file);
}}
>
<div class="panel-head">
<span>Documents</span>
<span class="keys">
<Hints hint={typing ? ["type to filter · ↑ ↓", ["Enter", "open"], ["Escape", "for actions"]] : ["j k", ["Enter", "open"], ["n", "new"], ["r", "rename"], ["s", "save as"], ["D", "delete"], ["x", "export"], ["i", "import"], ["/", "filter"], ["Escape", "close"]]} />
</span>
</div>
<input
class="filter"
ref={(el) => {
if (el && typing && document.activeElement !== el) el.focus();
}}
value={m.filter}
placeholder="Filter by title or text…"
onFocus={() => m.focus !== "filter" && ((m.focus = "filter"), store.emit())}
onInput={(e) => store.menuFilter((e.target as HTMLInputElement).value)}
onKeyDown={(e) => {
e.stopPropagation();
const k = e.key;
if (k === "ArrowDown" || (e.ctrlKey && (k === "n" || k === "j"))) (e.preventDefault(), store.menuMove(1));
else if (k === "ArrowUp" || (e.ctrlKey && (k === "p" || k === "k"))) (e.preventDefault(), store.menuMove(-1));
else if (k === "Enter") {
e.preventDefault();
// The selection as it is now: the filter may have changed since this was drawn.
const now = store.menuSelected();
if (now) store.openDoc(now.node, true);
} else if (k === "Escape" || k === "Tab") {
e.preventDefault();
m.focus = "list";
(e.target as HTMLInputElement).blur();
store.emit();
}
}}
/>
{m.prompt && <TitlePrompt />}
{m.confirm && (
<div class="confirm">
Delete “{clip(items.find((d) => d.node === m.confirm)?.title ?? "", 60)}” and everything in it? u brings it back.
<div class="actions">
<button onClick={act(() => store.deleteDocument(m.confirm!))}>delete (y)</button>
<button onClick={act(() => ((m.confirm = null), store.emit()))}>keep (n)</button>
</div>
</div>
)}
{m.problems && (
<div class="problems">
<b>The file was not imported:</b>
<ul>
{m.problems.slice(0, 30).map((p, i) => (
<li key={i}>{p}</li>
))}
</ul>
</div>
)}
<ul class="doclist">
{items.map((d) => {
const selected = d.node === sel?.node;
return (
<li
key={d.node}
class={`item doc${selected ? " selected" : ""}${d.node === current ? " current" : ""}`}
data-doc={d.slug}
onClick={() => {
// A click in the list hands the keys to the list.
m.selected = d.node;
m.focus = "list";
(document.activeElement as HTMLElement | null)?.blur();
store.emit();
}}
onDblClick={() => store.openDoc(d.node, true)}
>
<div class="line">
<span class="title">{d.title || "Untitled"}</span>
<span class="when">{d.node === current ? `open · ${SAVE_LABEL[store.saveState()]}` : `/doc/${d.slug}`}</span>
</div>
<div class="sub">{d.excerpt || "No text yet."}</div>
{selected && (
<div class="actions">
{d.node !== current && <button onClick={act(() => store.openDoc(d.node, true))}>open</button>}
<button onClick={act(() => store.menuPrompt("rename"))}>rename</button>
<button onClick={act(() => store.menuPrompt("duplicate"))}>save as</button>
<button onClick={act(() => store.exportDocument(d.node))}>export .md</button>
<button onClick={act(() => ((m.confirm = d.node), store.emit()))}>delete</button>
</div>
)}
</li>
);
})}
{!items.length && <li class="none">No document matches.</li>}
</ul>
<div class="panel-foot">
<button onClick={act(() => store.menuPrompt("new"))}>new document (n)</button>
<button onClick={act(() => store.pickFile())}>import .md (i)</button>
<span>or drop a .md file here</span>
</div>
</aside>
);
}
+7 -6
View File
@@ -10,9 +10,9 @@
import { Fragment, type ComponentChildren } from "preact";
import { createPortal } from "preact/compat";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { docOf, isLibraryRoot, label, staleness, type NodeId } from "../core/model";
import { isLibraryRoot, label, staleness, topOf, type NodeId } from "../core/model";
import { plain } from "../core/text";
import { articleRowEntries, barItems, nodeEntries, pageAct, pageEntries, paneEntries, selectionEntries, topEntries, type Entry, type Item, type NodeCtx, type SelCtx } from "./actions";
import { articleRowEntries, barItems, nodeEntries, pageAct, paneEntries, selectionEntries, topEntries, type Entry, type Item, type NodeCtx, type SelCtx } from "./actions";
import { press } from "./press";
import { store, type WRow } from "./store";
@@ -69,7 +69,6 @@ function nodeCtx(id: NodeId): NodeCtx {
locked: n.pinned,
target: !!store.targetOf(id),
library: isLibraryRoot(s, id),
doc: docOf(s, id) === id,
generating: store.generating,
};
}
@@ -88,7 +87,10 @@ function selCtx(): SelCtx {
link: r?.kind,
note: !!id && !!s.nodes[id].body.trim(),
suggestion: store.focusedSuggestion()?.title,
related: store.relatedOf(f.node).map((x) => ({ title: x.title, doc: s.nodes[docOf(s, x.node) ?? x.node]?.title })),
related: store.relatedOf(f.node).map((x) => {
const t = s.nodes[x.node] ? topOf(s, x.node) : null;
return { title: x.title, where: t && t !== x.node ? s.nodes[t].title : undefined };
}),
panes: store.panes,
};
}
@@ -112,7 +114,6 @@ export function menuHere(where: Where): Entry[] {
const id = store.focus.node;
if (!store.snap.nodes[id]) return [];
if (where === "pane" && store.panes) return paneEntries({ node: nodeCtx(id), pinned }, act);
if (where === "page") return pageEntries(nodeCtx(id), act);
return nodeEntries(nodeCtx(id), act);
}
@@ -524,7 +525,7 @@ export function Key({ k, what, shift }: { k: string; what: ComponentChildren; sh
return (
<button type="button" class="key" data-key={k} title={`${keyText(k)}`} onMouseDown={(e) => e.preventDefault()} onClick={(e) => {
e.stopPropagation();
// A box being typed in (the documents filter) gives the key back to the page.
// A box being typed in (the jump box, the command line) gives the key back to the page.
if ((document.activeElement as HTMLElement | null)?.matches?.("input, textarea")) (document.activeElement as HTMLElement).blur();
press(k, shift);
}}
+32 -16
View File
@@ -1,7 +1,7 @@
/** Rendering shared by both page layouts: a node's body with its notes, the outline rows, and the top of the page. */
import { Component, type ComponentChildren } from "preact";
import { useLayoutEffect, useRef, useState } from "preact/hooks";
import { anchorLost, ancestors, descendants, docOf, isLibraryRoot, label, notesOf, sections, staleness, type NodeId, type Snap } from "../core/model";
import { anchorLost, ancestors, descendants, isLibraryRoot, label, notesOf, sections, staleness, type NodeId, type Snap } from "../core/model";
import type { Ref } from "../core/ref";
import { clip, overlaps, paragraphs, plain, type Form, type Range } from "../core/text";
import { streamView } from "../core/marks";
@@ -11,7 +11,7 @@ import { store, type Pending } from "./store";
// ---- inline text ----
/** A note as the renderer sees it: one in the document, or one still being written. */
/** A note as the renderer sees it: one in the library, or one still being written. */
export interface VNote {
key: string;
id?: NodeId;
@@ -286,7 +286,7 @@ export function NodeBody({ id, inline, inNote }: { id: NodeId; inline?: boolean;
))}
{!paras.length && !inline && (
<p class="para first empty">
{isLibraryRoot(snap, id) ? "Every document is a section of this library. l or Enter opens one, a adds one, m lists them; c writes a note about the library here." : `No text yet. c to write it${store.generating ? ", e to have it written" : ""}.`}
{isLibraryRoot(snap, id) ? "This is the library, the root of everything in it. a adds a section, / jumps anywhere, :/import reads a .md file into it; c writes a note about the library here." : `No text yet. c to write it${store.generating ? ", e to have it written" : ""}.`}
</p>
)}
{orphans.map((o) => (
@@ -403,7 +403,7 @@ function SectionView({ id }: { id: NodeId }) {
<Row id={id} open={open} leaf={leaf} editing={editing} />
{open && (
<div class="content">
<NodeBody id={id} />
{isPrompt(snap, id) ? <Abstract id={id} /> : <NodeBody id={id} />}
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={id} />
<TargetRow id={id} />
@@ -426,9 +426,31 @@ export function Outline({ ids }: { ids: NodeId[] }) {
}
/**
* The head of a page or of a pane that is a page of its own: the top node, or a document. Crumbs
* (on the top only), title, byline, and the node's own text, folded if it is a prompt. The
* library's byline counts documents; a document's counts its own sections and nodes.
* Whether a node's text is a prompt: its sections cite its sentences (the first tree's top is one).
* A prompt is long, and the page should open on the outline, so it is folded until asked for.
*/
export function isPrompt(snap: Snap, id: NodeId): boolean {
return !isLibraryRoot(snap, id) && sections(snap, id).some((k) => snap.nodes[k].anchors.length > 0);
}
/** A node's own text under its head: plain, or a prompt, set apart and folded until asked for. */
export function Abstract({ id }: { id: NodeId }) {
const snap = store.snap;
const prompt = isPrompt(snap, id);
const folded = prompt && !store.unfolded.has(id) && !(store.focus.node === id && store.focus.grain !== "node") && store.edit?.node !== id;
return (
<>
<div class={`abstract${prompt ? " seed" : ""}${folded ? " folded" : ""}`} onClick={folded ? () => store.toggleFold(id) : undefined}>
<NodeBody id={id} />
</div>
{folded && <div class="unfold">{id === store.top ? "Enter" : "A click"} to read the whole prompt · every sentence of it is traced to a section below</div>}
</>
);
}
/**
* The head of a page, the same for every node: crumbs (the titles above it, from the library's
* own), title, byline (its sections and nodes, the branch, its flags and its ⋯), and its own text.
*/
export function TopMatter({ id }: { id: NodeId }) {
const snap = store.snap;
@@ -439,10 +461,7 @@ export function TopMatter({ id }: { id: NodeId }) {
const focused = store.focus.node === id;
const editing = store.edit?.node === id && store.edit.field === "title";
const library = isLibraryRoot(snap, id);
// A document whose sections cite its sentences is a prompt (the first document's is): long, and
// the page should open on the outline, so it is folded until asked for. Other text is plain.
const prompt = !library && docOf(snap, id) === id && kids.some((k) => snap.nodes[k].anchors.length > 0);
const folded = prompt && !store.unfolded.has(id) && !(focused && store.focus.grain !== "node") && store.edit?.node !== id;
// The library root's count leaves out the Wikipedia container, which is nobody's section.
const count = library ? kids.reduce((n, d) => n + 1 + descendants(snap, d).length, 0) : descendants(snap, id).length;
return (
<>
@@ -460,16 +479,13 @@ export function TopMatter({ id }: { id: NodeId }) {
<div class="byline">
{n.kind === "note"
? `a note in ${clip(label(snap, ownerSection(snap, id)), 40)}${n.by === "llm" ? ", written by the model" : ""}`
: `${library ? `${kids.length} document${kids.length === 1 ? "" : "s"}` : `${kids.length} section${kids.length === 1 ? "" : "s"}`} · ${count} nodes`}{" "}
: `${library ? "library · " : ""}${kids.length} section${kids.length === 1 ? "" : "s"} · ${count} nodes`}{" "}
· branch {store.repo.current}
<Flags id={id} />
<button type="button" class="more" data-more="page" tabIndex={-1} aria-haspopup="menu" title="More for this page (right-click works too)">⋯</button>
</div>
</header>
<div class={`abstract${prompt ? " seed" : ""}${folded ? " folded" : ""}`} onClick={folded ? () => store.toggleFold(id) : undefined}>
<NodeBody id={id} />
</div>
{folded && <div class="unfold">Enter to read the whole prompt · every sentence of it is traced to a section below</div>}
<Abstract id={id} />
</>
);
}
+10 -9
View File
@@ -1,7 +1,7 @@
/**
* The panes view: panes side by side, in the manner of Andy Matuschak's notes. It starts as the
* path down from the top node; a link followed from a pane opens its target in the next pane
* (another document's node, a Wikipedia article, a section of one), replacing what was to the
* (a node from anywhere in the library, a Wikipedia article, a section of one), replacing what was to the
* right. Moving back left closes nothing: the panes stay until something else is opened from an
* earlier pane, or q or a pane's × closes them. Earlier columns stay at the left as narrow spines
* when later ones slide over them.
@@ -17,11 +17,11 @@
*/
import { Component, type ComponentChildren } from "preact";
import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import { docOf, label, sections, staleness, type NodeId } from "../core/model";
import { ancestors, label, sections, staleness, type NodeId } from "../core/model";
import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes";
import { ACROSS, DOWN, mark, offsets, reveal, starts, stick, unmark, whole } from "./stack";
import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links";
import { Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter } from "./Node";
import { Abstract, Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter, isPrompt } from "./Node";
import { kidClass, refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store";
import { WikiView } from "./Wiki";
import { article } from "./wiki";
@@ -170,9 +170,9 @@ function NodePane(props: PaneProps & { id: NodeId }) {
const snap = store.snap;
const n = snap.nodes[id];
if (!n) return null;
// The first pane is the page, headed like the column's page (crumbs, byline, its ⋯); every other
// pane has a section's head, whatever node it shows.
const top = props.root && id === store.top;
// A document's pane is a page of its own, headed like one.
const page = top || docOf(snap, id) === id;
const kids = sections(snap, id);
const focused = active && !store.aux && store.focus.node === id;
const editing = store.edit?.node === id && store.edit.field === "title";
@@ -183,23 +183,24 @@ function NodePane(props: PaneProps & { id: NodeId }) {
const forked = new Set(t.kids.flatMap((k, j) => (j !== t.pick && k.ref.kind === "node" && store.continuesFrom(k.ref, props.p) ? [k.ref.id] : [])));
return (
<article
class={`pane${top ? " root" : ""}${page && !top ? " doc" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`}
class={`pane${top ? " root" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`}
{...paneAttrs(props, id)}
>
<Chrome props={props} title={label(snap, id)} />
<div class="pane-scroll">
<div class="pane-body">
<Orphaned on={props.orphan} />
{page ? (
{top ? (
<TopMatter id={id} />
) : (
<>
{jump && <div class="pane-from">{docOf(snap, id) ? snap.nodes[docOf(snap, id)!].title : "the library"}</div>}
{/* A pane opened by a jump (a link, a search) says where its node is: the titles above it. */}
{jump && <div class="pane-from">{ancestors(snap, id).reverse().map((a) => label(snap, a)).join(" › ")}</div>}
<header class={`pane-head${focused ? " focused" : ""}`} data-node={id}>
{editing ? <TitleEditor id={id} /> : <h2>{n.title || (n.kind === "note" ? label(snap, id) : <i class="untitled">untitled</i>)}</h2>}
<Flags id={id} />
</header>
<NodeBody id={id} />
{isPrompt(snap, id) ? <Abstract id={id} /> : <NodeBody id={id} />}
</>
)}
{kids.length > 0 && (
+1 -1
View File
@@ -282,7 +282,7 @@ function Senses({ title, lang, at }: { title: string; lang: string; at: (r: WRow
);
}
/** "Mentioned in": the library's nodes that link to this article, which is what makes an article a hub between documents. */
/** "Mentioned in": the library's nodes that link to this article, which is what makes an article a hub between places in the library. */
function Mentions({ title, lang, show, at }: { title: string; lang: string; show: boolean; at: (r: WRow) => boolean }) {
if (!show) return null;
return <Backlinks ids={store.mentionsOf(lang, title)} title="Mentioned in" focusedAt={(i) => at({ t: "back", i })} />;
+22 -24
View File
@@ -81,8 +81,8 @@ export interface SelCtx {
note?: boolean;
/** A suggested link on these words: what it would link to. */
suggestion?: string;
/** The node's Related list, numbered 1–5. */
related?: { title: string; doc?: string }[];
/** The node's Related list, numbered 1–5, each with where it is. */
related?: { title: string; where?: string }[];
panes: boolean;
}
@@ -125,7 +125,7 @@ export function selectionEntries(c: SelCtx, act: Act): Entry[] {
SEP,
!c.article && !c.link && !c.note && key(act, "Link to…", "w"),
related.length > 0 && head("Link to a related section"),
...related.map((r, i) => key(act, r.title, String(i + 1), { sub: r.doc })),
...related.map((r, i) => key(act, r.title, String(i + 1), { sub: r.where })),
SEP,
{ t: "choices", label: "Select", options: [{ label: "less", key: "H", run: () => act.press("H") }, { label: "more", key: "L", run: () => act.press("L") }] },
]);
@@ -143,15 +143,19 @@ export interface NodeCtx {
locked: boolean;
/** It has a target of its own (L opens it). */
target: boolean;
/** The library itself: nothing around it to add after, move among or delete it from. */
/** The library itself: nothing around it to add after, move among, copy or delete it from. */
library: boolean;
/** A document's top. */
doc: boolean;
generating: boolean;
}
/**
* A node's menu, the same for a row, a pane's head and a page's head. What acts on the node and
* everything under it (move under, copy, export, import under it, find links) acts on the
* section, so a note's menu leaves it out.
*/
export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
const fixed = c.library;
const tree = !c.note;
return tidy([
head(c.stale ? `${c.title} · ${c.stale === "parent" ? "its parent changed" : "its sections changed"}` : c.title),
c.stale && key(act, "Bring it in line", "R", { sub: c.locked ? "locked: the model will not rewrite it" : "the model rewrites it to match", disabled: c.locked || !c.generating }),
@@ -162,8 +166,8 @@ export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
key(act, "Write more", "e"),
key(act, "Edit text", "c"),
key(act, "Rename", "r"),
key(act, c.library ? "Add a document" : "Add a section inside", "a"),
!fixed && !c.note && key(act, c.doc ? "Add a document after" : "Add a section after", "A"),
key(act, "Add a section inside", "a"),
!fixed && !c.note && key(act, "Add a section after", "A"),
SEP,
key(act, "Ask the editor…", ":"),
c.generating && { t: "item", label: "Research on the web…", keyText: "/research", run: () => act.prompt("/research ") },
@@ -171,23 +175,19 @@ export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
c.target && key(act, "Open its target", "L"),
SEP,
!fixed && { t: "choices", label: "Move", options: [{ label: "up", key: "K", run: () => act.press("K") }, { label: "down", key: "J", run: () => act.press("J") }, { label: "in", key: ">", run: () => act.press(">") }, { label: "out", key: "<", run: () => act.press("<") }] },
!fixed && tree && key(act, "Move under…", "M", { sub: "any node in the library, with all under it" }),
c.note && key(act, "Change its form", "f", { sub: "inline · margin · inset" }),
key(act, "Open everything below", "o"),
key(act, "Collapse everything", "O"),
!fixed && key(act, "Lock", "p", { checked: c.locked, sub: "the model will not rewrite it" }),
!c.library && key(act, "Show only this", "z", { sub: "hoist it: h or Esc at its top steps out" }),
SEP,
!fixed && key(act, "Delete", "D", { sub: "u undoes" }),
]);
}
/** A document's own head: the node's items, and the document's. */
export function pageEntries(c: NodeCtx, act: Act): Entry[] {
return tidy([
...nodeEntries(c, act),
tree && { t: "item", label: "Find links here", keyText: "/linkhere", sub: "in it and everything under it", run: () => act.command("/linkhere") },
tree && !fixed && { t: "item", label: "Save a copy", keyText: "/duplicate", sub: "just after it", run: () => act.command("/duplicate") },
tree && { t: "item", label: "Export as .md", keyText: "/export", run: () => act.command("/export") },
tree && { t: "item", label: "Import a .md file into it…", keyText: "/import", run: () => act.command("/import") },
SEP,
c.doc && { t: "item", label: "Save a copy", keyText: "/duplicate", run: () => act.command("/duplicate") },
c.doc && { t: "item", label: "Export as .md", keyText: "/export", run: () => act.command("/export") },
!fixed && key(act, "Delete", "D", { sub: "u undoes" }),
]);
}
@@ -202,7 +202,7 @@ export interface PaneCtx {
}
export function paneEntries(c: PaneCtx, act: Act): Entry[] {
const own = c.node ? (c.node.doc || c.node.library ? pageEntries(c.node, act) : nodeEntries(c.node, act)) : [head(c.article ?? "Wikipedia"), key(act, "Open on wikipedia.org", "W")];
const own = c.node ? nodeEntries(c.node, act) : [head(c.article ?? "Wikipedia"), key(act, "Open on wikipedia.org", "W")];
return tidy([
...own,
SEP,
@@ -243,8 +243,6 @@ export interface TopCtx {
/** Where each fork's colour shows in the panes view (`/colors`). */
colors: "line" | "top" | "edge" | "off";
panes: boolean;
/** A document is open (its links can be looked for and reviewed). */
doc: boolean;
canRedo: boolean;
}
@@ -253,15 +251,15 @@ export function topEntries(c: TopCtx, act: Act): Entry[] {
const auto = (v: TopCtx["autolink"], label: string): Choice => ({ label, on: c.autolink === v, run: () => act.command(`/autolink ${v}`) });
const setting = (label: string, name: string, on: boolean, sub?: string): Item => ({ t: "item", label, sub, keyText: `/${name}`, checked: on, run: () => act.command(`/${name} ${on ? "off" : "on"}`) });
return tidy([
key(act, "Documents…", "m"),
key(act, "Jump to a section…", "/"),
key(act, "History and branches", "g"),
SEP,
key(act, "Undo", "u"),
key(act, "Redo", "U", { disabled: !c.canRedo }),
SEP,
c.doc && key(act, "Links found: review and reverse", "S"),
c.doc && { t: "item", label: "Find links in this document", keyText: "/linkdoc", run: () => act.command("/linkdoc") },
key(act, "Links found: review and reverse", "S", { sub: "in the node you are on and under it; on the root, the library" }),
{ t: "item", label: "Find links in the whole library", keyText: "/linkall", run: () => act.command("/linkall") },
{ t: "item", label: "Find links here", keyText: "/linkhere", sub: "in the node you are on and everything under it", run: () => act.command("/linkhere") },
SEP,
{ t: "choices", label: "Layout", options: [view("auto"), view("column"), view("panes")] },
{ t: "choices", label: "Links found", options: [auto("review", "review"), auto("suggest", "suggest"), auto("on", "link sure"), auto("off", "off")] },
+22 -103
View File
@@ -12,8 +12,8 @@ export const HELP: [string, [string, string][]][] = [
["i", "narrow the grain: node → sentence → word"],
["Esc", "widen the grain; leave a note; close a panel; stop the editor while it works"],
["Tab", "jump between spans that carry a note or a link; in an article, between its links and the notes on it"],
["/", "jump to a section by name, in any document"],
["z", "hoist: make this node the whole page (again, or h or Esc at its top, to step out)"],
["/", "jump to a section by name, anywhere in the library"],
["z", "hoist: make this node the whole page (again, or h or Esc at its top, to step out to its parent's page)"],
["v", "view: one column ↔ panes side by side (in panes, j k move among siblings)"],
["q", "in panes: close the active pane (the one under the heavy rule, whatever it shows) and every pane opened from it, except pinned ones; the focus goes back to where it was opened from. A pane's x does the same. Moving left never closes anything"],
["P", "in panes: pin or unpin the active pane (or its pin, top right). A pinned pane stays where it is when a pane it came from closes, is never replaced by a Shift open, and is never covered, in its column or along the strip"],
@@ -29,7 +29,7 @@ export const HELP: [string, [string, string][]][] = [
["", "a click on a sentence selects it, and a bar over it offers expand · define · why · example · challenge · ask · link, each with its key (on a phone, at the foot of the screen, × puts it away); a drag selects words, a double click a word"],
["", "right-click (a long press on a phone) on words, a row, a link, a note or a pane: what can be done with it, Copy first. Shift+right-click is the browser's own menu"],
["", "⋯ by a row, a pane's pin, a page's byline or a note (shown when pointed at): the same menu. A stale flag, clicked, offers what to do about it"],
["", "the top bar: undo, redo, and menu: documents, jump, history, links, layout and settings. A key named in the status line or a panel's head is a button that presses it"],
["", "the top bar: the library's name, undo, redo, and menu: jump, history, links, layout and settings. A key named in the status line or a panel's head is a button that presses it"],
],
],
[
@@ -42,8 +42,8 @@ export const HELP: [string, [string, string][]][] = [
["W", "open the focused article on wikipedia.org, in a new tab"],
["D", "on a link: remove it, and decline its words in that node so it is not made again (u undoes). Also in the right-click menu: Remove the link"],
["y n", "on a suggested link (a faint dashed underline; Tab reaches it): link it / decline it (a declined phrase is not suggested again in that node)"],
["S", "the links list of this document: every link found or made, with who decided and the reviewer's reason. 1 2 3 show or hide linked · rejected · pending (rejected is hidden at first); j k move (the words are selected in the text); y links (also a rejected one: you overrule); n declines, or on a link removes it for good; Y links all the pending shown; Enter goes to the words; Esc closes"],
["1–5", "the node's Related list (sections of other documents close in meaning, numbered under its text): with words selected, link them to that one; on the node, go there"],
["S", "the links list of the node you are on and everything under it (on the library root, the whole library): every link found or made, with who decided and the reviewer's reason. 1 2 3 show or hide linked · rejected · pending (rejected is hidden at first); j k move (the words are selected in the text); y links (also a rejected one: you overrule); n declines, or on a link removes it for good; Y links all the pending shown; Enter goes to the words; Esc closes"],
["1–5", "the node's Related list (sections elsewhere in the library close in meaning, numbered under its text): with words selected, link them to that one; on the node, go there"],
["l h j k", "in an article: sections are rows, as in a node; l opens one, h goes back"],
["i e d y x c :", "in an article: select words of its text as in a node, and write a note on them; the note belongs to the article and shows wherever it is opened (one whose words are gone from a newer revision is listed as detached)"],
],
@@ -64,14 +64,15 @@ export const HELP: [string, [string, string][]][] = [
[
["c", "edit the body (Esc saves). In it, [[ links a phrase: library titles first, then Wikipedia; a bare [[term]] left in the text is looked up when saved"],
["r", "rename"],
["a A", "add a section inside / after (on the library: a document)"],
["a A", "add a section inside / after (on the library root: a new top-level node)"],
["D", "delete (no confirmation; u undoes)"],
["J K", "move down / up among siblings"],
["> <", "indent / outdent (a document's sections can be moved into another this way, or over HTTP)"],
["> <", "indent / outdent"],
["M", "move under…: pick any node in the library (or the library root) and this node, with everything under it, becomes its last child (u undoes)"],
["p", "lock or unlock: a locked node is never rewritten by the model (your own edits lock it). Not the same as P, which pins a pane"],
["f", "on a note: cycle its form (inline · margin · inset)"],
[":", "on a node: tell the editor agent what to change"],
["u U", "undo / redo: the last edit made in this tab, in whichever document it was"],
["u U", "undo / redo: the last edit made in this tab, wherever in the library it was"],
],
],
[
@@ -84,19 +85,9 @@ export const HELP: [string, [string, string][]][] = [
],
],
[
"Documents (m)",
"The library",
[
["", "every document is a section of one library: the library is the first page (h or Esc steps out to it), and a document opens in place"],
["m", "the documents menu (or click the title in the top bar). Type to filter; ↑ ↓ select; Enter opens"],
["Esc", "in the filter: go to the list, where single keys act. In the list: close"],
["j k Enter", "in the list: select / open"],
["n", "new blank document (asks for a title)"],
["r", "rename the selected document"],
["s", "duplicate it: save as a copy under a new title, and open the copy"],
["D", "delete it (asks first; u brings it back)"],
["x", "export it: save to a .md file"],
["i", "import a .md file as a new document (or drop the file on the menu)"],
["/", "back to the filter"],
["", "everything is a node of one tree, whose root is the library: the first page. Any node can be moved under any other (M, > <), copied (/duplicate), saved to a file (/export) or given a file's tree under it (/import); each acts on the node you are on, with everything under it. The ⋯ menu of any node offers the same"],
],
],
[
@@ -109,9 +100,9 @@ export const HELP: [string, [string, string][]][] = [
["m", "merge the selected branch into this one"],
["1 2 3", "conflict: take side A / side B / the mechanical merge"],
["x", "conflict: reopen a resolution"],
["f", "show only what touched the current document, or everything"],
["f", "show only what touched the node you are on and what is under it, or everything"],
["v", "verify: check every commit reproduces its recorded hash"],
["", "each commit names the documents it touched; r reverts only the current document, the rest of the library stays as it is"],
["", "each commit names the top-level nodes it touched. r reverts only the node you are on and what is under it, the rest of the library stays as it is; on the library root, the whole library"],
],
],
[
@@ -127,18 +118,15 @@ export const HELP: [string, [string, string][]][] = [
["/curves on|off", "in panes: the faint curves from where each pane was opened to it"],
["/colors line|top|edge|off", "in panes: each fork's own colour, on its curves and the rule under its panes' titles (line, the default), across their tops, down their left edges, or none"],
["/user name", "set the name on your commits"],
["/new title", "new blank document"],
["/open name", "open a document by title or id"],
["/rename title", "rename this document"],
["/duplicate title", "save this document as a copy, and open the copy"],
["/export", "save this document to a .md file"],
["/import", "open a .md file as a new document"],
["/duplicate title", "save the node you are on, with everything under it, as a copy just after it (titled \"… (copy)\" unless given one); the copy has the focus"],
["/export", "save the node you are on, with everything under it, to a .md file (on the library root, the whole library)"],
["/import", "read a .md file into the node you are on, as its last child (on the library root, a new top-level node)"],
["/recover", "save edits this browser made before the library existed, and never sent, as .md files"],
["/link target", "link the selection (or the node): w:Title, /document/Section, an address, or a Wikipedia title"],
["/link target", "link the selection (or the node): w:Title, /Top title/Section (titles from the library root), an address, or a Wikipedia title"],
["/unlink", "remove the link on the selection (for good: its words are declined; a note that also links keeps its text), or the node's own target"],
["/autolink review|suggest|on|off", "after an edit: the model reviews what was found and links what it approves (review, the default with a model; u undoes, S lists every decision), suggest everything for you to decide (suggest; what review does without a model, or when the model fails or its limit is reached), link the scanner's sure ones unreviewed (on), or look for nothing (off)"],
["/linkdoc", "look for links in the whole document, in the background (reviewed, in review mode); progress and the reviewer's model calls in the status line"],
["/linkall", "look for links in the whole library, in the background"],
["/linkhere", "look for links in the node you are on and everything under it, in the background (reviewed, in review mode); progress and the reviewer's model calls in the status line"],
["/linkall", "look for links in the whole library, in the background (so does /linkhere on the library root)"],
["/linkcancel", "stop looking (what was found and reviewed is kept, and what was approved is linked)"],
["/research question", "the editor searches the web, reads a few pages and writes what it finds into the focused node, each claim linked to its page (within the server's limits, by default 5 searches and 5 pages read per request; Esc stops)"],
["", "an ordinary request to the editor may use the web too when it says so: \"look up…\", \"find sources for…\", \"search the web…\", \"cite sources\", \"fact-check\""],
@@ -261,75 +249,6 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
return done();
}
if (store.mode === "docs") {
// The filter and title boxes take their own keys (Menu.tsx); these are the list's.
const m = store.menu;
const d = store.menuSelected();
if (m.focus === "filter" && !m.prompt && !m.confirm) {
// The filter box is not focused (a key typed before it took focus, or after a click
// elsewhere in the panel): keys still mean what they would there.
if (k === "Escape" || k === "Tab") m.focus = "list";
else if (k === "Enter") return d && (e.preventDefault(), store.openDoc(d.node, true));
else if (k === "ArrowDown" || k === "ArrowUp") return e.preventDefault(), store.menuMove(k === "ArrowDown" ? 1 : -1);
else if (k.length === 1) return e.preventDefault(), store.menuFilter(m.filter + k);
else return;
store.emit();
return done();
}
if (m.confirm) {
if (k === "y") store.deleteDocument(m.confirm);
else if (k === "n" || k === "Escape" || k === "q") (m.confirm = null), store.emit();
else return;
return done();
}
switch (k) {
case "Escape":
case "q":
case "m":
store.closeMenu();
break;
case "j":
case "ArrowDown":
store.menuMove(1);
break;
case "k":
case "ArrowUp":
store.menuMove(-1);
break;
case "Enter":
if (d) store.openDoc(d.node, true);
break;
case "/":
m.focus = "filter";
store.emit();
break;
case "n":
store.menuPrompt("new");
break;
case "r":
store.menuPrompt("rename");
break;
case "s":
store.menuPrompt("duplicate");
break;
case "D":
if (d) (m.confirm = d.node), store.emit();
break;
case "x":
if (d) store.exportDocument(d.node);
break;
case "i":
store.pickFile();
break;
case "?":
store.setMode("help");
break;
default:
return;
}
return done();
}
if (store.mode === "review") {
switch (k) {
case "y":
@@ -528,6 +447,9 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
case "z":
store.setHoist(store.focus.node);
break;
case "M":
if (!selecting) store.startMove();
break;
default:
return;
}
@@ -562,9 +484,6 @@ function commonKey(k: string, hooks: KeyHooks): boolean {
case "g":
store.openHistory();
return true;
case "m":
store.openMenu();
return true;
case "/":
store.setMode("jump");
return true;
+19 -13
View File
@@ -15,7 +15,7 @@ import type { Related as RelatedRow, Suggestion as Sugg } from "../../server/lin
import { inArticles } from "../core/article";
import { applyLinks, nodeRef, phraseKey } from "../core/links";
import type { Mark } from "../core/marks";
import { ancestors, isLink, topOf, label, notesOf, type Doc, type NodeId, type Op, type Snap } from "../core/model";
import { ancestors, isLibraryRoot, isLink, label, notesOf, topOf, tops, type Doc, type NodeId, type Op, type Snap } from "../core/model";
import { describeTarget, sameTarget, type Ref } from "../core/ref";
import { clip, overlaps, type Range } from "../core/text";
import type { Nearby } from "../llm/prompts";
@@ -145,7 +145,7 @@ export class Linker {
private queue: Task[] = [];
private running = false;
job: JobState | null = null;
/** Documents whose pending list has been fetched since the page loaded. */
/** Subtrees whose pending list has been fetched since the page loaded (by the node at their top). */
private fetched = new Set<NodeId>();
/** Scans in flight or queued: the page waits on this in tests (`idle`). */
busy = 0;
@@ -219,7 +219,7 @@ export class Linker {
/** Queue a scan of a node that was just written. Off the keystroke: it runs after the write is saved. */
scan(node: NodeId, origin: Origin, forced: Mark[] = []) {
if (this.host.mode() === "off" && !(origin === "human" && forced.length)) return;
// Annotations on Wikipedia articles are not a document's text: nothing in them is linked.
// Annotations on Wikipedia articles are not the library's own text: nothing in them is linked.
const snap = this.host.doc().snap();
if (snap.nodes[node] && inArticles(snap, node)) return;
const had = this.queue.find((t) => t.node === node);
@@ -342,21 +342,27 @@ export class Linker {
}
/**
* A document's stored suggestions from the server, with what was decided about each (what a
* background job found, and the reviewer's verdicts), once per page load or on demand. With
* `claim`, also the links the reviewer approved that no page has made yet, handed to this one.
* The stored suggestions of a node and everything under it, from the server, with what was
* decided about each (what a background job found, and the reviewer's verdicts), once per page
* load or on demand. On the library root, each top-level tree's, side by side. With `claim`, also
* the links the reviewer approved that no page has made yet, handed to this one.
*/
async loadDoc(docId: NodeId, force = false, claim = false): Promise<{ found: Sugg[]; apply: Sugg[] }> {
if (!force && this.fetched.has(docId)) return { found: [], apply: [] };
this.fetched.add(docId);
async loadSubtree(id: NodeId, force = false, claim = false): Promise<{ found: Sugg[]; apply: Sugg[] }> {
const snap = this.host.doc().snap();
if (isLibraryRoot(snap, id)) {
const got = await Promise.all(tops(snap).map((t) => this.loadSubtree(t, force, claim)));
return { found: got.flatMap((g) => g.found), apply: got.flatMap((g) => g.apply) };
}
if (!force && this.fetched.has(id)) return { found: [], apply: [] };
this.fetched.add(id);
try {
const res = await fetch(`/api/links/pending?doc=${encodeURIComponent(docId)}&all=1${claim ? "&claim=1" : ""}`);
const res = await fetch(`/api/links/pending?node=${encodeURIComponent(id)}&subtree=1&all=1${claim ? "&claim=1" : ""}`);
if (!res.ok) return { found: [], apply: [] };
const r = (await res.json()) as { suggestions: Sugg[]; apply?: Sugg[] };
const by = new Map<NodeId, Sugg[]>();
for (const s of r.suggestions) by.set(s.node, [...(by.get(s.node) ?? []), s]);
for (const [id, list] of by) this.byNode.set(id, list);
// Nothing to draw, nothing to redraw: a document opened is not repainted for an empty list.
// Nothing to draw, nothing to redraw: a tree reached is not repainted for an empty list.
if (by.size) this.host.emit(...by.keys());
return { found: r.suggestions, apply: r.apply ?? [] };
} catch {
@@ -484,8 +490,8 @@ export class Linker {
// ---- background jobs ----
async startJob(scope: "doc" | "library", doc?: NodeId): Promise<JobState | string> {
const res = await post("jobs", { scope, doc, review: this.effective() === "review" });
async startJob(scope: "node" | "library", node?: NodeId): Promise<JobState | string> {
const res = await post("jobs", { scope, node: scope === "node" ? node : undefined, review: this.effective() === "review" });
const r = await res.json().catch(() => ({}));
if (!res.ok) return r.error ?? `the server answered ${res.status}`;
// A short job's end can be announced before this answer arrives: keep the later news.
+226 -320
View File
@@ -2,20 +2,21 @@
* Application state for the browser: the library's replicas, sync with the server, the focus
* model, and every action the keyboard, the mouse or the command bar can take.
*
* There is one library and everything in it is reachable from anywhere: a document is a section
* of the library root, opened by hoisting to it (the column) or by showing it in the next pane.
* Nothing is closed to open something else, so model work carries on wherever the reader goes,
* and writes into the node it was asked about.
* There is one library, a tree of nodes, and every node in it is reachable from anywhere: the
* library root is the first page, and any node can be made the whole page (hoisted, in the column)
* or shown in the next pane. Nothing is closed to open something else, so model work carries on
* wherever the reader goes, and writes into the node it was asked about.
*/
import { UndoManager } from "loro-crdt";
import {
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, docOf, documents, isLibraryRoot, isLink, isStale, label, notesOf, sections,
staleness, type NodeId, type Op, type Snap,
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, isLibraryRoot, isLink, isStale, label, notesOf, sections,
staleness, topOf, tops, type NodeId, type Op, type Snap,
} from "../core/model";
import { FormatError, serializeDoc } from "../core/format";
import { IMPORT_MAX, address, createDoc, deleteDoc, duplicateDoc, importDoc, listDocs, renameDoc, resolve, type DocInfo } from "../core/library";
import { address, resolve } from "../core/address";
import { IMPORT_MAX, importTree } from "../core/seed";
import {
Repo, at, decodeVV, healAnchors, history, reopenConflict, resolveConflict, revertDocTo, revertTo, touched, vvIncludes, type Commit,
Repo, at, decodeVV, healAnchors, history, reopenConflict, resolveConflict, revertSubtreeTo, revertTo, touched, vvIncludes, type Commit,
type MergeReport,
} from "../core/repo";
import { clip, formFor, plain, rangeAt, sentences, slugify, words, type Form, type Range } from "../core/text";
@@ -45,12 +46,12 @@ export interface Focus {
grain: Grain;
range?: Range;
}
export type Mode = "normal" | "edit" | "command" | "history" | "help" | "jump" | "docs" | "link" | "review";
export type Mode = "normal" | "edit" | "command" | "history" | "help" | "jump" | "move" | "link" | "review";
/**
* A pane of the panes view. The panes are a tree of forks (forks.ts) whose focused branch is the
* trail: it starts with the path down from the top node, and a link followed from a pane opens its
* target in the next pane, so it may hold another document's node, a Wikipedia article or a section
* target in the next pane, so it may hold a node from anywhere in the library, a Wikipedia article or a section
* of one. `from` is where a jump was made from, which h returns to.
*/
export type PaneRef =
@@ -111,18 +112,6 @@ export interface Picker {
}
export const sameAux = (a: Aux | null, b: Aux | null): boolean => JSON.stringify(a) === JSON.stringify(b);
/** The documents menu: its filter, selection, and any title being typed or deletion being confirmed. */
export interface Menu {
filter: string;
/** The selected document's node (kept by id, so a changed list does not move the selection). */
selected: NodeId | null;
/** Where the keys go: the filter box, or the list (single-key actions). */
focus: "filter" | "list";
prompt: { kind: "new" | "rename" | "duplicate"; id?: NodeId; value: string } | null;
confirm: NodeId | null;
/** Problems from the last import, shown until the menu closes. */
problems: string[] | null;
}
/** Page layout: one column with a margin, or panes side by side. Auto picks panes on wide windows. */
export type View = "auto" | "column" | "panes";
/** Where a fork's colour shows in the panes view: along its curves and title rules, across its panes' tops, down their left edges, or nowhere. */
@@ -131,7 +120,7 @@ const COLORS: Colors[] = ["line", "top", "edge", "off"];
/** The narrowest window, in CSS px, on which `auto` chooses panes. */
export const PANES_MIN_WIDTH = 900;
/** Text being generated that is not in the document yet. */
/** Text being generated that is not in the library yet. */
export interface Pending {
key: string;
node: NodeId;
@@ -217,7 +206,6 @@ class Store {
fatal: string | null = null;
/** The library's replicas and their sync. */
session!: Session;
menu: Menu = { filter: "", selected: null, focus: "filter", prompt: null, confirm: null, problems: null };
user = "you";
llm: LLM = remoteLLM("off");
online = false;
@@ -226,7 +214,7 @@ class Store {
focus!: Focus;
open = new Set<NodeId>();
hoist: NodeId | null = null;
/** Documents whose own text is unfolded, where it is a prompt that is folded by default. */
/** Nodes whose own text is unfolded, where it is a prompt that is folded by default. */
unfolded = new Set<NodeId>();
/** A past commit being looked at, read-only. */
preview: { commit: Commit; doc: Doc } | null = null;
@@ -236,10 +224,12 @@ class Store {
busy = 0;
log: { at: number; text: string }[] = [];
historyIndex = 0;
/** The history panel shows only what touched the current document. */
historyFilter = false;
/** The commit before the editor agent's last run, while `u` can still take it back. */
agentUndo: { commit: Commit; doc: NodeId | null } | null = null;
/** The history panel shows only what touched this node and what is under it (f). */
historyFilter: NodeId | null = null;
/** The commit before the editor agent's last run, while `u` can still take it back, and the top of the tree it worked in. */
agentUndo: { commit: Commit; top: NodeId | null } | null = null;
/** The node being moved while the reader picks where it goes (M). */
moving: NodeId | null = null;
/** Set by "new branch from this commit" until the name has been typed. */
branchFrom: Commit | null = null;
/** A note being previewed on hover, and where to draw it. */
@@ -256,10 +246,11 @@ class Store {
rendered: (id) => this.rendered(id),
});
/**
* The links list (S): every link found or made in the current document, as it stands, under
* The links list (S): every link found or made in a node and everything under it (on the library
* root, the whole library), as it stands, under
* filters by status; the selected row's words are focused in the text.
*/
review: { ids: NodeId[]; show: Record<Status, boolean>; key: string | null } | null = null;
review: { node: NodeId; ids: NodeId[]; show: Record<Status, boolean>; key: string | null } | null = null;
/** Whether the window is wide enough for `auto` to mean panes. Kept current by the page. */
wide = typeof window !== "undefined" && window.innerWidth >= PANES_MIN_WIDTH;
@@ -455,19 +446,16 @@ class Store {
}
/**
* The document the reader is in: the one the focus is in. On the column's library page, where
* documents are rows to be opened, none.
* The node the reader is on, for what acts on a node and everything under it (export, duplicate,
* import under it, move under, /linkhere, history's f and r): the focused section, or the section
* a focused note or selection is in. From an annotation (its article is not in the outline), the
* page's top.
*/
get currentDoc(): NodeId | null {
get activeNode(): NodeId {
const s = this.snap;
if (!this.panes && isLibraryRoot(s, this.top)) return null;
return docOf(s, this.focus.node);
}
/** The library page in the column: documents are opened by hoisting to them, never unfolded in the list. */
private listing(id: NodeId): boolean {
const s = this.snap;
return !this.panes && isLibraryRoot(s, this.top) && s.nodes[id]?.parent === s.root;
const f = this.focus.node;
if (!s.nodes[f] || inArticles(s, f)) return this.top;
return ownerSection(s, f);
}
/**
@@ -847,7 +835,7 @@ class Store {
return id === this.focus.node || id === this.top;
}
/** A node's Related list: sections of other documents close in meaning (fetched when it is drawn). */
/** A node's Related list: sections elsewhere in the library close in meaning (fetched when it is drawn). */
relatedOf(id: NodeId) {
if (this.preview || !this.snap.nodes[id] || isLibraryRoot(this.snap, id)) return [];
return this.links.relatedOf(id, this.snap) ?? [];
@@ -858,12 +846,11 @@ class Store {
if (this.colWiki) return this.wikiRows("col").map((row) => ({ aux: { kind: "wiki", host: "col", row } }));
const s = this.snap;
const out: Row[] = [];
const listing = isLibraryRoot(s, this.top);
const visit = (id: NodeId) => {
out.push({ node: id });
if (!this.isOpen(id)) return;
sections(s, id).forEach(visit);
if (!(listing && id === this.top)) out.push(...this.auxRows(id));
out.push(...this.auxRows(id));
};
visit(this.top);
return out;
@@ -1003,8 +990,8 @@ class Store {
private inOrder(ids: NodeId[]): NodeId[] {
if (ids.length < 2) return ids;
const s = this.snap;
const docs = documents(s);
const key = (id: NodeId) => [docs.indexOf(docOf(s, id) ?? s.root), label(s, ownerSection(s, id))] as const;
const order = tops(s);
const key = (id: NodeId) => [order.indexOf(topOf(s, id) ?? s.root), label(s, ownerSection(s, id))] as const;
return [...ids].sort((a, b) => {
const [da, la] = key(a);
const [db, lb] = key(b);
@@ -1082,7 +1069,7 @@ class Store {
}
isOpen(id: NodeId) {
return id === this.top || (this.open.has(id) && !this.listing(id));
return id === this.top || this.open.has(id);
}
/** On screen right now: every ancestor up to the top is open. */
@@ -1175,6 +1162,7 @@ class Store {
this.undoManager();
this.navigate(location.pathname, "replace");
this.ready = true;
this.prefetchLinks(this.focus.node);
this.emit();
// The first commit hashes the whole library once (later ones only the path to what they
// changed); do that while the page is idle rather than on the reader's first edit.
@@ -1198,10 +1186,10 @@ class Store {
}
/**
* The version that kept each document separately stored its replicas under `doc:<uid>:…` (and
* the single-document version under bare `branch:<name>` keys). They are never loaded into the
* library, but one may hold edits made offline that never reached the server: compare each with
* what the server had when it built the library, and say so if it is ahead.
* The version that kept each document separately stored its replicas under `doc:<uid>:…`. They
* are never loaded into the library, but one may hold edits made offline that never reached the
* server: compare each with what the server had when it built the library, and say so if it is
* ahead.
*/
private async checkOldReplicas(migrated: Migrated) {
const flag = `lib:${this.session.library}:old-checked`;
@@ -1219,12 +1207,6 @@ class Store {
const m = /^doc:([0-9a-f]+):branch:(.+)$/.exec(key);
if (m) await check(key, migrated.docs.find((d) => d.uid === m[1]), m[2]);
}
if (!(await idbGet("adopted"))) {
for (const key of keys) {
const m = /^branch:(.+)$/.exec(key);
if (m) await check(key, migrated.docs.find((d) => d.slug === "infinite-expand"), m[1]);
}
}
this.oldReplicas = found;
if (!found.length) return void idbSet(flag, true);
const names = found.map((r) => `“${clip(r.title, 30)}”${r.branch === "main" ? "" : ` (${r.branch})`}`).join(", ");
@@ -1238,21 +1220,14 @@ class Store {
const { text } = serializeDoc(Doc.load(r.bytes, this.user).snap());
download(`${r.slug}${r.branch === "main" ? "" : `-${r.branch.replace(/[^\w-]+/g, "-")}`}-unsent.md`, text);
}
this.say(`Saved ${this.oldReplicas.length} file${this.oldReplicas.length > 1 ? "s" : ""}; m then i imports one as a document.`);
this.say(`Saved ${this.oldReplicas.length} file${this.oldReplicas.length > 1 ? "s" : ""}; :/import brings one in under the node you are on.`);
this.oldReplicas = [];
void idbSet(`lib:${this.session.library}:old-checked`, true);
}
/** The current document's title, or the library's. */
docTitle(): string {
const s = this.snap;
const d = this.currentDoc;
return d ? s.nodes[d].title : s.nodes[s.root].title;
}
/** The window's title: the article on the column's article page, else the document. */
/** The window's title: the article on the column's article page, else the node the reader is on. */
private setTitle() {
document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : this.docTitle() || "Infinispand";
document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : label(this.snap, this.activeNode) || "Infinispand";
}
/** Every edit is saved as it is made; this says whether the server has it yet. */
@@ -1303,14 +1278,10 @@ class Store {
// ---- addresses ----
/**
* The address of what is on screen. On the column's library page it is the library; otherwise
* it is the focused node, so a reload, a link or Back lands on it again.
*/
/** The address of what is on screen: the focused node, so a reload, a link or Back lands on it again. */
here(): string {
if (!this.panes && this.colWiki) return `/w/${this.colWiki.lang}/${encodeURIComponent(this.colWiki.title.replace(/ /g, "_"))}`;
const s = this.snap;
if (!this.panes && isLibraryRoot(s, this.top)) return "/";
// An annotation has no address of its own: the address stays on what shows its article.
if (inArticles(s, this.focus.node)) return location.pathname;
return address(s, this.focus.node);
@@ -1318,8 +1289,8 @@ class Store {
/**
* Put the address in the bar. Moving the focus replaces the entry (after a pause: browsers
* throttle a page that rewrites its address on every keystroke); opening a document or
* jumping makes a new one, so Back returns to where the reader was.
* throttle a page that rewrites its address on every keystroke); changing the page (hoisting,
* stepping out) or jumping makes a new one, so Back returns to where the reader was.
*/
private remember(push = false) {
clearTimeout(this.addressTimer);
@@ -1363,13 +1334,9 @@ class Store {
this.hoist = null;
this.focus = { node: s.root, grain: "node" };
} else if (isLibraryRoot(s, found.node)) {
// The library page: in the column, on the row of the document the reader was in; in
// panes, the library alone.
const from = docOf(s, this.focus.node);
this.hoist = null;
this.focus = { node: (!this.panes && from) || s.root, grain: "node" };
this.focus = { node: s.root, grain: "node" };
} else {
if (!this.panes && found.node === docOf(s, found.node)) this.hoist = found.node;
this.reveal(found.node);
// In panes, the node an address names is shown in its own pane: the trail keeps it if it
// already shows it (Back to a pane of the trail), and is made again as the path to it if not.
@@ -1387,17 +1354,31 @@ class Store {
}
this.repairView();
this.saveView();
this.prefetchLinks(this.focus.node);
if (history === "replace") window.history.replaceState(null, "", this.here());
this.setTitle();
this.emit();
}
/**
* What the server stored about links in the top-level tree the reader has reached (what a
* background job found, the reviewer's verdicts), fetched once a page load, so its suggestions
* show in the text.
*/
private prefetchLinks(id: NodeId) {
if (this.preview || !this.ready) return;
const s = this.doc.snap();
const t = s.nodes[id] ? topOf(s, id) : null;
if (t) void this.links.loadSubtree(t);
}
// ---- navigation ----
setFocus(f: Focus, aux: Aux | null = null) {
const was = this.focus.node;
this.focus = f;
this.aux = aux;
this.prefetchLinks(f.node);
this.syncTrail();
this.saveView();
this.scheduleSpeculation();
@@ -1407,20 +1388,15 @@ class Store {
}
/**
* Open whatever needs opening for a node to be on screen. The column shows one document at a
* time, so a node in another one is shown by hoisting to its document; a document itself is a
* row of the library page until it is opened.
* Open whatever needs opening for a node to be on screen: everything above it, and the page
* itself if the node is not on it (outside the hoisted node, the page goes back to the library).
*/
reveal(id: NodeId) {
const s = this.snap;
// An annotation is shown with its article, wherever that is; the Wikipedia container is never a page.
if (!s.nodes[id] || inArticles(s, id)) return;
const chain = ancestors(s, id);
const under = this.hoist && (id === this.hoist || chain.includes(this.hoist));
if (!this.panes) {
if (isLibraryRoot(s, id)) this.hoist = null;
else if (!under && !(this.hoist === null && s.nodes[id].parent === s.root)) this.hoist = s.library ? docOf(s, id) : null;
} else if (this.hoist && !under) this.hoist = null;
if (this.hoist && id !== this.hoist && !chain.includes(this.hoist)) this.hoist = null;
for (const a of chain) this.open.add(a);
if (s.nodes[id].kind === "note") this.open.add(id);
}
@@ -1432,40 +1408,17 @@ class Store {
if (this.hoist !== hoist) this.remember(true);
}
/** Open a document: hoist to it in the column, show it in the next pane in panes. */
/** Open a document: from its row in the library, beside what is open; from the menu, a command or an address (`nav`), in place of it. */
openDoc(id: NodeId, nav = false) {
const s = this.doc.snap();
if (!s.nodes[id]) return;
void this.links.loadDoc(id);
this.preview = null;
this.mode = "normal";
this.aux = null;
this.colWiki = null;
if (this.panes) {
if (this.hoist && this.hoist !== id && !ancestors(s, this.hoist).includes(id)) this.hoist = null;
this.open.add(id);
this.focus = { node: id, grain: "node" };
this.syncTrail();
if (s.nodes[id].parent === this.top) this.withReplace(nav || this.replacing, () => this.openPane(this.paneAt, { kind: "node", id }));
} else this.hoist = id;
this.focus = { node: id, grain: "node" };
this.saveView();
this.remember(true);
this.emit();
}
/**
* Step out of the hoisted node: to its document if it is deeper, else to the library. The
* focus stays on what was the top, now a row of the page it opened from.
* Step out of the hoisted node, to its parent's page (from a child of the root, the library).
* The focus stays on what was the top, now a row of the page it opened from.
*/
stepOut() {
this.aux = null;
const s = this.snap;
const was = this.hoist;
if (!was) return;
const d = docOf(s, was);
this.hoist = d && d !== was ? d : null;
const p = s.nodes[was].parent;
this.hoist = p && !isLibraryRoot(s, p) ? p : null;
// A note opened as a page steps back out to its words.
const a = s.nodes[was].kind === "note" ? s.nodes[was].anchors[0] : undefined;
this.focus = a ? { node: s.nodes[was].parent!, grain: "word", range: [a.start, a.end] } : { node: was, grain: "node" };
@@ -1526,7 +1479,6 @@ class Store {
const s = this.snap;
const f = this.focus;
if (f.grain !== "node" || this.inArticleText) return this.move(1);
if (this.listing(f.node)) return this.openDoc(f.node);
if (this.panes && (s.nodes[f.node].kind === "section" || this.paneHead(f.node))) {
this.syncTrail();
const i = this.paneAt;
@@ -1631,7 +1583,6 @@ class Store {
toggle(id = this.focus.node) {
if (id === this.top) return this.toggleFold(id);
if (this.listing(id)) return this.openDoc(id);
// The head of a pane other than the first: Enter steps into its rows, as l does.
if (this.panes && this.paneAt > 0 && this.paneHead(id)) return this.into();
// In panes a row opens its pane, or focuses it where it is open already: closing is q's, or the pane's x.
@@ -1642,7 +1593,7 @@ class Store {
this.setOpen(id, !this.isOpen(id));
}
/** Unfold or fold a document's own text where it is a prompt. */
/** Unfold or fold a node's own text where it is a prompt. */
toggleFold(id: NodeId) {
if (this.unfolded.has(id)) this.unfolded.delete(id);
else this.unfolded.add(id);
@@ -1683,7 +1634,7 @@ class Store {
return;
}
if (f.grain === "node") {
if (!this.isOpen(f.node) && n.kind === "section" && !this.listing(f.node)) this.open.add(f.node);
if (!this.isOpen(f.node) && n.kind === "section") this.open.add(f.node);
if (n.kind === "section") this.rowPane(f.node, true);
const first = sentences(n.body)[0];
if (first) this.setFocus({ node: f.node, grain: "sentence", range: first });
@@ -1746,8 +1697,8 @@ class Store {
expandAll(id = this.focus.node) {
const s = this.snap;
// On the library, opening everything would mean every document; open the documents only.
const under = isLibraryRoot(s, id) ? documents(s) : descendants(s, id);
// On the library root, opening everything would open the whole library: its top-level nodes only.
const under = isLibraryRoot(s, id) ? tops(s) : descendants(s, id);
this.open.add(id);
for (const d of under) if (s.nodes[d].kind === "section") this.open.add(d);
this.saveView();
@@ -1842,7 +1793,7 @@ class Store {
startEdit(field: "title" | "body", fresh = false) {
if (!this.writable()) return;
const n = this.snap.nodes[this.focus.node];
if (field === "body" && !this.isOpen(n.id) && !this.listing(n.id)) this.open.add(n.id);
if (field === "body" && !this.isOpen(n.id)) this.open.add(n.id);
if (field === "body") this.rowPane(n.id, true);
this.edit = { node: n.id, field, value: n[field], fresh };
this.mode = "edit";
@@ -1899,7 +1850,7 @@ class Store {
return ops;
}
/** a: a new section inside the focused node. A: a new section after it. On the library, a section is a document. */
/** a: a new section inside the focused node. A: a new section after it. */
add(where: "child" | "after") {
if (!this.writable()) return;
const s = this.snap;
@@ -1907,9 +1858,9 @@ class Store {
const asChild = where === "child" || !n.parent || n.id === this.top || n.kind === "note";
const parent = asChild ? n.id : n.parent!;
const index = asChild ? undefined : s.nodes[parent].children.indexOf(n.id) + 1;
const [id] = this.apply([{ op: "create", parent, index, kind: "section", title: "", body: "" }], isLibraryRoot(s, parent) ? "Add document" : "Add section");
const [id] = this.apply([{ op: "create", parent, index, kind: "section", title: "", body: "" }], "Add section");
if (!id) return;
if (!this.listing(id)) this.open.add(parent);
this.open.add(parent);
this.focus = { node: id, grain: "node" };
this.startEdit("title", true);
}
@@ -1951,7 +1902,7 @@ class Store {
: this.panes ? sibs[j + 1] ?? sibs[j - 1] ?? n.parent
: order[i + 1 + descendants(s, n.id).filter((d) => order.includes(d)).length] ?? order[i - 1] ?? n.parent;
this.apply([{ op: "delete", id: n.id }], `Delete “${clip(label(s, n.id), 40)}”`);
if (this.hoist === n.id || (this.hoist && ancestors(s, this.hoist).includes(n.id))) this.hoist = docOf(s, n.parent) === n.parent ? n.parent : null;
if (this.hoist === n.id || (this.hoist && ancestors(s, this.hoist).includes(n.id))) this.hoist = isLibraryRoot(s, n.parent) ? null : n.parent;
this.focus = { node: this.snap.nodes[next] ? next : n.parent, grain: "node" };
this.remember();
this.say(`Deleted “${clip(label(s, n.id), 40)}”. u to undo.`);
@@ -1971,7 +1922,7 @@ class Store {
this.afterEdit(n.parent, `the subsections were reordered`);
}
/** >: make it a child of the section above. <: lift it out beside its parent. Either may carry it into another document. */
/** >: make it a child of the section above. <: lift it out beside its parent. M moves it under any node. */
indent(delta: number) {
if (!this.writable()) return;
const s = this.snap;
@@ -2054,9 +2005,9 @@ class Store {
// The agent's work arrives by merge, which the undo stack does not see. If it was the last
// thing to happen, undo means going back to the commit before it.
if (!redo && this.agentUndo) {
const { commit, doc } = this.agentUndo;
const { commit, top } = this.agentUndo;
this.agentUndo = null;
this.attempt(() => (doc ? revertDocTo(this.doc, commit, doc) : revertTo(this.doc, commit)));
this.attempt(() => (top ? revertSubtreeTo(this.doc, commit, top) : revertTo(this.doc, commit)));
this.repairView();
return this.say("Undid the editor's changes (as a revert commit).");
}
@@ -2080,11 +2031,10 @@ class Store {
const f = this.focus;
const n = s.nodes[f.node];
if (f.grain === "node") {
if (this.listing(n.id)) return this.openDoc(n.id);
if (!this.isOpen(n.id)) return this.setOpen(n.id, true);
const kids = sections(s, n.id);
const closed = kids.filter((k) => !this.open.has(k));
if (closed.length && !isLibraryRoot(s, n.id)) {
if (closed.length) {
closed.forEach((k) => this.open.add(k));
this.saveView();
// In panes a child's pane only shows once it is focused, so say what changed.
@@ -2225,8 +2175,6 @@ class Store {
if (!text) return;
const [verb, ...rest] = text.split(/\s+/);
const arg = rest.join(" ");
const here = this.currentDoc;
const needDoc = (fn: (id: NodeId) => void) => () => (here ? fn(here) : this.say("Open a document first (m), or name it in the menu."));
const builtin: Record<string, () => void> = {
branch: () => {
this.newBranch(arg, this.branchFrom ?? undefined);
@@ -2245,18 +2193,15 @@ class Store {
colors: () => this.setColors(arg),
view: () => (["auto", "column", "panes"].includes(arg) ? this.setView(arg as View) : this.say(`/view auto, column or panes (now ${this.settings.view}, showing ${this.panes ? "panes" : "column"})`)),
resolve: () => this.resolveAll(),
new: () => (arg ? this.newDoc(arg) : this.openMenu("new")),
open: () => this.openByName(arg),
rename: needDoc((id) => (arg ? this.renameDocument(id, arg) : this.say("Give the new title: /rename <title>"))),
duplicate: needDoc((id) => this.duplicateDocument(id, arg || `${this.snap.nodes[id].title} (copy)`)),
export: needDoc((id) => this.exportDocument(id)),
duplicate: () => this.duplicateNode(arg),
export: () => this.exportNode(),
import: () => this.pickFile(),
recover: () => this.recover(),
link: () => this.linkTo(arg),
unlink: () => this.unlink(),
autolink: () => this.setAutolink(arg),
linkdoc: needDoc((id) => void this.linkJob("doc", id)),
linkall: () => void this.linkJob("library"),
linkhere: () => void this.linkJob(this.activeNode),
linkall: () => void this.linkJob(this.snap.root),
linkcancel: () => void this.cancelLinkJob(),
research: () => this.agent(arg, { research: true }),
};
@@ -2800,7 +2745,7 @@ class Store {
if (typeof parsed === "string") return this.say(parsed);
let ref: Ref = parsed;
if (ref.kind === "node") {
const id = resolveNode(this.snap, ref, docOf(this.snap, spot.node) ?? undefined);
const id = resolveNode(this.snap, ref, spot.node);
if (!id) return this.say(`No node at ${text}.`);
ref = nodeRef(this.snap, id);
}
@@ -2898,7 +2843,7 @@ class Store {
const sources = result.sources.length ? ` · sources: ${result.sources.map((s) => (s.title ? `${clip(s.title, 40)} (${hostOf(s.url)})` : hostOf(s.url))).join(", ")}` : "";
this.say(`editor: ${clip(run.summary, 160)}${result.commits ? ` (${result.commits} change${result.commits > 1 ? "s" : ""}; u undoes, g reviews)` : ""}${sources}`);
if (result.commits) {
this.agentUndo = { commit: before, doc: docOf(doc.snap(), focus) };
this.agentUndo = { commit: before, top: topOf(doc.snap(), focus) };
await this.afterMerge(result.report);
}
} catch (err) {
@@ -2962,16 +2907,19 @@ class Store {
this.say(`Removed the link on “${clip(quote, 40)}”; it will not be made again here · u undoes`);
}
/** S: the links list of the current document (or, on the library, of the focused node). It opens at once; what the server has is fetched fresh behind it. */
/**
* S: the links list of the node the reader is on and everything under it; on the library root,
* of the whole library. It opens at once, on the first row waiting for a decision, else the
* first shown; what the server has is fetched fresh behind it.
*/
startReview() {
if (!this.writable()) return;
const s = this.snap;
const d = this.currentDoc;
const ids = d ? [d, ...descendants(s, d)] : [this.focus.node];
const review = { ids, show: { linked: true, pending: true, rejected: false } as Record<Status, boolean>, key: null as string | null };
const node = this.activeNode;
const ids = isLibraryRoot(s, node) ? [s.root, ...tops(s).flatMap((t) => [t, ...descendants(s, t)])] : [node, ...descendants(s, node)];
const review = { node, ids, show: { linked: true, pending: true, rejected: false } as Record<Status, boolean>, key: null as string | null };
this.review = review;
this.mode = "review";
// The first row waiting for a decision, else the first shown.
const first = () => {
if (this.review !== review || review.key) return;
const rows = this.reviewRows();
@@ -2980,7 +2928,7 @@ class Store {
};
first();
this.emit();
if (d) void this.links.loadDoc(d, true).then(() => (first(), this.emit()));
void this.links.loadSubtree(node, true).then(() => (first(), this.emit()));
}
/** Every row of the links list, whatever the filters. */
@@ -3145,9 +3093,12 @@ class Store {
this.say(c === "off" ? "colors off: forks in plain ink" : `colors ${c}`);
}
/** /linkdoc, /linkall: scan in the background on the server; progress shows in the status line. */
async linkJob(scope: "doc" | "library", doc?: NodeId, quiet = false) {
const r = await this.links.startJob(scope, doc);
/**
* /linkhere, /linkall: scan a node and everything under it (on the library root, the whole
* library) in the background on the server; progress shows in the status line.
*/
async linkJob(node: NodeId, quiet = false) {
const r = await this.links.startJob(isLibraryRoot(this.doc.snap(), node) ? "library" : "node", node);
if (typeof r === "string") return this.say(`Could not start looking for links: ${r}`);
// Already over (a short job announced its end first): that has been said.
if (r.state === "running" && (!quiet || r.slow)) this.say(this.jobText(r));
@@ -3188,9 +3139,9 @@ class Store {
}
if (before?.id === j.id && before.state !== "running") return;
void (async () => {
const docs = j.doc ? [j.doc] : documents(this.doc.snap());
const scope = j.node ? [j.node] : tops(this.doc.snap());
const claim = !!j.review && this.links.effective() === "review";
const got = await Promise.all(docs.map((d) => this.links.loadDoc(d, true, claim)));
const got = await Promise.all(scope.map((id) => this.links.loadSubtree(id, true, claim)));
let made: number | undefined;
if (claim) made = this.links.applyAuto(got.flatMap((g) => g.apply), this.doc, "reviewer").length;
else if (j.state === "done" && this.settings.autolink === "on") {
@@ -3208,127 +3159,33 @@ class Store {
while (!this.session.synced() && Date.now() < until) await new Promise((r) => setTimeout(r, 100));
}
// ---- documents: the menu (m) and what it does ----
// ---- a node and everything under it: copy, export, import, move ----
openMenu(prompt?: "new") {
const items = this.menuItems("");
const here = this.currentDoc;
this.menu = { filter: "", selected: items.find((d) => d.node === here)?.node ?? items[0]?.node ?? null, focus: "filter", prompt: null, confirm: null, problems: null };
this.mode = "docs";
if (prompt) this.menuPrompt(prompt);
this.emit();
}
closeMenu() {
this.mode = "normal";
this.emit();
}
/** The menu's rows: the documents matching the filter, in library order. */
menuItems(filter = this.menu.filter): DocInfo[] {
const terms = filter.toLowerCase().split(/\s+/).filter(Boolean);
const rows = listDocs(this.doc.snap());
return terms.length ? rows.filter((d) => terms.every((t) => `${d.title} ${d.slug} ${d.excerpt}`.toLowerCase().includes(t))) : rows;
}
menuSelected(): DocInfo | undefined {
const items = this.menuItems();
return items.find((d) => d.node === this.menu.selected) ?? items[0];
}
menuMove(delta: number) {
const items = this.menuItems();
if (!items.length) return;
const i = items.findIndex((d) => d.node === this.menuSelected()?.node);
this.menu.selected = items[Math.max(0, Math.min(items.length - 1, i + delta))].node;
this.emit();
}
menuFilter(text: string) {
this.menu.filter = text;
this.menu.selected = this.menuItems()[0]?.node ?? null;
this.emit();
}
/** Ask for a title in the menu: for a new document, or to rename or duplicate the selected one. */
menuPrompt(kind: "new" | "rename" | "duplicate") {
const d = this.menuSelected();
if (kind !== "new" && !d) return;
this.menu.prompt = { kind, id: d?.node, value: kind === "new" ? "" : kind === "rename" ? d!.title : `${d!.title} (copy)` };
this.menu.confirm = null;
this.emit();
}
menuSubmit(value: string) {
const p = this.menu.prompt;
this.menu.prompt = null;
this.menu.focus = "list";
this.emit();
if (!p) return;
if (p.kind === "new") this.newDoc(value);
else if (p.kind === "rename") this.renameDocument(p.id!, value);
else this.duplicateDocument(p.id!, value);
}
/** A document command on the replica on screen: refused while viewing history, reported if refused. */
private docWrite(fn: () => void) {
/** A write on the replica on screen: refused while viewing history, reported if refused. */
private nodeWrite(fn: () => void) {
if (!this.writable()) return;
this.agentUndo = null;
this.attempt(fn);
}
newDoc(title: string) {
title = title.replace(/\s+/g, " ").trim();
if (!title) return this.say("A new document needs a title: /new <title>");
this.docWrite(() => {
const id = createDoc(this.doc, title, this.user);
this.openDoc(id, true);
this.say(`Created “${clip(title, 60)}”: c writes its opening text, a adds a section.`);
/** /duplicate [title]: a copy of the active node and everything under it, placed just after it, which then has the focus. */
duplicateNode(title = "") {
const s = this.snap;
const id = this.activeNode;
if (isLibraryRoot(s, id)) return this.say("The library itself is not copied: /export saves it to a file.");
const name = title.replace(/\s+/g, " ").trim() || `${s.nodes[id].title} (copy)`;
this.nodeWrite(() => {
const parent = s.nodes[id].parent!;
const index = s.nodes[parent].children.indexOf(id) + 1;
const [copy] = this.doc.as(this.user, () => this.doc.apply([{ op: "copy", id, parent, index, title: name }], `Duplicate “${clip(s.nodes[id].title, 40)}” as “${clip(name, 40)}”`).created);
this.go(copy);
this.remember(true);
this.say(`Saved a copy as “${clip(name, 60)}”, just after the original; this is the copy.`);
});
}
/** Links keep working (they go by node id); on this branch, and u undoes it. */
renameDocument(id: NodeId, title: string) {
title = title.replace(/\s+/g, " ").trim();
if (!title) return this.say("A document needs a title.");
this.docWrite(() => {
renameDoc(this.doc, id, title, this.user);
this.remember();
this.say(`Renamed to “${clip(title, 60)}”.`);
});
}
/** Save as: a copy of the whole document, placed after it, which then opens. */
duplicateDocument(id: NodeId, title: string) {
title = title.replace(/\s+/g, " ").trim();
if (!title) return this.say("The copy needs a title.");
this.docWrite(() => {
const copy = duplicateDoc(this.doc, id, title, this.user);
this.openDoc(copy, true);
this.say(`Saved a copy as “${clip(title, 60)}”; this is the copy.`);
});
}
/** Delete (after the menu has asked): an ordinary delete, which u undoes. */
deleteDocument(id: NodeId) {
this.menu.confirm = null;
const s = this.doc.snap();
const title = s.nodes[id]?.title ?? "";
this.docWrite(() => {
const leaving = this.currentDoc === id || (this.hoist && docOf(s, this.hoist) === id);
deleteDoc(this.doc, id, this.user);
if (leaving) {
this.hoist = null;
this.focus = { node: s.root, grain: "node" };
this.remember(true);
}
this.repairView();
this.say(`Deleted “${clip(title, 50)}”. u brings it back.`);
});
}
/** Save to a file: the text format, written from this replica, so unsynced edits are included. */
exportDocument(id: NodeId) {
/** /export: the active node and everything under it, to a file in the text format, written from this replica, so unsynced edits are included. */
exportNode(id = this.activeNode) {
const s = this.doc.snap();
const n = s.nodes[id];
if (!n) return;
@@ -3337,11 +3194,13 @@ class Store {
const name = this.repo.current === "main" ? `${base}.md` : `${base}-${this.repo.current.replace(/[^\w-]+/g, "-")}.md`;
download(name, text);
const left = [skipped.orphans && `${skipped.orphans} orphaned note${skipped.orphans > 1 ? "s" : ""}`, skipped.inNotes && `${skipped.inNotes} section${skipped.inNotes > 1 ? "s" : ""} inside notes`].filter(Boolean);
this.say(`Saved “${clip(n.title, 50)}” to ${name}${left.length ? `. Left out: ${left.join(" and ")} (the format has no place for them)` : ""}.`);
this.say(`Saved “${clip(label(s, id), 50)}” to ${name}${left.length ? `. Left out: ${left.join(" and ")} (the format has no place for them)` : ""}.`);
}
/** Open a file: a file picker, whose choice is imported. */
/** /import: a file picker, whose choice is imported under the active node. */
pickFile() {
if (!this.writable()) return;
const parent = this.activeNode;
const input = document.createElement("input");
input.type = "file";
input.accept = ".md,.markdown,.txt,text/markdown,text/plain";
@@ -3349,42 +3208,81 @@ class Store {
input.onchange = () => {
const file = input.files?.[0];
input.remove();
if (file) void this.importFile(file);
if (file) void this.importFile(file, parent);
};
document.body.append(input);
input.click();
}
/** A .md file as a new document at the end of the library. */
async importFile(file: File) {
/** A .md file as a new last child of a node (the active one by default; on the library root, a new top-level node). */
async importFile(file: File, parent = this.activeNode) {
if (file.size > IMPORT_MAX) return this.say(`${file.name} is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB).`);
if (!this.writable()) return;
const text = await file.text();
if (!this.doc.snap().nodes[parent]) return this.say(`Could not import ${file.name}: the node it was to go under is gone.`);
try {
const id = importDoc(this.doc, text, file.name, { creator: this.user });
this.openDoc(id, true);
this.say(`Imported ${file.name} as “${clip(this.doc.snap().nodes[id].title, 60)}”.`);
const id = importTree(this.doc, text, file.name, { creator: this.user, parent });
this.agentUndo = null;
this.go(id);
this.remember(true);
const s = this.doc.snap();
this.say(`Imported ${file.name} as “${clip(s.nodes[id].title, 60)}”${isLibraryRoot(s, parent) ? "" : `, under “${clip(label(s, parent), 40)}”`}.`);
// Imported text is scanned like any other writing: by a background job, once the server has it.
if (this.settings.autolink !== "off") void this.whenSynced().then(() => this.linkJob("doc", id, true));
if (this.settings.autolink !== "off") void this.whenSynced().then(() => this.linkJob(id, true));
} catch (err) {
if (!(err instanceof FormatError)) return this.say(`Could not import ${file.name}: ${err instanceof Error ? err.message : err}`);
if (this.mode !== "docs") this.openMenu();
this.menu.problems = err.problems;
this.say(`Could not import ${file.name}: ${err.problems.length} problem${err.problems.length > 1 ? "s" : ""}, listed in the menu.`);
const n = err.problems.length;
this.say(`Could not import ${file.name}: ${err.problems[0]}${n > 1 ? ` (and ${n - 1} more problem${n > 2 ? "s" : ""})` : ""}`);
}
}
/** /open name: by slug, then by title (exact, then its start, then anywhere). */
openByName(name: string) {
const q = name.trim().toLowerCase();
if (!q) return this.openMenu();
const all = this.menuItems("");
const d =
all.find((x) => x.slug === q) ?? all.find((x) => x.title.toLowerCase() === q) ?? all.find((x) => x.title.toLowerCase().startsWith(q)) ??
all.find((x) => `${x.title} ${x.slug}`.toLowerCase().includes(q));
if (!d) return this.say(`No document matches “${name}”. m lists them.`);
this.openDoc(d.node, true);
this.say(`Opened “${clip(d.title, 60)}”.`);
/** M: pick a node to move the active node (and everything under it) under. The jump box is the picker. */
startMove() {
if (!this.writable()) return;
const id = this.activeNode;
if (isLibraryRoot(this.snap, id)) return this.say("The library root stays where it is: M moves a node under another.");
this.moving = id;
this.mode = "move";
this.emit();
}
/** What the move picker offers for a query: the library root and its sections, never the node being moved or anything under it. */
moveTargets(q: string): NodeId[] {
const s = this.snap;
const id = this.moving;
const away = new Set(id && s.nodes[id] ? [id, ...descendants(s, id)] : []);
const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
const root = !terms.length || terms.every((t) => s.nodes[s.root].title.toLowerCase().includes(t)) ? [s.root] : [];
const found = terms.length ? this.search(q, away) : tops(s).filter((t) => !away.has(t));
return [...root, ...found].slice(0, 12);
}
/** Enter in the move picker: the node goes under the one chosen, as its last child, in one commit (u undoes). */
moveUnder(target: NodeId) {
const id = this.moving;
this.moving = null;
this.mode = "normal";
const s = this.snap;
if (!id || !s.nodes[id] || !s.nodes[target]) return this.emit();
if (target === id || ancestors(s, target).includes(id)) return this.say("A node cannot go under itself or anything under it.");
const n = s.nodes[id];
if (n.parent === target) return this.say(`“${clip(label(s, id), 40)}” is under “${clip(label(s, target), 40)}” already.`);
const from = n.parent!;
this.nodeWrite(() => {
this.doc.as(this.user, () => this.doc.apply([{ op: "move", id, parent: target }], `Move “${clip(label(s, id), 40)}” under “${clip(label(s, target), 40)}”`));
this.open.add(target);
this.go(id);
this.remember(true);
this.say(`Moved “${clip(label(s, id), 40)}” under “${clip(label(s, target), 40)}”. u undoes.`);
if (!isLibraryRoot(s, target)) this.afterEdit(target, `the subsection “${n.title}” was moved in`);
if (!isLibraryRoot(s, from)) this.afterEdit(from, `the subsection “${n.title}” was moved out`);
});
}
/** Esc in the move picker. */
cancelMove() {
this.moving = null;
this.setMode("normal");
}
// ---- history, branches, merge ----
@@ -3398,33 +3296,37 @@ class Store {
}
/**
* The documents a commit wrote to, derived from the containers its ops changed (the commit
* itself does not record them), placed by where those nodes are now. A node deleted since
* cannot be placed without checking out the past, which costs the size of the library, so a
* commit that only deleted names no document.
* The nodes a commit wrote to, derived from the containers its ops changed (the commit itself
* does not record them), that are still in the library.
*/
touchedDocs(c: Commit): NodeId[] {
touchedNodes(c: Commit): NodeId[] {
const key = `${this.repo.current}:${c.id}`;
let out = this.touchedCache.get(key);
if (out) return out;
const s = this.doc.snap();
const docs = new Set<NodeId>();
for (const id of touched(this.doc, c.spans).nodes) {
const d = s.nodes[id] ? docOf(s, id) : null;
if (d) docs.add(d);
}
out = [...docs];
out = [...touched(this.doc, c.spans).nodes].filter((id) => s.nodes[id]);
this.touchedCache.set(key, out);
return out;
}
/**
* Where a commit wrote, for its line in history: the top-level nodes its nodes are under, placed
* by where those nodes are now. A node deleted since cannot be placed without checking out the
* past, which costs the size of the library, so a commit that only deleted names nothing.
*/
touchedTops(c: Commit): NodeId[] {
const s = this.doc.snap();
return [...new Set(this.touchedNodes(c).map((id) => topOf(s, id)).filter((t): t is NodeId => !!t))];
}
/** Items of the history panel, in the order j and k walk them. */
panel() {
const here = this.historyFilter ? this.currentDoc : null;
const s = this.doc.snap();
const conflicts = this.doc.conflicts().filter((c) => !here || [c.node, c.parent].some((x) => x && s.nodes[x] && docOf(s, x) === here));
const here = this.historyFilter && s.nodes[this.historyFilter] ? this.historyFilter : null;
const under = here ? new Set([here, ...descendants(s, here)]) : null;
const conflicts = this.doc.conflicts().filter((c) => !under || [c.node, c.parent].some((x) => x && under.has(x)));
const branches = [...this.repo.branches.keys()];
const commits = here ? this.commits().filter((c) => this.touchedDocs(c).includes(here)) : this.commits();
const commits = under ? this.commits().filter((c) => this.touchedNodes(c).some((id) => under.has(id))) : this.commits();
return [
...conflicts.map((c) => ({ type: "conflict" as const, conflict: c })),
...branches.map((b) => ({ type: "branch" as const, branch: b })),
@@ -3432,16 +3334,19 @@ class Store {
];
}
/** f in history: show only what touched the current document, or everything. */
/** f in history: show only what touched the active node and what is under it, or everything. */
toggleHistoryFilter() {
if (!this.historyFilter && !this.currentDoc) return this.say("Open a document first: the filter shows what touched the current one.");
this.historyFilter = !this.historyFilter;
const id = this.activeNode;
if (!this.historyFilter && isLibraryRoot(this.doc.snap(), id)) return this.say("On the library root history shows everything: focus a node first, and f shows only what touched it and what is under it.");
this.historyFilter = this.historyFilter ? null : id;
this.historyIndex = 0;
this.emit();
}
openHistory() {
this.mode = "history";
// The filter follows the reader: on another node it is that node's.
if (this.historyFilter) this.historyFilter = isLibraryRoot(this.doc.snap(), this.activeNode) ? null : this.activeNode;
this.historyIndex = Math.min(this.historyIndex, this.panel().length - 1);
const firstCommit = this.panel().findIndex((i) => i.type === "commit");
if (!this.doc.conflicts().some((c) => c.status === "open")) this.historyIndex = Math.max(this.historyIndex, firstCommit);
@@ -3476,17 +3381,19 @@ class Store {
}
/**
* r in history: roll the current document back to the commit, leaving the rest of the library
* as it is. On the library itself, the whole library goes back.
* r in history: roll the active node and everything under it back to the commit, leaving the
* rest of the library as it is. On the library root, the whole library goes back.
*/
revert(commit: Commit) {
this.preview = null;
const here = this.currentDoc;
const s = this.doc.snap();
if (!s.nodes[this.focus.node]) return this.repairView(), this.say("The node you were on is gone now: pick one, then r reverts it.");
const here = isLibraryRoot(s, this.activeNode) ? null : this.activeNode;
this.attempt(() => {
if (here) revertDocTo(this.doc, commit, here);
if (here) revertSubtreeTo(this.doc, commit, here);
else revertTo(this.doc, commit);
this.repairView();
this.say(here ? `Reverted “${clip(this.snap.nodes[here]?.title ?? "", 40)}” to “${clip(commit.message, 50)}” as a new commit; the rest of the library is unchanged.` : `Reverted the library to “${clip(commit.message, 50)}” as a new commit.`);
this.say(here ? `Reverted “${clip(label(this.snap, here), 40)}” and what is under it to “${clip(commit.message, 50)}” as a new commit; the rest of the library is unchanged.` : `Reverted the library to “${clip(commit.message, 50)}” as a new commit.`);
});
this.repairView();
this.emit();
@@ -3568,12 +3475,12 @@ class Store {
this.repairView();
}
/** Sections matching a query, across the whole library, for the jump box. */
search(q: string): NodeId[] {
/** Sections matching a query, across the whole library, for the jump box (and the move picker, leaving out `skip`). */
search(q: string, skip?: Set<NodeId>): NodeId[] {
const s = this.snap;
const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
const all = Object.values(s.nodes).filter((n) => n.kind === "section" && n.id !== s.root && !inArticles(s, n.id));
if (!terms.length) return documents(s).slice(0, 12);
const all = Object.values(s.nodes).filter((n) => n.kind === "section" && n.id !== s.root && !inArticles(s, n.id) && !skip?.has(n.id));
if (!terms.length) return tops(s).slice(0, 12);
const low = (n: (typeof all)[number]) => {
let l = lowered.get(n);
if (!l) lowered.set(n, (l = [n.title.toLowerCase(), n.body.toLowerCase()]));
@@ -3590,19 +3497,18 @@ class Store {
}
return total;
};
// Between equally good matches, the document the reader is in comes first.
const here = this.currentDoc;
const near = (id: NodeId) => (here && docOf(s, id) === here ? 0.5 : 0);
// Between equally good matches, those in the same top-level tree as the reader come first.
const here = s.nodes[this.focus.node] ? topOf(s, this.focus.node) : null;
const near = (id: NodeId) => (here && topOf(s, id) === here ? 0.5 : 0);
return all.map((n) => [n.id, score(n)] as const).filter(([, sc]) => sc > 0).map(([id, sc]) => [id, sc + near(id)] as const).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([id]) => id);
}
/** Enter in the jump box: a document opens; anything else is gone to, in whichever document it is. */
/** Enter in the jump box: the node is gone to, wherever it is (outside the hoisted node, the page goes back to the library). */
jumpTo(id: NodeId) {
this.mode = "normal";
this.aux = null;
this.colWiki = null;
const s = this.snap;
if (s.library && s.nodes[id]?.parent === s.root) return this.openDoc(id, true);
if (!this.snap.nodes[id]) return this.emit();
this.reveal(id);
this.focus = { node: id, grain: "node" };
this.saveView();
+12 -36
View File
@@ -187,7 +187,8 @@ article { width: min(100%, var(--col)); }
.node.open.d3 > .row > .title, .node.open.d6 > .row > .title { font-weight: 500; font-variant-caps: small-caps; letter-spacing: 0.02em; }
.node.focused > .row { background: var(--sel); }
.node.focused > .row .mark { color: var(--fg); }
.flags { margin-left: auto; padding-left: 1em; flex: none; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.05em; text-transform: uppercase; color: var(--faint); white-space: nowrap; }
/* Flags give way (cut short) before a cramped row runs off a narrow screen. */
.flags { margin-left: auto; padding-left: 1em; flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.05em; text-transform: uppercase; color: var(--faint); white-space: nowrap; }
.flags.attn { color: var(--attn); }
.byline .flags { margin-left: 0.8em; padding: 0; }
@@ -234,10 +235,10 @@ article.preview { opacity: 0.92; }
.lrow.rejected .lq, .lrow.rejected .lt { color: var(--faint); }
.lrow .sub { overflow-wrap: anywhere; }
.lrow .lwhere { color: var(--dim); }
.lempty { color: var(--faint); margin: 0.8rem 0.45rem; }
.lempty, .lmore { color: var(--faint); margin: 0.8rem 0.45rem; }
.hash { font-family: var(--mono); font-size: 0.62rem; color: var(--faint); flex: none; }
/* The documents a commit touched. */
.item .docs { color: var(--dim); font-size: 0.62rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* The top-level nodes a commit touched. */
.item .under { color: var(--dim); font-size: 0.62rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chip { margin-left: auto; font-size: 0.58rem; letter-spacing: 0.06em; text-transform: uppercase; border: 1px solid var(--rule); padding: 0 0.35em; border-radius: 2px; color: var(--dim); }
.conflict.open .chip { color: var(--attn); border-color: var(--attn); }
.sides { margin-top: 0.4rem; display: grid; gap: 0.35rem; font-family: var(--serif); font-size: 0.74rem; line-height: 1.4; cursor: default; }
@@ -273,6 +274,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.jump li .p { color: var(--faint); font-size: 0.66rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.jump li .p .in { font-weight: 600; color: var(--dim); }
.jump li.none { color: var(--faint); cursor: default; }
.jump-head { padding: 0.45rem 0.8rem 0; font-size: 0.62rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.popup {
position: fixed; width: 440px; max-height: 320px; overflow: auto; z-index: 15;
@@ -581,49 +583,23 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.orphan-note { text-transform: none; letter-spacing: 0.02em; font-style: italic; }
/* The first pane keeps the page title, set from the left so it stays readable when the pane is partly covered. */
.pane.root .top h1, .pane.root .byline, .pane.doc .top h1, .pane.doc .byline { text-align: left; }
.pane.root .rows, .pane.doc .rows { margin-top: 0; padding-top: 0; border-top: 0; }
.pane.root .top h1, .pane.root .byline { text-align: left; }
/* A pane has no margin: notes are set into its column, as on a narrow screen. */
.pane .sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
.pane .sidenote.focused { border-left: 2px solid var(--fg); }
/* ---- end panes view ---- */
/* ---- the top bar and the documents menu (src/ui/Menu.tsx) ----
* The bar sits in the page's top margin: the document's title, which opens the menu, and whether
* the server has every edit yet. The menu is a panel like history's.
/* ---- the top bar (src/ui/Menu.tsx) ----
* The bar sits in the page's top margin: the library's name, and whether the server has every
* edit yet; undo, redo and the menu on the right.
*/
.docbar { display: flex; align-items: baseline; gap: 0.9em; width: min(100%, var(--col)); margin: -30px 0 16px; min-width: 0; font-family: var(--sans); font-size: 0.66rem; color: var(--faint); letter-spacing: 0.02em; }
.doc-title { display: flex; align-items: baseline; gap: 0.35em; min-width: 0; max-width: 75%; padding: 0; border: 0; background: none; font-size: inherit; color: var(--dim); }
.doc-title .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.doc-title .chev { align-self: center; width: 0; height: 0; border: 0.38em solid transparent; border-top: 0.46em solid var(--faint); border-bottom: 0; margin-left: 0.1em; }
.doc-title:hover .name { color: var(--fg); text-decoration: underline dotted; text-underline-offset: 0.2em; }
.lib-name { min-width: 0; max-width: 75%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dim); }
.save-state { white-space: nowrap; }
.save-state.offline, .save-state.deleted { color: var(--attn); }
.view-panes .docbar { flex: none; width: auto; margin: 0; padding: 0.3rem 0.9rem 0.25rem; border-bottom: 1px solid var(--hair); }
.panel .filter, .panel .prompt input {
display: block; width: 100%; margin: 0.6rem 0 0.3rem; padding: 0.3rem 0.5rem; font: inherit; font-size: 0.8rem;
color: var(--fg); background: var(--bg); border: 1px solid var(--rule); border-radius: 2px; outline: none;
}
.panel .filter:focus, .panel .prompt input:focus { border-color: var(--fg); }
.panel .prompt { display: block; margin-top: 0.5rem; }
.panel .prompt span { font-size: 0.6rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.panel .prompt input { margin-top: 0.15rem; }
.doclist { list-style: none; margin: 0.3rem 0 0; padding: 0; }
.doc { margin-bottom: 0.1rem; }
.doc .title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
.doc .when { flex: none; font-size: 0.6rem; color: var(--faint); }
.doc .sub { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.doc.current .title::before { content: "● "; font-size: 0.7em; color: var(--dim); }
.doc .actions { flex-wrap: wrap; margin: 0.3rem 0 0.1rem; }
.doclist .none { padding: 0.3rem 0.45rem; color: var(--faint); }
.confirm, .problems { margin: 0.5rem 0; padding: 0.45rem 0.6rem; background: var(--wash); border-left: 2px solid var(--attn); }
.confirm .actions { margin-top: 0.4rem; }
.problems ul { margin: 0.3rem 0 0; padding-left: 1.1rem; font-family: var(--mono); font-size: 0.6rem; overflow-wrap: anywhere; }
.panel-foot { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.5rem; margin-top: 0.9rem; padding-top: 0.6rem; border-top: 1px solid var(--hair); font-size: 0.62rem; color: var(--faint); }
.panel.docs.dropping { outline: 2px dashed var(--fg); outline-offset: -6px; }
/* ---- end documents ---- */
/* ---- end top bar ---- */
/* ---- links (src/ui/Links.tsx) ----
* After gwern.net's typed links: the linked words keep the text's colour and get a thin solid
+27 -15
View File
@@ -1,7 +1,7 @@
/** What the mouse offers (src/ui/actions.ts): every item does what its key does, and the bar, the ⋯ menus and the right-click menu are built from one place. */
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { articleRowEntries, barItems, nodeEntries, pageEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
import { articleRowEntries, barItems, nodeEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
/** An Act that records what was asked of it. */
function recorder() {
@@ -19,9 +19,9 @@ const items = (es: Entry[]): Item[] => es.filter((e): e is Item => e.t === "item
const labels = (es: Entry[]) => es.map((e) => (e.t === "item" ? e.label : e.t === "head" ? `# ${e.text}` : e.t === "choices" ? `[${e.label}: ${e.options.map((o) => o.label).join(" ")}]` : "--"));
const find = (es: Entry[], label: string) => items(es).find((i) => i.label === label)!;
const node = (more: Partial<NodeCtx> = {}): NodeCtx => ({ title: "Training", text: "Training\n\nIt is trained.", note: false, locked: false, target: false, library: false, doc: false, generating: true, ...more });
const node = (more: Partial<NodeCtx> = {}): NodeCtx => ({ title: "Training", text: "Training\n\nIt is trained.", note: false, locked: false, target: false, library: false, generating: true, ...more });
const sel = (more: Partial<SelCtx> = {}): SelCtx => ({ text: "a probability for each possible next piece", article: false, panes: false, ...more });
const top = (more: Partial<TopCtx> = {}): TopCtx => ({ view: "auto", autolink: "suggest", auto: true, speculate: false, curves: true, colors: "line", panes: false, doc: true, canRedo: false, ...more });
const top = (more: Partial<TopCtx> = {}): TopCtx => ({ view: "auto", autolink: "suggest", auto: true, speculate: false, curves: true, colors: "line", panes: false, canRedo: false, ...more });
/** Every key the page's handler takes, read from keys.ts: an item's key must be one of them. */
const handled = new Set([...readFileSync(new URL("../src/ui/keys.ts", import.meta.url), "utf8").matchAll(/case "([^"]+)":/g)].map((m) => m[1]));
@@ -33,7 +33,7 @@ describe("actions", () => {
...barItems(sel(), act).flat(),
...items(selectionEntries(sel({ link: "wiki", note: true, suggestion: "Hoyle state", related: [{ title: "Nodes" }], panes: true }), act)),
...items(nodeEntries(node({ stale: "parent", target: true, note: true }), act)),
...items(pageEntries(node({ doc: true }), act)),
...items(nodeEntries(node({ library: true }), act)),
...items(paneEntries({ node: node(), pinned: false }, act)),
...items(paneEntries({ article: "Octopus", pinned: true }, act)),
...items(articleRowEntries("Octopus", true, act)),
@@ -57,7 +57,7 @@ describe("actions", () => {
it("the selection menu puts Copy first, then what the words carry, then the lenses, linking and Related", () => {
const { act, calls } = recorder();
const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", doc: "Infinispand" }, { title: "Nodes" }] }), act);
const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", where: "Infinispand" }, { title: "Nodes" }] }), act);
expect(labels(plain)).toEqual([
"# “a probability for each possible next piece”",
"Copy",
@@ -108,20 +108,28 @@ describe("actions", () => {
expect(find(nodeEntries(node(), act), "Lock").checked).toBe(false);
expect(labels(nodeEntries(node(), act)).join("|")).not.toMatch(/pin/i);
const lib = labels(nodeEntries(node({ library: true }), act));
for (const l of ["Delete", "Lock", "Add a section after", "[Move: up down in out]", "Show only this"]) expect(lib).not.toContain(l);
expect(lib).toContain("Add a document");
for (const l of ["Delete", "Lock", "Add a section after", "[Move: up down in out]", "Move under…", "Show only this", "Save a copy"]) expect(lib).not.toContain(l);
// The library root is a node like any other: it takes a section, and is exported, imported into and scanned like one.
for (const l of ["Add a section inside", "Export as .md", "Import a .md file into it…", "Find links here"]) expect(lib).toContain(l);
expect(labels(nodeEntries(node({ note: true }), act))).toContain("Change its form");
find(nodeEntries(node(), act), "Research on the web…").run();
expect(calls).toEqual(["prompt /research "]);
expect(labels(nodeEntries(node({ generating: false }), act))).not.toContain("Research on the web…");
});
it("a page adds the document's own items; a pane adds pin, close and the column", () => {
it("every node offers what acts on it and everything under it, a note none of it; a pane adds pin, close and the column", () => {
const { act, calls } = recorder();
const page = pageEntries(node({ doc: true }), act);
expect(labels(page).slice(-2)).toEqual(["Save a copy", "Export as .md"]);
find(page, "Export as .md").run();
expect(calls).toEqual(["command /export"]);
const any = nodeEntries(node(), act);
expect(labels(any).slice(-7)).toEqual(["--", "Find links here", "Save a copy", "Export as .md", "Import a .md file into it…", "--", "Delete"]);
expect(find(any, "Move under…")).toMatchObject({ key: "M" });
for (const [label, cmd] of [["Find links here", "/linkhere"], ["Save a copy", "/duplicate"], ["Export as .md", "/export"], ["Import a .md file into it…", "/import"]]) {
calls.length = 0;
find(any, label).run();
expect(calls).toEqual([`command ${cmd}`]);
}
const note = labels(nodeEntries(node({ note: true }), act));
for (const l of ["Move under…", "Save a copy", "Export as .md", "Import a .md file into it…", "Find links here"]) expect(note).not.toContain(l);
calls.length = 0;
const pane = paneEntries({ node: node(), pinned: true }, act);
expect(labels(pane).slice(-3)).toEqual(["Pin this pane", "Close this pane", "Show as one column"]);
expect(find(pane, "Pin this pane").checked).toBe(true);
@@ -131,7 +139,7 @@ describe("actions", () => {
expect(go.options.map((o) => `${o.label} ${o.key}`)).toEqual(["left A-h", "right A-l", "above A-k", "below A-j"]);
});
it("the top menu: documents, history, undo and redo, links, the layout and settings as commands", () => {
it("the top menu: jump, history, undo and redo, links, the layout and settings as commands", () => {
const { act, calls } = recorder();
const es = topEntries(top(), act);
expect(find(es, "Redo").disabled).toBe(true);
@@ -148,8 +156,12 @@ describe("actions", () => {
expect(colors.options.map((o) => `${o.label}${o.on ? "*" : ""}`)).toEqual(["line*", "top", "edge", "off"]);
colors.options[3].run();
expect(calls.at(-1)).toBe("command /colors off");
expect(labels(topEntries(top({ doc: false }), act))).not.toContain("Links found: review and reverse");
expect(labels(topEntries(top(), act))).toContain("Links found: review and reverse");
expect(labels(es)).not.toContain("Documents…");
expect(find(es, "Links found: review and reverse")).toMatchObject({ key: "S" });
calls.length = 0;
find(es, "Find links in the whole library").run();
find(es, "Find links here").run();
expect(calls).toEqual(["command /linkall", "command /linkhere"]);
});
it("tidy leaves no separator at an end or next to another", () => {
+3 -4
View File
@@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest";
import { annotationsOf, articleNodes, articleParent, containers, fold, inArticles, makeAnchor, reanchor, type ArticleKey, type SectionText } from "../src/core/article";
import { Doc, isStale, staleness, tops, type NodeId, type Op } from "../src/core/model";
import { mergeUpdate, verifyHistory } from "../src/core/repo";
import { listDocs } from "../src/core/library";
import type { Range } from "../src/core/text";
// ---- re-anchoring ----
@@ -138,9 +137,9 @@ const sync = (a: Doc, b: Doc) => {
};
describe("article nodes", () => {
it("are made on the first annotation, once; the container is not a document and nothing in it goes stale", () => {
it("are made on the first annotation, once; the container is not one of the root's sections and nothing in it goes stale", () => {
const doc = library();
const before = listDocs(doc.snap());
const before = tops(doc.snap());
expect(containers(doc.snap())).toEqual([]);
const first = annotate(doc, OCTOPUS, "arms");
const second = annotate(doc, { lang: "en", title: "octopus" }, "suckers");
@@ -152,7 +151,7 @@ describe("article nodes", () => {
expect(articleNodes(snap, { lang: "en", title: "Octopodes", pageId: 1200106 })).toHaveLength(1);
expect(articleNodes(snap, { lang: "fr", title: "Octopus" })).toHaveLength(0);
// Not one of the root's sections: not listed, no count.
expect(listDocs(snap)).toEqual(before);
expect(tops(snap)).toEqual(before);
expect(tops(snap)).toHaveLength(1);
const box = containers(snap)[0];
expect(inArticles(snap, first) && inArticles(snap, box) && !inArticles(snap, tops(snap)[0])).toBe(true);
+2 -2
View File
@@ -1,7 +1,7 @@
import { UndoManager } from "loro-crdt";
import { describe, expect, it } from "vitest";
import { Doc, SYSTEM_ORIGIN, ancestorsBelowRoot, isStale, retitleOps, staleness, sections, notesOf, topOf, tops, type NodeId } from "../src/core/model";
import { healAnchors, history, verifyHistory, revertTo, revertDocTo, mergeBranch, mergeUpdate, resolveConflict, reopenConflict, at, touched, Repo } from "../src/core/repo";
import { healAnchors, history, verifyHistory, revertTo, revertSubtreeTo, mergeBranch, mergeUpdate, resolveConflict, reopenConflict, at, touched, Repo } from "../src/core/repo";
import { formFor, paragraphs, sentences, sha256, words } from "../src/core/text";
function fixture() {
@@ -375,7 +375,7 @@ describe("library", () => {
doc.apply([{ op: "create", parent: a, title: "Added later" }], "Add a section");
doc.apply([{ op: "update", id: bLeaf, body: "Beta changed later too." }], "Change the other document");
const beta = doc.shape(doc.snap(), b);
revertDocTo(doc, mark, a);
revertSubtreeTo(doc, mark, a);
const snap = doc.snap();
expect(doc.shape(snap, a)).toBe(doc.shape(at(doc, mark).snap(), a));
expect(doc.shape(snap, b)).toBe(beta);
+5 -5
View File
@@ -10,7 +10,7 @@ import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
import { LibraryStore } from "../server/library";
import { Doc, descendants, isStale, tops, type NodeId } from "../src/core/model";
import { at, history, mergeBranch, revertDocTo, revertTo, verifyHistory } from "../src/core/repo";
import { at, history, mergeBranch, revertSubtreeTo, revertTo, verifyHistory } from "../src/core/repo";
const temp = () => mkdtempSync(join(tmpdir(), "ie-migrate-"));
@@ -88,7 +88,7 @@ describe("migration from the per-document layout", () => {
// One library: the first document first, then most recently changed first.
expect(snap.library).toBe(true);
expect(store.list().map((d) => d.title)).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
expect(store.titles()).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
const [nFirst, nTides, nCopy] = tops(snap);
for (const [node, old] of [[nFirst, first], [nTides, tides], [nCopy, copy]] as const) {
expect(lib.shape(snap, node)).toBe(old.shape());
@@ -117,7 +117,7 @@ describe("migration from the per-document layout", () => {
// Reverting the whole library to before it existed is refused; reverting the document to then works.
const humanEdit = h.find((c) => c.message === "Human edit")!;
expect(() => revertTo(lib, humanEdit)).toThrow(/before the library existed/);
revertDocTo(lib, humanEdit, first.snap().root);
revertSubtreeTo(lib, humanEdit, first.snap().root);
expect(lib.snap().nodes[one].title).toBe("One");
expect(lib.shape(lib.snap(), nTides)).toBe(tides.shape());
expect(verifyHistory(lib).mismatches).toEqual([]);
@@ -155,7 +155,7 @@ describe("migration from the per-document layout", () => {
const logs: string[] = [];
const store = new LibraryStore(data, (m) => logs.push(m)).open();
const snap = store.main.snap();
expect(store.list().map((d) => d.title)).toEqual(["Infinite Expand"]);
expect(store.titles()).toEqual(["Infinite Expand"]);
expect(store.main.shape(snap, tops(snap)[0])).toBe(main.shape());
expect(readdirSync(data).filter((f) => f.endsWith(".loro"))).toEqual([]);
expect(existsSync(join(data, "notes.txt"))).toBe(true); // anything else is left alone
@@ -169,7 +169,7 @@ describe("migration from the per-document layout", () => {
const data = temp();
const store = new LibraryStore(data, () => {}).open();
expect(store.main.snap().library).toBe(true);
expect(store.list()).toEqual([]);
expect(store.titles()).toEqual([]);
expect(readdirSync(data)).toEqual(["library"]);
});
});
+32
View File
@@ -332,6 +332,38 @@ describe("the scan route in review mode", () => {
expect(marked.suggestions.find((s: Suggestion) => s.kind === "forced")).toBeTruthy();
expect(marked.entries.find((s: Suggestion) => s.kind === "forced").review).toBeUndefined();
});
it("scopes by node: a node and everything under it (/linkhere), or on the library root the whole library (/linkall); pending lists a subtree", async () => {
const snap = ids.doc.snap();
expect(scopeNodes(snap, ids.minds)).toEqual([ids.minds, ids.arms]);
expect(scopeNodes(snap, ids.arms)).toEqual([ids.arms]);
expect(scopeNodes(snap, null)).toEqual([ids.minds, ids.arms, ids.stars]);
expect(scopeNodes(snap, ids.lib)).toEqual(scopeNodes(snap, null));
const done = async () => {
for (let i = 0; i < 200; i++) {
const { job } = await (await fetch(`${base}/api/links/jobs`)).json();
if (job.state !== "running") return job as JobState;
await new Promise((r) => setTimeout(r, 20));
}
throw new Error("the job did not finish");
};
expect((await post("jobs", { scope: "node", node: ids.minds })).job).toMatchObject({ scope: "node", node: ids.minds, title: "Octopus minds", total: 2 });
expect(await done()).toMatchObject({ state: "done", done: 2 });
expect((await post("jobs", { scope: "node", node: ids.lib })).job).toMatchObject({ scope: "library", title: "the library", total: 3 });
await done();
const lib = (await post("jobs", { scope: "library" })).job;
expect(lib).toMatchObject({ scope: "library", total: 3 });
expect(lib.node).toBeUndefined();
await done();
expect((await post("jobs", { scope: "doc", doc: "octopus-minds" })).error).toMatch(/scope is "node" or "library"/);
expect((await post("jobs", { scope: "node", node: "999@999" })).error).toMatch(/no node/);
// Pending: a node alone, or with everything under it.
const sub = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.minds)}&subtree=1&all=1`)).json();
expect(sub.suggestions.length).toBeGreaterThan(0);
expect(new Set(sub.suggestions.map((s: Suggestion) => s.node))).toEqual(new Set([ids.arms]));
const alone = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.minds)}&all=1`)).json();
expect(alone.suggestions.every((s: Suggestion) => s.node === ids.minds)).toBe(true);
});
});
describe("the links list in the page", () => {
+1 -1
View File
@@ -86,7 +86,7 @@ describe("a large library", () => {
writeFileSync(join(data, "library", "main.loro"), bytes);
t = performance.now();
const store = new LibraryStore(data, () => {}).open();
expect(store.list()).toHaveLength(100);
expect(store.titles()).toHaveLength(100);
const serverStart = performance.now() - t;
// The backlinks index follows every edit below; it is built once, here.
+75 -70
View File
@@ -1,14 +1,14 @@
/** The library on disk: seeding and starter files; and (until step 2 removes them) the UI's document features: the root's children made, listed and addressed. */
/** The library on disk (seeding and starter files), and a node with everything under it: imported, exported, copied, moved and addressed wherever it is. */
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { UndoManager } from "loro-crdt";
import { describe, expect, it } from "vitest";
import { LibraryStore } from "../server/library";
import { FormatError, serializeDoc } from "../src/core/format";
import { address, createDoc, deleteDoc, duplicateDoc, findTop, importDoc, listDocs, renameDoc, resolve } from "../src/core/library";
import { Doc, SYSTEM_ORIGIN, descendants, sections } from "../src/core/model";
import { SEED_TITLE, writeSeed } from "../src/core/seed";
import { address, resolve } from "../src/core/address";
import { resolveNode } from "../src/core/links";
import { Doc, descendants, isStale, sections, staleness, tops } from "../src/core/model";
import { SEED_TITLE, importTree, writeSeed } from "../src/core/seed";
import { seed } from "../src/seed/tree";
const prompt = readFileSync(new URL("../src/seed/prompt.txt", import.meta.url), "utf8");
@@ -21,7 +21,7 @@ describe("the library on disk", () => {
const data = temp();
const store = new LibraryStore(data, quiet).open();
store.seedFirst((doc) => writeSeed(doc, prompt, seed));
expect(store.list().map((d) => d.title)).toEqual([SEED_TITLE]);
expect(store.titles()).toEqual([SEED_TITLE]);
expect(store.main.snap().library).toBe(true);
expect(JSON.parse(readFileSync(join(data, "library.json"), "utf8")).imported).toEqual(["infinite-expand"]);
store.flush();
@@ -43,92 +43,97 @@ describe("the library on disk", () => {
const logs: string[] = [];
const store = new LibraryStore(data, (m) => logs.push(m)).open();
store.importLibrary(lib);
expect(store.list().map((d) => d.title)).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
expect(store.titles()).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
expect(logs.join("\n")).toMatch(/skipped broken\.md:\n {2}library\/broken\.md:9: in “One”: quote not found: "Missing"/);
deleteDoc(store.main, findTop(store.main.snap(), "good-one")!, "alice");
const good = tops(store.main.snap()).find((id) => store.main.snap().nodes[id].title === "Good one")!;
store.main.apply([{ op: "delete", id: good }], "Delete “Good one”");
store.save("main");
const again = new LibraryStore(data, quiet).open();
again.importLibrary(lib);
expect(again.list().map((d) => d.title)).toEqual(["Second"]);
expect(again.titles()).toEqual(["Second"]);
// Once fixed, the broken file is picked up.
writeFileSync(join(lib, "broken.md"), MD("Broken"));
again.importLibrary(lib);
expect(again.list().map((d) => d.title)).toEqual(["Second", "Broken"]);
expect(again.titles()).toEqual(["Second", "Broken"]);
});
});
describe("the root's children (the UI's documents, until step 2)", () => {
it("are created, renamed, duplicated and deleted as ordinary commits, with names made from their titles", () => {
describe("a node and everything under it, wherever it is", () => {
const LINKED = `# Imported\n\nA root body with a phrase.\n\n## One\n\nSection text.\n\n^ "Section" gloss: a note\n^ "text" link -> ./One\n`;
it("is imported under any node, its paths below the file's top stored from the library root, and exported back the same", () => {
const lib = Doc.library("alice");
const a = createDoc(lib, "My notes", "alice");
const snap = () => lib.snap();
expect(snap().nodes[a]).toMatchObject({ parent: snap().root, title: "My notes", by: "human" });
const nameOf = (title: string) => {
const id = createDoc(lib, title, "alice");
return listDocs(snap()).find((d) => d.node === id)!.slug;
};
expect(nameOf("My notes")).toBe("my-notes");
expect(nameOf("../../etc/passwd")).toBe("etc-passwd");
// A name another child has too finds the first; the id finds each.
expect(findTop(snap(), "my-notes")).toBe(a);
expect(findTop(snap(), a)).toBe(a);
const [inner] = lib.apply([{ op: "create", parent: a, title: "Inside" }], "add").created;
expect(findTop(snap(), "inside")).toBeUndefined();
renameDoc(lib, a, "Renamed", "alice");
expect(listDocs(snap()).find((d) => d.node === a)).toMatchObject({ title: "Renamed", slug: "renamed" });
const copy = duplicateDoc(lib, a, "Renamed (copy)", "alice");
expect(listDocs(snap()).find((d) => d.node === copy)).toMatchObject({ title: "Renamed (copy)", slug: "renamed-copy" });
expect(snap().nodes[snap().root].children.indexOf(copy)).toBe(snap().nodes[snap().root].children.indexOf(a) + 1);
expect(sections(snap(), copy).map((id) => snap().nodes[id].title)).toEqual(["Inside"]);
expect(sections(snap(), copy)[0]).not.toBe(inner); // a copy, not the same nodes
// Delete is an ordinary delete: undo brings it back, content and all.
const undo = new UndoManager(lib.loro, { mergeInterval: 0, excludeOriginPrefixes: [SYSTEM_ORIGIN] });
lib.group = { start: () => undo.groupStart(), end: () => undo.groupEnd() };
deleteDoc(lib, copy, "alice");
expect(findTop(snap(), "renamed-copy")).toBeUndefined();
expect(undo.undo()).toBe(true);
lib.touch();
const back = findTop(snap(), "renamed-copy")!;
expect(snap().nodes[back].title).toBe("Renamed (copy)");
expect(sections(snap(), back).map((id) => snap().nodes[id].title)).toEqual(["Inside"]);
});
it("import and export one tree in the text format; a file with a bad quote writes nothing", () => {
const lib = Doc.library("alice");
createDoc(lib, "Something else", "alice");
const id = importDoc(lib, MD("Imported thing"), "thing.md");
const snap = lib.snap();
const tides = importTree(lib, MD("Tides"), "tides.md");
const one = sections(lib.snap(), tides)[0];
// Under a section two levels down, at the end of its children.
const id = importTree(lib, LINKED, "linked.md", { parent: one });
let snap = lib.snap();
expect(snap.nodes[id].parent).toBe(one);
expect(snap.nodes[one].children.at(-1)).toBe(id);
expect([id, ...descendants(snap, id)].every((n) => snap.nodes[n].by === "llm")).toBe(true);
expect(serializeDoc(snap, id).text).toBe(MD("Imported thing"));
const inner = sections(snap, id)[0];
const link = snap.nodes[inner].children.map((c) => snap.nodes[c]).find((c) => c.ref)!;
expect(link.ref).toMatchObject({ kind: "node", id: inner, path: ["Tides", "One", "Imported", "One"] });
expect(resolveNode(snap, { kind: "node", path: ["Tides", "One", "Imported", "One"] })).toBe(inner);
// Nothing starts out stale under it; only the node it went under has a new section to summarise.
for (const n of [id, ...descendants(snap, id)]) expect(isStale(snap, n)).toBe(false);
expect(staleness(snap, one).up).toBe(true);
// Exported from where it is, its own paths are written relative to it again.
expect(serializeDoc(snap, id).text).toBe(LINKED);
// At a place among the children, when asked.
const first = importTree(lib, MD("First"), "first.md", { parent: tides, index: 0 });
snap = lib.snap();
expect(snap.nodes[tides].children[0]).toBe(first);
// A file with a bad quote writes nothing, wherever it was to go.
const before = lib.stateHash();
expect(() => importDoc(lib, MD("Bad").replace('"Section"', '"Nowhere"'), "bad.md")).toThrow(FormatError);
expect(() => importTree(lib, MD("Bad").replace('"Section"', '"Nowhere"'), "bad.md", { parent: inner })).toThrow(FormatError);
expect(lib.stateHash()).toBe(before);
expect(listDocs(lib.snap()).map((d) => d.slug)).toEqual(["something-else", "imported-thing"]);
});
it("have addresses: /doc/<name> for one, /doc/<name>/<node> for a node under it, / for the library", () => {
it("is copied just after itself with everything under it, and the copy's links inside it still point into the original", () => {
const lib = Doc.library("alice");
const a = importDoc(lib, MD("Tides"), "tides.md");
const b = importDoc(lib, MD("Codes"), "codes.md");
const tides = importTree(lib, MD("Tides"), "tides.md");
const id = importTree(lib, LINKED, "linked.md", { parent: sections(lib.snap(), tides)[0] });
const parent = lib.snap().nodes[id].parent!;
const [copy] = lib.apply([{ op: "copy", id, parent, index: lib.snap().nodes[parent].children.indexOf(id) + 1, title: "Imported (copy)" }], "Duplicate").created;
const snap = lib.snap();
expect(snap.nodes[parent].children.indexOf(copy)).toBe(snap.nodes[parent].children.indexOf(id) + 1);
expect(sections(snap, copy).map((c) => snap.nodes[c].title)).toEqual(["One"]);
expect(sections(snap, copy)[0]).not.toBe(sections(snap, id)[0]);
for (const n of [copy, ...descendants(snap, copy)]) expect(isStale(snap, n)).toBe(false);
});
it("is moved under any other node, never under itself", () => {
const lib = Doc.library("alice");
const a = importTree(lib, MD("Alpha"), "a.md");
const b = importTree(lib, MD("Beta"), "b.md");
const deep = sections(lib.snap(), b)[0];
lib.apply([{ op: "move", id: a, parent: deep }], "Move under");
expect(lib.snap().nodes[a].parent).toBe(deep);
expect(() => lib.apply([{ op: "move", id: b, parent: sections(lib.snap(), a)[0] }], "Move under itself")).toThrow(/inside itself/);
// And back to the top of the library.
lib.apply([{ op: "move", id: a, parent: lib.snap().root }], "Move to the top");
expect(tops(lib.snap())).toEqual([b, a]);
});
it("has an address made of its id alone: /n/<id>, and / for the library root", () => {
const lib = Doc.library("alice");
const a = importTree(lib, MD("Tides"), "tides.md");
const b = importTree(lib, MD("Codes"), "codes.md");
const snap = lib.snap();
const one = sections(snap, a)[0];
expect(address(snap, snap.root)).toBe("/");
expect(address(snap, a)).toBe("/doc/tides");
expect(address(snap, one)).toBe(`/doc/tides/${encodeURIComponent(one)}`);
expect(address(snap, a)).toBe(`/n/${encodeURIComponent(a)}`);
expect(address(snap, one)).toBe(`/n/${encodeURIComponent(one)}`);
for (const id of [snap.root, a, one]) expect(resolve(snap, address(snap, id))).toEqual({ node: id });
// The node id is what counts: a link whose node has moved to another document still finds it.
lib.apply([{ op: "move", id: one, parent: b }], "move");
expect(resolve(lib.snap(), `/doc/tides/${encodeURIComponent(one)}`)).toEqual({ node: one });
expect(address(lib.snap(), one)).toBe(`/doc/codes/${encodeURIComponent(one)}`);
// A moved node keeps its address; a renamed one too.
lib.apply([{ op: "move", id: one, parent: b }, { op: "update", id: one, title: "Renamed" }], "move and rename");
expect(address(lib.snap(), one)).toBe(`/n/${encodeURIComponent(one)}`);
expect(resolve(lib.snap(), `/n/${encodeURIComponent(one)}`)).toEqual({ node: one });
expect(resolve(lib.snap(), "/doc/nothing")).toEqual({ missing: "nothing called “nothing”" });
// A child of the root whose name another has too is addressed by its id as well.
const twin = importDoc(lib, MD("Tides"), "tides-2.md");
expect(address(lib.snap(), twin)).toBe(`/doc/tides/${encodeURIComponent(twin)}`);
expect(resolve(lib.snap(), address(lib.snap(), twin))).toEqual({ node: twin });
expect(address(lib.snap(), a)).toBe("/doc/tides");
// What names nothing says so (the page then shows the library): a gone node, an old document address, anything else.
expect(resolve(lib.snap(), "/n/999%40999")).toEqual({ missing: "no node 999@999" });
expect(resolve(lib.snap(), "/doc/tides")).toEqual({ missing: "no page /doc/tides" });
expect(resolve(lib.snap(), "/n/%E0%A4%A")).toMatchObject({ missing: expect.any(String) });
});
});