Panes by column: a forest of panes, curves between them, close, pin and an active rule

The tree of forks becomes a forest: a pinned pane stays open when a pane it was
opened from closes, as an orphan in its own column. Close takes a pane and what
was opened from it, pinned panes excepted; pin and unpin; [ and ] move to the
pane above or below in a column.

The panes view is laid out by column: column d holds every pane at depth d and
divides its own height among them, a short pane taking only what its text needs;
when they do not fit, all but the focused branch's pane (and pinned ones) fold
into one-line tabs. A faint curve runs from the words, row or link each pane was
opened from to its title, the focused branch's in a stronger ink; curves through
one gutter take lanes side by side, ordered to cross least. Every pane has the
same hairline right and bottom. The active pane has a heavy rule across its top,
the rest of the focused branch a hairline. Each pane has a pin and a x at its top
right (the x also on its spine); q closes the active pane, whatever it shows
(it used to close a whole fork from wherever the fork began, which closed the
node an article was opened from); P pins it. /curves off hides the curves.

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-16 00:37:59 -05:00
1 parent 2f8ca98207
commit 3298cc430c
20 files changed
+1785 -746

No files matched your search

+2 -2
View File
@@ -7,12 +7,12 @@
import { expect, test, type Page } from "@playwright/test"; import { expect, test, type Page } from "@playwright/test";
import { command, idle, jump, keys, seedLinks, selected, settle, state } from "./helpers"; import { command, idle, jump, keys, seedLinks, selected, settle, state } from "./helpers";
const panes = (page: Page) => page.locator(".strip > .pane"); const panes = (page: Page) => page.locator(".strip .pane");
async function wide(page: Page, path = "/doc/fixed-points") { async function wide(page: Page, path = "/doc/fixed-points") {
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await page.goto(path); await page.goto(path);
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
} }
async function column(page: Page, path: string) { async function column(page: Page, path: string) {
+426 -160
View File
@@ -1,29 +1,41 @@
/** /**
* Forks in the panes view: a modified open (Shift+Enter, Shift-, Ctrl- or middle-click) opens its * Forks in the panes view, laid out by column: a modified open (Shift+Enter, Shift-, Ctrl- or
* pane beside what is to the right instead of replacing it, and the space right of the pane * middle-click) opens its pane below what is in the next column instead of replacing it; column d
* divides into rows, one per fork. Same build, mock model, mock Wikipedia and shared library as * holds every pane at depth d and divides its own height among them, folding all but one into tabs
* the other specs; the documents are hoisted to (z) as in panes.spec.ts. * when they do not fit. Curves run from where each pane was opened to its title; panes close (q, ×)
* and pin (P, pin). Same build, mock model, mock Wikipedia and shared library as the other specs;
* the documents are hoisted to (z) as in panes.spec.ts.
*/ */
import { expect, test, type Page } from "@playwright/test"; import { expect, test, type Page } from "@playwright/test";
import { focusedTitle, jump, keys, seedLinks, selected, settle, state } from "./helpers"; import { focusedTitle, jump, keys, seedLinks, selected, settle, state } from "./helpers";
/** The tree of panes by title, the picked child starred: [title, [children]] or a leaf's title. */ /** The first tree of panes by title, the picked child starred: [title, [children]] or a leaf's title. */
const tree = (page: Page) => const tree = (page: Page) =>
state(page, (s) => { state(page, (s) => {
const name = (p: any) => (p.kind === "node" ? s.snap.nodes[p.id]?.title || s.snap.nodes[p.id]?.anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`); const name = (p: any) => (p.kind === "node" ? s.snap.nodes[p.id]?.title || s.snap.nodes[p.id]?.anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`);
const go = (n: any): unknown => (n.kids.length ? [name(n.ref), n.kids.map((k: any, j: number) => (j === n.pick ? ["*", go(k)] : go(k)))] : name(n.ref)); const go = (n: any): unknown => (n.kids.length ? [name(n.ref), n.kids.map((k: any, j: number) => (j === n.pick ? ["*", go(k)] : go(k)))] : name(n.ref));
return go(s.tree); return go(s.forest.trees[0]);
}); });
/** The focused branch, by title. */ /** The focused branch, by title. */
const trail = (page: Page) => state(page, (s) => s.trail.map((p: any) => (p.kind === "node" ? s.snap.nodes[p.id]?.title || s.snap.nodes[p.id]?.anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`))); const trail = (page: Page) => state(page, (s) => s.trail.map((p: any) => (p.kind === "node" ? s.snap.nodes[p.id]?.title || s.snap.nodes[p.id]?.anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`)));
/** The rows right of the first pane with forks, each as the titles of its panes, left to right. */ /** The columns on screen, left to right, each as its panes' titles top to bottom. */
const forkRows = (page: Page) => const columns = (page: Page) =>
page.evaluate(() => page.evaluate(() =>
[...document.querySelectorAll(".strip .forks")][0] [...document.querySelectorAll(".strip > .col")].map((c) =>
? [...document.querySelector(".strip .forks")!.children].map((row) => [...c.querySelectorAll(":scope > .pane")].map((p) => p.querySelector(".wiki-head h2, .pane-head h2, .top h1")?.textContent?.trim() ?? ""),
[...row.querySelectorAll(".pane")].map((p) => p.querySelector(".wiki-head h2, .pane-head h2, .top h1")?.textContent?.trim() ?? ""), ),
) );
: [], /** A pane by its title. */
const pane = (page: Page, title: string) => page.locator(".strip .pane", { has: page.locator(`:is(.wiki-head h2, .pane-head h2, .top h1):text-is("${title}")`) }).first();
/** Each pane's box, by title. */
const boxes = (page: Page) =>
page.evaluate(() =>
Object.fromEntries(
[...document.querySelectorAll<HTMLElement>(".strip .pane")].map((p) => {
const r = p.getBoundingClientRect();
return [p.querySelector(".wiki-head h2, .pane-head h2, .top h1")?.textContent?.trim() ?? "", { x: r.x, y: r.y, w: r.width, h: r.height, tab: p.hasAttribute("data-tab") }];
}),
),
); );
/** A section's child sections, by title. */ /** A section's child sections, by title. */
const childTitles = (page: Page, title: string) => const childTitles = (page: Page, title: string) =>
@@ -32,14 +44,39 @@ const childTitles = (page: Page, title: string) =>
const n = (Object.values(s.snap.nodes) as any[]).find((x) => x.title === t); const n = (Object.values(s.snap.nodes) as any[]).find((x) => x.title === t);
return n.children.filter((c: string) => s.snap.nodes[c].kind === "section").map((c: string) => s.snap.nodes[c].title) as string[]; return n.children.filter((c: string) => s.snap.nodes[c].kind === "section").map((c: string) => s.snap.nodes[c].title) as string[];
}, title); }, title);
/** The curves drawn: from which pane to which (ids in the forest), their classes, and their ends on screen. */
const curves = (page: Page) =>
page.evaluate(() => {
const svg = document.querySelector<SVGSVGElement>(".curves")!;
const box = svg.getBoundingClientRect();
return [...svg.querySelectorAll("path")].map((p) => {
const a = p.getPointAtLength(0);
const b = p.getPointAtLength(p.getTotalLength());
return { from: Number(p.dataset.from), to: Number(p.dataset.to), cls: p.getAttribute("class") ?? "", a: { x: a.x + box.x, y: a.y + box.y }, b: { x: b.x + box.x, y: b.y + box.y } };
});
});
const tid = (page: Page, title: string) => pane(page, title).evaluate((el) => Number((el as HTMLElement).dataset.tid));
const nextFrames = (page: Page) => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
/** Wait until the strip has stopped scrolling sideways (it scrolls smoothly to follow the focus), and the curves have been drawn after. */
async function still(page: Page) {
await page.waitForFunction(
() =>
new Promise((r) => {
const el = document.querySelector(".strip")!;
const x = el.scrollLeft;
setTimeout(() => r(el.scrollLeft === x), 300);
}),
);
await nextFrames(page);
}
async function open(page: Page) { async function open(page: Page) {
await page.goto("/doc/infinite-expand"); await page.goto("/doc/infinite-expand");
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await expect(page.locator(".strip > .pane")).toHaveCount(2); await expect(page.locator(".strip .pane")).toHaveCount(2);
await page.keyboard.press("z"); await page.keyboard.press("z");
await expect(page.locator(".strip > .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
} }
/** Tab through the focused text's marked spans until the selection is these words. */ /** Tab through the focused text's marked spans until the selection is these words. */
@@ -51,13 +88,23 @@ async function tabTo(page: Page, words: string) {
throw new Error(`Tab never reached “${words}”`); throw new Error(`Tab never reached “${words}”`);
} }
/** Whether an element's box is inside the strip's visible box. */ /** The owner's screenshot: Two kinds of cell, with Eukaryote (opened from its link), Simple cells and Complex cells beside each other in the next column, and Bacteria opened from Eukaryote's text. */
const inView = (page: Page, sel: string) => async function cells(page: Page) {
page.evaluate((sel) => { await page.goto("/doc/the-eukaryotic-cell");
const strip = document.querySelector<HTMLElement>(".strip")!.getBoundingClientRect(); await page.waitForSelector(".strip .pane");
const r = document.querySelector(sel)!.getBoundingClientRect(); await page.evaluate(() => document.fonts.ready);
return r.top >= strip.top - 1 && r.bottom <= strip.bottom + 1; await jump(page, "Two kinds of cell");
}, sel); await keys(page, "Enter");
await tabTo(page, "Eukaryotes");
await keys(page, "Enter");
await expect(pane(page, "Eukaryote").locator(".wiki-text a[data-wiki]").first()).toBeVisible();
await pane(page, "Eukaryote").locator('.wiki-text a[data-wiki="Bacteria"]').first().click();
await expect(pane(page, "Bacteria").locator(".wiki-text").first()).toBeVisible();
await page.locator(".pane .row", { hasText: "Simple cells" }).first().click({ modifiers: ["Shift"] });
await page.locator(".pane .row", { hasText: "Complex cells" }).first().click({ modifiers: ["Shift"] });
await expect.poll(() => columns(page)).toEqual([["Library"], ["The one merger"], ["Two kinds of cell"], ["Eukaryote", "Simple cells", "Complex cells"], ["Bacteria"]]);
await still(page);
}
test.use({ viewport: { width: 1920, height: 1080 } }); test.use({ viewport: { width: 1920, height: 1080 } });
test.describe.configure({ mode: "serial" }); test.describe.configure({ mode: "serial" });
@@ -70,39 +117,35 @@ test.beforeEach(async ({ context }) => {
}); });
test.afterEach(({ page }) => settle(page)); test.afterEach(({ page }) => settle(page));
test("Shift+Enter on a section row opens a fork beside the pane to the right; Enter still replaces, and focuses a fork already open", async ({ page }) => { test("Shift+Enter on a section row opens a fork below in the next column; Enter still replaces, and focuses a fork already open", async ({ page }) => {
await open(page); await open(page);
await keys(page, "l l l"); // Expansion by depth showing; the focus on its first row await keys(page, "l l l"); // Expansion by depth showing; the focus on its first row
// Nothing to the right yet: a fork is a plain open, and a plain trail is drawn as before. // Nothing to the right yet: a fork is a plain open, and a plain trail is one pane per column.
await keys(page, "Shift+Enter"); await keys(page, "Shift+Enter");
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Expansion by depth", [["*", "Levels of a node"]]]]]]); expect(await tree(page)).toEqual(["Infinispand", [["*", ["Expansion by depth", [["*", "Levels of a node"]]]]]]);
await expect(page.locator(".strip:not(.forked) > .pane")).toHaveCount(3); expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node"]]);
await expect(page.locator(".forks")).toHaveCount(0);
await keys(page, "j Shift+Enter"); await keys(page, "j Shift+Enter");
expect(await forkRows(page)).toEqual([["Levels of a node"], ["Pre-generated depth"]]); expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Pre-generated depth"]]);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]);
// The rows divide the height; both start in the column next to the pane they came from. // They share the column's height, one above the other, beside the pane they came from.
const [a, b, parent] = await Promise.all([ const b = await boxes(page);
page.locator(".forks > .fork").nth(0).locator(".pane").boundingBox(), const [a, c, parent] = [b["Levels of a node"], b["Pre-generated depth"], b["Expansion by depth"]];
page.locator(".forks > .fork").nth(1).locator(".pane").boundingBox(), expect(a.x).toBeCloseTo(c.x, 0);
page.locator('.pane[data-pane-index="1"]').boundingBox(), expect(c.y).toBeCloseTo(a.y + a.h, 0);
]); expect(a.x).toBeGreaterThan(parent.x);
expect(a!.x).toBeCloseTo(b!.x, 0); const strip = await page.locator(".strip").evaluate((el) => el.clientHeight);
expect(b!.y).toBeGreaterThanOrEqual(a!.y + a!.height - 1); expect(Math.abs(a.h + c.h - strip)).toBeLessThan(2);
expect(a!.x).toBeGreaterThan(parent!.x);
expect(a!.height).toBeGreaterThan(300);
// The pane they came from marks both, the focused one as before and the other lightly. // The pane they came from marks both, the focused one as before and the other lightly.
await expect(page.locator('.pane[data-pane-index="1"] .node.showing > .row')).toHaveText([/Pre-generated depth/]); await expect(pane(page, "Expansion by depth").locator(".node.showing > .row")).toHaveText([/Pre-generated depth/]);
await expect(page.locator('.pane[data-pane-index="1"] .node.forked > .row')).toHaveText([/Levels of a node/]); await expect(pane(page, "Expansion by depth").locator(".node.forked > .row")).toHaveText([/Levels of a node/]);
// A plain Enter replaces only the focused fork. // A plain Enter replaces only the focused fork.
await keys(page, "j Enter"); await keys(page, "j Enter");
expect(await forkRows(page)).toEqual([["Levels of a node"], ["Generation on demand"]]); expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]);
// Enter (or Shift+Enter) on the row of a fork already open focuses that fork: no second copy. // Enter (or Shift+Enter) on the row of a fork already open focuses that fork: no second copy.
await keys(page, "k k Enter"); await keys(page, "k k Enter");
expect(await forkRows(page)).toEqual([["Levels of a node"], ["Generation on demand"]]); expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]); expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]);
await keys(page, "j j Shift+Enter"); await keys(page, "j j Shift+Enter");
expect(await forkRows(page)).toEqual([["Levels of a node"], ["Generation on demand"]]);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]); expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]);
}); });
@@ -120,26 +163,325 @@ test("Shift-, Ctrl- and middle-click fork from section rows; a click in another
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Borrowed from Gwern", [kids[0], kids[1], ["*", kids[2]]]]]]]); expect(await tree(page)).toEqual(["Infinispand", [["*", ["Borrowed from Gwern", [kids[0], kids[1], ["*", kids[2]]]]]]]);
// A Shift-click selected no text on the way. // A Shift-click selected no text on the way.
expect(await page.evaluate(() => window.getSelection()?.isCollapsed ?? true)).toBe(true); expect(await page.evaluate(() => window.getSelection()?.isCollapsed ?? true)).toBe(true);
// A click anywhere in the first fork's pane focuses that fork. // A click on the first fork's heading focuses that fork, and makes that pane the active one.
await page.locator(".forks > .fork").nth(0).locator(".pane-head").click(); await pane(page, kids[0]).locator(".pane-head").click();
expect(await trail(page)).toEqual(["Infinispand", "Borrowed from Gwern", kids[0]]); expect(await trail(page)).toEqual(["Infinispand", "Borrowed from Gwern", kids[0]]);
expect(await focusedTitle(page)).toBe(kids[0]); expect(await focusedTitle(page)).toBe(kids[0]);
await expect(page.locator(".forks > .fork.on")).toHaveCount(1); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[0]);
expect(await page.locator(".forks > .fork").nth(0).getAttribute("class")).toContain("on"); // The first pane forks too: its forks share the next column, and the panes opened from each the one after.
// A plain click on a row replaces the focused fork, and a Shift-click on the focused row whose pane shows does not close it.
await row("Display forms").click({ modifiers: ["Shift"] }); // the first pane forks too: a stack right of it
await expect(page.locator(".strip > .forks > .fork")).toHaveCount(2);
await expect(page.locator(".strip > .forks > .fork").nth(0).locator(".forks > .fork")).toHaveCount(3);
await row("Display forms").click({ modifiers: ["Shift"] }); await row("Display forms").click({ modifiers: ["Shift"] });
await expect(page.locator(".strip > .forks > .fork")).toHaveCount(2); expect(await columns(page)).toEqual([["Infinispand"], ["Borrowed from Gwern", "Display forms"], kids.slice(0, 3)]);
await row("Display forms").click({ modifiers: ["Shift"] });
expect((await columns(page))[1]).toEqual(["Borrowed from Gwern", "Display forms"]);
await row("Editing and regeneration").click(); await row("Editing and regeneration").click();
expect(await trail(page)).toEqual(["Infinispand", "Editing and regeneration"]); expect(await trail(page)).toEqual(["Infinispand", "Editing and regeneration"]);
await expect(page.locator(".strip > .forks > .fork").nth(1).locator(".pane-head h2")).toHaveText("Editing and regeneration"); expect((await columns(page))[1]).toEqual(["Borrowed from Gwern", "Editing and regeneration"]);
});
test("the owner's screenshot: the lone pane in the next column fills its height; the shared column gives short panes what they need", async ({ page }) => {
await cells(page);
const b = await boxes(page);
const strip = await page.locator(".strip").evaluate((el) => el.clientHeight);
// Bacteria, alone in its column, is as tall as the strip.
expect(Math.abs(b["Bacteria"].h - strip)).toBeLessThan(1);
expect(b["Bacteria"].y).toBeCloseTo(b["Eukaryote"].y, 0);
// The three forks share their column's height, top to bottom, with nothing left over.
const col = ["Eukaryote", "Simple cells", "Complex cells"].map((t) => b[t]);
expect(Math.abs(col.reduce((h, x) => h + x.h, 0) - strip)).toBeLessThan(2);
for (let i = 1; i < 3; i++) expect(col[i].y).toBeCloseTo(col[i - 1].y + col[i - 1].h, 0);
for (const t of ["Eukaryote", "Simple cells", "Complex cells"]) expect(await pane(page, t).getAttribute("data-tab")).toBeNull();
});
test("every pane has the same hairline on its right and bottom, shared with its neighbours: none missing, none doubled", async ({ page }) => {
await cells(page);
const edges = await page.evaluate(() =>
[...document.querySelectorAll<HTMLElement>(".strip .pane")].map((p) => {
const cs = getComputedStyle(p);
const last = p === p.parentElement!.lastElementChild;
return { title: p.querySelector("h1, h2")?.textContent, right: cs.borderRightWidth, bottom: cs.borderBottomWidth, top: cs.borderTopWidth, left: cs.borderLeftWidth, rightColor: cs.borderRightColor, bottomColor: cs.borderBottomColor, last, flush: document.querySelector(".strip")!.hasAttribute("data-flush") };
}),
);
const color = edges[0].rightColor;
for (const e of edges) {
expect(e.right, `${e.title} right`).toBe("1px");
expect(e.bottom, `${e.title} bottom`).toBe("1px");
expect(e.rightColor).toBe(color);
// Between panes there is one line: the upper or left pane's, never both.
expect(e.top).toBe("0px");
expect(e.left).toBe("0px");
// The last pane of a column meets the status line, which draws that line, unless a scrollbar runs between them.
if (!e.last || !e.flush) expect(e.bottomColor).toBe(color);
}
// In the shared column each pane's box ends where the next begins: the line between them is the upper one's bottom edge.
const b = await boxes(page);
expect(b["Simple cells"].y).toBeCloseTo(b["Eukaryote"].y + b["Eukaryote"].h, 0);
// An article's tinted ground meets the plain one at the same line.
const tint = await pane(page, "Eukaryote").evaluate((el) => getComputedStyle(el).backgroundColor);
expect(tint).not.toBe(await pane(page, "Simple cells").evaluate((el) => getComputedStyle(el).backgroundColor));
expect(await pane(page, "Eukaryote").evaluate((el) => getComputedStyle(el).borderBottomColor)).toBe(color);
});
test("a curve per open edge, from where each pane was opened to its title; it follows a pane's scroll and the strip's, and the focused branch's is drawn differently", async ({ page }) => {
await cells(page);
// Library and The one merger are covered to spines, so the curves into and out of them are not drawn.
const ids: Record<string, number> = {};
for (const t of ["Two kinds of cell", "Eukaryote", "Simple cells", "Complex cells", "Bacteria"]) ids[t] = await tid(page, t);
let cs = await curves(page);
const edge = (from: string, to: string) => cs.filter((c) => c.from === ids[from] && c.to === ids[to]);
for (const [f, t] of [["Two kinds of cell", "Eukaryote"], ["Two kinds of cell", "Simple cells"], ["Two kinds of cell", "Complex cells"], ["Eukaryote", "Bacteria"]]) expect(edge(f, t), `${f} → ${t}`).toHaveLength(1);
expect(cs.filter((c) => c.to === ids["Two kinds of cell"])).toHaveLength(0);
// Ends: near the link words, the row, and the child's title.
const near = async (sel: string, p: { x: number; y: number }, slack = 16) => {
const r = (await page.locator(sel).first().boundingBox())!;
expect(p.x).toBeGreaterThan(r.x - slack);
expect(p.x).toBeLessThan(r.x + r.width + slack);
expect(p.y).toBeGreaterThan(r.y - slack);
expect(p.y).toBeLessThan(r.y + r.height + slack);
};
const kinds = pane(page, "Two kinds of cell");
const nearIn = async (loc: ReturnType<Page["locator"]>, p: { x: number; y: number }, slack = 16) => {
const r = (await loc.first().boundingBox())!;
expect(p.x).toBeGreaterThan(r.x - slack);
expect(p.x).toBeLessThan(r.x + r.width + slack);
expect(p.y).toBeGreaterThan(r.y - slack);
expect(p.y).toBeLessThan(r.y + r.height + slack);
};
await nearIn(kinds.locator(".lnk", { hasText: "Eukaryotes" }), edge("Two kinds of cell", "Eukaryote")[0].a);
await nearIn(kinds.locator(".node.forked > .row", { hasText: "Simple cells" }), edge("Two kinds of cell", "Simple cells")[0].a);
const title = (t: string) => pane(page, t).locator(".wiki-head h2, .pane-head h2").first();
for (const t of ["Eukaryote", "Simple cells", "Complex cells"]) {
const end = edge("Two kinds of cell", t)[0].b;
const r = (await title(t).boundingBox())!;
expect(end.x).toBeLessThanOrEqual(r.x + 2);
expect(end.x, t).toBeGreaterThan(r.x - 30);
expect(end.y).toBeGreaterThan(r.y - 4);
expect(end.y).toBeLessThan(r.y + r.height + 4);
}
await near('.wiki-pane .wiki-text a[data-wiki="Bacteria"]', edge("Eukaryote", "Bacteria")[0].a);
// The focused branch (Two kinds of cell → Complex cells) in its own ink; the others not.
expect(edge("Two kinds of cell", "Complex cells")[0].cls).toContain("on");
expect(edge("Two kinds of cell", "Simple cells")[0].cls).not.toContain("on");
expect(await page.locator(".curves path.on").first().evaluate((el) => getComputedStyle(el).stroke)).not.toBe(await page.locator(".curves path:not(.on)").first().evaluate((el) => getComputedStyle(el).stroke));
// Scroll Eukaryote's text: the curve out of it moves with its link.
const before = edge("Eukaryote", "Bacteria")[0].a;
await pane(page, "Eukaryote").locator(".pane-scroll").evaluate((el) => (el.scrollTop = 40));
await nextFrames(page);
cs = await curves(page);
expect(Math.abs(edge("Eukaryote", "Bacteria")[0].a.y - (before.y - 40))).toBeLessThan(3);
// Scrolled out of its pane, the source is held at the pane's edge and the curve is dotted.
await pane(page, "Eukaryote").locator(".pane-scroll").evaluate((el) => (el.scrollTop = 400));
await nextFrames(page);
cs = await curves(page);
expect(edge("Eukaryote", "Bacteria")[0].cls).toContain("lost");
const top = (await pane(page, "Eukaryote").locator(".pane-scroll").boundingBox())!.y;
expect(Math.abs(edge("Eukaryote", "Bacteria")[0].a.y - top)).toBeLessThan(6);
// Scroll the strip: the curves move with the panes.
const was = edge("Two kinds of cell", "Simple cells")[0].b;
await page.locator(".strip").evaluate((el) => (el.scrollLeft += el.scrollLeft >= 200 ? -200 : 200));
await still(page);
cs = await curves(page);
const now = edge("Two kinds of cell", "Simple cells")[0].b;
const r = (await title("Simple cells").boundingBox())!;
expect(Math.abs(now.x - was.x)).toBeGreaterThan(20);
expect(now.x).toBeGreaterThan(r.x - 30);
expect(now.x).toBeLessThanOrEqual(r.x + 2);
// And they can be turned off, and on again.
await page.keyboard.press(":");
await page.keyboard.type("/curves off");
await page.keyboard.press("Enter");
await expect(page.locator(".curves path")).toHaveCount(0);
await page.keyboard.press(":");
await page.keyboard.type("/curves on");
await page.keyboard.press("Enter");
await expect.poll(async () => (await curves(page)).length).toBeGreaterThan(3);
});
test("exactly one pane is active, under a heavy rule; the rest of the focused branch under a hairline", async ({ page }) => {
await cells(page);
const marks = () =>
page.evaluate(() =>
[...document.querySelectorAll<HTMLElement>(".strip .pane")].map((p) => ({
title: p.querySelector("h1, h2")?.textContent?.trim(),
active: p.classList.contains("active"),
rule: getComputedStyle(p, "::after").height,
})),
);
let m = await marks();
expect(m.filter((x) => x.active).map((x) => x.title)).toEqual([await state(page, (s) => s.snap.nodes[s.trail[s.paneAt].id].title)]);
expect(m.find((x) => x.active)!.rule).toBe("3px");
expect(m.filter((x) => x.rule === "3px")).toHaveLength(1);
// The other panes on the focused branch: a hairline; off it, nothing.
expect(m.find((x) => x.title === "Complex cells")!.rule).toBe("1px");
expect(m.find((x) => x.title === "Simple cells")!.rule).toBe("0px");
// Into an article: it is the active pane now, and still the only one.
await pane(page, "Bacteria").locator(".wiki-head").click();
m = await marks();
expect(m.filter((x) => x.active).map((x) => x.title)).toEqual(["Bacteria"]);
expect(m.filter((x) => x.rule === "3px").map((x) => x.title)).toEqual(["Bacteria"]);
});
/** Five sections of the first pane, opened side by side: five panes in column 1. */
async function five(page: Page) {
await open(page);
await keys(page, "j Shift+Enter j Shift+Enter j Shift+Enter j Shift+Enter j Shift+Enter");
const kids = (await childTitles(page, "Infinispand")).slice(0, 5);
expect((await columns(page))[1]).toEqual(kids);
return kids;
}
test("a column with more panes than fit folds all but the focused one into tabs; moving the focus there, or a click on a tab, opens it", async ({ page }) => {
const kids = await five(page);
const strip = await page.locator(".strip").evaluate((el) => el.clientHeight);
let b = await boxes(page);
// The focused fork (the last) takes the height less a tab's for each of the others; the others are tabs, in order, above it.
expect(kids.slice(0, 4).every((t) => b[t].tab)).toBe(true);
expect(b[kids[4]].tab).toBe(false);
expect(Math.abs(b[kids[4]].h - (strip - 4 * 30))).toBeLessThan(2);
for (let i = 1; i < 5; i++) expect(b[kids[i]].y).toBeCloseTo(b[kids[i - 1]].y + b[kids[i - 1]].h, 0);
await expect(pane(page, kids[0]).locator(".tabline .tabtitle")).toHaveText(kids[0]);
await expect(pane(page, kids[0]).locator(".tabline")).toBeVisible();
await expect(pane(page, kids[0]).locator(".pane-ctl .pane-btn.close")).toBeVisible();
// l steps into the focused fork's pane; [ moves up the column: that tab opens, the one left folds.
await keys(page, "l");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]);
const where = await focusedTitle(page);
await keys(page, "[");
expect(await trail(page)).toEqual(["Infinispand", kids[3]]);
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[3]);
b = await boxes(page);
expect(b[kids[3]].tab).toBe(false);
expect(b[kids[4]].tab).toBe(true);
// ] comes back down, to where the focus was.
await keys(page, "]");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]);
expect(await focusedTitle(page)).toBe(where);
await keys(page, "]");
await expect(page.locator(".status .message")).toContainText("No pane below");
// A click on a tab opens that pane and makes it the active one.
await pane(page, kids[1]).locator(".tabline").click();
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[1]);
b = await boxes(page);
expect(b[kids[1]].tab).toBe(false);
expect(b[kids[4]].tab).toBe(true);
});
test("a pinned pane does not fold in its column, outlives a closed parent as an orphan in its column, and is not covered to a spine", async ({ page }) => {
const kids = await five(page);
// Pin the second fork, by its button: it opens beside the focused one and stays open as the focus moves up and down the column.
await pane(page, kids[1]).locator(".pane-ctl .pane-btn.pin").click();
await expect(pane(page, kids[1])).toHaveClass(/pinned/);
let b = await boxes(page);
expect(b[kids[1]].tab).toBe(false);
expect(b[kids[1]].h).toBeGreaterThan(200);
await keys(page, "l [ [");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[2]);
b = await boxes(page);
expect(b[kids[1]].tab).toBe(false);
expect(b[kids[4]].tab).toBe(true);
// The pin is kept across a reload.
await page.reload();
await page.waitForSelector(".strip .pane");
await expect(pane(page, kids[1])).toHaveClass(/pinned/);
// Pin a pane opened from the first fork, then close that fork with its ×: the pinned pane stays where it was, an orphan, with no curve into it.
await pane(page, kids[0]).locator(".tabline").click();
const grand = (await childTitles(page, kids[0]))[0];
await keys(page, "l l l P");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(grand);
await expect(page.locator(".pane.active")).toHaveClass(/pinned/);
const orphan = await tid(page, grand);
await pane(page, kids[0]).locator(".pane-ctl .pane-btn.close").click();
expect((await columns(page))[1]).not.toContain(kids[0]);
expect((await columns(page))[2]).toEqual([grand]);
await expect(pane(page, grand).locator(".orphan-note")).toBeVisible();
expect(await state(page, (s) => s.forest.trees.length)).toBe(2);
await nextFrames(page);
expect((await curves(page)).filter((c) => c.to === orphan)).toHaveLength(0);
// Its own × closes it.
await pane(page, grand).locator(".pane-ctl .pane-btn.close").click();
expect(await columns(page)).toHaveLength(2);
});
test("a pinned column is not covered to a spine as the strip scrolls; later columns slide past it", async ({ page }) => {
await page.setViewportSize({ width: 1600, height: 1000 });
await open(page);
await keys(page, "l l l j j l l l");
await expect.poll(async () => (await columns(page)).length).toBe(4);
const covered = () => page.evaluate(() => [...document.querySelectorAll(".strip > .col")].map((c) => c.hasAttribute("data-covered")));
// Unpinned, column 1 is covered once the strip has scrolled to the last.
await page.locator(".strip").evaluate((el) => (el.scrollLeft = el.scrollWidth));
await expect.poll(async () => (await covered())[1]).toBe(true);
await pane(page, "Expansion by depth").locator(".spine-title").click();
await keys(page, "P");
await expect(pane(page, "Expansion by depth")).toHaveClass(/pinned/);
await page.locator(".strip").evaluate((el) => (el.scrollLeft = el.scrollWidth));
await still(page);
expect((await covered())[1]).toBe(false);
const col1 = (await pane(page, "Expansion by depth").boundingBox())!;
const col2x = await page.evaluate(() => document.querySelectorAll(".strip > .col")[2].getBoundingClientRect().x);
expect(col1.x).toBeGreaterThanOrEqual(0);
expect(col2x).toBeGreaterThanOrEqual(col1.x + col1.width - 1);
// The last column can still be scrolled fully into view.
const last = (await pane(page, "Deepening a leaf").boundingBox())!;
expect(last.x + last.width).toBeLessThanOrEqual(1600 + 1);
await keys(page, "P");
await expect(pane(page, "Expansion by depth")).not.toHaveClass(/pinned/);
});
test("× and q close the pane they are on, whatever it shows, with what was opened from it; pinned panes under it stay", async ({ page }) => {
// A node: × on a fork that is not focused closes it alone.
await cells(page);
await pane(page, "Simple cells").locator(".pane-ctl .pane-btn.close").click();
expect((await columns(page))[3]).toEqual(["Eukaryote", "Complex cells"]);
// An article opened from an article: q closes it only, and the focus goes back to its link.
await pane(page, "Bacteria").locator(".wiki-head").click();
await keys(page, "q");
expect(await columns(page)).toEqual([["Library"], ["The one merger"], ["Two kinds of cell"], ["Eukaryote", "Complex cells"]]);
await expect(page.locator(".pane.active .wiki-head h2")).toHaveText("Eukaryote");
// Pinned panes under a closed pane stay: open Bacteria again, pin it, close Eukaryote.
await pane(page, "Eukaryote").locator('.wiki-text a[data-wiki="Bacteria"]').first().click();
await keys(page, "P");
await pane(page, "Eukaryote").locator(".pane-ctl .pane-btn.close").click();
expect(await columns(page)).toEqual([["Library"], ["The one merger"], ["Two kinds of cell"], ["Complex cells"], ["Bacteria"]]);
await expect(pane(page, "Bacteria").locator(".orphan-note")).toBeVisible();
// Its own × closes the orphan.
await pane(page, "Bacteria").locator(".pane-ctl .pane-btn.close").click();
expect(await columns(page)).toEqual([["Library"], ["The one merger"], ["Two kinds of cell"], ["Complex cells"]]);
// A note that also links, opened as a pane of its own: q closes it, back to its words.
await page.goto("/doc/octopus-minds");
await page.waitForSelector(".strip .pane");
await jump(page, "The common ancestor");
await keys(page, "l");
await page.locator(".pane .anchor", { hasText: "The camera-like eye" }).click();
await expect(page.locator(".pane.note-pane")).toHaveCount(1);
await expect(page.locator(".pane.active")).toHaveClass(/note-pane/);
await keys(page, "q");
await expect(page.locator(".pane.note-pane")).toHaveCount(0);
expect(await selected(page)).toBe("The camera-like eye");
});
test("q on an article opened from an article in a fork closes that article only (the owner's bug)", async ({ page }) => {
await page.goto("/doc/fixed-points");
await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready);
await jump(page, "Recursion without names");
// A fork beside it from the document's pane: Recursion without names starts a fork.
await keys(page, "k Enter j Shift+Enter");
expect((await trail(page)).at(-1)).toBe("Recursion without names");
await tabTo(page, "fixed-point combinator");
await keys(page, "Enter");
await expect(page.locator(".wiki-pane .wiki-head h2", { hasText: "Fixed-point combinator" })).toHaveCount(1);
await page.locator('.wiki-pane .wiki-text a[data-wiki="Haskell Curry"]').first().click();
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator", "W:Haskell Curry"]);
await keys(page, "q");
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator"]);
await keys(page, "q");
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names"]);
expect(await selected(page)).toBe("fixed-point combinator");
}); });
test("from a Wikipedia link, a node link and a link inside an article: forks, each marked where it was opened", async ({ page }) => { test("from a Wikipedia link, a node link and a link inside an article: forks, each marked where it was opened", async ({ page }) => {
await page.goto("/doc/fixed-points"); await page.goto("/doc/fixed-points");
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await jump(page, "Recursion without names"); await jump(page, "Recursion without names");
await tabTo(page, "fixed-point combinator"); await tabTo(page, "fixed-point combinator");
@@ -149,115 +491,28 @@ test("from a Wikipedia link, a node link and a link inside an article: forks, ea
expect(await selected(page)).toBe("fixed-point combinator"); expect(await selected(page)).toBe("fixed-point combinator");
await tabTo(page, "Y combinator"); await tabTo(page, "Y combinator");
await keys(page, "Shift+Enter"); await keys(page, "Shift+Enter");
expect(await forkRows(page)).toEqual([["Fixed-point combinator"], ["How Y works"]]); expect((await columns(page))[3]).toEqual(["Fixed-point combinator", "How Y works"]);
// In the text it came from, both links are marked, the focused fork's more strongly. // In the text it came from, both links are marked, the focused fork's more strongly.
const from = page.locator('.pane[data-pane-index="2"]'); const from = page.locator('.pane[data-pane-index="2"]');
await expect(from.locator(".lnk.forked.picked")).toHaveText("Y combinator"); await expect(from.locator(".lnk.forked.picked")).toHaveText("Y combinator");
await expect(from.locator(".lnk.forked:not(.picked)")).toHaveText("fixed-point combinator"); await expect(from.locator(".lnk.forked:not(.picked)")).toHaveText("fixed-point combinator");
// [ goes up to the article's row; its sections open as rows, as before. // Into How Y works, then [ goes up the column to the article; its sections open as rows, as before.
await pane(page, "How Y works").locator(".pane-head").click();
await keys(page, "["); await keys(page, "[");
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator"]); expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator"]);
expect(await state(page, (s) => s.aux)).toMatchObject({ kind: "wiki", host: "p3", row: { t: "head" } }); expect(await state(page, (s) => s.aux)).toMatchObject({ kind: "wiki", host: "p3", row: { t: "head" } });
await expect(from.locator(".lnk.forked.picked")).toHaveText("fixed-point combinator"); await expect(from.locator(".lnk.forked.picked")).toHaveText("fixed-point combinator");
await expect(page.locator(".wiki-pane .wrow").first()).toBeVisible();
await keys(page, "j j l"); await keys(page, "j j l");
expect((await trail(page)).at(-1)).toBe("W:Fixed-point combinator#2"); expect((await trail(page)).at(-1)).toBe("W:Fixed-point combinator#2");
// A Shift-click on a link in the article's text forks beside that section. // A Shift-click on a link in the article's text forks beside that section.
const art = page.locator(".forks > .fork").nth(0).locator(".wiki-pane").first(); const art = pane(page, "Fixed-point combinator");
await art.locator('.wiki-text a[data-wiki="Haskell Curry"]').click({ modifiers: ["Shift"] }); await art.locator('.wiki-text a[data-wiki="Haskell Curry"]').click({ modifiers: ["Shift"] });
const article = ["W:Fixed-point combinator", ["W:Fixed-point combinator#2", ["*", "W:Haskell Curry"]]]; const article = ["W:Fixed-point combinator", ["W:Fixed-point combinator#2", ["*", "W:Haskell Curry"]]];
const recursion = ["Recursion without names", [["*", article], "How Y works"]]; const recursion = ["Recursion without names", [["*", article], "How Y works"]];
expect(await tree(page)).toEqual(["Library", [["*", ["Fixed points", [["*", recursion]]]]]]); expect(await tree(page)).toEqual(["Library", [["*", ["Fixed points", [["*", recursion]]]]]]);
await expect(art.locator(".wrow.forked > .row .title")).toHaveText("Y combinator"); await expect(art.locator(".wrow.forked > .row .title")).toHaveText("Y combinator");
await expect(art.locator('.wiki-text a.forked.picked[data-wiki="Haskell Curry"]')).toHaveCount(1); await expect(art.locator('.wiki-text a.forked.picked[data-wiki="Haskell Curry"]')).toHaveCount(1);
// And Shift+Enter on a link selected by Tab in the article's text: a third fork of the article. expect((await columns(page))[4]).toHaveLength(2);
await keys(page, "h");
for (let i = 0; i < 6 && (await state(page, (s) => s.aux?.host)) !== "p3"; i++) await keys(page, "h");
await keys(page, "k k k");
await tabTo(page, "lambda calculus");
await keys(page, "Shift+Enter");
await expect(page.locator(".wiki-pane .wiki-head h2", { hasText: "Lambda calculus" })).toHaveCount(1);
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator", "W:Lambda calculus"]);
const stack = page.locator(".forks > .fork").nth(0).locator(".forks > .fork");
await expect(stack).toHaveCount(3);
});
test("three forks of one pane, one forked again: [ and ] move between them, q closes a fork, and the last but one leaves a plain trail", async ({ page }) => {
await open(page);
await keys(page, "l l l Shift+Enter j Shift+Enter j Shift+Enter");
await keys(page, "l Shift+Enter j Shift+Enter"); // into Generation on demand, and fork from it too
expect(await tree(page)).toEqual([
"Infinispand",
[["*", ["Expansion by depth", ["Levels of a node", "Pre-generated depth", ["*", ["Generation on demand", ["Deepening a leaf", ["*", "Expanding a selection"]]]]]]]],
]);
await expect(page.locator(".strip > .forks > .fork")).toHaveCount(3);
await expect(page.locator(".strip > .forks > .fork").nth(2).locator(".forks > .fork")).toHaveCount(2);
await keys(page, "]");
await expect(page.locator(".status .message")).toContainText("No fork below");
// Up, row by row, in the order they are drawn: the nearest fork first.
await keys(page, "[");
expect((await trail(page)).at(-1)).toBe("Deepening a leaf");
expect(await focusedTitle(page)).toBe("Deepening a leaf");
await keys(page, "[");
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]);
expect(await focusedTitle(page)).toBe("Pre-generated depth");
await keys(page, "[");
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]);
await keys(page, "[");
await expect(page.locator(".status .message")).toContainText("No fork above");
// Down again; back in a fork, the focus is where it was left.
await keys(page, "] ]");
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]);
expect(await focusedTitle(page)).toBe("Deepening a leaf");
// q at the end of a fork closes that fork; the other stays, as a plain trail.
await keys(page, "q");
expect(await tree(page)).toEqual([
"Infinispand",
[["*", ["Expansion by depth", ["Levels of a node", "Pre-generated depth", ["*", ["Generation on demand", [["*", "Expanding a selection"]]]]]]]],
]);
// In a fork with panes right of the one being read, q closes those, as it always has.
await keys(page, "h");
expect(await focusedTitle(page)).toBe("Generation on demand");
await keys(page, "q");
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]);
// With nothing right of it, the whole fork.
await keys(page, "q");
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Expansion by depth", ["Levels of a node", ["*", "Pre-generated depth"]]]]]]);
await keys(page, "[ q");
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Expansion by depth", [["*", "Pre-generated depth"]]]]]]);
await expect(page.locator(".forks")).toHaveCount(0);
await expect(page.locator(".strip:not(.forked) > .pane")).toHaveCount(3);
await keys(page, "]");
await expect(page.locator(".status .message")).toContainText("No forks open");
});
test("many forks: the rows scroll down with the focused one in view; a reload brings the tree back", async ({ page }) => {
await open(page);
await keys(page, "j Shift+Enter");
for (let i = 0; i < 5; i++) await keys(page, "j Shift+Enter");
await expect(page.locator(".strip > .forks > .fork")).toHaveCount(6);
const strip = page.locator(".strip");
expect(await strip.evaluate((el) => el.scrollHeight > el.clientHeight + 100)).toBe(true);
// Each row is a third of the strip's height; the last, focused, is in view, and the first pane stays at the top.
const h = await strip.evaluate((el) => el.clientHeight);
const rowH = (await page.locator(".forks > .fork").nth(2).boundingBox())!.height;
expect(Math.abs(rowH - Math.floor(h / 3))).toBeLessThanOrEqual(2);
await expect.poll(() => inView(page, ".forks > .fork.on")).toBe(true);
await expect.poll(() => strip.evaluate((el) => el.scrollTop)).toBeGreaterThan(100);
const first = await page.locator(".strip > .pane").first().boundingBox();
const sbox = (await strip.boundingBox())!;
expect(Math.abs(first!.y - sbox.y)).toBeLessThanOrEqual(1);
// Up to the first fork: the strip scrolls back.
await keys(page, "[ [ [ [ [");
await expect.poll(() => inView(page, ".forks > .fork.on")).toBe(true);
await expect.poll(() => strip.evaluate((el) => el.scrollTop)).toBeLessThan(5);
const before = await tree(page);
const was = await trail(page);
await page.reload();
await page.waitForSelector(".strip > .pane");
expect(await tree(page)).toEqual(before);
expect(await trail(page)).toEqual(was);
await expect(page.locator(".strip > .forks > .fork")).toHaveCount(6);
}); });
test("a fork whose node is deleted closes, and the others stay", async ({ page, request }) => { test("a fork whose node is deleted closes, and the others stay", async ({ page, request }) => {
@@ -271,30 +526,41 @@ test("a fork whose node is deleted closes, and the others stay", async ({ page,
const kids = await childTitles(page, "Expansion by depth"); const kids = await childTitles(page, "Expansion by depth");
for (let i = 1; i < kids.indexOf("A section to delete"); i++) await keys(page, "j"); for (let i = 1; i < kids.indexOf("A section to delete"); i++) await keys(page, "j");
await keys(page, "j Shift+Enter"); await keys(page, "j Shift+Enter");
expect(await forkRows(page)).toEqual([["Levels of a node"], ["A section to delete"]]); expect((await columns(page))[2]).toEqual(["Levels of a node", "A section to delete"]);
await keys(page, "["); await page.locator(".pane .row", { hasText: "Levels of a node" }).first().click();
const id = await state(page, (s) => (Object.values(s.snap.nodes) as any[]).find((n) => n.title === "A section to delete").id); const id = await state(page, (s) => (Object.values(s.snap.nodes) as any[]).find((n) => n.title === "A section to delete").id);
const res = await request.post("/api/ops", { data: { author: "another", message: "Delete it", ops: [{ op: "delete", id }] } }); const res = await request.post("/api/ops", { data: { author: "another", message: "Delete it", ops: [{ op: "delete", id }] } });
expect(res.ok()).toBe(true); expect(res.ok()).toBe(true);
// The fork that was not focused goes; the focused one stays, now a plain trail. await expect.poll(async () => (await columns(page))[2]).toEqual(["Levels of a node"]);
await expect.poll(() => page.locator(".forks").count()).toBe(0);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]); expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]);
}); });
test("a window too short for rows shows only the focused branch, and says which fork it is and how to switch", async ({ page }) => { test("a window too short to share a column folds it at once: the focused pane open, the others tabs", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 480 }); await page.setViewportSize({ width: 1920, height: 480 });
await open(page); await open(page);
await keys(page, "l l l Shift+Enter j Shift+Enter"); await keys(page, "l l l Shift+Enter j Shift+Enter");
await expect(page.locator(".forks")).toHaveCount(0); let b = await boxes(page);
await expect(page.locator(".strip > .pane")).toHaveCount(3); expect(b["Levels of a node"].tab).toBe(true);
await expect(page.locator(".fork-note")).toContainText("fork 2 of 2"); expect(b["Pre-generated depth"].tab).toBe(false);
await keys(page, "["); // With room again, they share the column.
await expect(page.locator(".fork-note")).toContainText("fork 1 of 2");
expect((await trail(page)).at(-1)).toBe("Levels of a node");
// With room again, the rows come back.
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await expect(page.locator(".strip > .forks > .fork")).toHaveCount(2); await expect.poll(async () => (await boxes(page))["Levels of a node"].tab).toBe(false);
await expect(page.locator(".fork-note")).toHaveCount(0); b = await boxes(page);
expect(b["Pre-generated depth"].tab).toBe(false);
});
test("many forks: a reload brings the forest back", async ({ page }) => {
await open(page);
await keys(page, "j Shift+Enter");
for (let i = 0; i < 5; i++) await keys(page, "j Shift+Enter");
expect((await columns(page))[1]).toHaveLength(6);
const before = await tree(page);
const was = await trail(page);
await page.reload();
await page.waitForSelector(".strip .pane");
expect(await tree(page)).toEqual(before);
expect(await trail(page)).toEqual(was);
expect((await columns(page))[1]).toHaveLength(6);
}); });
test("in the column a modified open is a plain open, and the status line says why once", async ({ page }) => { test("in the column a modified open is a plain open, and the status line says why once", async ({ page }) => {
+4 -1
View File
@@ -3,7 +3,7 @@
* exposes as globalThis.__ie, waiting for it to settle, and the links written into the shared * exposes as globalThis.__ie, waiting for it to settle, and the links written into the shared
* library over the op API, as an outside agent would (every kind of target, a note that also links, * library over the op API, as an outside agent would (every kind of target, a note that also links,
* a cross-document node link, two documents mentioning one article, a link and a note on the same * a cross-document node link, two documents mentioning one article, a link and a note on the same
* words; the articles are the mock * words, links on the screenshot's cells; the articles are the mock
* Wikipedia's fixtures in server/wikiMock.ts). * Wikipedia's fixtures in server/wikiMock.ts).
*/ */
import { writeFileSync } from "node:fs"; import { writeFileSync } from "node:fs";
@@ -88,6 +88,7 @@ export async function seedLinks(request: APIRequestContext) {
const separate = find(s, "octopus-minds", "A separate experiment"); const separate = find(s, "octopus-minds", "A separate experiment");
const ancestor = find(s, "octopus-minds", "A separate experiment", "The common ancestor"); const ancestor = find(s, "octopus-minds", "A separate experiment", "The common ancestor");
const programs = find(s, "what-a-proof-is", "Proof assistants", "Proofs as programs"); const programs = find(s, "what-a-proof-is", "Proof assistants", "Proofs as programs");
const kinds = find(s, "the-eukaryotic-cell", "Two kinds of cell");
const ops = [ const ops = [
{ op: "create", parent: recursion, kind: "note", quote: "fixed-point combinator", ref: W("Fixed-point combinator") }, { op: "create", parent: recursion, kind: "note", quote: "fixed-point combinator", ref: W("Fixed-point combinator") },
{ op: "update", id: noteOn(s, recursion, "lambda calculus"), ref: W("Lambda calculus") }, { op: "update", id: noteOn(s, recursion, "lambda calculus"), ref: W("Lambda calculus") },
@@ -101,6 +102,8 @@ export async function seedLinks(request: APIRequestContext) {
{ op: "create", parent: ancestor, kind: "note", quote: "The camera-like eye", ref: W("Cephalopod") }, { op: "create", parent: ancestor, kind: "note", quote: "The camera-like eye", ref: W("Cephalopod") },
{ op: "create", parent: programs, kind: "note", quote: "a function turning proofs", ref: W("Lambda calculus") }, { op: "create", parent: programs, kind: "note", quote: "a function turning proofs", ref: W("Lambda calculus") },
{ op: "create", parent: programs, kind: "note", quote: "Several of the leading systems", ref: { kind: "node", id: recursion, doc: "fixed-points", path: ["Recursion without names"] } }, { op: "create", parent: programs, kind: "note", quote: "Several of the leading systems", ref: { kind: "node", id: recursion, doc: "fixed-points", path: ["Recursion without names"] } },
{ op: "create", parent: kinds, kind: "note", quote: "Eukaryotes", ref: W("Eukaryote") },
{ op: "create", parent: kinds, kind: "note", quote: "Bacteria", ref: W("Bacteria") },
]; ];
const res = await request.post("/api/ops", { data: { author: "linker", message: "Seed links for the link tests", ops } }); const res = await request.post("/api/ops", { data: { author: "linker", message: "Seed links for the link tests", ops } });
if (!res.ok()) throw new Error(`seeding links failed: ${res.status()} ${await res.text()}`); if (!res.ok()) throw new Error(`seeding links failed: ${res.status()} ${await res.text()}`);
+3 -3
View File
@@ -10,7 +10,7 @@ import { command, focusedTitle, jump, keys, seedLinks, selected, settle, state,
/** The panes' titles, left to right: a node's title, or W:article for a Wikipedia pane. */ /** The panes' titles, left to right: a node's title, or W:article for a Wikipedia pane. */
const trail = (page: Page) => const trail = (page: Page) =>
state(page, (s) => s.trail.map((p: any) => (p.kind === "node" ? s.snap.nodes[p.id].title || s.snap.nodes[p.id].anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`))); state(page, (s) => s.trail.map((p: any) => (p.kind === "node" ? s.snap.nodes[p.id].title || s.snap.nodes[p.id].anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`)));
const panes = (page: Page) => page.locator(".strip > .pane"); const panes = (page: Page) => page.locator(".strip .pane");
/** Tab through the focused section's marked spans until the selection is these words. */ /** Tab through the focused section's marked spans until the selection is these words. */
async function tabTo(page: Page, words: string) { async function tabTo(page: Page, words: string) {
@@ -30,7 +30,7 @@ async function column(page: Page, path = "/doc/fixed-points") {
async function wide(page: Page, path = "/doc/fixed-points") { async function wide(page: Page, path = "/doc/fixed-points") {
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await page.goto(path); await page.goto(path);
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
} }
/** Open a section in panes and select the first marked span in its text. */ /** Open a section in panes and select the first marked span in its text. */
@@ -174,7 +174,7 @@ test("panes: Tab and Enter open an article in the next pane; its sections open a
for (let i = 0; i < 4 && (await state(page, (s) => s.selectedText())) !== "Alonzo Church"; i++) await keys(page, "Tab"); for (let i = 0; i < 4 && (await state(page, (s) => s.selectedText())) !== "Alonzo Church"; i++) await keys(page, "Tab");
await keys(page, "Enter"); await keys(page, "Enter");
await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Alonzo Church"); await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Alonzo Church");
const spine = page.locator(".wiki-pane[data-covered] .spine").first(); const spine = page.locator(".col[data-covered] .wiki-pane .spine").first();
await expect(spine.locator(".wmark")).toHaveText("W"); await expect(spine.locator(".wmark")).toHaveText("W");
expect(await spine.evaluate((el) => getComputedStyle(el).backgroundColor)).not.toBe(await page.locator(".pane.root .spine").evaluate((el) => getComputedStyle(el).backgroundColor)); expect(await spine.evaluate((el) => getComputedStyle(el).backgroundColor)).not.toBe(await page.locator(".pane.root .spine").evaluate((el) => getComputedStyle(el).backgroundColor));
}); });
+3 -3
View File
@@ -325,14 +325,14 @@ test("the : commands do the same", async ({ page }) => {
test("the menu works in panes and at phone width", async ({ page }) => { test("the menu works in panes and at phone width", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await open(page, "/doc/infinite-expand"); await open(page, "/doc/infinite-expand");
await expect(page.locator(".strip > .pane")).toHaveCount(2); // the library, and the document await expect(page.locator(".strip .pane")).toHaveCount(2); // the library, and the document
await openByMenu(page, "menu fixture"); await openByMenu(page, "menu fixture");
await expect(page.locator(".strip .pane.root h1")).toHaveText("Library"); await expect(page.locator(".strip .pane.root h1")).toHaveText("Library");
await expect(page.locator(".strip .pane.doc h1")).toHaveText("Menu fixture"); await expect(page.locator(".strip .pane.doc h1")).toHaveText("Menu fixture");
await keys(page, "l l"); await keys(page, "l l");
await expect(page.locator(".strip > .pane")).toHaveCount(3); await expect(page.locator(".strip .pane")).toHaveCount(3);
await openByMenu(page, "infinispand"); await openByMenu(page, "infinispand");
await expect(page.locator(".strip > .pane")).toHaveCount(2); // the pane path is the other document's own await expect(page.locator(".strip .pane")).toHaveCount(2); // the pane path is the other document's own
await expect(page.locator(".strip .pane.doc h1")).toHaveText("Infinispand"); await expect(page.locator(".strip .pane.doc h1")).toHaveText("Infinispand");
await page.setViewportSize({ width: 390, height: 800 }); await page.setViewportSize({ width: 390, height: 800 });
+37 -29
View File
@@ -10,9 +10,9 @@ import { command, focusedTitle, idle, jump, keys, settle, state, writeReport, ty
/** Each pane's title and box, left to right. */ /** Each pane's title and box, left to right. */
const panes = (page: Page) => const panes = (page: Page) =>
page.evaluate(() => page.evaluate(() =>
[...document.querySelectorAll<HTMLElement>(".strip > .pane")].map((p) => { [...document.querySelectorAll<HTMLElement>(".strip .pane")].map((p) => {
const r = p.getBoundingClientRect(); const r = p.getBoundingClientRect();
return { title: p.querySelector(".pane-head h2, .top h1")?.textContent ?? "", left: r.left, right: r.right, width: r.width, covered: p.hasAttribute("data-covered") }; return { title: p.querySelector(".pane-head h2, .top h1")?.textContent ?? "", left: r.left, right: r.right, width: r.width, covered: !!p.closest(".col")?.hasAttribute("data-covered") };
}), }),
); );
const paneTitles = async (page: Page) => (await panes(page)).map((p) => p.title); const paneTitles = async (page: Page) => (await panes(page)).map((p) => p.title);
@@ -20,12 +20,12 @@ const nodeId = (page: Page, title: string) => page.evaluate((t) => (Object.value
async function open(page: Page) { async function open(page: Page) {
await page.goto("/doc/infinite-expand"); await page.goto("/doc/infinite-expand");
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
// The library pane and the document's; hoisting makes the document the first. // The library pane and the document's; hoisting makes the document the first.
await expect(page.locator(".strip > .pane")).toHaveCount(2); await expect(page.locator(".strip .pane")).toHaveCount(2);
await page.keyboard.press("z"); await page.keyboard.press("z");
await expect(page.locator(".strip > .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
} }
test.use({ viewport: { width: 1920, height: 1080 } }); test.use({ viewport: { width: 1920, height: 1080 } });
@@ -35,7 +35,7 @@ test.afterEach(({ page }) => settle(page));
test("the library is the first pane, and a document opens in the next; reload and Back keep the place", async ({ page }) => { test("the library is the first pane, and a document opens in the next; reload and Back keep the place", async ({ page }) => {
await page.goto("/"); await page.goto("/");
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
expect(await paneTitles(page)).toEqual(["Library"]); expect(await paneTitles(page)).toEqual(["Library"]);
await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).length)); await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).length));
await keys(page, "j l"); // the first document's row, then open it await keys(page, "j l"); // the first document's row, then open it
@@ -48,7 +48,7 @@ test("the library is the first pane, and a document opens in the next; reload an
expect(third).toHaveLength(3); expect(third).toHaveLength(3);
await expect(page).toHaveURL(/\/doc\/a-mind-made-of-text\/\d+%40\d+$/); await expect(page).toHaveURL(/\/doc\/a-mind-made-of-text\/\d+%40\d+$/);
await page.reload(); await page.reload();
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
expect(await paneTitles(page)).toEqual(third); expect(await paneTitles(page)).toEqual(third);
// Opening a document from the menu is a new page in the address bar's history; Back returns. // Opening a document from the menu is a new page in the address bar's history; Back returns.
await page.keyboard.press("m"); await page.keyboard.press("m");
@@ -64,27 +64,27 @@ test("the library is the first pane, and a document opens in the next; reload an
test("auto shows panes at 1920 px and one column at 1440; v and /view switch", async ({ page }) => { test("auto shows panes at 1920 px and one column at 1440; v and /view switch", async ({ page }) => {
await open(page); await open(page);
await expect(page.locator(".app.view-panes .strip > .pane")).toHaveCount(1); await expect(page.locator(".app.view-panes .strip .pane")).toHaveCount(1);
await expect(page.locator(".strip .pane.root h1")).toHaveText("Infinispand"); await expect(page.locator(".strip .pane.root h1")).toHaveText("Infinispand");
await page.setViewportSize({ width: 1440, height: 900 }); await page.setViewportSize({ width: 1440, height: 900 });
await expect(page.locator(".strip")).toHaveCount(0); await expect(page.locator(".strip")).toHaveCount(0);
await expect(page.locator("article > .outline > .node").first()).toBeVisible(); await expect(page.locator("article > .outline > .node").first()).toBeVisible();
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await expect(page.locator(".strip > .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
await keys(page, "v"); await keys(page, "v");
await expect(page.locator(".strip")).toHaveCount(0); await expect(page.locator(".strip")).toHaveCount(0);
await expect(page.locator(".status .message")).toContainText("one column"); await expect(page.locator(".status .message")).toContainText("one column");
await keys(page, "v"); await keys(page, "v");
await expect(page.locator(".strip > .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
await expect(page.locator(".status .message")).toContainText("panes"); await expect(page.locator(".status .message")).toContainText("panes");
await command(page, "/view column"); await command(page, "/view column");
await expect(page.locator(".strip")).toHaveCount(0); await expect(page.locator(".strip")).toHaveCount(0);
expect(await state(page, (s) => s.settings.view)).toBe("column"); expect(await state(page, (s) => s.settings.view)).toBe("column");
await command(page, "/view auto"); await command(page, "/view auto");
await expect(page.locator(".strip > .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
// The setting is remembered. // The setting is remembered.
await page.reload(); await page.reload();
await page.waitForSelector(".strip > .pane"); await page.waitForSelector(".strip .pane");
expect(await page.evaluate(() => JSON.parse(localStorage.getItem("ie:settings")!).view)).toBe("auto"); expect(await page.evaluate(() => JSON.parse(localStorage.getItem("ie:settings")!).view)).toBe("auto");
}); });
@@ -92,7 +92,7 @@ test("opening three levels deep gives four panes left to right; h moves back lef
await open(page); await open(page);
// l: first child · l: open it · l: its first child · j j · l open · l first child · l open // l: first child · l: open it · l: its first child · j j · l open · l first child · l open
await keys(page, "l l l j j l l l"); await keys(page, "l l l j j l l l");
await expect(page.locator(".strip > .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
const ps = await panes(page); const ps = await panes(page);
expect(ps.map((p) => p.title)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]); expect(ps.map((p) => p.title)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]);
for (let i = 1; i < ps.length; i++) expect(ps[i].left).toBeGreaterThan(ps[i - 1].left); for (let i = 1; i < ps.length; i++) expect(ps[i].left).toBeGreaterThan(ps[i - 1].left);
@@ -100,7 +100,7 @@ test("opening three levels deep gives four panes left to right; h moves back lef
await expect(page.locator(".pane .node.showing > .row")).toHaveText(["Expansion by depth", "Generation on demand", "Deepening a leaf"].map((t) => new RegExp(t))); await expect(page.locator(".pane .node.showing > .row")).toHaveText(["Expansion by depth", "Generation on demand", "Deepening a leaf"].map((t) => new RegExp(t)));
// Moving back left closes nothing: the trail stays as it was. // Moving back left closes nothing: the trail stays as it was.
await keys(page, "h"); await keys(page, "h");
await expect(page.locator(".strip > .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
expect(await focusedTitle(page)).toBe("Generation on demand"); expect(await focusedTitle(page)).toBe("Generation on demand");
await keys(page, "h"); await keys(page, "h");
expect(await focusedTitle(page)).toBe("Expansion by depth"); expect(await focusedTitle(page)).toBe("Expansion by depth");
@@ -108,13 +108,21 @@ test("opening three levels deep gives four panes left to right; h moves back lef
// And forward again along the same trail. // And forward again along the same trail.
await keys(page, "l"); await keys(page, "l");
expect(await focusedTitle(page)).toBe("Levels of a node"); expect(await focusedTitle(page)).toBe("Levels of a node");
await expect(page.locator(".strip > .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
// q closes the panes right of the one being read; again, that one. // q closes the active pane (the one holding the focus, under the heavy rule) and every pane opened from it; the focus goes back to the row it was opened from.
await keys(page, "h q"); await keys(page, "j j l");
expect(await focusedTitle(page)).toBe("Deepening a leaf");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText("Generation on demand");
await keys(page, "q");
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth"]); expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth"]);
expect(await focusedTitle(page)).toBe("Generation on demand");
await keys(page, "q"); await keys(page, "q");
expect(await paneTitles(page)).toEqual(["Infinispand"]); expect(await paneTitles(page)).toEqual(["Infinispand"]);
expect(await focusedTitle(page)).toBe("Expansion by depth"); expect(await focusedTitle(page)).toBe("Expansion by depth");
// The first pane stays.
await keys(page, "q");
expect(await paneTitles(page)).toEqual(["Infinispand"]);
await expect(page.locator(".status .message")).toContainText("first pane stays");
}); });
test("j and k move among siblings, and the strip follows", async ({ page }) => { test("j and k move among siblings, and the strip follows", async ({ page }) => {
@@ -122,7 +130,7 @@ test("j and k move among siblings, and the strip follows", async ({ page }) => {
await keys(page, "j"); // from the top: its first child await keys(page, "j"); // from the top: its first child
expect(await focusedTitle(page)).toBe("Expansion by depth"); expect(await focusedTitle(page)).toBe("Expansion by depth");
await jump(page, "Levels of a node"); await jump(page, "Levels of a node");
await expect(page.locator(".strip > .pane")).toHaveCount(2); await expect(page.locator(".strip .pane")).toHaveCount(2);
await keys(page, "j"); await keys(page, "j");
expect(await focusedTitle(page)).toBe("Pre-generated depth"); expect(await focusedTitle(page)).toBe("Pre-generated depth");
await keys(page, "l"); // open it: its pane appears await keys(page, "l"); // open it: its pane appears
@@ -146,7 +154,7 @@ test("a pre-generated note opened in a pane is set inside the pane", async ({ pa
await open(page); await open(page);
await jump(page, "Expansion by depth"); await jump(page, "Expansion by depth");
await keys(page, "l Tab Enter"); await keys(page, "l Tab Enter");
const pane = page.locator(".strip > .pane").nth(1); const pane = page.locator(".strip .pane").nth(1);
const note = pane.locator(".sidenote").first(); const note = pane.locator(".sidenote").first();
await expect(note).toBeVisible(); await expect(note).toBeVisible();
const [n, p, body] = await Promise.all([note.boundingBox(), pane.boundingBox(), pane.locator(".pane-head").boundingBox()]); const [n, p, body] = await Promise.all([note.boundingBox(), pane.boundingBox(), pane.locator(".pane-head").boundingBox()]);
@@ -180,7 +188,7 @@ test("in panes everything is reachable with the mouse: rows, headings, marked sp
await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click();
await page.locator(".pane .row", { hasText: "Typography" }).click(); await page.locator(".pane .row", { hasText: "Typography" }).click();
// Dragging across a pane's text makes that range the focus. // Dragging across a pane's text makes that range the focus.
const para = page.locator(".strip > .pane").last().locator(".para").first(); const para = page.locator(".strip .pane").last().locator(".para").first();
const box = (await para.boundingBox())!; const box = (await para.boundingBox())!;
await page.mouse.move(box.x + 6, box.y + 12); await page.mouse.move(box.x + 6, box.y + 12);
await page.mouse.down(); await page.mouse.down();
@@ -196,7 +204,7 @@ test("in panes everything is reachable with the mouse: rows, headings, marked sp
test("past the viewport, earlier panes become spines; a click on one brings it back", async ({ page }) => { test("past the viewport, earlier panes become spines; a click on one brings it back", async ({ page }) => {
await open(page); await open(page);
await keys(page, "l l l j j l l l"); await keys(page, "l l l j j l l l");
await expect(page.locator(".strip > .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
// The focused pane, and its parent with the marked row, end up fully in view. // The focused pane, and its parent with the marked row, end up fully in view.
await expect.poll(async () => { await expect.poll(async () => {
const ps = await panes(page); const ps = await panes(page);
@@ -205,26 +213,26 @@ test("past the viewport, earlier panes become spines; a click on one brings it b
const strip = page.locator(".strip"); const strip = page.locator(".strip");
expect(await strip.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); expect(await strip.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true);
// The root has slid under the rest and shows as a spine, its title set vertically. // The root has slid under the rest and shows as a spine, its title set vertically.
const spine = page.locator('.pane[data-covered] .spine').first(); const spine = page.locator('.col[data-covered] .spine').first();
await expect(spine).toHaveText("Infinispand"); await expect(spine).toHaveText("Infinispand");
await expect.poll(() => spine.evaluate((el) => getComputedStyle(el).opacity)).toBe("1"); await expect.poll(() => spine.evaluate((el) => getComputedStyle(el).opacity)).toBe("1");
expect(await spine.locator("span").evaluate((el) => getComputedStyle(el).writingMode)).toBe("vertical-rl"); expect(await spine.locator(".spine-title").evaluate((el) => getComputedStyle(el).writingMode)).toBe("vertical-rl");
const box = (await spine.boundingBox())!; const box = (await spine.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0); expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.width).toBeLessThan(60); expect(box.width).toBeLessThan(60);
await spine.click(); await spine.click();
expect(await focusedTitle(page)).toBe("Infinispand"); expect(await focusedTitle(page)).toBe("Infinispand");
// The trail stays; the strip slides back to show the first pane whole. // The trail stays; the strip slides back to show the first pane whole.
await expect(page.locator(".strip > .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
await expect.poll(async () => (await panes(page))[0].left).toBe(0); await expect.poll(async () => (await panes(page))[0].left).toBe(0);
await expect(page.locator(".pane[data-covered]")).toHaveCount(0); await expect(page.locator(".col[data-covered]")).toHaveCount(0);
}); });
test("generation in a pane: a note on a sentence streams in; a leaf gets sections as rows", async ({ page }) => { test("generation in a pane: a note on a sentence streams in; a leaf gets sections as rows", async ({ page }) => {
await open(page); await open(page);
await jump(page, "Why it ends"); await jump(page, "Why it ends");
await keys(page, "l i j e"); await keys(page, "l i j e");
const last = page.locator(".strip > .pane").last(); const last = page.locator(".strip .pane").last();
await expect(last.locator(".pane-head h2")).toHaveText("Why it ends"); await expect(last.locator(".pane-head h2")).toHaveText("Why it ends");
await expect(last.locator(".sidenote.pending")).toBeVisible(); await expect(last.locator(".sidenote.pending")).toBeVisible();
await idle(page); await idle(page);
@@ -236,7 +244,7 @@ test("generation in a pane: a note on a sentence streams in; a leaf gets section
const pane = page.locator(`.pane[data-pane="${await nodeId(page, "Downward: rendered children")}"]`); const pane = page.locator(`.pane[data-pane="${await nodeId(page, "Downward: rendered children")}"]`);
await expect(pane.locator(".rows .row")).toHaveText([/First part of Downward: rendered children/, /Second part of Downward: rendered children/]); await expect(pane.locator(".rows .row")).toHaveText([/First part of Downward: rendered children/, /Second part of Downward: rendered children/]);
await keys(page, "l l"); // into the new section, and open it: a fifth pane await keys(page, "l l"); // into the new section, and open it: a fifth pane
await expect(page.locator(".strip > .pane")).toHaveCount(5); await expect(page.locator(".strip .pane")).toHaveCount(5);
expect((await paneTitles(page)).at(-1)).toBe("First part of Downward: rendered children"); expect((await paneTitles(page)).at(-1)).toBe("First part of Downward: rendered children");
}); });
@@ -249,7 +257,7 @@ test("editing in a pane: c, type, Esc", async ({ page }) => {
await page.keyboard.press("Control+a"); await page.keyboard.press("Control+a");
await page.keyboard.type("Rewritten in a pane."); await page.keyboard.type("Rewritten in a pane.");
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await expect(page.locator(".strip > .pane").last().locator(".body").first()).toHaveText("Rewritten in a pane."); await expect(page.locator(".strip .pane").last().locator(".body").first()).toHaveText("Rewritten in a pane.");
expect(await state(page, (s) => s.snap.nodes[s.focus.node].body)).toBe("Rewritten in a pane."); expect(await state(page, (s) => s.snap.nodes[s.focus.node].body)).toBe("Rewritten in a pane.");
// r renames at the head of the pane. // r renames at the head of the pane.
await keys(page, "r"); await keys(page, "r");
@@ -292,7 +300,7 @@ test("keypress → paint stays within the 50 ms budget in panes", async ({ page
test("only the strip scrolls sideways, and nothing hides behind the status line", async ({ page }) => { test("only the strip scrolls sideways, and nothing hides behind the status line", async ({ page }) => {
await open(page); await open(page);
await keys(page, "l l l j j l l l"); await keys(page, "l l l j j l l l");
await expect(page.locator(".strip > .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth && document.body.scrollWidth <= window.innerWidth)).toBe(true); expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth && document.body.scrollWidth <= window.innerWidth)).toBe(true);
expect(await page.evaluate(() => (window.scrollX, document.scrollingElement!.scrollLeft))).toBe(0); expect(await page.evaluate(() => (window.scrollX, document.scrollingElement!.scrollLeft))).toBe(0);
expect(await page.locator(".strip").evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); expect(await page.locator(".strip").evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true);
+2 -2
View File
@@ -245,11 +245,11 @@ test("Tab then Enter on an article that is still loading go to its first link on
await keys(page, "Tab"); await keys(page, "Tab");
expect(await selected(page)).toBe("Hoyle state"); expect(await selected(page)).toBe("Hoyle state");
await keys(page, "Enter"); await keys(page, "Enter");
await expect(page.locator(".strip > .pane").last().locator(".wiki-wait")).toBeVisible(); await expect(page.locator(".strip .pane").last().locator(".wiki-wait")).toBeVisible();
await keys(page, "Tab Enter"); await keys(page, "Tab Enter");
await expect(page.locator(".status .message")).toContainText("still loading"); await expect(page.locator(".status .message")).toContainText("still loading");
// When it arrives, the Tab goes to its first link and the Enter opens that. // When it arrives, the Tab goes to its first link and the Enter opens that.
await expect(page.locator(".strip > .pane").last().locator(".wiki-head h2")).toHaveText("Carbon-12", { timeout: 10_000 }); await expect(page.locator(".strip .pane").last().locator(".wiki-head h2")).toHaveText("Carbon-12", { timeout: 10_000 });
}); });
test("keypress → paint stays within a frame while suggestions are on screen and scans run after edits", async ({ page }) => { test("keypress → paint stays within a frame while suggestions are on screen and scans run after edits", async ({ page }) => {
+1 -1
View File
@@ -100,7 +100,7 @@ test("a library of over 5,000 nodes in 100 more documents: keypress → paint an
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await page.goto("/"); await page.goto("/");
await ready(page); await ready(page);
await expect(page.locator(".strip > .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0)); await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0));
for (let i = 0; i < 40; i++) await paced(page, "j"); for (let i = 0; i < 40; i++) await paced(page, "j");
for (let i = 0; i < 6; i++) await paced(page, "l l l j l i j Escape h h h j"); for (let i = 0; i < 6; i++) await paced(page, "l l l j l i j Escape h h h j");
+39
View File
@@ -223,6 +223,45 @@ const FIXTURES: Record<string, Fixture> = {
}, },
], ],
}, },
Eukaryote: {
id: 1_200_120,
description: "Domain of life whose cells have nuclei",
lead: [
`The <b>eukaryotes</b> are organisms whose cells have a membrane-bound nucleus.[ref] They include all animals, plants, fungi and many single-celled organisms, the protists, and with the [[Bacteria|bacteria]] and the [[Archaea|archaea]] they make up the three domains of life. Eukaryotic cells also contain other membrane-bound compartments, such as [[Mitochondrion|mitochondria]] and the Golgi apparatus, and are typically much larger than those of prokaryotes.`,
`Eukaryotes probably emerged within the archaea, and the leading theory holds that the first eukaryotic cell arose when an archaeon took in a bacterium that became the mitochondrion.[ref] All living eukaryotes descend from a single last common ancestor, which already had most of the features that distinguish them.`,
],
sections: [
{
heading: "Cell features",
body: [
`Eukaryotic cells are on average about ten thousand times the volume of prokaryotic cells. Their DNA is organised into several linear chromosomes inside the nucleus, and a cytoskeleton of protein filaments gives the cell its shape and lets it move material from place to place.`,
`Most eukaryotes reproduce sexually at some stage of their life cycle, by meiosis and the fusion of gametes, although many single-celled species also divide asexually.`,
],
},
{
heading: "Origin",
body: [
`The timing of the origin of eukaryotes is uncertain: the oldest fossils accepted as eukaryotic are about 1.6 billion years old. Comparisons of genes place their nearest living relatives among the Asgard archaea, discovered in deep-sea sediments in 2015.`,
],
},
],
},
Bacteria: {
id: 1_200_121,
description: "Domain of prokaryotic microorganisms",
lead: [
`<b>Bacteria</b> are ubiquitous, mostly free-living organisms often consisting of one biological cell.[ref] They constitute a large domain of prokaryotic microorganisms. Typically a few micrometres in length, bacteria were among the first life forms to appear on Earth, and are present in most of its habitats, from soil and water to acidic hot springs and the deep biosphere.`,
`Bacteria play a vital role in many stages of the nutrient cycle, by recycling nutrients and fixing nitrogen from the atmosphere. Most have not been characterised, and many species cannot be grown in the laboratory. Their study is known as bacteriology, a branch of microbiology.`,
],
sections: [
{
heading: "Structure",
body: [
`A bacterial cell is surrounded by a membrane and, in most species, a cell wall. Its DNA lies in the cytoplasm, usually as a single circular chromosome, with no nucleus around it. Many bacteria swim by turning a flagellum.`,
],
},
],
},
"Hoyle state": { "Hoyle state": {
id: 1_200_108, id: 1_200_108,
description: "Excited state of the carbon-12 nucleus", description: "Excited state of the carbon-12 nucleus",
+7 -1
View File
@@ -512,6 +512,9 @@ export function App() {
const click = (e: MouseEvent) => { const click = (e: MouseEvent) => {
if (store.mode === "edit") return; if (store.mode === "edit") return;
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
// A pane's × and pin act on that pane, wherever the focus is.
const ctl = target.closest<HTMLElement>("[data-close], [data-pin]");
if (ctl) return ctl.dataset.close ? store.closePane(Number(ctl.dataset.close)) : store.togglePanePin(Number(ctl.dataset.pin));
const paneEl = target.closest<HTMLElement>("[data-pane-index]"); const paneEl = target.closest<HTMLElement>("[data-pane-index]");
const paneIndex = paneEl ? Number(paneEl.dataset.paneIndex) : store.paneAt; const paneIndex = paneEl ? Number(paneEl.dataset.paneIndex) : store.paneAt;
// A pane in another fork: that fork becomes the focused branch first, then the click does what it would there. // A pane in another fork: that fork becomes the focused branch first, then the click does what it would there.
@@ -647,7 +650,10 @@ export function App() {
if (hit) return store.go(at.id, "sentence", hit); if (hit) return store.go(at.id, "sentence", hit);
} }
const node = target.closest<HTMLElement>("[data-node]"); const node = target.closest<HTMLElement>("[data-node]");
if (node) store.go(node.dataset.node as NodeId); if (!node) return;
// A pane's head makes that pane the active one.
if (panes && paneEl && node.matches(".pane-head, .top")) store.paneAt = paneIndex;
store.go(node.dataset.node as NodeId);
}; };
const onOver = (e: MouseEvent) => { const onOver = (e: MouseEvent) => {
+8 -4
View File
@@ -9,7 +9,7 @@ import { ownerSection, resolveNode } from "../core/links";
import { docOf, isLink, label, type NodeId } from "../core/model"; import { docOf, isLink, label, type NodeId } from "../core/model";
import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref"; import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref";
import { clip, plain } from "../core/text"; import { clip, plain } from "../core/text";
import { sameAux, store, type Aux } from "./store"; import { kidClass, sameAux, store, type Aux } from "./store";
import type { Sugg } from "./linker"; import type { Sugg } from "./linker";
import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion } from "./wiki"; import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion } from "./wiki";
@@ -144,14 +144,18 @@ export function TargetRow({ id }: { id: NodeId }) {
export const PaneCtx = createContext<number | undefined>(undefined); export const PaneCtx = createContext<number | undefined>(undefined);
/** /**
* In a pane with forks, what marks the words, rows and links its forks were opened from: each open * In a pane with children, what marks the words, rows and links they were opened from: with forks,
* child is "forked", the focused one "forked picked". By the keys a pane's child goes by (refKey). * each open child is "forked", the focused one "forked picked"; always, a class named after the
* child (kidClass), which the curves start from. By the keys a pane's child goes by (refKey).
*/ */
export function useForkMark(): ((...keys: (string | undefined)[]) => string) | null { export function useForkMark(): ((...keys: (string | undefined)[]) => string) | null {
const marks = store.forkMarks(useContext(PaneCtx)); const marks = store.forkMarks(useContext(PaneCtx));
if (!marks) return null; if (!marks) return null;
return (...keys) => { return (...keys) => {
for (const k of keys) if (k && marks.has(k)) return marks.get(k) ? "forked picked" : "forked"; for (const k of keys) {
const m = k && marks.get(k);
if (m) return `${m.many ? (m.picked ? "forked picked " : "forked ") : ""}${kidClass(k!)}`;
}
return ""; return "";
}; };
} }
+481 -141
View File
@@ -3,23 +3,26 @@
* path down from the top node; a link followed from a pane opens its target in the next pane * 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 * (another document's node, 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 * right. Moving back left closes nothing: the panes stay until something else is opened from an
* earlier pane, or q closes them. Earlier panes stay pinned at the left as narrow spines when later * earlier pane, or q or a pane's × closes them. Earlier columns stay at the left as narrow spines
* ones slide over them. * when later ones slide over them.
* *
* A modified open (Shift+Enter, Shift- or Ctrl-click) makes a fork instead: the new pane opens * A modified open (Shift+Enter, Shift- or Ctrl-click) makes a fork instead: the new pane opens
* beside what was to the right, and the space right of the pane divides into rows, one per fork, * below what was in the next column. The panes are a forest (forks.ts) and the screen is laid out
* each continuing its own trail (forks.ts). The panes are `store.tree`; its focused branch is * by column: column d holds every open pane at depth d, top to bottom in tree order, and divides
* `store.trail`, and which pane on it holds the focus is `store.paneAt`. Clicks are handled by the * its own height among them; when they do not fit, all but the pane on the focused branch (and any
* page (App.tsx), exactly as in the column view; a click in another fork first makes it the * pinned one) fold into one-line tabs. A faint curve runs from what each pane was opened from to
* focused branch. * its title. The focused branch is `store.trail`, and the pane on it holding the focus, the active
* pane, is `store.paneAt`. Clicks are handled by the page (App.tsx), exactly as in the column
* view; a click in a pane off the branch first brings it onto the branch.
*/ */
import { Component, type ComponentChildren } from "preact"; import { Component, type ComponentChildren } from "preact";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks"; import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import { docOf, label, sections, staleness, type NodeId } from "../core/model"; import { docOf, label, sections, staleness, type NodeId } from "../core/model";
import { leaves } from "./forks"; import type { Placed } from "./forks";
import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes";
import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links"; import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links";
import { Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter } from "./Node"; import { Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter } from "./Node";
import { refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store"; import { kidClass, refKey, store, type Aux, type Back, type Pane as PaneNode, type PaneRef } from "./store";
import { WikiView } from "./Wiki"; import { WikiView } from "./Wiki";
import { article } from "./wiki"; import { article } from "./wiki";
@@ -28,20 +31,24 @@ interface PaneProps {
p: PaneRef; p: PaneRef;
/** The pane it was opened from, the one to its left. */ /** The pane it was opened from, the one to its left. */
parent?: PaneRef; parent?: PaneRef;
/** Its depth in its tree: its place on the focused branch, when its tree is focused. */
index: number; index: number;
/** Its children, and which is picked, as a key (redraw when they change). */ /** Its children, and which is picked, as a key (redraw when they change). */
kids: string; kids: string;
/** Off the focused branch: drawn, but the keys are elsewhere; a click brings its fork onto the branch (App.tsx). Only an article pane draws differently (how its article is named). */ /** Off the focused branch: drawn, but the keys are elsewhere; a click brings it onto the branch (App.tsx). Only an article pane draws differently (how its article is named). */
off: boolean; off: boolean;
/** In the narrow layout, where only the focused branch is drawn: which fork of how many this pane starts, if it starts one. */
forkOf?: [number, number];
/** The aux focus, when this pane holds it. */ /** The aux focus, when this pane holds it. */
aux: Aux | null; aux: Aux | null;
/** The pane the keys act on. */
active: boolean; active: boolean;
/** The first tree's root: the top node's pane. */
root: boolean;
/** An orphan's root: a pinned pane whose source has closed. */
orphan: boolean;
} }
// `off` is left out: a node pane draws the same on the branch or off it, and moving between forks should redraw only what changed. // `off` is left out: a node pane draws the same on the branch or off it, and moving between forks should redraw only what changed.
const key = (p: PaneProps) => `${refKey(p.p)}|${p.index}|${p.kids}|${p.active}|${p.forkOf ?? ""}|${JSON.stringify(p.aux)}`; const key = (p: PaneProps) => `${refKey(p.p)}|${p.index}|${p.kids}|${p.active}|${!!p.t.pinned}|${p.root}|${p.orphan}|${JSON.stringify(p.aux)}`;
/** Redraws a pane only when something drawn in it changed (see `store.paneDirty`). An article pane is cheap to redraw: its HTML is set once. */ /** Redraws a pane only when something drawn in it changed (see `store.paneDirty`). An article pane is cheap to redraw: its HTML is set once. */
class Pane extends Component<PaneProps> { class Pane extends Component<PaneProps> {
@@ -56,50 +63,84 @@ class Pane extends Component<PaneProps> {
} }
} }
/** The attributes every pane has: which it is, its column, and its place in the tree. */ /** The attributes every pane has: which it is, its place in its tree, and its id there. */
const paneAttrs = (props: PaneProps, name: string) => ({ const paneAttrs = (props: PaneProps, name: string) => ({
"data-pane": name, "data-pane": name,
"data-pane-index": props.index, "data-pane-index": props.index,
"data-tid": props.t.id, "data-tid": props.t.id,
style: { left: `calc(${props.index} * var(--spine))` },
}); });
const paneClass = (props: PaneProps) => `${props.active ? " active" : ""}${props.t.pinned ? " pinned" : ""}${props.orphan ? " orphaned" : ""}`;
/** In the narrow layout, a pane that starts a fork says so, and how to get to the others. */ /**
function ForkNote({ of }: { of?: [number, number] }) { * What every pane carries besides its text: its spine (its title set vertically, shown when later
if (!of) return null; * columns cover it), its tab (one line, shown when its column folds it), and, top right, its pin
* and its ×. Clicks on them are handled by the page (App.tsx).
*/
function Chrome({ props, title, mark }: { props: PaneProps; title: string; mark?: ComponentChildren }) {
const tid = props.t.id;
const pinned = !!props.t.pinned;
return ( return (
<div class="fork-note"> <>
fork {of[0] + 1} of {of[1]} · <kbd>[</kbd> <kbd>]</kbd> for the others <div class="spine" data-spine={props.index} title={title}>
<span role="button" class="pane-btn close" data-close={tid} title="Close this pane and what was opened from it (q)" aria-label="Close">
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M3 3l6 6M9 3l-6 6" />
</svg>
</span>
<span class="spine-title">
{mark}
{mark && " "}
{title}
</span>
</div> </div>
<div class="tabline" data-spine={props.index} title={title}>
{mark}
<span class="tabtitle">{title}</span>
</div>
<div class="pane-ctl">
<span role="button" class={`pane-btn pin${pinned ? " on" : ""}`} data-pin={tid} title={pinned ? "Unpin this pane (P)" : "Pin this pane: it stays when what opened it closes, and never folds away (P)"} aria-label={pinned ? "Unpin" : "Pin"}>
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M4 1.5h4M4.6 1.5v3.6L2.8 7.2h6.4L7.4 5.1V1.5M6 7.2V11" />
</svg>
</span>
<span role="button" class="pane-btn close" data-close={tid} title="Close this pane and what was opened from it (q)" aria-label="Close">
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M3 3l6 6M9 3l-6 6" />
</svg>
</span>
</div>
</>
); );
} }
/** An orphan says, quietly, that what it was opened from has closed. */
const Orphaned = ({ on }: { on: boolean }) => (on ? <div class="pane-from orphan-note">opened from a pane since closed</div> : null);
function NodePane(props: PaneProps & { id: NodeId }) { function NodePane(props: PaneProps & { id: NodeId }) {
const { id, index, active, t, parent } = props; const { id, active, t, parent } = props;
const snap = store.snap; const snap = store.snap;
const n = snap.nodes[id]; const n = snap.nodes[id];
if (!n) return null; if (!n) return null;
const top = id === store.top && index === 0; const top = props.root && id === store.top;
// A document's pane is a page of its own, headed like one. // A document's pane is a page of its own, headed like one.
const page = top || docOf(snap, id) === id; const page = top || docOf(snap, id) === id;
const kids = sections(snap, id); const kids = sections(snap, id);
const focused = active && !store.aux && store.focus.node === id; const focused = active && !store.aux && store.focus.node === id;
const editing = store.edit?.node === id && store.edit.field === "title"; const editing = store.edit?.node === id && store.edit.field === "title";
const jump = index > 0 && !store.continuesFrom(props.p, parent); const jump = !props.root && !props.orphan && !store.continuesFrom(props.p, parent);
// Its children open to the right: the picked one's row is marked as showing; other forks' rows as forked. // Its children open to the right: the picked one's row is marked as showing; other forks' rows as forked.
const kid = t.kids[t.pick]; const kid = t.kids[t.pick];
const showing = kid?.ref.kind === "node" && store.continuesFrom(kid.ref, props.p) ? kid.ref.id : undefined; const showing = kid?.ref.kind === "node" && store.continuesFrom(kid.ref, props.p) ? kid.ref.id : undefined;
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] : []))); 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 ( return (
<article <article
class={`pane${top ? " root" : ""}${page && !top ? " doc" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}`} class={`pane${top ? " root" : ""}${page && !top ? " doc" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`}
{...paneAttrs(props, id)} {...paneAttrs(props, id)}
> >
<div class="spine" data-spine={index} title={label(snap, id)}> <Chrome props={props} title={label(snap, id)} />
<span>{label(snap, id)}</span>
</div>
<div class="pane-scroll"> <div class="pane-scroll">
<ForkNote of={props.forkOf} /> <div class="pane-body">
<Orphaned on={props.orphan} />
{page ? ( {page ? (
<TopMatter id={id} /> <TopMatter id={id} />
) : ( ) : (
@@ -124,6 +165,7 @@ function NodePane(props: PaneProps & { id: NodeId }) {
<NodeBacklinks id={id} /> <NodeBacklinks id={id} />
<NodeRelated id={id} /> <NodeRelated id={id} />
</div> </div>
</div>
</article> </article>
); );
} }
@@ -135,17 +177,15 @@ function WikiPane(props: PaneProps) {
const sec = p.sec && a.state === "ready" ? a.value.sections.find((x) => x.id === p.sec) : undefined; const sec = p.sec && a.state === "ready" ? a.value.sections.find((x) => x.id === p.sec) : undefined;
const title = sec ? `${sec.heading} · ${p.title}` : a.state === "ready" ? a.value.title : p.title; const title = sec ? `${sec.heading} · ${p.title}` : a.state === "ready" ? a.value.title : p.title;
return ( return (
<article class={`pane wiki-pane${p.from ? " jumped" : ""}`} {...paneAttrs(props, `w:${p.title}${p.sec ? `#${p.sec}` : ""}`)}> <article class={`pane wiki-pane${p.from ? " jumped" : ""}${paneClass(props)}`} {...paneAttrs(props, `w:${p.title}${p.sec ? `#${p.sec}` : ""}`)}>
<div class="spine" data-spine={index} title={`Wikipedia: ${title}`}> <Chrome props={props} title={title} mark={<b class="wmark">W</b>} />
<span>
<b class="wmark">W</b> {title}
</span>
</div>
<div class="pane-scroll"> <div class="pane-scroll">
<ForkNote of={props.forkOf} /> <div class="pane-body">
<Orphaned on={props.orphan} />
{/* On the focused branch an article pane is named by its column; off it, by its place in the tree. */} {/* On the focused branch an article pane is named by its column; off it, by its place in the tree. */}
<WikiView host={props.off ? `f${props.t.id}` : `p${index}`} /> <WikiView host={props.off ? `f${props.t.id}` : `p${index}`} />
</div> </div>
</div>
</article> </article>
); );
} }
@@ -160,7 +200,10 @@ function PaneRow({ id, showing, forked, active }: { id: NodeId; showing: boolean
// While its pane is showing, the title is edited at the head of that pane instead. // While its pane is showing, the title is edited at the head of that pane instead.
const editing = !showing && store.edit?.node === id && store.edit.field === "title"; const editing = !showing && store.edit?.node === id && store.edit.field === "title";
return ( return (
<li class={`node d${Math.min(n.depth - (snap.library ? 1 : 0), 6)}${open ? " open" : ""}${focused ? " focused" : ""}${showing ? " showing" : ""}${forked ? " forked" : ""}${st.up || st.down ? " stale" : ""}`} data-node={id}> <li
class={`node d${Math.min(n.depth - (snap.library ? 1 : 0), 6)}${open ? " open" : ""}${focused ? " focused" : ""}${showing ? " showing" : ""}${forked ? " forked" : ""}${showing || forked ? ` ${kidClass(`n:${id}`)}` : ""}${st.up || st.down ? " stale" : ""}`}
data-node={id}
>
<Row id={id} open={open} leaf={leaf} editing={editing} /> <Row id={id} open={open} leaf={leaf} editing={editing} />
</li> </li>
); );
@@ -179,70 +222,186 @@ function nearestY(el: Element | null | false) {
else if (r.bottom > c.bottom - pad) box.scrollTop += Math.min(r.bottom - c.bottom + pad, r.top - c.top - pad); else if (r.bottom > c.bottom - pad) box.scrollTop += Math.min(r.bottom - c.bottom + pad, r.top - c.top - pad);
} }
const setAttr = (el: HTMLElement | undefined, name: string, on: boolean) => { const setAttr = (el: Element | undefined, name: string, on: boolean) => {
if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name); if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name);
}; };
/** The least height a fork's row gets, on any window; below it the rows scroll. */ /** The least height a pane keeps in a column while all its panes fit; below it, the column folds all but one into tabs. */
const ROW_FLOOR = 220; export const PANE_MIN = 260;
/** Rows share the strip's height equally down to a third of it each (never below ROW_FLOOR); past that the stack of rows scrolls. */ /** A folded pane's tab. */
const rowMin = (h: number) => Math.max(ROW_FLOOR, Math.floor(h / 3)); export const TAB = 30;
/** Whether forks can be drawn as rows: room for two rows, and for a fork's pane beside the pane it came from. */
const roomy = (w: number, h: number, pane: number) => h >= 2 * ROW_FLOOR && w >= 2 * pane;
const kidsKey = (t: PaneNode) => `${t.pick}:${t.kids.map((k) => refKey(k.ref)).join(",")}`; /**
* Heights for the panes of one column of height h, from what each needs to show all it holds:
* each gets that, or an equal share of what is left, whichever is less; what no pane needs goes to
* the one that needs most. So short panes are no taller than their text, and long ones share the rest.
*/
export function fill(h: number, needs: number[]): number[] {
const out = needs.map(() => 0);
const order = needs.map((_, i) => i).sort((a, b) => needs[a] - needs[b]);
let rest = h;
order.forEach((i, k) => {
const share = rest / (order.length - k);
out[i] = Math.floor(k === order.length - 1 ? rest : Math.min(needs[i], share));
rest -= out[i];
});
return out;
}
/** The panes drawn, by their id in the tree. */ /** The panes drawn, by their id in the forest. */
const paneEls = (el: HTMLElement) => { const paneEls = (el: HTMLElement) => {
const m = new Map<number, HTMLElement>(); const m = new Map<number, HTMLElement>();
for (const e of el.querySelectorAll<HTMLElement>(".pane[data-tid]")) m.set(Number(e.dataset.tid), e); for (const e of el.querySelectorAll<HTMLElement>(".pane[data-tid]")) m.set(Number(e.dataset.tid), e);
return m; return m;
}; };
const kidsKey = (t: PaneNode) => `${t.pick}:${t.kids.map((k) => refKey(k.ref)).join(",")}`;
type Spot = Placed<PaneRef, Back>;
export function Panes() { export function Panes() {
store.syncTrail(); store.syncTrail();
const tree = store.tree;
const strip = useRef<HTMLDivElement>(null); const strip = useRef<HTMLDivElement>(null);
const svg = useRef<SVGSVGElement>(null);
const followed = useRef(""); const followed = useRef("");
const [room, setRoom] = useState(true); /** Per column, the pane last on the focused branch there: the one a folded column keeps open when the branch is elsewhere. */
// Forks are drawn as rows when there is room; otherwise only the focused branch is. const lastIn = useRef(new Map<number, number>());
const rows = room && store.hasForks(); /** What each pane last needed to show all it holds (a folded pane cannot be measured). */
const needs = useRef(new Map<number, number>());
/** Each column's sticky left edge, in px, as last set. */
const lefts = useRef<number[]>([]);
const frame = useRef(0);
/** A pending layout of the columns other than the active pane's. */
const later = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
/** Each column's panes when last laid out. */
const laid = useRef(new Map<HTMLElement, string>());
/** The layout of the latest render (a pending one uses it). */
const latest = useRef<(all?: boolean) => void>(() => {});
/** The active pane's column when the strip last followed it. */
const lastCol = useRef(-1);
const placed = store.panesPlaced;
const branch = store.branchNodes;
const onBranch = new Set(branch.map((n) => n.id));
const activeId = branch[store.paneAt]?.id;
const cols = new Map<number, Spot[]>();
for (const x of placed) {
const c = cols.get(x.col);
if (c) c.push(x);
else cols.set(x.col, [x]);
}
const order = [...cols.keys()].sort((a, b) => a - b);
/** /**
* Mark how far each pane is covered by the next. Any overlap gives the upper pane a shadow edge * Lay out the columns: each column's sticky left edge (every column before it leaves a spine, or
* (data-over); once too little of the pane is left to read its own heading, it shows as a spine * the whole of a pinned pane's column), and the heights of the panes in each column with several.
* with its title (data-covered). A pane's forks all start at the same column. */
const layout = (all = false) => {
const el = strip.current;
if (!el) return;
const colEls = [...el.children].filter((c): c is HTMLElement => c.classList.contains("col"));
if (!colEls.length) return;
clearTimeout(later.current);
const activeCol = activeId === undefined ? null : paneEls(el).get(activeId)?.parentElement;
const w = colEls[0].offsetWidth;
const spine = colEls[0].querySelector<HTMLElement>(".spine")?.offsetWidth ?? 0;
const view = el.clientWidth;
const n = colEls.length;
// With no scrollbar under the panes (none needed, or one drawn over them) their last bottom edge meets the status line's: one line, not two.
setAttr(el, "data-flush", el.offsetHeight - el.clientHeight < 1);
let left = 0;
lefts.current = colEls.map((c, i) => {
// Far enough left that the columns after it can still all be scrolled to.
const l = Math.round(Math.min(left, Math.max(i * spine, view - w - (n - 1 - i) * spine)));
if (c.style.left !== `${l}px`) c.style.left = `${l}px`;
left += c.hasAttribute("data-pinned") ? w : spine;
return l;
});
for (const c of colEls) {
const ps = [...c.children] as HTMLElement[];
if (ps.length < 2) {
for (const p of ps) {
setAttr(p, "data-tab", false);
if (p.style.height) (p.style.height = ""), (p.style.flex = "");
}
continue;
}
const h = c.clientHeight;
const col = Number(c.dataset.col);
const pad = (() => {
const s = ps.find((p) => !p.hasAttribute("data-tab"))?.querySelector<HTMLElement>(".pane-scroll");
if (!s) return 60;
const cs = getComputedStyle(s);
return parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + 1;
})();
const tids = ps.map((p) => Number(p.dataset.tid));
const need = ps.map((p, i) => {
const body = p.hasAttribute("data-tab") ? null : p.querySelector<HTMLElement>(".pane-body");
if (body) needs.current.set(tids[i], body.offsetHeight + pad);
return needs.current.get(tids[i]) ?? PANE_MIN;
});
const pinned = ps.map((p) => p.classList.contains("pinned"));
const fits = need.reduce((s, x) => s + Math.min(x, PANE_MIN), 0) <= h;
let heights: number[];
let tab: boolean[];
if (fits) {
tab = ps.map(() => false);
heights = fill(h, need);
} else {
// Too many to share the height: the pane on the focused branch (or the one last on it here) keeps it, pinned panes keep their least, the rest fold.
const here = tids.find((t) => onBranch.has(t));
const keep = here ?? (tids.includes(lastIn.current.get(col)!) ? lastIn.current.get(col)! : tids[0]);
tab = tids.map((t, i) => t !== keep && !pinned[i]);
const folded = tab.filter(Boolean).length;
const kept = tids.map((t, i) => (!tab[i] && t !== keep ? Math.min(need[i], PANE_MIN) : 0));
const rest = h - folded * TAB - kept.reduce((s, x) => s + x, 0);
heights = tids.map((t, i) => (tab[i] ? TAB : t === keep ? Math.max(PANE_MIN, rest) : kept[i]));
}
// Folding and unfolding repaints whole panes: as the focus moves, in the active pane's column at once, in the others once the keys pause.
const sig = tids.map((t, i) => `${t}${pinned[i] ? "^" : ""}`).join();
const same = laid.current.get(c) === sig;
laid.current.set(c, sig);
if (!all && same && c !== activeCol && ps.some((p, i) => p.hasAttribute("data-tab") !== tab[i])) {
later.current = setTimeout(() => {
latest.current(true);
schedule();
}, 150);
continue;
}
ps.forEach((p, i) => {
setAttr(p, "data-tab", tab[i]);
if (p.style.height !== `${heights[i]}px`) (p.style.height = `${heights[i]}px`), (p.style.flex = "none");
});
}
// The focused branch's panes, marked without redrawing them.
for (const [id, p] of paneEls(el)) p.classList.toggle("on-branch", onBranch.has(id));
for (const x of placed) if (onBranch.has(x.node.id)) lastIn.current.set(x.col, x.node.id);
};
/**
* Mark how far each column is covered by the next. Any overlap gives the column above a shadow
* edge (data-over); once too little of it is left to read its own heading, its panes show as
* spines with their titles (data-covered).
*/ */
const measure = () => { const measure = () => {
const el = strip.current; const el = strip.current;
const t = store.tree; if (!el) return;
if (!el || !t) return; const colEls = el.querySelectorAll<HTMLElement>(":scope > .col");
const els = paneEls(el); if (!colEls.length) return;
const first = els.get(t.id); const w = colEls[0].offsetWidth;
if (!first) return; const xs = [...colEls].map((c) => c.getBoundingClientRect().left);
const w = first.offsetWidth; colEls.forEach((c, i) => {
const marks: [HTMLElement, number, HTMLElement[]][] = []; const visible = i + 1 < xs.length ? xs[i + 1] - xs[i] : w;
const visit = (n: PaneNode) => { setAttr(c, "data-covered", visible < w * 0.4);
const e = els.get(n.id); setAttr(colEls[i + 1], "data-over", visible < w - 1);
if (!e) return; });
const kids = n.kids.flatMap((k) => els.get(k.id) ?? []);
const next = els.get(n.kids[n.pick]?.id) ?? kids[0];
marks.push([e, next ? next.getBoundingClientRect().left - e.getBoundingClientRect().left : w, kids]);
n.kids.forEach(visit);
};
visit(t);
for (const [e, visible, kids] of marks) {
setAttr(e, "data-covered", visible < w * 0.4);
for (const k of kids) setAttr(k, "data-over", visible < w - 1);
}
}; };
/** /**
* Keep the focus in view. Vertically, the pane holding the focus scrolls to its focused row, * Keep the focus in view. Vertically, the pane holding the focus scrolls to its focused row,
* selection or link. Horizontally, the strip scrolls as little as it can so that pane is fully * selection or link. Horizontally, the strip scrolls as little as it can so that pane's column is
* visible and, when there is room, so is the pane beside it: for a row whose pane is showing, * fully visible and, when there is room, so is the column beside it: for a row whose pane is
* that pane; otherwise the pane before. With forks, the strip also scrolls down or up as little * showing, that pane's; otherwise the one before.
* as it can to show the focused branch's row.
*/ */
const follow = () => { const follow = () => {
const el = strip.current; const el = strip.current;
@@ -250,7 +409,7 @@ export function Panes() {
const f = store.focus; const f = store.focus;
const at = store.paneAt; const at = store.paneAt;
const nodes = store.branchNodes; const nodes = store.branchNodes;
const key = `${f.node}|${f.grain}|${f.range?.join()}|${JSON.stringify(store.aux)}|${at}|${nodes.map((n) => n.id).join(",")}|${el.clientWidth}|${el.clientHeight}|${store.mode === "edit"}`; const key = `${f.node}|${f.grain}|${f.range?.join()}|${JSON.stringify(store.aux)}|${at}|${nodes.map((n) => n.id).join(",")}|${el.clientWidth}|${el.clientHeight}|${store.mode === "edit"}|${lefts.current.join(",")}`;
if (key === followed.current) return; if (key === followed.current) return;
followed.current = key; followed.current = key;
const els = paneEls(el); const els = paneEls(el);
@@ -263,99 +422,280 @@ export function Panes() {
const pane = panes[at]; const pane = panes[at];
nearestY(pane?.querySelector(".sel, .wfocus, .node.focused > .row, .wrow.focused > .row, .backlinks li.focused, .target-row.focused, .wiki-head.focused, .pane-head.focused, .focused")); nearestY(pane?.querySelector(".sel, .wfocus, .node.focused > .row, .wrow.focused > .row, .backlinks li.focused, .target-row.focused, .wiki-head.focused, .pane-head.focused, .focused"));
} }
const w = panes[0].offsetWidth; const colEls = [...el.querySelectorAll<HTMLElement>(":scope > .col")];
const spine = (panes[0].querySelector(".spine") as HTMLElement | null)?.offsetWidth ?? 0; const colOf = (p: HTMLElement | undefined) => (p ? colEls.indexOf(p.parentElement as HTMLElement) : -1);
const w = colEls[0].offsetWidth;
const view = el.clientWidth; const view = el.clientWidth;
const b = Math.min(panes.length - 1, showing ? at + 1 : at); const L = lefts.current;
const b = colOf(panes[Math.min(panes.length - 1, showing ? at + 1 : at)]);
if (b < 0) return;
// Up and down a column (or within a pane) the strip stays still while the pane looked at is fully in view.
const here = colOf(panes[at]);
const was = lastCol.current;
lastCol.current = here;
if (here === was && el.scrollLeft >= (b + 1) * colEls[0].offsetWidth - el.clientWidth - 1 && el.scrollLeft <= b * colEls[0].offsetWidth - (lefts.current[b] ?? 0) + 1) return;
let a = b > 0 && (showing || f.grain === "node") ? b - 1 : b; let a = b > 0 && (showing || f.grain === "node") ? b - 1 : b;
// Pane i starts at i·w. It is uncovered while scrollLeft ≤ i·(w − spine), and its right edge is in view while scrollLeft ≥ (i+1)·w − view. // Column i starts at i·w. It is uncovered while scrollLeft ≤ i·w − its sticky left, and its right edge is in view while scrollLeft ≥ (i+1)·w − view.
const lo = (b + 1) * w - view; const lo = (b + 1) * w - view;
if (lo > a * (w - spine)) a = b; if (lo > a * w - (L[a] ?? 0)) a = b;
const hi = a * (w - spine); const hi = a * w - (L[a] ?? 0);
const target = Math.max(0, Math.min(el.scrollWidth - view, Math.min(Math.max(el.scrollLeft, lo), hi))); const target = Math.max(0, Math.min(el.scrollWidth - view, Math.min(Math.max(el.scrollLeft, lo), hi)));
// The row the branch ends in holds every pane of the branch (a pane with forks stays at the top while its rows scroll).
let top = el.scrollTop;
const row = panes[panes.length - 1].closest<HTMLElement>(".fork");
if (row) {
const r = row.getBoundingClientRect();
const c = el.getBoundingClientRect().top;
if (r.top < c) top += r.top - c;
else if (r.bottom > c + el.clientHeight) top += Math.min(r.bottom - c - el.clientHeight, r.top - c);
}
// Down or up to another row at once: a smooth scroll that way repaints every row's panes on each frame, which costs frames on a slow machine.
if (Math.abs(top - el.scrollTop) > 1) el.scrollTop = top;
if (Math.abs(target - el.scrollLeft) > 1) el.scrollTo({ left: target, behavior: reducedMotion() ? "auto" : "smooth" }); if (Math.abs(target - el.scrollLeft) > 1) el.scrollTo({ left: target, behavior: reducedMotion() ? "auto" : "smooth" });
}; };
/** The rows' sizes follow the strip's height; whether there is room for rows at all, its size and a pane's width. */ /** Draw the curves on the next frame (after the layout this frame settles). */
const size = () => { const schedule = () => {
const el = strip.current; if (!frame.current)
if (!el) return; frame.current = requestAnimationFrame(() => {
el.style.setProperty("--strip-h", `${el.clientHeight}px`); frame.current = 0;
el.style.setProperty("--row-min", `${rowMin(el.clientHeight)}px`); curves(strip.current, svg.current);
const pane = el.querySelector<HTMLElement>(".pane")?.offsetWidth ?? 0; });
setRoom(roomy(el.clientWidth, el.clientHeight, pane));
}; };
latest.current = layout;
useLayoutEffect(() => { useLayoutEffect(() => {
layout();
follow(); follow();
measure(); measure();
schedule();
}); });
useLayoutEffect(size, []);
useEffect(() => { useEffect(() => {
const el = strip.current!; const el = strip.current!;
let frame = 0; const wrap = el.parentElement!;
const onScroll = () => { const onScroll = (e: Event) => {
if (!frame) frame = requestAnimationFrame(() => ((frame = 0), measure())); if (e.target === el) measure();
schedule();
}; };
const onResize = () => { const onResize = () => {
size(); latest.current(true);
followed.current = ""; followed.current = "";
follow(); follow();
measure(); measure();
schedule();
}; };
el.addEventListener("scroll", onScroll, { passive: true }); // Panes scroll on their own: their scroll events are caught on the way down.
// The strip changes width with the window and when the history panel opens or closes. wrap.addEventListener("scroll", onScroll, { passive: true, capture: true });
// The strip changes size with the window and when the history panel opens or closes.
const sizes = new ResizeObserver(onResize); const sizes = new ResizeObserver(onResize);
sizes.observe(el); sizes.observe(el);
document.fonts?.ready.then(onResize);
return () => { return () => {
cancelAnimationFrame(frame); cancelAnimationFrame(frame.current);
el.removeEventListener("scroll", onScroll); clearTimeout(later.current);
wrap.removeEventListener("scroll", onScroll, { capture: true });
sizes.disconnect(); sizes.disconnect();
}; };
}, []); }, []);
const onBranch = new Set(store.branchNodes.map((n) => n.id));
/**
* A pane and what is right of it. A plain trail is a flat run of panes, as before; to the right of
* a pane with forks, a stack of rows, one per fork in the order they were opened, each holding
* that fork's panes (and perhaps a stack of its own). Without room for rows, only the picked fork.
*/
const draw = (t: PaneNode, depth: number, parent?: PaneRef, forkOf?: [number, number]): ComponentChildren[] => {
const off = !onBranch.has(t.id);
const active = !off && store.paneAt === depth;
const out: ComponentChildren[] = [
<Pane key={t.id} t={t} p={t.ref} parent={parent} index={depth} kids={kidsKey(t)} off={off} forkOf={forkOf} active={active} aux={active ? store.aux : null} />,
];
if (!t.kids.length) return out;
if (t.kids.length === 1 || !rows) return [...out, ...draw(t.kids[t.pick], depth + 1, t.ref, t.kids.length > 1 ? [t.pick, t.kids.length] : undefined)];
out.push(
<div key={`f${t.id}`} class="forks" style={`--leaves:${leaves(t)}`}>
{t.kids.map((k) => (
<div key={k.id} class={`fork${onBranch.has(k.id) ? " on" : ""}`} style={`--leaves:${leaves(k)}`}>
{draw(k, depth + 1, t.ref)}
</div>
))}
</div>,
);
return out;
};
return ( return (
<div class={`strip${rows ? " forked" : ""}`} ref={strip}> <div class="panes">
{tree && draw(tree, 0)} <div class="strip" ref={strip}>
{order.map((c) => {
const items = cols.get(c)!;
return (
<div key={c} class={`col${items.length > 1 ? " split" : ""}`} data-col={c} data-pinned={items.some((x) => x.node.pinned) || undefined}>
{items.map((x) => {
const off = !onBranch.has(x.node.id);
const active = x.node.id === activeId;
return (
<Pane
key={x.node.id}
t={x.node}
p={x.node.ref}
parent={x.parent?.ref}
index={x.depth}
kids={kidsKey(x.node)}
off={off}
active={active}
aux={active ? store.aux : null}
root={x.ti === 0 && x.depth === 0}
orphan={x.ti > 0 && x.depth === 0}
/>
);
})}
</div>
);
})}
</div>
<svg class="curves" ref={svg} aria-hidden="true" />
</div> </div>
); );
} }
/** One curve, measured: where it leaves its source (y, and x where the lead-out starts), the edge of the source's text, where it arrives, and the gutter it runs down. */
interface Edge {
from: number;
to: number;
/** The child's column: the gutter, just inside its left edge. */
gutter: number;
left: number;
sx: number;
sy: number;
/** For words: the right end of their underline, which a short step joins to the lead-out. */
under?: { x: number; y: number };
textRight: number;
ex: number;
ey: number;
on: boolean;
lost: boolean;
}
/** A font's descent, by its CSS font string: where its baseline sits above the bottom of an inline box. */
const descents = new Map<string, number>();
let measurer: CanvasRenderingContext2D | null | undefined;
/** Where the underline of linked or annotated words runs, given their last line's box: a link's under the baseline by its offset; a note's dotted rule at the box's foot. */
function underline(s: HTMLElement, r: DOMRect): number {
const cs = getComputedStyle(s);
const fs = parseFloat(cs.fontSize) || 16;
if (s.matches(".anchor")) return r.bottom - 0.08 * fs - 0.5;
let d = descents.get(cs.font);
if (d === undefined) {
measurer ??= document.createElement("canvas").getContext("2d");
if (measurer) measurer.font = cs.font;
d = measurer?.measureText("x").fontBoundingBoxDescent ?? 0.25 * fs;
descents.set(cs.font, d);
}
const off = parseFloat(cs.textUnderlineOffset);
return r.bottom - d + (Number.isFinite(off) ? off : 0.1 * fs) + 0.5;
}
/** Where a curve arrives, from its column's left edge: just short of the title. */
const ARRIVE = 36;
/** The lane order last used in each gutter, by the curves' keys. */
const lanesUsed = new Map<number, string[]>();
/**
* The curves: one per pane opened from another, from what it was opened from to its title. A
* curve leaves its source sideways, through the gap under the line (an extended
* underline, for words) to the edge of the text, turns into a lane of the gutter just inside the
* next column, and turns again into the child's title. Curves through one gutter run side by side
* in lanes, like a ribbon cable, ordered so they cross as little as they can; past the lanes there
* is room for, the rest share the outermost. On the focused branch a curve is drawn in a stronger
* ink, last. A source scrolled out of its pane, folded into a tab or under the next column is held
* at the pane's edge and the curve dotted; a curve into or out of a column covered down to its
* spines is not drawn.
*/
function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
if (!el || !svg) return;
if (!store.settings.curves) {
if (svg.firstChild) svg.replaceChildren();
return;
}
const box = svg.getBoundingClientRect();
const els = paneEls(el);
const colEls = [...el.children] as HTMLElement[];
const branch = new Set(store.branchNodes.map((n) => n.id));
const edges: Edge[] = [];
for (const x of store.panesPlaced) {
const parent = x.parent;
if (!parent) continue;
const pe = els.get(parent.id);
const ce = els.get(x.node.id);
const pcol = pe?.parentElement;
const ccol = ce?.parentElement;
if (!pe || !ce || !pcol || !ccol || pcol.hasAttribute("data-covered") || ccol.hasAttribute("data-covered")) continue;
const left = ccol.getBoundingClientRect().left;
// Where it arrives: just before the child's title, or its tab's.
const cbox = ce.getBoundingClientRect();
let ey: number;
if (ce.hasAttribute("data-tab")) ey = cbox.top + TAB / 2;
else {
const scroll = ce.querySelector<HTMLElement>(".pane-scroll")!.getBoundingClientRect();
const tr = ce.querySelector<HTMLElement>(".pane-head h2, .top h1, .wiki-head h2")?.getBoundingClientRect();
ey = tr && tr.bottom > scroll.top + 4 ? Math.max(scroll.top + 6, tr.top + Math.min(tr.height, 32) / 2) : scroll.top + 14;
}
// Where it starts: the words, row or link it was opened from. The text's edge: the pane's right padding, or the next column where it covers the pane.
const pbox = pe.getBoundingClientRect();
const textRight = Math.min(pbox.right - 33, left - 2);
let sx = textRight;
let sy: number;
let under: { x: number; y: number } | undefined;
let lost = false;
if (pe.hasAttribute("data-tab")) {
sy = pbox.top + TAB / 2;
lost = true;
} else {
const sc = pe.querySelector<HTMLElement>(".pane-scroll")!.getBoundingClientRect();
const cands = pe.querySelectorAll<HTMLElement>(`.${kidClass(refKey(x.node.ref))}`);
let src: HTMLElement | undefined;
for (const c of cands) {
const r = c.getBoundingClientRect();
if (r.height && r.bottom > sc.top && r.top < sc.bottom) {
src = c;
break;
}
}
src ??= cands[0];
const head = pe.querySelector<HTMLElement>(".pane-head h2, .top h1, .wiki-head h2");
const s = src ?? head;
if (!s) continue;
const row = s.matches("li") ? s.querySelector<HTMLElement>(":scope > .row") : null;
const rects = (row ?? s).getClientRects();
const r = rects[rects.length - 1] ?? (row ?? s).getBoundingClientRect();
if (row || s === head) {
// A row is left from its right end, mid-height.
sy = r.top + r.height / 2;
sx = Math.min(r.right + 4, textRight);
} else {
// Words: from just under their last line, in the gap before the next, joined by a short step to the end of their underline.
sy = r.bottom + 1;
const uy = underline(s, r);
const j = Math.max(2, sy - uy);
under = { x: r.right, y: uy };
sx = r.right + 2 * j;
}
if (sy < sc.top + 2 || sy > sc.bottom - 2 || sx > textRight + 1) {
lost = true;
under = undefined;
sx = textRight;
sy = Math.max(sc.top + 2, Math.min(sc.bottom - 2, sy));
}
}
const gutter = colEls.indexOf(ccol);
edges.push({ from: parent.id, to: x.node.id, gutter, left: left - box.left, sx: sx - box.left, sy: sy - box.top, under: under && { x: under.x - box.left, y: under.y - box.top }, textRight: textRight - box.left, ex: left + ARRIVE - box.left, ey: ey - box.top, on: branch.has(x.node.id) && branch.has(parent.id), lost });
}
// Lanes, gutter by gutter.
const lane = new Map<Edge, number>();
const gutters = new Map<number, Edge[]>();
for (const e of edges) gutters.set(e.gutter, [...(gutters.get(e.gutter) ?? []), e]);
for (const [g, es] of gutters) {
const keyed = es.map((e) => ({ e, key: `${e.from}>${e.to}`, sy: e.sy, ey: e.ey }));
const order = laneOrder(keyed, lanesUsed.get(g));
lanesUsed.set(
g,
order.map((o) => o.key),
);
order.forEach((o, i) => lane.set(o.e, Math.min(i, LANES - 1)));
}
for (const g of [...lanesUsed.keys()]) if (!gutters.has(g)) lanesUsed.delete(g);
const fx = (n: number) => Math.round(n * 2) / 2;
const out: string[] = [];
edges.sort((a, b) => Number(a.on) - Number(b.on));
for (const e of edges) {
const i = lane.get(e)!;
// Lane 0 is nearest the panes, the last nearest the column's edge.
const g = e.left + LANE_LAST - i * LANE_PITCH;
const dy = e.ey - e.sy;
let d: string;
const join = e.under ? `M${fx(e.under.x)} ${fx(e.under.y)}C${fx((e.under.x + e.sx) / 2)} ${fx(e.under.y)} ${fx((e.under.x + e.sx) / 2)} ${fx(e.sy)} ${fx(e.sx)} ${fx(e.sy)}` : `M${fx(e.sx)} ${fx(e.sy)}`;
if (Math.abs(dy) < 1.5) d = `${join}H${fx(e.ex)}`;
else {
// A lead-out to the lane, a quarter turn, the lane, a quarter turn into the title. Each turn's radius grows by a pitch per lane outwards, so a bundle turning together stays parallel; a turn never starts inside the text.
const sg = Math.sign(dy);
const r1 = Math.max(1, Math.min(Math.abs(dy) / 2, g - Math.max(e.sx, e.textRight), 8 + (LANE_LAST - LANE_FIRST) - i * LANE_PITCH));
const r2 = Math.max(1, Math.min(Math.abs(dy) / 2, e.ex - g - 1));
const k = 0.552;
d =
`${join}H${fx(g - r1)}` +
`C${fx(g - r1 + k * r1)} ${fx(e.sy)} ${fx(g)} ${fx(e.sy + sg * r1 * (1 - k))} ${fx(g)} ${fx(e.sy + sg * r1)}` +
`V${fx(e.ey - sg * r2)}` +
`C${fx(g)} ${fx(e.ey - sg * r2 * (1 - k))} ${fx(g + r2 - k * r2)} ${fx(e.ey)} ${fx(g + r2)} ${fx(e.ey)}` +
`H${fx(e.ex)}`;
}
out.push(`<path data-from="${e.from}" data-to="${e.to}" data-lane="${i}" class="${e.on ? "on" : ""}${e.lost ? " lost" : ""}" d="${d}"/>`);
}
const html = out.join("");
if (svg.innerHTML !== html) svg.innerHTML = html;
}
+2 -2
View File
@@ -214,7 +214,7 @@ export function WikiView({ host }: { host: string }) {
const v = art.value; const v = art.value;
const sec = h.sec ? v.sections.find((x) => x.id === h.sec) : undefined; const sec = h.sec ? v.sections.find((x) => x.id === h.sec) : undefined;
// A section open as a pane to the right is marked: the picked child "showing", another fork "forked". // A section open as a pane to the right is marked: the picked child "showing", another fork "forked".
const showing = (id: number) => (store.panes ? store.kidMark(tid, (r) => r.kind === "wiki" && r.title === h.title && r.sec === id) : undefined); const showing = (id: number): string | undefined => (store.panes ? store.kidMark(tid, (r) => r.kind === "wiki" && r.title === h.title && r.sec === id) : undefined);
return ( return (
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}> <section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
<Head title={v.title} sub={sec?.heading} focused={at({ t: "head" })} /> <Head title={v.title} sub={sec?.heading} focused={at({ t: "head" })} />
@@ -229,7 +229,7 @@ export function WikiView({ host }: { host: string }) {
); );
} }
function Rows(props: { article: Article; host: string; lang: string; parent: number; nested: boolean; at: (r: WRow) => boolean; showing: (id: number) => "showing" | "forked" | undefined }) { function Rows(props: { article: Article; host: string; lang: string; parent: number; nested: boolean; at: (r: WRow) => boolean; showing: (id: number) => string | undefined }) {
const { article: v, host, lang, parent, nested, at, showing } = props; const { article: v, host, lang, parent, nested, at, showing } = props;
const kids = sectionsUnder(v, parent); const kids = sectionsUnder(v, parent);
if (!kids.length) return null; if (!kids.length) return null;
+249 -101
View File
@@ -1,13 +1,17 @@
/** /**
* The panes view's panes as a tree. Each pane may have several children ("forks"), each of which * The panes view's panes as a forest. Each pane may have several children ("forks"), each of which
* continues its own trail to the right and may fork again. Every node remembers which child is * continues its own trail to the right and may fork again; a pane's column is its depth. The first
* picked; following the picks from the root gives the focused branch, the trail the keys move along * tree starts at the top node; the others are orphans: pinned panes that stayed open when a pane
* (`store.trail`), so there is always exactly one. A plain trail is the tree with one child * they were opened from closed, each keeping the column it was in.
* everywhere. *
* Every node remembers which child is picked; following the picks from the root of the focused
* tree gives the focused branch, the trail the keys move along (`store.trail`), so there is always
* exactly one. A plain trail is one tree with one child everywhere.
* *
* Pure functions on immutable trees: an operation copies the path it changes and shares the rest, * Pure functions on immutable trees: an operation copies the path it changes and shares the rest,
* so a tree that did not change is the same object (the store memoises on identity). A node's `id` * so a forest that did not change is the same object (the store memoises on identity). A node's
* names the pane for as long as it is open (keys, the hosts of article panes off the branch). * `id` names the pane for as long as it is open (keys, curves, the hosts of article panes off the
* branch).
*/ */
export interface Tree<R, S = unknown> { export interface Tree<R, S = unknown> {
@@ -16,8 +20,18 @@ export interface Tree<R, S = unknown> {
/** Which child the branch goes on to (0 with none): the focused one, or the one last focused. */ /** Which child the branch goes on to (0 with none): the focused one, or the one last focused. */
pick: number; pick: number;
id: number; id: number;
/** Where the reader was when they last left this fork (to come back to). */ /** Where the reader was when they last left this pane by [ or ] (to come back to). */
seen?: S; seen?: S;
/** Pinned: stays open when a pane it was opened from closes, is never replaced by a plain open, and never collapses. */
pinned?: boolean;
/** On the root of an orphan: the column it stays in. */
col?: number;
}
/** The trees, the first starting at the top node; `at` is the one the focused branch is in. */
export interface Forest<R, S = unknown> {
trees: Tree<R, S>[];
at: number;
} }
export type Same<R> = (a: R, b: R) => boolean; export type Same<R> = (a: R, b: R) => boolean;
@@ -32,14 +46,26 @@ export function chain<R, S>(refs: R[]): Tree<R, S> | null {
return t; return t;
} }
/** The nodes of the focused branch, from the root. */ /** A forest of one tree (none for no refs). */
export const plain = <R, S>(refs: R[]): Forest<R, S> => {
const t = chain<R, S>(refs);
return { trees: t ? [t] : [], at: 0 };
};
/** The column a tree's root is in. */
export const colOf = (t: Tree<unknown, unknown>) => t.col ?? 0;
/** The focused tree. */
export const focused = <R, S>(f: Forest<R, S>): Tree<R, S> | null => f.trees[f.at] ?? null;
/** The nodes of a tree's focused branch, from the root. */
export function path<R, S>(t: Tree<R, S> | null): Tree<R, S>[] { export function path<R, S>(t: Tree<R, S> | null): Tree<R, S>[] {
const out: Tree<R, S>[] = []; const out: Tree<R, S>[] = [];
for (let n: Tree<R, S> | undefined = t ?? undefined; n; n = n.kids[n.pick]) out.push(n); for (let n: Tree<R, S> | undefined = t ?? undefined; n; n = n.kids[n.pick]) out.push(n);
return out; return out;
} }
/** Replace the node at depth i of the focused branch with f(node), copying the path above it. */ /** Replace the node at depth i of a tree's focused branch with f(node), copying the path above it. */
function at<R, S>(t: Tree<R, S>, i: number, f: (n: Tree<R, S>) => Tree<R, S>): Tree<R, S> { function at<R, S>(t: Tree<R, S>, i: number, f: (n: Tree<R, S>) => Tree<R, S>): Tree<R, S> {
if (i <= 0) return f(t); if (i <= 0) return f(t);
const kid = t.kids[t.pick]; const kid = t.kids[t.pick];
@@ -49,7 +75,7 @@ function at<R, S>(t: Tree<R, S>, i: number, f: (n: Tree<R, S>) => Tree<R, S>): T
return { ...t, kids }; return { ...t, kids };
} }
/** The path of nodes from the root to the node with this id, or null. */ /** The path of nodes from a tree's root to the node with this id, or null. */
export function trace<R, S>(t: Tree<R, S> | null, id: number): Tree<R, S>[] | null { export function trace<R, S>(t: Tree<R, S> | null, id: number): Tree<R, S>[] | null {
if (!t) return null; if (!t) return null;
if (t.id === id) return [t]; if (t.id === id) return [t];
@@ -60,17 +86,34 @@ export function trace<R, S>(t: Tree<R, S> | null, id: number): Tree<R, S>[] | nu
return null; return null;
} }
/** Every node, depth first, top row first, with its depth (its column). */ /** Where a pane is: its tree, and the path to it from that tree's root. */
export function all<R, S>(t: Tree<R, S> | null, depth = 0, out: { node: Tree<R, S>; depth: number }[] = []) { export function find<R, S>(f: Forest<R, S>, id: number): { ti: number; path: Tree<R, S>[] } | null {
if (!t) return out; for (let ti = 0; ti < f.trees.length; ti++) {
out.push({ node: t, depth }); const p = trace(f.trees[ti], id);
for (const k of t.kids) all(k, depth + 1, out); if (p) return { ti, path: p };
return out; }
return null;
} }
/** How many leaves (rows at the far right) a subtree has. */ export interface Placed<R, S> {
export function leaves<R, S>(t: Tree<R, S>): number { node: Tree<R, S>;
return t.kids.length ? t.kids.reduce((n, k) => n + leaves(k), 0) : 1; /** Its depth in its own tree (its place on that tree's branch, when the tree is focused). */
depth: number;
/** Its column on screen. */
col: number;
ti: number;
parent?: Tree<R, S>;
}
/** Every pane, tree by tree, depth first, earlier forks first: the order panes stand in a column, top to bottom. */
export function all<R, S>(f: Forest<R, S>): Placed<R, S>[] {
const out: Placed<R, S>[] = [];
const go = (node: Tree<R, S>, depth: number, col: number, ti: number, parent?: Tree<R, S>) => {
out.push({ node, depth, col, ti, parent });
for (const k of node.kids) go(k, depth + 1, col + 1, ti, node);
};
f.trees.forEach((t, ti) => go(t, 0, colOf(t), ti));
return out;
} }
/** Change the node with this id, copying the path to it. */ /** Change the node with this id, copying the path to it. */
@@ -85,50 +128,15 @@ export function update<R, S>(t: Tree<R, S>, id: number, f: (n: Tree<R, S>) => Tr
return changed ? { ...t, kids } : t; return changed ? { ...t, kids } : t;
} }
/** /** Change the node with this id, in whichever tree it is. */
* Open something to the right of pane i of the focused branch. If it is already open there (as any export function updateIn<R, S>(f: Forest<R, S>, id: number, fn: (n: Tree<R, S>) => Tree<R, S>): Forest<R, S> {
* of the forks) that fork is picked and kept as it is. Otherwise a fork adds a child below the const hit = find(f, id);
* others; a plain open replaces the picked child (and everything right of it), or adds the first. if (!hit) return f;
*/ const t = update(f.trees[hit.ti], id, fn);
export function open<R, S>(t: Tree<R, S>, i: number, ref: R, fork: boolean, same: Same<R>): Tree<R, S> { return t === f.trees[hit.ti] ? f : { ...f, trees: f.trees.map((x, j) => (j === hit.ti ? t : x)) };
return at(t, i, (n) => {
const k = n.kids.findIndex((c) => same(c.ref, ref));
if (k >= 0) return k === n.pick ? n : { ...n, pick: k };
if (!n.kids.length) return { ...n, kids: [leaf(ref)], pick: 0 };
if (fork) return { ...n, kids: [...n.kids, leaf(ref)], pick: n.kids.length };
const kids = n.kids.slice();
kids[n.pick] = leaf(ref);
return { ...n, kids };
});
} }
/** Close everything right of pane i of the focused branch, every fork of it included. */ /** Make the node with this id lie on its tree's focused branch (its own picks below it kept). */
export function closeRight<R, S>(t: Tree<R, S>, i: number): Tree<R, S> {
return at(t, i, (n) => (n.kids.length ? { ...n, kids: [], pick: 0 } : n));
}
/** Remove a child of a node, picking the one that takes its place (the one below, else the one above). */
function dropKid<R, S>(n: Tree<R, S>, k: number): Tree<R, S> {
const kids = n.kids.filter((_, j) => j !== k);
const pick = k < n.pick ? n.pick - 1 : Math.max(0, Math.min(n.pick, kids.length - 1));
return { ...n, kids, pick };
}
/** Close pane i of the focused branch (i ≥ 1) and everything right of it. Its siblings stay. */
export function closeAt<R, S>(t: Tree<R, S>, i: number): Tree<R, S> {
if (i < 1) return t;
return at(t, i - 1, (n) => (n.kids.length ? dropKid(n, n.pick) : n));
}
/** Close the child of pane i of the focused branch that shows this (whichever fork it is). */
export function closeChild<R, S>(t: Tree<R, S>, i: number, ref: R, same: Same<R>): Tree<R, S> {
return at(t, i, (n) => {
const k = n.kids.findIndex((c) => same(c.ref, ref));
return k < 0 ? n : dropKid(n, k);
});
}
/** Make the node with this id lie on the focused branch (its own picks below it kept). */
export function select<R, S>(t: Tree<R, S>, id: number): Tree<R, S> | null { export function select<R, S>(t: Tree<R, S>, id: number): Tree<R, S> | null {
if (t.id === id) return t; if (t.id === id) return t;
for (let k = 0; k < t.kids.length; k++) { for (let k = 0; k < t.kids.length; k++) {
@@ -138,72 +146,196 @@ export function select<R, S>(t: Tree<R, S>, id: number): Tree<R, S> | null {
return null; return null;
} }
/** /** Make the pane with this id lie on the focused branch: its tree focused, and picked down to it. */
* The fork above (delta −1) or below (+1) the focused branch, in the order the rows are drawn: from export function focus<R, S>(f: Forest<R, S>, id: number): Forest<R, S> {
* the branch's last pane leftwards, the nearest pane with a sibling in that direction. Returns the const hit = find(f, id);
* tree with that sibling picked and the depth it is at, or null at the top or bottom. if (!hit) return f;
*/ const t = select(f.trees[hit.ti], id)!;
export function sibling<R, S>(t: Tree<R, S>, delta: number): { tree: Tree<R, S>; depth: number } | null { if (t === f.trees[hit.ti] && hit.ti === f.at) return f;
const p = path(t); return { trees: t === f.trees[hit.ti] ? f.trees : f.trees.map((x, j) => (j === hit.ti ? t : x)), at: hit.ti };
for (let d = p.length - 1; d >= 1; d--) {
const parent = p[d - 1];
const k = parent.pick + delta;
if (k >= 0 && k < parent.kids.length) return { tree: at(t, d - 1, (n) => ({ ...n, pick: k })), depth: d };
}
return null;
} }
/** Drop every pane whose ref fails `keep` (with everything right of it). Null if the root goes. Unchanged trees are returned as they are. */ /**
export function prune<R, S>(t: Tree<R, S> | null, keep: (r: R) => boolean): Tree<R, S> | null { * What stays open when a pane closes: the pinned panes inside it (topmost first, each with what it
if (!t || !keep(t.ref)) return null; * opened), as orphans in the columns they were in. `self`: whether the pane itself may stay.
*/
function survivors<R, S>(n: Tree<R, S>, col: number, self: boolean): Tree<R, S>[] {
if (self && n.pinned) return [{ ...n, col }];
return n.kids.flatMap((k) => survivors(k, col + 1, true));
}
/** Put a tree in place of tree ti (null removes it), with orphans right after it. The focused tree stays focused. */
function replace<R, S>(f: Forest<R, S>, ti: number, t: Tree<R, S> | null, orphans: Tree<R, S>[]): Forest<R, S> {
if (t === f.trees[ti] && !orphans.length) return f;
const trees = [...f.trees.slice(0, ti), ...(t ? [t] : []), ...orphans, ...f.trees.slice(ti + 1)];
const was = f.trees[f.at];
const at = trees.indexOf(was);
return { trees, at: at >= 0 ? at : Math.min(ti, trees.length - 1) };
}
/** Remove a child of a node, picking the one that takes its place (the one below, else the one above). */
function dropKid<R, S>(n: Tree<R, S>, k: number): Tree<R, S> {
const kids = n.kids.filter((_, j) => j !== k);
const pick = k < n.pick ? n.pick - 1 : Math.max(0, Math.min(n.pick, kids.length - 1));
return { ...n, kids, pick };
}
/**
* Open something to the right of pane i of the focused branch. If it is already open there (as any
* of the forks) that fork is picked and kept as it is. Otherwise a fork adds a child below the
* others; a plain open replaces the picked child (and everything right of it), or adds the first.
* A pinned child is never replaced: a plain open beside it is a fork. Pinned panes in what is
* replaced stay, as orphans.
*/
export function open<R, S>(f: Forest<R, S>, i: number, ref: R, fork: boolean, same: Same<R>): Forest<R, S> {
const t = focused(f);
if (!t) return plain([ref]);
const orphans: Tree<R, S>[] = [];
const next = at(t, i, (n) => {
const k = n.kids.findIndex((c) => same(c.ref, ref));
if (k >= 0) return k === n.pick ? n : { ...n, pick: k };
if (!n.kids.length) return { ...n, kids: [leaf(ref)], pick: 0 };
if (fork || n.kids[n.pick].pinned) return { ...n, kids: [...n.kids, leaf(ref)], pick: n.kids.length };
orphans.push(...survivors(n.kids[n.pick], colOf(t) + i + 1, true));
const kids = n.kids.slice();
kids[n.pick] = leaf(ref);
return { ...n, kids };
});
return replace(f, f.at, next, orphans);
}
/**
* Close a pane and everything opened from it, except pinned panes, which stay where they are as
* orphans (with what they opened). The first tree's root never closes. `active` is the pane the keys
* act on; returned is the forest, with the active pane on its focused branch, and that pane: the
* same one if it is still open, else the closed pane's parent, else (for an orphan's root) the
* nearest pane of the tree before it.
*/
export function close<R, S>(f: Forest<R, S>, id: number, active: number): { forest: Forest<R, S>; active: number } {
const hit = find(f, id);
if (!hit || (hit.ti === 0 && hit.path.length === 1 && !f.trees[0].col)) return { forest: f, active };
const t = f.trees[hit.ti];
const node = hit.path[hit.path.length - 1];
const col = colOf(t) + hit.path.length - 1;
const orphans = survivors(node, col, false);
let g: Forest<R, S>;
let fallback: number;
if (hit.path.length === 1) {
g = replace(f, hit.ti, null, orphans);
const before = g.trees[Math.max(0, hit.ti - 1)];
const p = path(before);
fallback = p[Math.max(0, Math.min(p.length - 1, col - 1 - colOf(before)))].id;
} else {
const parent = hit.path[hit.path.length - 2];
g = replace(f, hit.ti, update(t, parent.id, (n) => dropKid(n, n.kids.indexOf(node))), orphans);
fallback = parent.id;
}
const still = find(g, active) ? active : fallback;
return { forest: focus(g, still), active: still };
}
/** Pin or unpin a pane. */
export const pin = <R, S>(f: Forest<R, S>, id: number, on: boolean): Forest<R, S> => updateIn(f, id, (n) => (!!n.pinned === on ? n : { ...n, pinned: on || undefined }));
/** The pane above (−1) or below (+1) this one in its column, or null at the top or bottom. */
export function besideInColumn<R, S>(f: Forest<R, S>, id: number, delta: number): number | null {
const placed = all(f);
const me = placed.find((x) => x.node.id === id);
if (!me) return null;
const col = placed.filter((x) => x.col === me.col);
return col[col.indexOf(me) + delta]?.node.id ?? null;
}
/** Drop every pane whose ref fails `keep` (with everything right of it but pinned panes, which stay as orphans). Unchanged forests are returned as they are. */
export function prune<R, S>(f: Forest<R, S>, keep: (r: R) => boolean): Forest<R, S> {
const go = (t: Tree<R, S>, col: number, out: Tree<R, S>[]): Tree<R, S> | null => {
if (!keep(t.ref)) {
for (const s of survivors(t, col, false)) {
const p = go(s, s.col!, out);
if (p) out.push(p);
}
return null;
}
let changed = false; let changed = false;
// The picked child, or the one that takes its place: as many kept children before it. // The picked child, or the one that takes its place: as many kept children before it.
let pick = 0; let pick = 0;
const kids: Tree<R, S>[] = []; const kids: Tree<R, S>[] = [];
t.kids.forEach((k, j) => { t.kids.forEach((k, j) => {
const p = prune(k, keep); const p = go(k, col + 1, out);
if (p !== k) changed = true; if (p !== k) changed = true;
if (p) kids.push(p); if (p) kids.push(p);
if (j === t.pick) pick = kids.length - (p ? 1 : 0); if (j === t.pick) pick = kids.length - (p ? 1 : 0);
}); });
if (!changed) return t; if (!changed) return t;
return { ...t, kids, pick: Math.max(0, Math.min(pick, kids.length - 1)) }; return { ...t, kids, pick: Math.max(0, Math.min(pick, kids.length - 1)) };
};
let g = f;
for (let ti = f.trees.length - 1; ti >= 0; ti--) {
const t = f.trees[ti];
const out: Tree<R, S>[] = [];
const p = go(t, colOf(t), out);
if (p !== t || out.length) g = replace(g, g.trees.indexOf(t), p, out);
}
return g;
} }
/** Whether the first tree is the one starting at this ref (not missing, not an orphan). */
export const rooted = <R, S>(f: Forest<R, S>, ref: R, same: Same<R>) => !!f.trees[0] && !f.trees[0].col && same(f.trees[0].ref, ref);
/** /**
* Make the focused branch this list of refs, keeping every pane that is already on the way: where a * Make the focused branch the first tree's path along this list of refs, keeping every pane that is
* ref is already a child it is picked; where it is not, the picked child is replaced by the rest of * already on the way: where a ref is already a child it is picked; where it is not, the picked child
* the list. Panes right of the list's end close. A different root starts again. * is replaced by the rest of the list (a pinned one is kept beside it). Panes right of the list's
* end close, but pinned ones. A different root starts again. Orphans stay; pinned panes in what
* closes become orphans.
*/ */
export function withBranch<R, S>(t: Tree<R, S> | null, refs: R[], same: Same<R>): Tree<R, S> | null { export function withBranch<R, S>(f: Forest<R, S>, refs: R[], same: Same<R>): Forest<R, S> {
if (!refs.length) return null; if (!refs.length) return f;
if (!t || !same(t.ref, refs[0])) return chain(refs); const orphans: Tree<R, S>[] = [];
if (!rooted(f, refs[0], same)) {
const old = f.trees[0] && !f.trees[0].col ? f.trees[0] : null;
if (old) orphans.push(...survivors(old, 0, false));
const rest = old ? f.trees.slice(1) : f.trees;
return { trees: [chain<R, S>(refs)!, ...orphans, ...rest], at: 0 };
}
const go = (n: Tree<R, S>, i: number): Tree<R, S> => { const go = (n: Tree<R, S>, i: number): Tree<R, S> => {
if (i === refs.length) return n.kids.length ? { ...n, kids: [], pick: 0 } : n; if (i === refs.length) {
const kept = n.kids.filter((k) => k.pinned);
if (kept.length === n.kids.length) return n;
for (const k of n.kids) if (!k.pinned) orphans.push(...survivors(k, i, true));
return { ...n, kids: kept, pick: 0 };
}
const k = n.kids.findIndex((c) => same(c.ref, refs[i])); const k = n.kids.findIndex((c) => same(c.ref, refs[i]));
if (k < 0) { if (k < 0) {
const rest = chain<R, S>(refs.slice(i))!; const rest = chain<R, S>(refs.slice(i))!;
const kids = n.kids.length ? n.kids.map((c, j) => (j === n.pick ? rest : c)) : [rest]; if (!n.kids.length) return { ...n, kids: [rest], pick: 0 };
return { ...n, kids, pick: n.kids.length ? n.pick : 0 }; if (n.kids[n.pick].pinned) return { ...n, kids: [...n.kids, rest], pick: n.kids.length };
orphans.push(...survivors(n.kids[n.pick], i, true));
return { ...n, kids: n.kids.map((c, j) => (j === n.pick ? rest : c)) };
} }
const sub = go(n.kids[k], i + 1); const sub = go(n.kids[k], i + 1);
return sub === n.kids[k] && k === n.pick ? n : { ...n, kids: n.kids.map((c, j) => (j === k ? sub : c)), pick: k }; return sub === n.kids[k] && k === n.pick ? n : { ...n, kids: n.kids.map((c, j) => (j === k ? sub : c)), pick: k };
}; };
return go(t, 1); const t = go(f.trees[0], 1);
const g = replace(f, 0, t, orphans);
return g.at === 0 ? g : { ...g, at: 0 };
} }
/** As stored: refs (made storable by the caller), children and picks; no ids, nothing remembered. */ /** As stored: refs (made storable by the caller), children, picks, pins and an orphan's column; no ids, nothing remembered. */
export interface Saved<R> { export interface Saved<R> {
ref: R; ref: R;
kids?: Saved<R>[]; kids?: Saved<R>[];
pick?: number; pick?: number;
pin?: 1;
col?: number;
} }
export function save<R, S, O>(t: Tree<R, S> | null, ref: (r: R) => O): Saved<O> | null { export function save<R, S, O>(t: Tree<R, S>, ref: (r: R) => O): Saved<O> {
if (!t) return null;
const out: Saved<O> = { ref: ref(t.ref) }; const out: Saved<O> = { ref: ref(t.ref) };
if (t.kids.length) out.kids = t.kids.map((k) => save(k, ref)!); if (t.kids.length) out.kids = t.kids.map((k) => save(k, ref));
if (t.pick) out.pick = t.pick; if (t.pick) out.pick = t.pick;
if (t.pinned) out.pin = 1;
if (t.col) out.col = t.col;
return out; return out;
} }
@@ -213,23 +345,39 @@ export function load<R, S>(o: unknown, ok: (r: unknown) => r is R): Tree<R, S> |
const s = o as Saved<unknown>; const s = o as Saved<unknown>;
const kids = (Array.isArray(s.kids) ? s.kids : []).map((k) => load<R, S>(k, ok)).filter((k): k is Tree<R, S> => !!k); const kids = (Array.isArray(s.kids) ? s.kids : []).map((k) => load<R, S>(k, ok)).filter((k): k is Tree<R, S> => !!k);
const pick = Math.max(0, Math.min(typeof s.pick === "number" ? Math.floor(s.pick) : 0, kids.length - 1)); const pick = Math.max(0, Math.min(typeof s.pick === "number" ? Math.floor(s.pick) : 0, kids.length - 1));
return { ref: s.ref as R, kids, pick, id: ++ids }; const t: Tree<R, S> = { ref: s.ref as R, kids, pick, id: ++ids };
if (s.pin) t.pinned = true;
if (typeof s.col === "number" && s.col >= 1) t.col = Math.floor(s.col);
return t;
} }
/** What was stored: the tree, or, from before there were forks, the trail as a tree with one branch. */ /**
export function restore<R, S>(saved: unknown, trail: unknown[] | undefined, ok: (r: unknown) => r is R): Tree<R, S> | null { * What was stored: the forest; from before orphans, one tree; from before forks, the trail as a
return saved ? load<R, S>(saved, ok) : chain<R, S>((trail ?? []).filter(ok)); * tree with one branch. An orphan stored first (its tree's root gone) is dropped.
*/
export function restore<R, S>(saved: { forest?: unknown; at?: unknown; forks?: unknown; trail?: unknown[] }, ok: (r: unknown) => r is R): Forest<R, S> {
if (Array.isArray(saved.forest)) {
const trees = saved.forest.map((o) => load<R, S>(o, ok)).filter((t): t is Tree<R, S> => !!t);
const first = trees.findIndex((t) => !t.col);
const kept = first < 0 ? trees.filter((t) => t.col) : [trees[first], ...trees.filter((t, j) => j !== first && t.col)];
const at = typeof saved.at === "number" ? Math.floor(saved.at) : 0;
return { trees: kept, at: at >= 0 && at < kept.length ? at : 0 };
}
const t = saved.forks ? load<R, S>(saved.forks, ok) : chain<R, S>((saved.trail ?? []).filter(ok));
return { trees: t ? [t] : [], at: 0 };
} }
/** Whether a tree is well formed: picks in range, no pane twice among siblings, ids unique. */ /** Whether a forest is well formed: picks in range, no pane twice among siblings, ids unique, orphans in a column right of the first, the focused tree there. */
export function valid<R, S>(t: Tree<R, S> | null, same: Same<R>): boolean { export function valid<R, S>(f: Forest<R, S>, same: Same<R>): boolean {
const seen = new Set<number>(); const seen = new Set<number>();
const ok = (n: Tree<R, S>): boolean => { const ok = (n: Tree<R, S>): boolean => {
if (seen.has(n.id)) return false; if (seen.has(n.id)) return false;
seen.add(n.id); seen.add(n.id);
if (n.pick < 0 || n.pick >= Math.max(1, n.kids.length) || !Number.isInteger(n.pick)) return false; if (n.pick < 0 || n.pick >= Math.max(1, n.kids.length) || !Number.isInteger(n.pick)) return false;
for (let a = 0; a < n.kids.length; a++) for (let b = a + 1; b < n.kids.length; b++) if (same(n.kids[a].ref, n.kids[b].ref)) return false; for (let a = 0; a < n.kids.length; a++) for (let b = a + 1; b < n.kids.length; b++) if (same(n.kids[a].ref, n.kids[b].ref)) return false;
return n.kids.every(ok); return n.kids.every((k) => k.col === undefined && ok(k));
}; };
return !t || ok(t); if (!f.trees.length) return f.at === 0;
if (f.at < 0 || f.at >= f.trees.length) return false;
return f.trees.every((t, ti) => (ti === 0 ? !t.col : (t.col ?? 0) >= 1) && ok(t));
} }
+8 -3
View File
@@ -15,9 +15,10 @@ export const HELP: [string, [string, string][]][] = [
["/", "jump to a section by name, in any document"], ["/", "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)"], ["z", "hoist: make this node the whole page (again, or h or Esc at its top, to step out)"],
["v", "view: one column ↔ panes side by side (in panes, j k move among siblings)"], ["v", "view: one column ↔ panes side by side (in panes, j k move among siblings)"],
["q", "in panes: close the panes right of the one being read, every fork among them; with none, close that one, or in a fork the whole fork. Moving left never closes anything"], ["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 × does the same. Moving left never closes anything"],
["Shift+Enter", "in panes: open a fork: what Enter opens goes in a new row beside the pane to the right instead of replacing it (Shift-, Ctrl- or Cmd-click, or a middle click, does the same). With nothing open to the right it is a plain Enter; on something already open as a fork, it focuses that fork"], ["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 plain open, and never folds into a tab or a spine"],
["[ ]", "in panes: the fork above / below (back where you were in it, or its pane nearest your column)"], ["Shift+Enter", "in panes: open a fork: what Enter opens goes in the next column below what is open there, instead of replacing it (Shift-, Ctrl- or Cmd-click, or a middle click, does the same). With nothing open to the right it is a plain Enter; on something already open as a fork, it focuses that fork"],
["[ ]", "in panes: the pane above / below in the same column, whichever fork it belongs to (back where you were in it, or at its head); at the top or bottom of the column nothing moves. A faint curve runs from where each pane was opened to its title"],
], ],
], ],
[ [
@@ -112,6 +113,7 @@ export const HELP: [string, [string, string][]][] = [
["/auto on|off", "reconcile automatically after edits"], ["/auto on|off", "reconcile automatically after edits"],
["/speculate on|off", "start writing the focused sentence's expansion early"], ["/speculate on|off", "start writing the focused sentence's expansion early"],
["/view mode", "page layout: auto, column or panes; auto shows panes on windows 1600 px wide or more"], ["/view mode", "page layout: auto, column or panes; auto shows panes on windows 1600 px wide or more"],
["/curves on|off", "in panes: the faint curves from where each pane was opened to it"],
["/user name", "set the name on your commits"], ["/user name", "set the name on your commits"],
["/new title", "new blank document"], ["/new title", "new blank document"],
["/open name", "open a document by title or id"], ["/open name", "open a document by title or id"],
@@ -498,6 +500,9 @@ function commonKey(k: string, hooks: KeyHooks): boolean {
case "q": case "q":
if (store.panes) store.closePane(); if (store.panes) store.closePane();
return true; return true;
case "P":
store.togglePanePin();
return true;
case "[": case "[":
case "]": case "]":
store.focusFork(k === "[" ? -1 : 1); store.focusFork(k === "[" ? -1 : 1);
+68
View File
@@ -0,0 +1,68 @@
/**
* Lanes for the panes view's curves (Panes.tsx): where several curves run down one gutter, each gets
* a lane of its own, side by side like a ribbon cable, in the order that crosses least.
*/
/** Lanes in a gutter: vertical runs this far apart, from just inside the column's edge to just short of its titles. */
export const LANE_PITCH = 4;
export const LANE_FIRST = 5;
export const LANE_LAST = 29;
export const LANES = Math.floor((LANE_LAST - LANE_FIRST) / LANE_PITCH) + 1;
/**
* How many times curves in one gutter cross, for an order of lanes (rightmost first): a lead-out
* comes in from the left at its source's height, crossing the lanes left of its own still running
* there; an arrival goes right at its title's height, crossing the lanes right of its own.
*/
export function crossings(order: { sy: number; ey: number }[]): number {
const runs = (c: { sy: number; ey: number }, y: number) => y > Math.min(c.sy, c.ey) && y < Math.max(c.sy, c.ey);
let n = 0;
for (let i = 0; i < order.length; i++)
for (let j = i + 1; j < order.length; j++) {
// order[i] is right of order[j].
if (runs(order[j], order[i].sy)) n++;
if (runs(order[i], order[j].ey)) n++;
}
return n;
}
/**
* The order of a gutter's lanes, rightmost first, so that curves cross as little as they can: the
* curve with the shortest way to go takes the lane nearest the panes, and the rest outwards. Starting from the order last used, with new curves put
* where that rule puts them, a curve is moved to another lane only while that removes crossings, so a
* scroll or an open elsewhere does not reshuffle the bundle.
*/
export function laneOrder<T extends { key: string; sy: number; ey: number }>(edges: T[], last: string[] = []): T[] {
const rule = [...edges].sort((a, b) => {
const da = a.ey >= a.sy ? a.ey - a.sy : a.sy - a.ey;
const db = b.ey >= b.sy ? b.ey - b.sy : b.sy - b.ey;
return da - db;
});
const byKey = new Map(edges.map((e) => [e.key, e]));
const order = last.flatMap((k) => byKey.get(k) ?? []);
for (const e of rule) {
if (order.includes(e)) continue;
const r = rule.indexOf(e);
const at = order.findIndex((o) => rule.indexOf(o) > r);
order.splice(at < 0 ? order.length : at, 0, e);
}
// Move one curve to another lane while that removes crossings (a few curves per gutter: cheap).
let best = crossings(order);
for (let pass = 0, better = true; better && pass < order.length; pass++) {
better = false;
for (let i = 0; i < order.length && best; i++)
for (let j = 0; j < order.length; j++) {
if (j === i) continue;
const moved = order.slice();
moved.splice(j, 0, ...moved.splice(i, 1));
const n = crossings(moved);
if (n < best) {
order.splice(0, order.length, ...moved);
best = n;
better = true;
}
}
}
return order;
}
+141 -122
View File
@@ -36,7 +36,7 @@ import { remoteLLM } from "./remote";
import { Session } from "./session"; import { Session } from "./session";
import { refreshAfterCalls } from "./usage"; import { refreshAfterCalls } from "./usage";
import { Linker, type AutoMode, type JobState, type Sugg } from "./linker"; import { Linker, type AutoMode, type JobState, type Sugg } from "./linker";
import { all, chain, closeAt, closeChild, closeRight, open as openIn, path, prune, restore as restoreTree, save as saveTree, select, sibling, trace, update, withBranch, type Tree } from "./forks"; import { all, besideInColumn, close as closeIn, focus as focusIn, focused, open as openIn, path, pin as pinIn, prune, restore as restoreForest, rooted, save as saveTree, updateIn, withBranch, type Forest, type Placed, type Tree } from "./forks";
import { stripMarks, type Mark } from "../core/marks"; import { stripMarks, type Mark } from "../core/marks";
import { SEED_SLUG } from "../core/seed"; import { SEED_SLUG } from "../core/seed";
@@ -62,8 +62,14 @@ export interface Back {
aux: Aux | null; aux: Aux | null;
pane: number; pane: number;
} }
/** A pane in the tree of forks; `seen` is where the reader was when they last left its fork. */ /** A pane in the forest of forks; `seen` is where the reader was when they last left it by [ or ]. */
export type Pane = Tree<PaneRef, Back>; export type Pane = Tree<PaneRef, Back>;
/** The DOM class that marks, in a pane, what a child pane of it was opened from (a row, a link, words): by what the child shows. */
export const kidClass = (key: string) => {
let h = 5381;
for (let i = 0; i < key.length; i++) h = ((h * 33) ^ key.charCodeAt(i)) >>> 0;
return `k${h.toString(36)}`;
};
/** Whether two panes show the same thing (a node, or an article or one of its sections). */ /** Whether two panes show the same thing (a node, or an article or one of its sections). */
export const sameRef = (a: PaneRef, b: PaneRef): boolean => export const sameRef = (a: PaneRef, b: PaneRef): boolean =>
a.kind === b.kind && (a.kind === "node" ? a.id === (b as { id: NodeId }).id : a.title === (b as { title: string }).title && a.sec === (b as { sec?: number }).sec); a.kind === b.kind && (a.kind === "node" ? a.id === (b as { id: NodeId }).id : a.title === (b as { title: string }).title && a.sec === (b as { sec?: number }).sec);
@@ -223,7 +229,7 @@ class Store {
branchFrom: Commit | null = null; branchFrom: Commit | null = null;
/** A note being previewed on hover, and where to draw it. */ /** A note being previewed on hover, and where to draw it. */
popup: { note: NodeId; x: number; top: number; bottom: number } | null = null; popup: { note: NodeId; x: number; top: number; bottom: number } | null = null;
settings: { auto: boolean; speculate: boolean; view: View; autolink: AutoMode } = { auto: true, speculate: false, view: "auto", autolink: "suggest", ...lsGet("ie:settings", {}) }; settings: { auto: boolean; speculate: boolean; view: View; autolink: AutoMode; curves: boolean } = { auto: true, speculate: false, view: "auto", autolink: "suggest", curves: true, ...lsGet("ie:settings", {}) };
/** Link discovery: scans after writes, suggestions, Related, the background job. */ /** Link discovery: scans after writes, suggestions, Related, the background job. */
links = new Linker({ links = new Linker({
doc: () => this.doc, doc: () => this.doc,
@@ -244,20 +250,29 @@ class Store {
/** Replicas of pre-library documents whose edits never reached the server. */ /** Replicas of pre-library documents whose edits never reached the server. */
oldReplicas: OldReplica[] = []; oldReplicas: OldReplica[] = [];
/** The panes as a tree of forks; its focused branch is `trail`, and `paneAt` is the pane on it that holds the focus. */ /** The panes as a forest of forks (forks.ts); its focused branch is `trail`, and `paneAt` is the pane on it that holds the focus: the active pane. */
tree: Pane | null = null; forest: Forest<PaneRef, Back> = { trees: [], at: 0 };
paneAt = 0; paneAt = 0;
/** The focused tree. */
get tree(): Pane | null {
return focused(this.forest);
}
/** Set while a modified open (Shift+Enter, Shift-, Ctrl- or middle-click) runs: it opens a fork beside what is there. */ /** Set while a modified open (Shift+Enter, Shift-, Ctrl- or middle-click) runs: it opens a fork beside what is there. */
forking = false; forking = false;
private toldForks = false; private toldForks = false;
private memo: { tree: Pane | null; nodes: Pane[]; trail: PaneRef[]; index?: Map<number, { node: Pane; depth: number }>; ids?: Set<NodeId> } = { tree: null, nodes: [], trail: [] }; private memo: { forest: Forest<PaneRef, Back> | null; nodes: Pane[]; trail: PaneRef[]; placed?: Placed<PaneRef, Back>[]; index?: Map<number, Placed<PaneRef, Back>>; ids?: Set<NodeId> } = { forest: null, nodes: [], trail: [] };
private get branch() { private get branch() {
if (this.memo.tree !== this.tree) { if (this.memo.forest !== this.forest) {
const nodes = path(this.tree); const nodes = path(this.tree);
this.memo = { tree: this.tree, nodes, trail: nodes.map((n) => n.ref) }; this.memo = { forest: this.forest, nodes, trail: nodes.map((n) => n.ref) };
} }
return this.memo; return this.memo;
} }
/** Every pane, with its column, in the order panes stand in a column. */
get panesPlaced(): Placed<PaneRef, Back>[] {
const m = this.branch;
return (m.placed ??= all(this.forest));
}
/** The focused branch: the panes the keys move along, left to right. */ /** The focused branch: the panes the keys move along, left to right. */
get trail(): PaneRef[] { get trail(): PaneRef[] {
return this.branch.trail; return this.branch.trail;
@@ -438,59 +453,37 @@ class Store {
return p.sec !== undefined && (q.kind === "wiki" ? q.title === p.title : this.targetOf(q.id)?.kind === "wiki"); return p.sec !== undefined && (q.kind === "wiki" ? q.title === p.title : this.targetOf(q.id)?.kind === "wiki");
} }
/** Pane i of the focused branch holds a focus (see holdsIn). */ /** Pane i of the focused branch holds a focus (see holdsIn); a continuation's head only while it is the active pane. */
private holds(i: number, f: Focus): boolean { private holds(i: number, f: Focus): boolean {
return this.holdsIn(this.trail[i], this.trail[i - 1], i === 0, `p${i}`, f); return this.holdsIn(this.trail[i], this.trail[i - 1], i === 0 || i === this.paneAt, `p${i}`, f);
} }
/** /**
* Whether a pane (p, opened from q; host: how its article is named) holds a focus: its node's * Whether a pane (p, opened from q; host: how its article is named) holds a focus: its node's
* text (a selection, a note in it), one of its rows, or its head when it is not a continuation (a * text (a selection, a note in it), one of its rows, or its head when it is not a continuation (a
* continuation's node is focused as the row it was opened from, in the pane before). * continuation's node is focused as the row it was opened from, in the pane before), or when
* `head` says it may (the first pane, or the active pane, landed on by [ ] or a click).
*/ */
private holdsIn(p: PaneRef | undefined, q: PaneRef | undefined, first: boolean, host: string, f: Focus): boolean { private holdsIn(p: PaneRef | undefined, q: PaneRef | undefined, head: boolean, host: string, f: Focus): boolean {
const s = this.snap; const s = this.snap;
const n = s.nodes[f.node]; const n = s.nodes[f.node];
// An annotation is held by the pane showing its article. // An annotation is held by the pane showing its article.
if (p && n && inArticles(s, f.node)) return this.shows(p.kind === "wiki" ? host : `n${p.id}`, f.node); if (p && n && inArticles(s, f.node)) return this.shows(p.kind === "wiki" ? host : `n${p.id}`, f.node);
if (!p || p.kind !== "node" || !n) return false; if (!p || p.kind !== "node" || !n) return false;
if (f.grain !== "node" || n.kind === "note") return ownerSection(s, f.node) === p.id || f.node === p.id; if (f.grain !== "node" || n.kind === "note") return ownerSection(s, f.node) === p.id || f.node === p.id;
if (f.node === p.id) return first || !this.continuesFrom(p, q); if (f.node === p.id) return head || !this.continuesFrom(p, q);
return n.parent === p.id; return n.parent === p.id;
} }
/** A pane off the focused branch that holds a focus: the tree with it on the branch, and its column. */ /** A pane off the focused branch that holds a focus: the forest with it on the branch, and its depth. */
private forkHolding(f: Focus): { tree: Pane; depth: number } | null { private forkHolding(f: Focus): { forest: Forest<PaneRef, Back>; depth: number } | null {
const t = this.tree;
if (!t) return null;
const on = new Set(this.branchNodes.map((n) => n.id)); const on = new Set(this.branchNodes.map((n) => n.id));
const find = (n: Pane, q: PaneRef | undefined, d: number): { id: number; depth: number } | null => { const hit = this.panesPlaced.find((x) => !on.has(x.node.id) && this.holdsIn(x.node.ref, x.parent?.ref, x.depth === 0, `f${x.node.id}`, f));
if (!on.has(n.id) && this.holdsIn(n.ref, q, d === 0, `f${n.id}`, f)) return { id: n.id, depth: d }; return hit ? { forest: focusIn(this.forest, hit.node.id), depth: hit.depth } : null;
for (const k of n.kids) {
const hit = find(k, n.ref, d + 1);
if (hit) return hit;
}
return null;
};
const hit = find(t, undefined, 0);
return hit ? { tree: select(t, hit.id)!, depth: hit.depth } : null;
} }
/** private setForest(next: Forest<PaneRef, Back>) {
* Change the tree. When the focused branch leaves a fork that stays open, the fork remembers this.forest = next;
* where the reader was in it, for [ and ] to come back to.
*/
private setTree(next: Pane | null, remember = true) {
const old = this.branchNodes;
if (next && remember && old.length) {
const now = path(next);
const d = old.findIndex((n, k) => now[k]?.id !== n.id);
if (d > 0 && trace(next, old[d].id)) {
const here = this.backHere();
next = update(next, old[d].id, (n) => ({ ...n, seen: here }));
}
}
this.tree = next;
} }
/** The panes as a plain trail down to the focus (open sections on the way). */ /** The panes as a plain trail down to the focus (open sections on the way). */
@@ -508,9 +501,9 @@ class Store {
syncTrail() { syncTrail() {
if (!this.panes || !this.session) return; if (!this.panes || !this.session) return;
const s = this.snap; const s = this.snap;
let t = prune(this.tree, (p) => p.kind === "wiki" || !!s.nodes[p.id]); let f = prune(this.forest, (p) => p.kind === "wiki" || !!s.nodes[p.id]);
if (!t || t.ref.kind !== "node" || t.ref.id !== this.top) t = chain(this.pathRefs()); if (!rooted(f, { kind: "node", id: this.top }, sameRef)) f = withBranch(f, this.pathRefs(), sameRef);
if (t !== this.tree) this.setTree(t, false); if (f !== this.forest) this.setForest(f);
this.paneAt = Math.max(0, Math.min(this.paneAt, this.trail.length - 1)); this.paneAt = Math.max(0, Math.min(this.paneAt, this.trail.length - 1));
if (this.aux) return; if (this.aux) return;
const n = this.trail.length; const n = this.trail.length;
@@ -518,22 +511,22 @@ class Store {
for (const i of order) if (i >= 0 && i < n && this.holds(i, this.focus)) return void (this.paneAt = i); for (const i of order) if (i >= 0 && i < n && this.holds(i, this.focus)) return void (this.paneAt = i);
const fork = this.forkHolding(this.focus); const fork = this.forkHolding(this.focus);
if (fork) { if (fork) {
this.setTree(fork.tree, false); this.setForest(fork.forest);
this.paneAt = fork.depth; this.paneAt = fork.depth;
return; return;
} }
this.setTree(withBranch(this.tree, this.pathRefs(), sameRef), false); this.setForest(withBranch(this.forest, this.pathRefs(), sameRef));
const at = this.trail.findIndex((_, i) => this.holds(i, this.focus)); const at = this.trail.findIndex((_, i) => this.holds(i, this.focus));
this.paneAt = at >= 0 ? at : this.trail.length - 1; this.paneAt = at >= 0 ? at : this.trail.length - 1;
} }
/** /**
* Open something to the right of pane i. If it is already open there, as any fork, that fork is * Open something to the right of pane i. If it is already open there, as any fork, that fork is
* focused. Otherwise a plain open replaces what was to the right; a fork (`forking`) opens it * focused. Otherwise a plain open replaces what was to the right (a pinned pane stays beside it);
* beside that, as a new row below. Returns the pane it is in. * a fork (`forking`) opens it beside that, below in the next column. Returns the pane it is in.
*/ */
openPane(i: number, ref: PaneRef): number { openPane(i: number, ref: PaneRef): number {
this.setTree(this.tree ? openIn(this.tree, i, ref, this.forking, sameRef) : chain([ref])); this.setForest(openIn(this.forest, i, ref, this.forking, sameRef));
this.saveView(); this.saveView();
this.emit(); this.emit();
return Math.min(i + 1, this.trail.length - 1); return Math.min(i + 1, this.trail.length - 1);
@@ -541,10 +534,9 @@ class Store {
/** Close the pane that shows this node to the right of pane i (whichever fork it is). */ /** Close the pane that shows this node to the right of pane i (whichever fork it is). */
closeRow(i: number, id: NodeId) { closeRow(i: number, id: NodeId) {
if (!this.tree) return; const kid = this.branchNodes[i]?.kids.find((k) => k.ref.kind === "node" && k.ref.id === id);
this.setTree(closeChild(this.tree, i, { kind: "node", id }, sameRef)); if (!kid) return;
this.saveView(); this.closePane(kid.id);
this.emit();
} }
/** Run an open with or without a fork. In the column a fork is a plain open, and the status line says so once. */ /** Run an open with or without a fork. In the column a fork is a plain open, and the status line says so once. */
@@ -562,33 +554,28 @@ class Store {
} }
} }
/** The tree's panes by id, with their columns. */ /** A pane of the forest by its id: its node, depth in its tree, column, tree and parent. */
forkNode(id: number): { node: Pane; depth: number } | undefined { forkNode(id: number): Placed<PaneRef, Back> | undefined {
const m = this.branch; const m = this.branch;
if (!m.index) m.index = new Map(all(this.tree).map((x) => [x.node.id, x])); if (!m.index) m.index = new Map(this.panesPlaced.map((x) => [x.node.id, x]));
return m.index.get(id); return m.index.get(id);
} }
/** Whether any pane in the tree shows this node. */ /** Whether any pane shows this node. */
private paneShows(id: NodeId): boolean { private paneShows(id: NodeId): boolean {
const m = this.branch; const m = this.branch;
if (!m.ids) m.ids = new Set(all(this.tree).flatMap((x) => (x.node.ref.kind === "node" ? [x.node.ref.id] : []))); if (!m.ids) m.ids = new Set(this.panesPlaced.flatMap((x) => (x.node.ref.kind === "node" ? [x.node.ref.id] : [])));
return m.ids.has(id); return m.ids.has(id);
} }
/** Whether some pane has forks. */
hasForks(): boolean {
return all(this.tree).some((x) => x.node.kids.length > 1);
}
/** /**
* For a pane with forks: its children by what they show (refKey), each true if it is the picked * For a pane with children: its children by what they show (refKey), each with whether it is the
* one. Null for a pane with one child or none, which marks nothing new (its row is marked as before). * picked one and whether there are several (forks, marked as such).
*/ */
forkMarks(tid: number | undefined): Map<string, boolean> | null { forkMarks(tid: number | undefined): Map<string, { picked: boolean; many: boolean }> | null {
const n = tid === undefined ? undefined : this.forkNode(tid)?.node; const n = tid === undefined ? undefined : this.forkNode(tid)?.node;
if (!n || n.kids.length < 2) return null; if (!n || !n.kids.length) return null;
return new Map(n.kids.map((k, j) => [refKey(k.ref), j === n.pick])); return new Map(n.kids.map((k, j) => [refKey(k.ref), { picked: j === n.pick, many: n.kids.length > 1 }]));
} }
/** A link's target by the key of the pane it opens (refKey); none for a web page or a node that is gone. */ /** A link's target by the key of the pane it opens (refKey); none for a web page or a node that is gone. */
@@ -599,16 +586,16 @@ class Store {
return id ? `n:${id}` : undefined; return id ? `n:${id}` : undefined;
} }
/** How a child is marked in the pane it was opened from: "showing" (the picked child), "forked" (another fork), or not open. */ /** How a child is marked in the pane it was opened from: "showing" (the picked child), "forked" (another fork), or not open; with the class that names it. */
kidMark(tid: number | undefined, match: (r: PaneRef) => boolean): "showing" | "forked" | undefined { kidMark(tid: number | undefined, match: (r: PaneRef) => boolean): string | undefined {
const n = tid === undefined ? undefined : this.forkNode(tid)?.node; const n = tid === undefined ? undefined : this.forkNode(tid)?.node;
const k = n ? n.kids.findIndex((c) => match(c.ref)) : -1; const k = n ? n.kids.findIndex((c) => match(c.ref)) : -1;
return k < 0 ? undefined : k === n!.pick ? "showing" : "forked"; return k < 0 ? undefined : `${k === n!.pick ? "showing" : "forked"} ${kidClass(refKey(n!.kids[k].ref))}`;
} }
/** /**
* Put the focus on pane c of the focused branch: on its node (for a continuation, that is the row * Put the focus on pane c of the focused branch, making it the active pane: on its node (its head;
* it was opened from, in the pane before), or on an article's head. * a continuation's too, while it is active), or on an article's head.
*/ */
land(c: number) { land(c: number) {
const p = this.trail[c]; const p = this.trail[c];
@@ -618,30 +605,34 @@ class Store {
else this.setFocus(this.focus, { kind: "wiki", host: `p${c}`, row: { t: "head" } }); else this.setFocus(this.focus, { kind: "wiki", host: `p${c}`, row: { t: "head" } });
} }
/** A click in a pane off the focused branch: its fork becomes the focused branch, with the focus on that pane. */ /** A click in a pane off the focused branch (or a tab): that pane comes onto the focused branch, with the focus on it. */
enterFork(id: number) { enterFork(id: number) {
const f = focusIn(this.forest, id);
const hit = this.forkNode(id); const hit = this.forkNode(id);
const t = this.tree && select(this.tree, id); if (!hit || f === this.forest) return;
if (!hit || !t || t === this.tree) return; this.setForest(f);
this.setTree(t);
this.land(hit.depth); this.land(hit.depth);
} }
/** /**
* [ and ]: the fork above or below, in the order the rows are drawn (the nearest pane, from the * [ and ]: the pane above or below the active one in its column (whichever fork or tree it is in).
* branch's end leftwards, that has another fork that way). The focus goes back where it was in * The focus goes back where it was when that pane was last left this way, or to the pane's head.
* that fork, or to its pane nearest the column the reader was in.
*/ */
focusFork(delta: number) { focusFork(delta: number) {
if (!this.panes) return this.say("Forks are side by side in the panes view (v); one column shows one page."); if (!this.panes) return this.say("Forks are side by side in the panes view (v); one column shows one page.");
this.syncTrail(); this.syncTrail();
const s = this.tree && sibling(this.tree, delta); const here = this.branchNodes[this.paneAt];
if (!s) return this.say(this.hasForks() ? `No fork ${delta < 0 ? "above" : "below"} this one.` : "No forks open. Shift+Enter, or a Shift- or Ctrl-click, opens one beside the pane to the right."); const next = here && besideInColumn(this.forest, here.id, delta);
const col = this.paneAt + (this.showingFocus() ? 1 : 0); if (next === null || next === undefined) {
this.setTree(s.tree); const alone = here && besideInColumn(this.forest, here.id, -delta) === null;
const b = this.branchNodes[s.depth].seen; return this.say(alone ? "This is the only pane in its column. Shift+Enter, or a Shift- or Ctrl-click, opens a fork below the pane to the right." : `No pane ${delta < 0 ? "above" : "below"} this one in its column.`);
if (b && b.pane >= s.depth && b.pane < this.trail.length && this.snap.nodes[b.focus.node] && (b.aux ? this.auxValid(b.aux) : this.holds(b.pane, b.focus))) return this.restore(b); }
this.land(Math.max(s.depth, Math.min(col, this.trail.length - 1))); const seen = this.backHere();
this.setForest(focusIn(updateIn(this.forest, here.id, (n) => ({ ...n, seen })), next));
const hit = this.forkNode(next)!;
const b = hit.node.seen;
if (b && b.pane === hit.depth && this.snap.nodes[b.focus.node] && (b.aux ? this.auxValid(b.aux) : this.holds(b.pane, b.focus))) return this.restore(b);
this.land(hit.depth);
} }
/** Whether the focus is a row whose pane is open next to it (so that pane is the one the reader is looking at). */ /** Whether the focus is a row whose pane is open next to it (so that pane is the one the reader is looking at). */
@@ -651,34 +642,53 @@ class Store {
} }
/** /**
* q, on the pane the reader is looking at (for a row, the pane it shows): close the panes to its * q (on the active pane) or a pane's ×: close the pane and everything opened from it, except
* right, every fork among them. With none there, close it and step left; in a fork, that closes * pinned panes, which stay where they are. If the focus was in what closed, it goes back to where
* the whole fork (from where it branched off to its end), and the others stay. * the pane was opened from (its row, its link, the article section) in the pane before.
*/ */
closePane() { closePane(id = this.branchNodes[this.paneAt]?.id) {
const showing = this.showingFocus(); const hit = id === undefined ? undefined : this.forkNode(id);
const i = this.paneAt + (showing ? 1 : 0); if (!hit) return;
if (!this.tree) return; if (hit.ti === 0 && hit.depth === 0) return this.say("The first pane stays; h or Esc at its top steps out of it.");
if (i + 1 < this.trail.length) { const active = this.branchNodes[this.paneAt];
this.setTree(closeRight(this.tree, i)); const wasAt = this.paneAt;
const r = closeIn(this.forest, hit.node.id, active.id);
this.setForest(r.forest);
this.saveView(); this.saveView();
const now = this.forkNode(r.active)!;
this.paneAt = now.depth;
if (r.active === active.id) {
// Still open; an article pane that became an orphan's root is named by its new place.
const a = this.aux;
if (now.depth !== wasAt && a?.kind === "wiki" && a.host === `p${wasAt}`) this.aux = { ...a, host: `p${now.depth}` };
return this.emit(); return this.emit();
} }
// The nearest pane to the left with forks: the fork the reader is in starts right of it. if (hit.parent && r.active === hit.parent.id) return this.toSource(hit.node.ref, now.depth);
const nodes = this.branchNodes; this.land(now.depth);
let j = i - 1; }
while (j >= 0 && nodes[j].kids.length < 2) j--;
const k = j >= 0 ? j + 1 : i; /** Back in pane i to where a pane (shown by ref, opened from pane i) was opened from: the jump's place, the row it continues, or the article's section row. */
if (k === 0) return this.say("The first pane stays; h or Esc at its top steps out of it."); private toSource(ref: PaneRef, i: number) {
const from = this.trail[k].from; const q = this.trail[i];
this.setTree(closeAt(this.tree, k)); if (ref.from && ref.from.pane === i) return this.restore(ref.from);
this.paneAt = i;
if (ref.kind === "node" && q?.kind === "node" && this.continuesFrom(ref, q) && this.snap.nodes[ref.id]) return this.setFocus({ node: ref.id, grain: "node" });
if (ref.kind === "wiki" && ref.sec !== undefined && q) {
const host = q.kind === "wiki" ? `p${i}` : `n${q.id}`;
return this.setFocus(q.kind === "node" ? { node: q.id, grain: "node" } : this.focus, { kind: "wiki", host, row: { t: "sec", id: ref.sec } });
}
this.land(i);
}
/** P (on the active pane) or a pane's pin: pin or unpin it. */
togglePanePin(id = this.branchNodes[this.paneAt]?.id) {
if (!this.panes) return this.say("Panes are pinned in the panes view (v).");
const hit = id === undefined ? undefined : this.forkNode(id);
if (!hit) return;
const on = !hit.node.pinned;
this.setForest(pinIn(this.forest, hit.node.id, on));
this.saveView(); this.saveView();
if (showing && k === i) return this.emit(); this.say(on ? "Pinned: this pane stays open when what it was opened from closes, and never folds away. P again unpins it." : "Unpinned.");
this.paneAt = k - 1;
if (from && from.pane < k) return this.restore(from);
const p = this.trail[k - 1];
if (p.kind === "node") this.setFocus({ node: p.id, grain: "node" });
else this.setFocus(this.focus, { kind: "wiki", host: `p${k - 1}`, row: { t: "head" } });
} }
/** Go back to where a jump was made from. */ /** Go back to where a jump was made from. */
@@ -1148,12 +1158,12 @@ class Store {
} }
private restoreView() { private restoreView() {
const s = this.doc.snap(); const s = this.doc.snap();
const v = lsGet<{ open: NodeId[]; focus: Focus | null; hoist: NodeId | null; forks?: unknown; trail?: PaneRef[]; paneAt?: number }>(this.viewKey(), { open: [], focus: null, hoist: null }); const v = lsGet<{ open: NodeId[]; focus: Focus | null; hoist: NodeId | null; forest?: unknown; at?: number; forks?: unknown; trail?: PaneRef[]; paneAt?: number }>(this.viewKey(), { open: [], focus: null, hoist: null });
this.open = new Set(v.open.filter((id) => s.nodes[id])); this.open = new Set(v.open.filter((id) => s.nodes[id]));
this.hoist = v.hoist && s.nodes[v.hoist] ? v.hoist : null; this.hoist = v.hoist && s.nodes[v.hoist] ? v.hoist : null;
this.focus = v.focus && s.nodes[v.focus.node] ? v.focus : { node: this.top, grain: "node" }; this.focus = v.focus && s.nodes[v.focus.node] ? v.focus : { node: this.top, grain: "node" };
// The tree of forks; a view saved before there were forks has only its trail, which loads as one branch. // The forest of forks; a view saved before orphans has one tree, and before forks only its trail, which loads as one branch.
this.tree = prune(restoreTree<PaneRef, Back>(v.forks, v.trail, isPaneRef), (p) => p.kind === "wiki" || !!s.nodes[p.id]); this.forest = prune(restoreForest<PaneRef, Back>(v, isPaneRef), (p) => p.kind === "wiki" || !!s.nodes[p.id]);
this.paneAt = Math.min(v.paneAt ?? 0, Math.max(0, this.trail.length - 1)); this.paneAt = Math.min(v.paneAt ?? 0, Math.max(0, this.trail.length - 1));
this.aux = null; this.aux = null;
this.repairView(); this.repairView();
@@ -1161,7 +1171,7 @@ class Store {
saveView() { saveView() {
const bare = (p: PaneRef): PaneRef => ({ ...p, from: undefined }); const bare = (p: PaneRef): PaneRef => ({ ...p, from: undefined });
// The trail too, for a build from before forks. // The trail too, for a build from before forks.
lsSet(this.viewKey(), { open: [...this.open], focus: this.focus, hoist: this.hoist, forks: saveTree(this.tree, bare), trail: this.trail.map(bare), paneAt: this.paneAt }); lsSet(this.viewKey(), { open: [...this.open], focus: this.focus, hoist: this.hoist, forest: this.forest.trees.map((t) => saveTree(t, bare)), at: this.forest.at, trail: this.trail.map(bare), paneAt: this.paneAt });
} }
/** Keep focus on something that exists and is on screen. */ /** Keep focus on something that exists and is on screen. */
private repairView() { private repairView() {
@@ -1254,11 +1264,11 @@ class Store {
this.aux = null; this.aux = null;
// A pane in another fork that shows it brings that fork onto the branch. // A pane in another fork that shows it brings that fork onto the branch.
const at = this.trail.findIndex((p) => p.kind === "node" && p.id === found.node); const at = this.trail.findIndex((p) => p.kind === "node" && p.id === found.node);
const fork = at < 0 && this.panes ? all(this.tree).find((x) => x.node.ref.kind === "node" && x.node.ref.id === found.node) : undefined; const fork = at < 0 && this.panes ? this.panesPlaced.find((x) => x.node.ref.kind === "node" && x.node.ref.id === found.node) : undefined;
if (fork && this.tree) { if (fork) {
this.setTree(select(this.tree, fork.node.id), false); this.setForest(focusIn(this.forest, fork.node.id));
this.paneAt = fork.depth; this.paneAt = fork.depth;
} else if (this.panes && at < 0) this.setTree(withBranch(this.tree, this.pathRefs(), sameRef), false); } else if (this.panes && at < 0) this.setForest(withBranch(this.forest, this.pathRefs(), sameRef));
else if (at >= 0) this.paneAt = at; else if (at >= 0) this.paneAt = at;
} }
this.repairView(); this.repairView();
@@ -1411,7 +1421,9 @@ class Store {
const next = this.trail[i + 1]; const next = this.trail[i + 1];
if (next?.kind === "node" && next.id === f.node && this.continues(i + 1)) { if (next?.kind === "node" && next.id === f.node && this.continues(i + 1)) {
const rows = this.paneRows(i + 1); const rows = this.paneRows(i + 1);
// Into its first row; with none, onto its head, which makes it the active pane.
if (rows[0]) this.focusRow(rows[0], i + 1); if (rows[0]) this.focusRow(rows[0], i + 1);
else this.land(i + 1);
return; return;
} }
this.open.add(f.node); this.open.add(f.node);
@@ -1463,7 +1475,11 @@ class Store {
this.syncTrail(); this.syncTrail();
const i = this.paneAt; const i = this.paneAt;
const p = this.trail[i]; const p = this.trail[i];
if (p?.kind === "node" && p.id !== f.node) return this.setFocus({ node: p.id, grain: "node" }); // From a row to its pane's node: for a continuation, that is its row in the pane before.
if (p?.kind === "node" && (p.id !== f.node || (i > 0 && this.continues(i)))) {
if (i > 0 && this.continues(i)) this.paneAt = i - 1;
return this.setFocus({ node: p.id, grain: "node" });
}
if (i > 0) { if (i > 0) {
const from = this.trail[i].from; const from = this.trail[i].from;
if (from && from.pane < i) return this.restore(from); if (from && from.pane < i) return this.restore(from);
@@ -1484,7 +1500,7 @@ class Store {
this.syncTrail(); this.syncTrail();
const p = this.trail[this.paneAt]; const p = this.trail[this.paneAt];
if (open && p?.kind === "node" && this.snap.nodes[id]?.parent === p.id && this.snap.nodes[id].kind === "section") this.openPane(this.paneAt, { kind: "node", id }); if (open && p?.kind === "node" && this.snap.nodes[id]?.parent === p.id && this.snap.nodes[id].kind === "section") this.openPane(this.paneAt, { kind: "node", id });
else if (!open && this.tree) this.setTree(closeChild(this.tree, this.paneAt, { kind: "node", id }, sameRef)); else if (!open) this.closeRow(this.paneAt, id);
} }
setOpen(id: NodeId, open: boolean) { setOpen(id: NodeId, open: boolean) {
@@ -1501,6 +1517,8 @@ class Store {
toggle(id = this.focus.node) { toggle(id = this.focus.node) {
if (id === this.top) return this.toggleFold(id); if (id === this.top) return this.toggleFold(id);
if (this.listing(id)) return this.openDoc(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 whose pane is open as a fork that is not the focused one, or any row opened as a fork, opens (focuses) its pane rather than closing it. // In panes, a row whose pane is open as a fork that is not the focused one, or any row opened as a fork, opens (focuses) its pane rather than closing it.
if (this.panes) { if (this.panes) {
this.syncTrail(); this.syncTrail();
@@ -2102,6 +2120,7 @@ class Store {
}, },
auto: () => this.set("auto", arg !== "off"), auto: () => this.set("auto", arg !== "off"),
speculate: () => this.set("speculate", arg !== "off"), speculate: () => this.set("speculate", arg !== "off"),
curves: () => (this.set("curves", arg !== "off"), this.emit()),
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"})`)), 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(), resolve: () => this.resolveAll(),
new: () => (arg ? this.newDoc(arg) : this.openMenu("new")), new: () => (arg ? this.newDoc(arg) : this.openMenu("new")),
@@ -2705,7 +2724,7 @@ class Store {
this.setView(this.panes ? "column" : "panes"); this.setView(this.panes ? "column" : "panes");
} }
private set(key: "auto" | "speculate", on: boolean) { private set(key: "auto" | "speculate" | "curves", on: boolean) {
this.settings = { ...this.settings, [key]: on }; this.settings = { ...this.settings, [key]: on };
lsSet("ie:settings", this.settings); lsSet("ie:settings", this.settings);
this.say(`${key} ${on ? "on" : "off"}`); this.say(`${key} ${on ? "on" : "off"}`);
+68 -35
View File
@@ -322,9 +322,12 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
/* ---- end usage ---- */ /* ---- end usage ---- */
/* ---- panes view (src/ui/Panes.tsx) ---- /* ---- panes view (src/ui/Panes.tsx) ----
* The path to the focus as a strip of panes, side by side, after notes.andymatuschak.org. Pane i * The panes as columns, side by side, after notes.andymatuschak.org. Column i sticks i spines from
* sticks i spines from the left edge, so later panes slide over earlier ones and leave each a * the left edge (a pinned pane's column, a whole pane), so later columns slide over earlier ones
* narrow spine that carries its title. Each pane scrolls on its own; only the strip scrolls sideways. * and leave each a narrow spine that carries its title. A column holds every pane at its depth, top
* to bottom, sharing its height (Panes.tsx sets the heights); folded panes are one-line tabs. Each
* pane scrolls on its own; only the strip scrolls sideways. Every pane has the same hairline on its
* right and bottom, so neighbours share one line and the outer edges meet the bars above and below.
*/ */
:root { :root {
--pane-text: 34rem; --pane-text: 34rem;
@@ -332,9 +335,17 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
--pane-pad: 1.8rem; --pane-pad: 1.8rem;
--pane: calc(var(--spine) + var(--pane-text) + var(--pane-pad)); --pane: calc(var(--spine) + var(--pane-text) + var(--pane-pad));
--shade: rgb(0 0 0 / 0.2); --shade: rgb(0 0 0 / 0.2);
--pane-rule: #d9d9d9;
--curve: rgb(0 0 0 / 0.17);
--curve-on: color-mix(in srgb, var(--link) 62%, transparent);
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:root { --shade: rgb(0 0 0 / 0.6); } :root {
--shade: rgb(0 0 0 / 0.6);
--pane-rule: #3a3a3a;
--curve: rgb(255 255 255 / 0.16);
--curve-on: color-mix(in srgb, var(--link) 62%, transparent);
}
} }
.view-panes .page { .view-panes .page {
position: fixed; top: 0; left: 0; right: 0; bottom: 1.75rem; position: fixed; top: 0; left: 0; right: 0; bottom: 1.75rem;
@@ -342,22 +353,30 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
} }
.view-panes.with-panel .page { right: min(440px, 92vw); } .view-panes.with-panel .page { right: min(440px, 92vw); }
.view-panes .banner { flex: none; width: auto; margin: 0; } .view-panes .banner { flex: none; width: auto; margin: 0; }
.panes { flex: 1; min-height: 0; display: flex; position: relative; }
.strip { .strip {
flex: 1; min-height: 0; display: flex; overflow-x: auto; overflow-y: hidden; flex: 1; min-width: 0; display: flex; overflow-x: auto; overflow-y: hidden;
overscroll-behavior-x: contain; scrollbar-width: thin; scrollbar-color: var(--rule) transparent; overscroll-behavior-x: contain; scrollbar-width: thin; scrollbar-color: var(--rule) transparent;
} }
.pane { position: sticky; flex: none; width: var(--pane); width: round(down, var(--pane), 1px); height: 100%; background: var(--bg); border-left: 1px solid var(--hair); } .col { position: sticky; flex: none; width: var(--pane); width: round(down, var(--pane), 1px); height: 100%; display: flex; flex-direction: column; background: var(--bg); }
.strip > .pane:first-child { border-left-color: transparent; } .col.split { overflow-y: auto; scrollbar-width: none; }
.pane[data-over] { border-left-color: var(--rule); box-shadow: -14px 0 20px -12px var(--shade); } .pane { position: relative; flex: none; width: 100%; height: 100%; overflow: hidden; color: var(--fg); background: var(--bg); border-right: 1px solid var(--pane-rule); border-bottom: 1px solid var(--pane-rule); }
.col.split > .pane { height: auto; flex: 1 1 0; min-height: 0; }
.strip[data-flush] .pane:last-child { border-bottom-color: transparent; }
.col[data-over] { box-shadow: -14px 0 20px -12px var(--shade); }
.col[data-over]::before { content: ""; position: absolute; z-index: 4; top: 0; bottom: 0; left: 0; width: 1px; background: var(--rule); }
.pane-scroll { .pane-scroll {
height: 100%; overflow-x: hidden; overflow-y: auto; padding: 1.9rem var(--pane-pad) 30vh var(--spine); height: 100%; overflow-x: hidden; overflow-y: auto; padding: 1.9rem var(--pane-pad) 30vh var(--spine);
scrollbar-width: thin; scrollbar-color: var(--hair) transparent; scrollbar-width: thin; scrollbar-color: var(--hair) transparent;
} }
/* In a shared column a pane is only as tall as its text needs, so it scrolls no further than its end. */
.col.split .pane-scroll { padding-bottom: 1.4rem; }
/* The spine: a covered pane's title, set vertically in the left gutter. */ /* The spine: a covered pane's title, set vertically in the left gutter. */
.spine { position: absolute; top: 0; bottom: 0; left: 0; width: var(--spine); z-index: 2; background: var(--bg); opacity: 0; pointer-events: none; cursor: pointer; transition: opacity 0.12s; } .spine { position: absolute; top: 0; bottom: 0; left: 0; width: var(--spine); z-index: 2; background: inherit; opacity: 0; pointer-events: none; cursor: pointer; transition: opacity 0.12s; }
.pane[data-covered] .spine { opacity: 1; pointer-events: auto; } .col[data-covered] .spine { opacity: 1; pointer-events: auto; }
.spine span { .spine .pane-btn { position: absolute; top: 0.3rem; left: 50%; margin-left: -0.65rem; }
.spine-title {
display: block; max-height: 100%; padding: 1.95rem 0 1.2rem; writing-mode: vertical-rl; line-height: var(--spine); display: block; max-height: 100%; padding: 1.95rem 0 1.2rem; writing-mode: vertical-rl; line-height: var(--spine);
font-family: var(--sans); font-size: 0.74rem; letter-spacing: 0.03em; color: var(--dim); font-family: var(--sans); font-size: 0.74rem; letter-spacing: 0.03em; color: var(--dim);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
@@ -367,6 +386,41 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.spine { transition: none; } .spine { transition: none; }
} }
/* A folded pane: one line, its title (and W for an article), its pin and ×; a click opens it. */
.tabline {
display: none; align-items: center; gap: 0.4em; height: 100%; padding: 0 3.4rem 0 var(--spine); cursor: pointer;
font-family: var(--sans); font-size: 0.74rem; letter-spacing: 0.02em; color: var(--dim); white-space: nowrap;
}
.tabline .tabtitle { overflow: hidden; text-overflow: ellipsis; }
.tabline:hover { color: var(--fg); }
.pane[data-tab] > .tabline { display: flex; }
.pane[data-tab] > .pane-scroll, .pane[data-tab] > .spine { display: none; }
/* A pane's pin and ×, top right, in the margin above its title: quiet until pointed at. A pinned pane's pin is filled. */
.pane-ctl { position: absolute; z-index: 3; top: 0.25rem; right: 0.3rem; display: flex; gap: 0.05rem; }
.pane[data-tab] > .pane-ctl { top: 2px; }
.pane-btn { display: block; width: 1.3rem; height: 1.3rem; padding: 0.3rem; border-radius: 2px; cursor: pointer; color: var(--rule); }
.pane-btn svg { display: block; width: 100%; height: 100%; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
.pane:hover .pane-btn { color: var(--faint); }
.pane .pane-btn:hover { color: var(--fg); background: var(--sel); }
.pane-btn.pin.on { color: var(--fg); }
.pane-btn.pin.on svg { fill: currentColor; }
/*
* The active pane, where the keys act: a heavy rule across its top, as gwern sets a heading's;
* the other panes on the focused branch, a hairline in the text's colour. The status line's mode
* badge is set in the same ink.
*/
.pane::after { content: ""; position: absolute; z-index: 3; top: 0; left: 0; right: 0; height: 0; background: var(--fg); pointer-events: none; }
.pane.active::after { height: 3px; }
.pane.on-branch:not(.active)::after { height: 1px; background: var(--faint); }
/* The curves: from what each pane was opened from to its title, behind nothing but in the gaps between lines. */
.curves { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 2; pointer-events: none; overflow: hidden; }
.curves path { fill: none; stroke: var(--curve); stroke-width: 1; }
.curves path.on { stroke: var(--curve-on); }
.curves path.lost { stroke-dasharray: 1 3; }
/* A pane's head: a section heading, smaller than the page title the first pane keeps. */ /* A pane's head: a section heading, smaller than the page title the first pane keeps. */
.pane-head { display: flex; align-items: baseline; gap: 0.6em; margin: 0 0 0.85rem; padding-bottom: 0.3rem; border-bottom: 1px solid var(--faint); cursor: pointer; } .pane-head { display: flex; align-items: baseline; gap: 0.6em; margin: 0 0 0.85rem; padding-bottom: 0.3rem; border-bottom: 1px solid var(--faint); cursor: pointer; }
.pane-head.focused { border-bottom-color: var(--fg); } .pane-head.focused { border-bottom-color: var(--fg); }
@@ -381,25 +435,6 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.node.showing > .row .mark { color: var(--fg); } .node.showing > .row .mark { color: var(--fg); }
.node.showing > .row::after { content: "→"; flex: none; margin-left: auto; padding-left: 0.8em; font-family: var(--sans); font-size: 0.72em; color: var(--dim); } .node.showing > .row::after { content: "→"; flex: none; margin-left: auto; padding-left: 0.8em; font-family: var(--sans); font-size: 0.72em; color: var(--dim); }
/*
* Forks (src/ui/forks.ts): right of a pane with several children, one row per fork, top to bottom
* in the order they were opened, divided by a line; a row holds its fork's panes and perhaps a
* stack of rows of its own. Rows share the strip's height down to --row-min each (a stack needs a
* row's worth per fork at its far right, --leaves); past that the strip scrolls down, and a pane
* with forks stays at the top while its rows go by. Sideways the strip scrolls as one, so a fork's
* pane is always in the column next to the pane it came from.
*/
.strip.forked { overflow-y: auto; overscroll-behavior-y: contain; }
.forks { flex: none; display: flex; flex-direction: column; min-height: calc(var(--row-min) * var(--leaves)); }
.fork { flex: 1 1 0; display: flex; min-height: calc(var(--row-min) * var(--leaves)); }
.fork + .fork { border-top: 1px solid var(--rule); }
/* The line is drawn on the row's panes too: a pane slid sideways over the row's edge would cover it. */
.fork + .fork .pane { border-top: 1px solid var(--rule); }
/* The focused fork: its first pane's left edge in the text's colour. */
.fork.on > .pane:first-child { border-left-color: var(--fg); }
.strip.forked .pane { height: auto; max-height: var(--strip-h); top: 0; }
/* A row's height is only known after the rows are laid out, so a pane's own scroller is fitted to the pane rather than sized by percent. */
.strip.forked .pane-scroll { position: absolute; inset: 0; height: auto; padding-bottom: min(30vh, calc(var(--row-min) / 2)); }
/* What each fork was opened from, in the pane it came from: the focused fork's row, words or link marked as before, the others lightly. */ /* What each fork was opened from, in the pane it came from: the focused fork's row, words or link marked as before, the others lightly. */
.node.forked > .row::after, .wrow.forked > .row::after { content: "→"; flex: none; margin-left: auto; padding-left: 0.8em; font-family: var(--sans); font-size: 0.72em; color: var(--faint); } .node.forked > .row::after, .wrow.forked > .row::after { content: "→"; flex: none; margin-left: auto; padding-left: 0.8em; font-family: var(--sans); font-size: 0.72em; color: var(--faint); }
.wrow.forked > .row:has(.wnum)::after { margin-left: 0.5em; } .wrow.forked > .row:has(.wnum)::after { margin-left: 0.5em; }
@@ -408,9 +443,8 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
:is(.lnk, .anchor, .wiki-text a).forked.picked { background-color: color-mix(in srgb, var(--link) 30%, transparent); } :is(.lnk, .anchor, .wiki-text a).forked.picked { background-color: color-mix(in srgb, var(--link) 30%, transparent); }
:is(.backlinks, .related-list) li.forked { box-shadow: inset 2px 0 0 var(--rule); } :is(.backlinks, .related-list) li.forked { box-shadow: inset 2px 0 0 var(--rule); }
:is(.backlinks, .related-list) li.forked.picked { box-shadow: inset 2px 0 0 var(--fg); } :is(.backlinks, .related-list) li.forked.picked { box-shadow: inset 2px 0 0 var(--fg); }
/* Where there is no room for rows only the focused branch is drawn; a pane that starts a fork says so. */ /* An orphan: a pinned pane whose source has closed. */
.fork-note { margin: -1.1rem 0 0.9rem; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.03em; color: var(--dim); } .orphan-note { text-transform: none; letter-spacing: 0.02em; font-style: italic; }
.fork-note kbd { font-size: 0.95em; }
/* The first pane keeps the page title, set from the left so it stays readable when the pane is partly covered. */ /* 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 .top h1, .pane.root .byline, .pane.doc .top h1, .pane.doc .byline { text-align: left; }
@@ -512,8 +546,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
* Its own ground, its own face (the bundled sans), a W at its head, its licence at its foot. * Its own ground, its own face (the bundled sans), a W at its head, its licence at its foot.
*/ */
.wiki { font-family: var(--sans); color: var(--soft); } .wiki { font-family: var(--sans); color: var(--soft); }
.wiki-pane .pane-scroll, .wiki-pane .spine { background: var(--wiki-bg); } .pane.wiki-pane { background: var(--wiki-bg); }
.wiki-pane { border-left-color: var(--wiki-rule); }
.wiki-pane .spine span { color: var(--dim); } .wiki-pane .spine span { color: var(--dim); }
.wiki-pane .spine .wmark { font-weight: 600; } .wiki-pane .spine .wmark { font-weight: 600; }
.wiki-head { margin: 0 0 0.8rem; padding-bottom: 0.35rem; border-bottom: 1px solid var(--wiki-rule); cursor: pointer; } .wiki-head { margin: 0 0 0.8rem; padding-bottom: 0.35rem; border-bottom: 1px solid var(--wiki-rule); cursor: pointer; }
+184 -136
View File
@@ -1,185 +1,233 @@
/** The panes view's tree of forks (src/ui/forks.ts): each operation, and any sequence of them leaving one well-formed tree with one focused branch. */ /** The panes view's forest of forks (src/ui/forks.ts): each operation, and any sequence of them leaving a well-formed forest with one focused branch and one active pane. */
import fc from "fast-check"; import fc from "fast-check";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { all, chain, closeAt, closeChild, closeRight, leaves, load, open, path, prune, restore, save, select, sibling, valid, withBranch, type Tree } from "../src/ui/forks"; import { all, besideInColumn, close, find, focus, focused, load, open, path, pin, plain, prune, restore, save, valid, withBranch, type Forest, type Tree } from "../src/ui/forks";
type F = Forest<string>;
type T = Tree<string>; type T = Tree<string>;
const same = (a: string, b: string) => a === b; const same = (a: string, b: string) => a === b;
const branch = (t: T | null) => path(t).map((n) => n.ref); const branch = (f: F) => path(focused(f)).map((n) => n.ref);
/** The tree drawn as nested lists, the picked child starred. */ /** A tree drawn as nested lists, the picked child starred, a pinned pane marked with a leading ^. */
const shape = (t: T | null): unknown => (t ? (t.kids.length ? [t.ref, t.kids.map((k, j) => (j === t.pick ? ["*", shape(k)] : shape(k)))] : t.ref) : null); const shape = (t: T | null): unknown => {
if (!t) return null;
const me = `${t.pinned ? "^" : ""}${t.ref}`;
return t.kids.length ? [me, t.kids.map((k, j) => (j === t.pick ? ["*", shape(k)] : shape(k)))] : me;
};
const shapes = (f: F) => f.trees.map((t) => (t.col ? [t.col, shape(t)] : shape(t)));
const idOf = (f: F, ref: string) => all(f).find((x) => x.node.ref === ref)!.node.id;
describe("forks", () => { describe("forks", () => {
it("a plain trail is a chain, and a plain open replaces what is right of the pane", () => { it("a plain trail is a chain, and a plain open replaces what is right of the pane", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "c"]);
expect(branch(t)).toEqual(["a", "b", "c"]); expect(branch(f)).toEqual(["a", "b", "c"]);
t = open(t, 0, "x", false, same); f = open(f, 0, "x", false, same);
expect(branch(t)).toEqual(["a", "x"]); expect(branch(f)).toEqual(["a", "x"]);
expect(t.kids).toHaveLength(1); expect(f.trees[0].kids).toHaveLength(1);
// Already there: nothing changes, and what is right of it stays. // Already there: nothing changes, and what is right of it stays.
const u = chain<string, unknown>(["a", "b", "c"])!; const u: F = plain(["a", "b", "c"]);
expect(open(u, 0, "b", false, same)).toBe(u); expect(open(u, 0, "b", false, same)).toBe(u);
}); });
it("a fork adds a child below the others and picks it; with no child it is a plain open", () => { it("a fork adds a child below the others and picks it; with no child it is a plain open", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "c"]);
t = open(t, 0, "x", true, same); f = open(f, 0, "x", true, same);
expect(shape(t)).toEqual(["a", [["b", [["*", "c"]]], ["*", "x"]]]); expect(shapes(f)).toEqual([["a", [["b", [["*", "c"]]], ["*", "x"]]]]);
expect(branch(t)).toEqual(["a", "x"]); f = open(f, 1, "y", true, same); // x has no child: a plain open
t = open(t, 1, "y", true, same); // x has no child: a plain open expect(branch(f)).toEqual(["a", "x", "y"]);
expect(branch(t)).toEqual(["a", "x", "y"]); f = open(f, 0, "z", true, same);
expect(t.kids[1].kids).toHaveLength(1); expect(f.trees[0].kids.map((k) => k.ref)).toEqual(["b", "x", "z"]);
t = open(t, 0, "z", true, same);
expect(t.kids.map((k) => k.ref)).toEqual(["b", "x", "z"]);
expect(leaves(t)).toBe(3);
}); });
it("opening what is already a fork of the pane picks that fork, plain or not, instead of a duplicate", () => { it("opening what is already a fork of the pane picks that fork, plain or not, instead of a duplicate", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "c"]);
t = open(t, 0, "x", true, same); f = open(f, 0, "x", true, same);
t = open(t, 0, "b", false, same); f = open(f, 0, "b", false, same);
expect(branch(t)).toEqual(["a", "b", "c"]); expect(branch(f)).toEqual(["a", "b", "c"]);
expect(t.kids.map((k) => k.ref)).toEqual(["b", "x"]); expect(f.trees[0].kids.map((k) => k.ref)).toEqual(["b", "x"]);
t = open(t, 0, "x", true, same); f = open(f, 0, "x", true, same);
expect(branch(t)).toEqual(["a", "x"]); expect(branch(f)).toEqual(["a", "x"]);
expect(t.kids).toHaveLength(2);
}); });
it("a plain open in a fork replaces only that fork", () => { it("a plain open beside a pinned pane forks instead of replacing it; pinned panes in what is replaced stay as orphans in their columns", () => {
let t = chain<string, unknown>(["a", "b"])!; let f: F = plain(["a", "b", "c", "d"]);
t = open(t, 0, "x", true, same); f = pin(f, idOf(f, "b"), true);
t = open(t, 0, "y", false, same); f = open(f, 0, "x", false, same);
expect(t.kids.map((k) => k.ref)).toEqual(["b", "y"]); expect(shapes(f)).toEqual([["a", [["^b", [["*", ["c", [["*", "d"]]]]]], ["*", "x"]]]]);
expect(branch(t)).toEqual(["a", "y"]); let g: F = plain(["a", "b", "c", "d"]);
g = pin(g, idOf(g, "c"), true);
g = open(g, 0, "x", false, same);
expect(shapes(g)).toEqual([["a", [["*", "x"]]], [2, ["^c", [["*", "d"]]]]]);
expect(branch(g)).toEqual(["a", "x"]);
}); });
it("moves to the fork above and below in the order rows are drawn, from the deepest pane with one", () => { it("closes a pane and what was opened from it; the one below (else above) takes its pick; the first pane stays", () => {
// a ─ b ─ b1 rows: b/b1, b/b2, c let f: F = plain(["a", "b", "c"]);
// └ b2 f = open(f, 0, "x", true, same);
// └ c f = open(f, 0, "y", true, same);
let t = chain<string, unknown>(["a", "b", "b1"])!; const active = idOf(f, "y");
t = open(t, 1, "b2", true, same); let r = close(f, active, active);
t = open(t, 0, "c", true, same); expect(r.forest.trees[0].kids.map((k) => k.ref)).toEqual(["b", "x"]);
expect(branch(t)).toEqual(["a", "c"]); expect(r.active).toBe(idOf(f, "a"));
let s = sibling(t, -1)!; expect(branch(r.forest)).toEqual(["a", "x"]);
expect(s.depth).toBe(1); // Closing a pane off the focused branch leaves the active pane as it is.
expect(branch(s.tree)).toEqual(["a", "b", "b2"]); // b remembers b2 was picked r = close(f, idOf(f, "b"), active);
s = sibling(s.tree, -1)!; expect(r.active).toBe(active);
expect(s.depth).toBe(2); expect(branch(r.forest)).toEqual(["a", "y"]);
expect(branch(s.tree)).toEqual(["a", "b", "b1"]); expect(shapes(r.forest)).toEqual([["a", ["x", ["*", "y"]]]]);
expect(sibling(s.tree, -1)).toBeNull(); // The first pane never closes.
s = sibling(s.tree, 1)!; expect(close(f, idOf(f, "a"), active).forest).toBe(f);
expect(branch(s.tree)).toEqual(["a", "b", "b2"]); // Deep in a fork, only that pane (the owner's bug: q closed the whole fork).
s = sibling(s.tree, 1)!; let g: F = plain(["a", "b"]);
expect(branch(s.tree)).toEqual(["a", "c"]); g = open(g, 0, "r", true, same);
expect(sibling(s.tree, 1)).toBeNull(); g = open(g, 1, "w1", false, same);
expect(sibling(chain<string, unknown>(["a", "b"])!, 1)).toBeNull(); g = open(g, 2, "w2", false, same);
r = close(g, idOf(g, "w2"), idOf(g, "w2"));
expect(branch(r.forest)).toEqual(["a", "r", "w1"]);
expect(r.active).toBe(idOf(g, "w1"));
}); });
it("closes a branch: right of a pane (every fork), a pane and what follows it, or one child", () => { it("a pinned pane outlives the pane it was opened from: an orphan in its column, with what it opened; closing it closes it", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "c", "d", "e"]);
t = open(t, 0, "x", true, same); f = pin(f, idOf(f, "d"), true);
t = open(t, 0, "y", true, same); const e = idOf(f, "e");
expect(branch(closeRight(t, 0))).toEqual(["a"]); let r = close(f, idOf(f, "b"), e);
// Close the focused fork (y, the last): the one above takes its place. expect(shapes(r.forest)).toEqual(["a", [3, ["^d", [["*", "e"]]]]]);
let u = closeAt(t, 1); // The active pane was inside the orphan: it stays active, its tree focused.
expect(u.kids.map((k) => k.ref)).toEqual(["b", "x"]); expect(r.active).toBe(e);
expect(branch(u)).toEqual(["a", "x"]); expect(r.forest.at).toBe(1);
// The middle one: the one below takes its place. expect(branch(r.forest)).toEqual(["d", "e"]);
u = closeAt(select(t, t.kids[1].id)!, 1); expect(valid(r.forest, same)).toBe(true);
expect(branch(u)).toEqual(["a", "y"]); // Closing the orphan's root closes it (its pin protects it from its parent, not from itself); the nearest pane of the tree before is active.
// Closing the last-but-one fork leaves a plain trail. const d = idOf(r.forest, "d");
u = closeAt(closeAt(t, 1), 1); const s = close(r.forest, d, e);
expect(shape(u)).toEqual(["a", [["*", ["b", [["*", "c"]]]]]]); expect(shapes(s.forest)).toEqual(["a"]);
// One child by what it shows, whichever fork it is; picks stay on the same pane. expect(s.active).toBe(idOf(f, "a"));
u = closeChild(t, 0, "b", same); expect(s.forest.at).toBe(0);
expect(u.kids.map((k) => k.ref)).toEqual(["x", "y"]);
expect(branch(u)).toEqual(["a", "y"]);
expect(closeChild(t, 0, "nope", same)).toBe(t);
expect(closeAt(t, 0)).toBe(t);
}); });
it("drops a deleted node's pane wherever it is, with what is right of it", () => { it("[ and ]: the pane above and below in a column, across forks and trees", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "b1"]);
t = open(t, 0, "x", true, same); f = open(f, 1, "b2", true, same);
t = open(t, 1, "gone", false, same); f = open(f, 0, "c", true, same);
t = open(t, 2, "after", false, same); f = open(f, 1, "c1", false, same);
expect(branch(t)).toEqual(["a", "x", "gone", "after"]); // Column 2 holds b1, b2, c1, in that order.
const p = prune(t, (r) => r !== "gone")!; expect(besideInColumn(f, idOf(f, "c1"), -1)).toBe(idOf(f, "b2"));
expect(branch(p)).toEqual(["a", "x"]); expect(besideInColumn(f, idOf(f, "b2"), -1)).toBe(idOf(f, "b1"));
expect(branch(select(p, p.kids[0].id))).toEqual(["a", "b", "c"]); expect(besideInColumn(f, idOf(f, "b1"), -1)).toBeNull();
// A deleted fork that is not focused goes without moving the branch. expect(besideInColumn(f, idOf(f, "c1"), 1)).toBeNull();
const q = prune(select(t, t.kids[0].id)!, (r) => r !== "x")!; expect(besideInColumn(f, idOf(f, "a"), 1)).toBeNull();
expect(branch(q)).toEqual(["a", "b", "c"]); const g = focus(f, idOf(f, "b1"));
expect(q.kids).toHaveLength(1); expect(branch(g)).toEqual(["a", "b", "b1"]);
// Nothing deleted: the same tree. expect(focus(g, idOf(f, "b1"))).toBe(g);
expect(prune(t, () => true)).toBe(t);
expect(prune(t, (r) => r !== "a")).toBeNull();
}); });
it("makes a path the branch, keeping the forks off it", () => { it("drops a deleted node's pane wherever it is, with what is right of it but pinned panes", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "c"]);
t = open(t, 0, "x", true, same); f = open(f, 0, "x", true, same);
let u = withBranch(t, ["a", "b", "d"], same)!; f = open(f, 1, "gone", false, same);
f = open(f, 2, "after", false, same);
expect(branch(f)).toEqual(["a", "x", "gone", "after"]);
expect(branch(prune(f, (r) => r !== "gone"))).toEqual(["a", "x"]);
expect(prune(f, () => true)).toBe(f);
const p = prune(pin(f, idOf(f, "after"), true), (r) => r !== "gone");
expect(shapes(p)).toEqual([["a", [["b", [["*", "c"]]], ["*", "x"]]], [3, "^after"]]);
});
it("makes a path the branch, keeping the forks off it and the pinned panes", () => {
let f: F = plain(["a", "b", "c"]);
f = open(f, 0, "x", true, same);
let u = withBranch(f, ["a", "b", "d"], same);
expect(branch(u)).toEqual(["a", "b", "d"]); expect(branch(u)).toEqual(["a", "b", "d"]);
expect(u.kids.map((k) => k.ref)).toEqual(["b", "x"]); expect(u.trees[0].kids.map((k) => k.ref)).toEqual(["b", "x"]);
u = withBranch(t, ["a", "x"], same)!; u = withBranch(f, ["a", "x"], same);
expect(u).toBe(t); expect(u).toBe(f);
expect(branch(withBranch(t, ["q", "r"], same))).toEqual(["q", "r"]); expect(branch(withBranch(f, ["q", "r"], same))).toEqual(["q", "r"]);
expect(branch(withBranch(t, ["a"], same))).toEqual(["a"]); expect(branch(withBranch(f, ["a"], same))).toEqual(["a"]);
// A pinned pane right of the list's end stays where it is.
let h: F = plain(["a", "b", "c"]);
h = pin(h, idOf(h, "c"), true);
expect(shapes(withBranch(h, ["a"], same))).toEqual(["a", [2, "^c"]]);
expect(shapes(withBranch(h, ["a", "b"], same))).toEqual([["a", [["*", ["b", [["*", "^c"]]]]]]]);
}); });
it("is stored without ids, and an old stored trail loads as a tree with one branch", () => { it("is stored without ids, pins and orphans kept; an old stored tree or trail loads", () => {
let t = chain<string, unknown>(["a", "b", "c"])!; let f: F = plain(["a", "b", "c"]);
t = open(t, 0, "x", true, same); f = open(f, 0, "x", true, same);
t = open(t, 1, "y", true, same); f = pin(f, idOf(f, "c"), true);
f = close(f, idOf(f, "b"), idOf(f, "x")).forest;
const isStr = (r: unknown): r is string => typeof r === "string"; const isStr = (r: unknown): r is string => typeof r === "string";
const back = load<string, unknown>(JSON.parse(JSON.stringify(save(t, (r) => r))), isStr); const stored = JSON.parse(JSON.stringify({ forest: f.trees.map((t) => save(t, (r) => r)), at: f.at }));
expect(shape(back)).toEqual(shape(t)); const back = restore<string, unknown>(stored, isStr);
expect(restore<string, unknown>(undefined, ["a", "b"], isStr)!.kids[0].ref).toBe("b"); expect(shapes(back)).toEqual(shapes(f));
expect(branch(restore<string, unknown>(undefined, ["a", "b"], isStr))).toEqual(["a", "b"]); expect(valid(back, same)).toBe(true);
expect(restore(undefined, [], isStr)).toBeNull(); expect(branch(restore<string, unknown>({ trail: ["a", "b"] }, isStr))).toEqual(["a", "b"]);
expect(shapes(restore<string, unknown>({ forks: { ref: "a", kids: [{ ref: "b" }, { ref: "c" }], pick: 1 } }, isStr))).toEqual([["a", ["b", ["*", "c"]]]]);
expect(restore({}, isStr).trees).toEqual([]);
// Junk is dropped, not trusted. // Junk is dropped, not trusted.
expect(load({ ref: "a", kids: [{ ref: 3 }, { ref: "b" }], pick: 9 }, isStr)!.kids.map((k) => k.ref)).toEqual(["b"]); expect(load({ ref: "a", kids: [{ ref: 3 }, { ref: "b" }], pick: 9 }, isStr)!.kids.map((k) => k.ref)).toEqual(["b"]);
expect(load({ ref: "a", kids: [{ ref: 3 }, { ref: "b" }], pick: 9 }, isStr)!.pick).toBe(0);
expect(load("nonsense", isStr)).toBeNull(); expect(load("nonsense", isStr)).toBeNull();
expect(restore<string, unknown>({ forest: [{ ref: "o", col: 2 }, { ref: "a" }], at: 7 }, isStr).trees.map((t) => t.ref)).toEqual(["a", "o"]);
}); });
it("any sequence of operations leaves a well-formed tree with exactly one focused branch", () => { it("any sequence of open, fork, close, pin, unpin and focus leaves a valid forest with exactly one active pane, and closing removes no pinned pane but the one closed", () => {
const refs = ["a", "b", "c", "d", "e"]; const refs = ["a", "b", "c", "d", "e"];
const op = fc.record({ kind: fc.integer({ min: 0, max: 8 }), i: fc.nat(6), r: fc.integer({ min: 0, max: refs.length - 1 }), d: fc.boolean() }); const op = fc.record({ kind: fc.integer({ min: 0, max: 8 }), i: fc.nat(40), r: fc.integer({ min: 0, max: refs.length - 1 }), d: fc.boolean() });
fc.assert( fc.assert(
fc.property(fc.array(op, { maxLength: 60 }), (ops) => { fc.property(fc.array(op, { maxLength: 60 }), (ops) => {
let t: T | null = chain<string, unknown>(["root"]); let f: F = plain(["root"]);
// The active pane, by id: on the focused branch.
let active = f.trees[0].id;
for (const o of ops) { for (const o of ops) {
if (!t) t = chain<string, unknown>(["root"])!; const p = path(focused(f));
const depth = path(t).length; const i = Math.max(0, p.findIndex((n) => n.id === active));
const i = o.i % depth; const panes = all(f);
const r = refs[o.r]; const any = panes[o.i % panes.length].node;
switch (o.kind) { switch (o.kind) {
case 0: t = open(t, i, r, false, same); break; case 0:
case 1: t = open(t, i, r, true, same); break; case 1:
case 2: t = sibling(t, o.d ? 1 : -1)?.tree ?? t; break; f = open(f, i, refs[o.r], o.kind === 1, same);
case 3: t = closeRight(t, i); break; active = path(focused(f))[Math.min(i + 1, path(focused(f)).length - 1)].id;
case 4: t = closeAt(t, i); break; break;
case 5: t = closeChild(t, i, r, same); break; case 2:
case 6: t = prune(t, (x) => x !== r); break; case 3: {
case 7: { const pinned = new Set(all(f).filter((x) => x.node.pinned && x.node.id !== any.id).map((x) => x.node.id));
const nodes = all(t); const r = close(f, any.id, active);
t = select(t, nodes[o.i % nodes.length].node.id) ?? t; f = r.forest;
active = r.active;
const left = new Set(all(f).map((x) => x.node.id));
for (const id of pinned) if (!left.has(id)) return false;
break; break;
} }
case 8: t = withBranch(t, ["root", ...refs.slice(0, i)], same); break; case 4:
case 5:
f = pin(f, any.id, o.kind === 4);
break;
case 6:
f = focus(f, any.id);
active = any.id;
break;
case 7: {
const next = besideInColumn(f, active, o.d ? 1 : -1);
if (next !== null) (f = focus(f, next)), (active = next);
break;
} }
if (!valid(t, same)) return false; case 8:
// One branch, from the root to a pane with nothing right of it, each step a picked child. f = withBranch(f, ["root", ...refs.slice(0, o.i % 4)], same);
const p = path(t); active = f.trees[0].id;
if (t && (p[0] !== t || p[p.length - 1].kids.length !== 0)) return false; break;
for (let k = 1; k < p.length; k++) if (p[k - 1].kids[p[k - 1].pick] !== p[k]) return false; }
if (!valid(f, same)) return false;
// One branch, from the focused tree's root to a pane with nothing right of it, each step a picked child.
const b = path(focused(f));
if (!b.length || b[b.length - 1].kids.length) return false;
for (let k = 1; k < b.length; k++) if (b[k - 1].kids[b[k - 1].pick] !== b[k]) return false;
// Exactly one active pane: it is open, once, and on the focused branch.
if (all(f).filter((x) => x.node.id === active).length !== 1 || !b.some((n) => n.id === active)) return false;
if (!find(f, active) || f.trees[0].ref !== "root") return false;
} }
return true; return true;
}), }),
{ numRuns: 400 }, { numRuns: 500 },
); );
}); });
}); });
+52
View File
@@ -0,0 +1,52 @@
/** Lanes for the panes view's curves (src/ui/lanes.ts): the order crosses least, and stays put. */
import fc from "fast-check";
import { describe, expect, it } from "vitest";
import { crossings, laneOrder, LANES } from "../src/ui/lanes";
const e = (key: string, sy: number, ey: number) => ({ key, sy, ey });
const keys = (o: { key: string }[]) => o.map((x) => x.key);
/** The fewest crossings any order has. */
const least = <T extends { sy: number; ey: number }>(es: T[]): number => {
if (es.length < 2) return 0;
let best = Infinity;
const go = (left: T[], done: T[]) => {
if (!left.length) best = Math.min(best, crossings(done));
left.forEach((x, i) => go([...left.slice(0, i), ...left.slice(i + 1)], [...done, x]));
};
go(es, []);
return best;
};
describe("lanes", () => {
it("fit the gutter: seven at a 4 px pitch", () => {
expect(LANES).toBe(7);
});
it("rows fanning out to panes stacked below them do not cross: the one with least to go nearest the panes", () => {
// Three rows 35 px apart, opening three panes stacked down the next column.
const rows = [e("a", 300, 100), e("b", 335, 400), e("c", 370, 700)];
const o = laneOrder(rows);
expect(crossings(o)).toBe(0);
// The owner's screenshot: two rows to panes above them, and a link above them to a pane far below, whose run passes both sources (two crossings no order avoids).
const shot = [e("complex", 319, 73), e("shared", 354, 307), e("archaea", 140, 592)];
expect(crossings(laneOrder(shot))).toBe(least(shot));
});
it("never does worse than the rule it starts from, and keeps the last order unless a swap removes a crossing", () => {
fc.assert(
fc.property(fc.array(fc.tuple(fc.integer({ min: 0, max: 1000 }), fc.integer({ min: 0, max: 1000 })), { minLength: 1, maxLength: 9 }), (ys) => {
const es = ys.map(([a, b], i) => e(String(i), a, b));
const o = laneOrder(es);
const again = laneOrder(es, keys(o));
return o.length === es.length && new Set(keys(o)).size === es.length && keys(again).join() === keys(o).join() && (es.length > 6 || crossings(o) <= least(es) + 1);
}),
);
// A small scroll that changes no crossing keeps the lanes as they were.
const before = laneOrder([e("a", 300, 100), e("b", 335, 400), e("c", 370, 700)]);
const after = laneOrder([e("a", 290, 100), e("b", 325, 400), e("c", 360, 700)], keys(before));
expect(keys(after)).toEqual(keys(before));
// A new curve goes where the rule puts it; the others keep their order.
const more = laneOrder([e("a", 300, 100), e("b", 335, 400), e("c", 370, 700), e("d", 500, 520)], keys(before));
expect(keys(more).filter((k) => k !== "d")).toEqual(keys(before));
});
});