Panes open beside by default; columns stack as the strip does; peek and drag

Enter, l and a click (a Ctrl-, Cmd- or middle click too) open into the next
column beside what is there; Shift+Enter and a Shift-click open in place of the
focused branch's pane there. Opening what is open focuses it; a second Enter on
an open row keeps it. A document from the menu or /open still opens in place.

A crowded column now stacks its panes the way the strip stacks columns, by the
same code (stack.ts): each pane stuck a tab below the one before, the one looked
at whole, the others slid under it, partly and at the limit down to a tab, a
pinned one never covered. What is covered down to its strip is not painted.

The mouse resting on a covered pane, tab or spine peeks it out over its
neighbours; a click makes it the active pane. A pane's grip, the band above its
title, or its tab drags it up or down its column (Esc cancels).

Curves from words start at the end of their underline. Curves keep their
elements and are drawn on a layer of their own, so a change repaints only what
moved; with many curves in a gutter, lanes are ordered by swapping neighbours.

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 01:40:24 -05:00
1 parent 7a2df56440
commit 3789255147
13 files changed
+783 -254

No files matched your search

+219 -58
View File
@@ -1,8 +1,9 @@
/** /**
* Forks in the panes view, laid out by column: a modified open (Shift+Enter, Shift-, Ctrl- or * Forks in the panes view, laid out by column: an open (Enter, a click, a Ctrl-, Cmd- or middle
* middle-click) opens its pane below what is in the next column instead of replacing it; column d * click) puts its pane below what is in the next column; Shift+Enter or a Shift-click opens it in
* holds every pane at depth d and divides its own height among them, folding all but one into tabs * place of the focused branch's pane there. Column d holds every pane at depth d and divides its
* when they do not fit. Curves run from where each pane was opened to its title; panes close (q, ×) * own height among them; when they do not fit it stacks them as the strip stacks columns, covering
* all but the pane looked at, partly and then down to a tab. 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; * 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. * the documents are hoisted to (z) as in panes.spec.ts.
*/ */
@@ -33,7 +34,8 @@ const boxes = (page: Page) =>
Object.fromEntries( Object.fromEntries(
[...document.querySelectorAll<HTMLElement>(".strip .pane")].map((p) => { [...document.querySelectorAll<HTMLElement>(".strip .pane")].map((p) => {
const r = p.getBoundingClientRect(); 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") }]; const c = p.parentElement!.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-covered"), whole: r.top >= c.top - 2 && r.bottom <= c.bottom + 2 && !p.nextElementSibling?.hasAttribute("data-over") }];
}), }),
), ),
); );
@@ -57,14 +59,14 @@ const curves = (page: Page) =>
}); });
const tid = (page: Page, title: string) => pane(page, title).evaluate((el) => Number((el as HTMLElement).dataset.tid)); 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)))); 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. */ /** Wait until the strip and its columns have stopped scrolling (the strip follows the focus smoothly, columns other than the active pane's once the keys pause), and the curves have been drawn after. */
async function still(page: Page) { async function still(page: Page) {
await page.waitForFunction( await page.waitForFunction(
() => () =>
new Promise((r) => { new Promise((r) => {
const el = document.querySelector(".strip")!; const at = () => [document.querySelector(".strip")!, ...document.querySelectorAll(".strip > .col")].map((el) => `${el.scrollLeft},${el.scrollTop}`).join();
const x = el.scrollLeft; const x = at();
setTimeout(() => r(el.scrollLeft === x), 300); setTimeout(() => r(at() === x), 300);
}), }),
); );
await nextFrames(page); await nextFrames(page);
@@ -100,8 +102,8 @@ async function cells(page: Page) {
await expect(pane(page, "Eukaryote").locator(".wiki-text a[data-wiki]").first()).toBeVisible(); 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 pane(page, "Eukaryote").locator('.wiki-text a[data-wiki="Bacteria"]').first().click();
await expect(pane(page, "Bacteria").locator(".wiki-text").first()).toBeVisible(); 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: "Simple cells" }).first().click();
await page.locator(".pane .row", { hasText: "Complex cells" }).first().click({ modifiers: ["Shift"] }); await page.locator(".pane .row", { hasText: "Complex cells" }).first().click();
await expect.poll(() => columns(page)).toEqual([["Library"], ["The one merger"], ["Two kinds of cell"], ["Eukaryote", "Simple cells", "Complex cells"], ["Bacteria"]]); await expect.poll(() => columns(page)).toEqual([["Library"], ["The one merger"], ["Two kinds of cell"], ["Eukaryote", "Simple cells", "Complex cells"], ["Bacteria"]]);
await still(page); await still(page);
} }
@@ -117,14 +119,14 @@ test.beforeEach(async ({ context }) => {
}); });
test.afterEach(({ page }) => settle(page)); test.afterEach(({ page }) => settle(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 }) => { test("Enter on a section row opens its pane below in the next column; Shift+Enter in place of the focused one; Enter on one open focuses it", 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 one pane per column. // Nothing to the right yet: a plain trail is one pane per column.
await keys(page, "Shift+Enter"); await keys(page, "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"]]]]]]);
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node"]]); expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node"]]);
await keys(page, "j Shift+Enter"); await keys(page, "j Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["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"]);
// They share the column's height, one above the other, beside the pane they came from. // They share the column's height, one above the other, beside the pane they came from.
@@ -138,44 +140,87 @@ test("Shift+Enter on a section row opens a fork below in the next column; Enter
// 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(pane(page, "Expansion by depth").locator(".node.showing > .row")).toHaveText([/Pre-generated depth/]); await expect(pane(page, "Expansion by depth").locator(".node.showing > .row")).toHaveText([/Pre-generated depth/]);
await expect(pane(page, "Expansion by depth").locator(".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. // Shift+Enter opens in place of the focused one.
await keys(page, "j Enter"); await keys(page, "j Shift+Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["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 pane already open focuses it: no second copy, and nothing closes.
await keys(page, "k k Enter"); await keys(page, "k k Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["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, "Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]);
await keys(page, "j j Shift+Enter"); await keys(page, "j j Shift+Enter");
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]); expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]);
}); });
test("Shift-, Ctrl- and middle-click fork from section rows; a click in another fork makes it the focused one", async ({ page }) => { test("a click, a Ctrl- and a middle click open beside; a Shift-click in place; a click in another fork makes it the focused one", async ({ page }) => {
await open(page); await open(page);
const kids = await childTitles(page, "Borrowed from Gwern"); const kids = await childTitles(page, "Borrowed from Gwern");
expect(kids.length).toBeGreaterThanOrEqual(3); expect(kids.length).toBeGreaterThanOrEqual(3);
const row = (t: string) => page.locator(".pane .row", { hasText: t }).first(); const row = (t: string) => page.locator(".pane .row", { hasText: t }).first();
await row("Borrowed from Gwern").click(); await row("Borrowed from Gwern").click();
await row(kids[0]).click({ modifiers: ["Shift"] }); // nothing right of it yet: a plain open await row(kids[0]).click();
expect(await trail(page)).toEqual(["Infinispand", "Borrowed from Gwern", kids[0]]); expect(await trail(page)).toEqual(["Infinispand", "Borrowed from Gwern", kids[0]]);
await row(kids[1]).click({ modifiers: ["Control"] }); await row(kids[1]).click({ modifiers: ["Control"] });
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Borrowed from Gwern", [kids[0], ["*", kids[1]]]]]]]); expect(await tree(page)).toEqual(["Infinispand", [["*", ["Borrowed from Gwern", [kids[0], ["*", kids[1]]]]]]]);
await row(kids[2]).click({ button: "middle" }); await row(kids[2]).click({ button: "middle" });
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.
expect(await page.evaluate(() => window.getSelection()?.isCollapsed ?? true)).toBe(true);
// A click on the first fork's heading focuses that fork, and makes that pane the active one. // A click on the first fork's heading focuses that fork, and makes that pane the active one.
await pane(page, kids[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(".pane.active .pane-head h2")).toHaveText(kids[0]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[0]);
// The first pane forks too: its forks share the next column, and the panes opened from each the one after. // The first pane's rows too: beside, in the next column; and a click on a row already open keeps it.
await row("Display forms").click({ modifiers: ["Shift"] }); await row("Display forms").click();
expect(await columns(page)).toEqual([["Infinispand"], ["Borrowed from Gwern", "Display forms"], kids.slice(0, 3)]); expect(await columns(page)).toEqual([["Infinispand"], ["Borrowed from Gwern", "Display forms"], kids.slice(0, 3)]);
await row("Display forms").click({ modifiers: ["Shift"] }); await row("Display forms").click();
expect((await columns(page))[1]).toEqual(["Borrowed from Gwern", "Display forms"]); expect((await columns(page))[1]).toEqual(["Borrowed from Gwern", "Display forms"]);
await row("Editing and regeneration").click(); // A Shift-click opens in place of the focused one (Display forms), and selects no text on the way.
await row("Editing and regeneration").click({ modifiers: ["Shift"] });
expect(await trail(page)).toEqual(["Infinispand", "Editing and regeneration"]); expect(await trail(page)).toEqual(["Infinispand", "Editing and regeneration"]);
expect((await columns(page))[1]).toEqual(["Borrowed from Gwern", "Editing and regeneration"]); expect((await columns(page))[1]).toEqual(["Borrowed from Gwern", "Editing and regeneration"]);
expect(await page.evaluate(() => window.getSelection()?.isCollapsed ?? true)).toBe(true);
});
test("a link and an article's link open beside by default, in place with Shift; twenty opens stay usable", 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");
await tabTo(page, "fixed-point combinator");
await keys(page, "Enter");
await keys(page, "h");
await tabTo(page, "Y combinator");
await keys(page, "Enter");
expect((await columns(page))[3]).toEqual(["Fixed-point combinator", "How Y works"]);
await keys(page, "h");
await tabTo(page, "lambda calculus");
await keys(page, "Shift+Enter");
expect((await columns(page))[3]).toEqual(["Fixed-point combinator", "“lambda calculus”"]); // a note on the words, with the article beneath
// In an article: a click opens beside, a Shift-click in place.
const art = pane(page, "Fixed-point combinator");
await art.locator('.wiki-text a[data-wiki="Haskell Curry"]').click();
await art.locator('.wiki-text a[data-wiki="Recursion (computer science)"]').click();
expect((await columns(page))[4]).toEqual(["Haskell Curry", "Recursion (computer science)"]);
await art.locator('.wiki-text a[data-wiki="Lambda calculus"]').first().click({ modifiers: ["Shift"] });
expect((await columns(page))[4]).toEqual(["Haskell Curry", "Lambda calculus"]);
// Twenty opens in a row: each a pane of its own, the column stacked, the keys still quick.
await open(page);
await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0));
const paced = async (seq: string) => {
for (const k of seq.split(" ")) {
await page.keyboard.press(k);
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null))));
}
};
await paced("l l l");
for (let i = 0; i < 20; i++) await paced(i % 4 === 3 ? "k k Enter" : "j Enter");
await paced("[ [ [ ] ] ] l h j k");
expect((await state(page, (s) => s.forest.trees[0].kids[0].kids.length)) as number).toBeGreaterThanOrEqual(3);
const ms = (await state(page, (s) => s.samples.map((x: any) => x.ms))).sort((a: number, b: number) => a - b);
const p95 = ms[Math.floor(ms.length * 0.95)];
console.log("twenty opens keypress → paint (ms):", JSON.stringify({ n: ms.length, median: ms[ms.length >> 1], p95 }));
expect(p95).toBeLessThan(50);
}); });
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 }) => { 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 }) => {
@@ -247,6 +292,12 @@ test("a curve per open edge, from where each pane was opened to its title; it fo
expect(p.y).toBeLessThan(r.y + r.height + 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(".lnk", { hasText: "Eukaryotes" }), edge("Two kinds of cell", "Eukaryote")[0].a);
// From words, the curve starts at the right end of their underline (a short step joins it to the lead-out in the gap below).
const link = (await kinds.locator(".lnk", { hasText: "Eukaryotes" }).first().boundingBox())!;
const start = edge("Two kinds of cell", "Eukaryote")[0].a;
expect(Math.abs(start.x - (link.x + link.width))).toBeLessThan(2);
expect(start.y).toBeGreaterThan(link.y + link.height - 9);
expect(start.y).toBeLessThan(link.y + link.height);
await nearIn(kinds.locator(".node.forked > .row", { hasText: "Simple cells" }), edge("Two kinds of cell", "Simple cells")[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(); const title = (t: string) => pane(page, t).locator(".wiki-head h2, .pane-head h2").first();
for (const t of ["Eukaryote", "Simple cells", "Complex cells"]) { for (const t of ["Eukaryote", "Simple cells", "Complex cells"]) {
@@ -296,6 +347,30 @@ test("a curve per open edge, from where each pane was opened to its title; it fo
await expect.poll(async () => (await curves(page)).length).toBeGreaterThan(3); await expect.poll(async () => (await curves(page)).length).toBeGreaterThan(3);
}); });
test("curves down one gutter take lanes of their own, side by side, up to as many as fit; the rest share the outermost", async ({ page }) => {
await page.goto("/");
await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready);
// Ten documents opened from the library: ten curves down the gutter into column 1.
for (let i = 0; i < 10; i++) await keys(page, "j Enter");
await still(page);
const runs = await page.evaluate(() =>
[...document.querySelectorAll<SVGPathElement>(".curves path")].map((p) => {
const v = /C[^C]*?([\d.]+) [\d.]+V/.exec(p.getAttribute("d")!);
return { lane: Number(p.dataset.lane), x: v ? Number(v[1]) : NaN };
}),
);
expect(runs).toHaveLength(10);
const lanes = await page.evaluate(() => 7);
const xs = new Set(runs.map((r) => r.x));
expect(xs.size).toBe(lanes);
// Each lane a pitch from the next.
const sorted = [...xs].sort((a, b) => a - b);
for (let i = 1; i < sorted.length; i++) expect(sorted[i] - sorted[i - 1]).toBeCloseTo(4, 0);
// Beyond the lanes, the rest share the outermost (the last).
expect(runs.filter((r) => r.lane === lanes - 1).length).toBe(10 - lanes + 1);
});
test("exactly one pane is active, under a heavy rule; the rest of the focused branch under a hairline", async ({ page }) => { test("exactly one pane is active, under a heavy rule; the rest of the focused branch under a hairline", async ({ page }) => {
await cells(page); await cells(page);
const marks = () => const marks = () =>
@@ -323,25 +398,32 @@ test("exactly one pane is active, under a heavy rule; the rest of the focused br
/** Five sections of the first pane, opened side by side: five panes in column 1. */ /** Five sections of the first pane, opened side by side: five panes in column 1. */
async function five(page: Page) { async function five(page: Page) {
await open(page); await open(page);
await keys(page, "j Shift+Enter j Shift+Enter j Shift+Enter j Shift+Enter j Shift+Enter"); await keys(page, "j Enter j Enter j Enter j Enter j Enter");
const kids = (await childTitles(page, "Infinispand")).slice(0, 5); const kids = (await childTitles(page, "Infinispand")).slice(0, 5);
expect((await columns(page))[1]).toEqual(kids); expect((await columns(page))[1]).toEqual(kids);
await still(page);
return 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 }) => { test("a crowded column stacks its panes as the strip stacks columns: covered partly, then to a tab; moving the focus there, or a click on a tab, shows it whole", async ({ page }) => {
const kids = await five(page); const kids = await five(page);
const strip = await page.locator(".strip").evaluate((el) => el.clientHeight); const col = page.locator(".strip > .col").nth(1);
await expect(col).toHaveClass(/crowded/);
const top = (await col.boundingBox())!.y;
let b = await boxes(page); 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. // The focused fork (the last) is whole; the ones before it are stuck a tab apart, the first covered down to its tab.
expect(kids.slice(0, 4).every((t) => b[t].tab)).toBe(true); expect(b[kids[4]].whole).toBe(true);
expect(b[kids[4]].tab).toBe(false); // Each stuck no higher than a tab below the one before; the first covered down to its tab.
expect(Math.abs(b[kids[4]].h - (strip - 4 * 30))).toBeLessThan(2); for (let i = 0; i < 4; i++) expect(b[kids[i]].y).toBeGreaterThanOrEqual(top + i * 30 - 1);
for (let i = 1; i < 5; i++) expect(b[kids[i]].y).toBeCloseTo(b[kids[i - 1]].y + b[kids[i - 1]].h, 0); expect(b[kids[0]].y).toBeCloseTo(top, 0);
await expect(pane(page, kids[0]).locator(".tabline .tabtitle")).toHaveText(kids[0]); expect(b[kids[0]].tab).toBe(true);
for (let i = 1; i < 5; i++) expect(b[kids[i]].y).toBeGreaterThan(b[kids[i - 1]].y);
await expect(pane(page, kids[0]).locator(".tabline")).toBeVisible(); await expect(pane(page, kids[0]).locator(".tabline")).toBeVisible();
await expect(pane(page, kids[0]).locator(".tabline .tabtitle")).toHaveText(kids[0]);
await expect(pane(page, kids[0]).locator(".pane-ctl .pane-btn.close")).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. // Its content is still there under the panes over it, clipped: the same pane, not a separate tab.
expect(await pane(page, kids[0]).locator(".pane-scroll").evaluate((el) => getComputedStyle(el).display)).not.toBe("none");
// l steps into the focused fork's pane; [ moves up the column: that pane is whole, the one below slid partly out of view.
await keys(page, "l"); await keys(page, "l");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]);
const where = await focusedTitle(page); const where = await focusedTitle(page);
@@ -349,35 +431,114 @@ test("a column with more panes than fit folds all but the focused one into tabs;
expect(await trail(page)).toEqual(["Infinispand", kids[3]]); expect(await trail(page)).toEqual(["Infinispand", kids[3]]);
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[3]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[3]);
b = await boxes(page); b = await boxes(page);
expect(b[kids[3]].tab).toBe(false); expect(b[kids[3]].whole).toBe(true);
expect(b[kids[4]].tab).toBe(true); expect(b[kids[4]].whole).toBe(false);
const bottom = top + (await col.evaluate((el) => el.clientHeight));
expect(b[kids[4]].y).toBeLessThan(bottom);
// ] comes back down, to where the focus was. // ] comes back down, to where the focus was.
await keys(page, "]"); await keys(page, "]");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]);
expect(await focusedTitle(page)).toBe(where); expect(await focusedTitle(page)).toBe(where);
await keys(page, "]"); await keys(page, "]");
await expect(page.locator(".status .message")).toContainText("No pane below"); await expect(page.locator(".status .message")).toContainText("No pane below");
// A click on a tab opens that pane and makes it the active one. // A click on a tab makes that pane the active one, whole.
await pane(page, kids[1]).locator(".tabline").click(); await pane(page, kids[0]).locator(".tabline").click();
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[1]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[0]);
b = await boxes(page); b = await boxes(page);
expect(b[kids[1]].tab).toBe(false); expect(b[kids[0]].whole).toBe(true);
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 }) => { test("a pane resting covered peeks out under the mouse, over its neighbours without moving them; a click makes it active", async ({ page }) => {
const kids = await five(page);
const before = await boxes(page);
const tab = pane(page, kids[1]).locator(".tabline");
await tab.hover();
// Not at once: passing the mouse across does not flicker.
expect(await pane(page, kids[1]).getAttribute("data-peek")).toBeNull();
await expect(pane(page, kids[1])).toHaveAttribute("data-peek", "");
const peeked = (await pane(page, kids[1]).boundingBox())!;
expect(peeked.height).toBeGreaterThan(100);
expect(await pane(page, kids[1]).evaluate((el) => Number(getComputedStyle(el).zIndex))).toBeGreaterThan(2);
// Nothing else moved.
const after = await boxes(page);
for (const t of kids) if (t !== kids[1]) expect(after[t].y).toBeCloseTo(before[t].y, 0);
// Leaving puts it back.
await page.mouse.move(5, 500);
await expect(pane(page, kids[1])).not.toHaveAttribute("data-peek", "");
// A click on it makes it the active pane, whole.
await tab.hover();
await expect(pane(page, kids[1])).toHaveAttribute("data-peek", "");
await pane(page, kids[1]).locator(".pane-head").click();
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[1]);
expect((await boxes(page))[kids[1]].whole).toBe(true);
// A column covered across the strip peeks too, raised over the columns past it.
await page.setViewportSize({ width: 1600, height: 1000 });
await page.evaluate(() => localStorage.clear());
await open(page);
await keys(page, "l l l j j l l l");
await expect.poll(async () => (await columns(page)).length).toBe(4);
await expect.poll(() => page.evaluate(() => document.querySelectorAll(".strip > .col")[0].hasAttribute("data-covered"))).toBe(true);
await page.locator(".strip > .col").nth(0).locator(".spine-title").hover();
await expect(page.locator(".strip > .col").nth(0)).toHaveAttribute("data-peek", "");
});
test("a pane is dragged by its grip, or its tab, up or down its column; the order is kept, and Esc cancels", async ({ page }) => {
const kids = await five(page);
// Five panes: the column shares out its height once the window is tall enough.
await page.setViewportSize({ width: 1920, height: 1800 });
await expect.poll(() => page.locator(".strip > .col").nth(1).getAttribute("class")).not.toContain("crowded");
const drag = async (from: string, to: string, esc = false) => {
const g = (await pane(page, from).locator(".grip").boundingBox())!;
const t = (await pane(page, to).boundingBox())!;
await page.mouse.move(g.x + g.width / 2, g.y + g.height / 2);
await page.mouse.down();
await page.mouse.move(g.x + g.width / 2, g.y + 20, { steps: 3 });
await page.mouse.move(g.x + g.width / 2, t.y + 8, { steps: 6 });
await expect(page.locator(".drop-line")).toHaveCount(1);
if (esc) await page.keyboard.press("Escape");
await page.mouse.up();
};
// The grip shows only under the mouse.
expect(await pane(page, kids[4]).locator(".grip").evaluate((el) => getComputedStyle(el, "::before").opacity)).toBe("0");
await drag(kids[4], kids[0]);
expect((await columns(page))[1]).toEqual([kids[4], ...kids.slice(0, 4)]);
await expect(page.locator(".drop-line")).toHaveCount(0);
// Esc cancels.
await drag(kids[2], kids[0], true);
expect((await columns(page))[1]).toEqual([kids[4], ...kids.slice(0, 4)]);
// [ and ] go by the new order; curves follow.
await page.reload();
await page.waitForSelector(".strip .pane");
expect((await columns(page))[1]).toEqual([kids[4], ...kids.slice(0, 4)]);
// And by its tab, in a crowded column.
await page.setViewportSize({ width: 1920, height: 1080 });
await expect.poll(() => page.locator(".strip > .col").nth(1).getAttribute("class")).toContain("crowded");
const t = (await pane(page, kids[0]).locator(".tabline").boundingBox().catch(() => null)) ?? null;
if (t && (await pane(page, kids[0]).getAttribute("data-covered")) !== null) {
const last = (await pane(page, kids[3]).boundingBox())!;
await page.mouse.move(t.x + 200, t.y + t.height / 2);
await page.mouse.down();
await page.mouse.move(t.x + 200, t.y + 30, { steps: 3 });
await page.mouse.move(t.x + 200, last.y + last.height - 4, { steps: 8 });
await page.mouse.up();
expect((await columns(page))[1].indexOf(kids[0])).toBeGreaterThan(1);
}
});
test("a pinned pane is not covered in its column, and outlives a closed parent as an orphan in its column", async ({ page }) => {
const kids = await five(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. // 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 pane(page, kids[1]).locator(".pane-ctl .pane-btn.pin").click();
await expect(pane(page, kids[1])).toHaveClass(/pinned/); await expect(pane(page, kids[1])).toHaveClass(/pinned/);
let b = await boxes(page); let b = await boxes(page);
expect(b[kids[1]].tab).toBe(false); expect(b[kids[1]].whole).toBe(true);
expect(b[kids[1]].h).toBeGreaterThan(200); expect(b[kids[1]].h).toBeGreaterThan(200);
await keys(page, "l [ ["); await keys(page, "l [ [");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[2]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[2]);
b = await boxes(page); b = await boxes(page);
expect(b[kids[1]].tab).toBe(false); expect(b[kids[1]].whole).toBe(true);
expect(b[kids[4]].tab).toBe(true); expect(b[kids[2]].whole).toBe(true);
expect(b[kids[4]].whole).toBe(false);
// The pin is kept across a reload. // The pin is kept across a reload.
await page.reload(); await page.reload();
await page.waitForSelector(".strip .pane"); await page.waitForSelector(".strip .pane");
@@ -465,7 +626,7 @@ test("q on an article opened from an article in a fork closes that article only
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await jump(page, "Recursion without names"); await jump(page, "Recursion without names");
// A fork beside it from the document's pane: Recursion without names starts a fork. // A fork beside it from the document's pane: Recursion without names starts a fork.
await keys(page, "k Enter j Shift+Enter"); await keys(page, "k Enter j Enter");
expect((await trail(page)).at(-1)).toBe("Recursion without names"); expect((await trail(page)).at(-1)).toBe("Recursion without names");
await tabTo(page, "fixed-point combinator"); await tabTo(page, "fixed-point combinator");
await keys(page, "Enter"); await keys(page, "Enter");
@@ -490,7 +651,7 @@ test("from a Wikipedia link, a node link and a link inside an article: forks, ea
await keys(page, "h"); // back to the words await keys(page, "h"); // back to the words
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, "Enter");
expect((await columns(page))[3]).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"]');
@@ -504,9 +665,9 @@ test("from a Wikipedia link, a node link and a link inside an article: forks, ea
await expect(from.locator(".lnk.forked.picked")).toHaveText("fixed-point combinator"); await expect(from.locator(".lnk.forked.picked")).toHaveText("fixed-point combinator");
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 click on a link in the article's text opens beside that section.
const art = pane(page, "Fixed-point combinator"); 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();
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]]]]]]);
@@ -522,10 +683,10 @@ test("a fork whose node is deleted closes, and the others stay", async ({ page,
const made = await request.post("/api/ops", { data: { author: "another", message: "Add a section", ops: [{ op: "create", parent: depth, title: "A section to delete", body: "Soon gone." }] } }); const made = await request.post("/api/ops", { data: { author: "another", message: "Add a section", ops: [{ op: "create", parent: depth, title: "A section to delete", body: "Soon gone." }] } });
expect(made.ok()).toBe(true); expect(made.ok()).toBe(true);
await open(page); await open(page);
await keys(page, "l l l Shift+Enter"); await keys(page, "l l l Enter");
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 Enter");
expect((await columns(page))[2]).toEqual(["Levels of a node", "A section to delete"]); expect((await columns(page))[2]).toEqual(["Levels of a node", "A section to delete"]);
await page.locator(".pane .row", { hasText: "Levels of a node" }).first().click(); 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);
@@ -535,10 +696,10 @@ test("a fork whose node is deleted closes, and the others stay", async ({ page,
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 to share a column folds it at once: the focused pane open, the others tabs", async ({ page }) => { test("a window too short to share a column stacks it at once: the focused pane whole, the other covered to its tab", 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 Enter j Enter");
let b = await boxes(page); let b = await boxes(page);
expect(b["Levels of a node"].tab).toBe(true); expect(b["Levels of a node"].tab).toBe(true);
expect(b["Pre-generated depth"].tab).toBe(false); expect(b["Pre-generated depth"].tab).toBe(false);
@@ -551,8 +712,8 @@ test("a window too short to share a column folds it at once: the focused pane op
test("many forks: a reload brings the forest back", async ({ page }) => { test("many forks: a reload brings the forest back", async ({ page }) => {
await open(page); await open(page);
await keys(page, "j Shift+Enter"); await keys(page, "j Enter");
for (let i = 0; i < 5; i++) await keys(page, "j Shift+Enter"); for (let i = 0; i < 5; i++) await keys(page, "j Enter");
expect((await columns(page))[1]).toHaveLength(6); expect((await columns(page))[1]).toHaveLength(6);
const before = await tree(page); const before = await tree(page);
const was = await trail(page); const was = await trail(page);
@@ -563,7 +724,7 @@ test("many forks: a reload brings the forest back", async ({ page }) => {
expect((await columns(page))[1]).toHaveLength(6); 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 Shift open is a plain open, and the status line says why once", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 }); await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/doc/fixed-points"); await page.goto("/doc/fixed-points");
await page.waitForFunction(() => (globalThis as any).__ie?.ready); await page.waitForFunction(() => (globalThis as any).__ie?.ready);
+14 -15
View File
@@ -155,7 +155,7 @@ test("panes: Tab and Enter open an article in the next pane; its sections open a
expect(await selected(page)).toBe("fixed-point combinator"); expect(await selected(page)).toBe("fixed-point combinator");
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator", "W:Fixed-point combinator#2", "W:Lambda calculus"]); expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator", "W:Fixed-point combinator#2", "W:Lambda calculus"]);
await expect(panes(page)).toHaveCount(6); await expect(panes(page)).toHaveCount(6);
// Opening something else from an earlier pane replaces what is to its right. // Opening something else from an earlier pane opens it beside what is to its right.
await tabTo(page, "lambda calculus"); await tabTo(page, "lambda calculus");
await keys(page, "Enter"); await keys(page, "Enter");
expect((await trail(page)).slice(3)).toEqual(["lambda calculus"]); expect((await trail(page)).slice(3)).toEqual(["lambda calculus"]);
@@ -167,13 +167,12 @@ test("panes: Tab and Enter open an article in the next pane; its sections open a
expect(req.url()).toBe("https://en.wikipedia.org/wiki/Fixed-point_combinator"); expect(req.url()).toBe("https://en.wikipedia.org/wiki/Fixed-point_combinator");
for (const p of page.context().pages()) if (p !== page) await p.close(); for (const p of page.context().pages()) if (p !== page) await p.close();
// Spines of covered article panes carry the W and the tint. // Spines of covered article panes carry the W and the tint.
await keys(page, "j j l l Tab Enter"); await page.locator('.pane.active .wiki-text a[data-wiki="Lambda calculus"]').first().click();
await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Lambda calculus"); await expect(page.locator(".pane.active .wiki-head h2")).toHaveText("Lambda calculus");
// (Tab also stops on notes the library keeps on the article, if an earlier test wrote one.) await page.locator('.pane.active .wiki-text a[data-wiki="Alonzo Church"]').first().click();
await expect(panes(page).last().locator(".wiki-text a[data-wiki]").first()).toBeVisible(); await expect(page.locator(".pane.active .wiki-head h2")).toHaveText("Alonzo Church");
for (let i = 0; i < 4 && (await state(page, (s) => s.selectedText())) !== "Alonzo Church"; i++) await keys(page, "Tab"); await page.locator('.pane.active .wiki-text a[data-wiki="Lambda calculus"]').first().click();
await keys(page, "Enter"); await expect(page.locator(".pane.active .wiki-head h2")).toHaveText("Lambda calculus");
await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Alonzo Church");
const spine = page.locator(".col[data-covered] .wiki-pane .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));
@@ -388,30 +387,30 @@ test("a disambiguation page lists its senses as rows; a missing article, an unre
await keys(page, "i i"); await keys(page, "i i");
await command(page, "/link w:Mercury"); await command(page, "/link w:Mercury");
await keys(page, "Enter"); await keys(page, "Enter");
const art = page.locator(".wiki-pane").last(); const art = page.locator(".wiki-pane.active");
await expect(art.locator(".senses h3")).toContainText("may refer to"); await expect(art.locator(".senses h3")).toContainText("may refer to");
await expect(art.locator(".sense .title")).toHaveText(["Mercury (planet)", "Mercury (element)", "Mercury (mythology)", "Freddie Mercury"]); await expect(art.locator(".sense .title")).toHaveText(["Mercury (planet)", "Mercury (element)", "Mercury (mythology)", "Freddie Mercury"]);
await keys(page, "j l"); await keys(page, "j l");
await expect(page.locator(".wiki-pane").last().locator(".wiki-head h2")).toHaveText("Mercury (planet)"); await expect(page.locator(".wiki-pane.active").locator(".wiki-head h2")).toHaveText("Mercury (planet)");
await expect(page.locator(".wiki-pane").last().locator(".wattr")).toBeVisible(); await expect(page.locator(".wiki-pane.active").locator(".wattr")).toBeVisible();
for (const [title, says] of [["No such article zzz", "No article"], ["Offline example", "could not be reached"]]) { for (const [title, says] of [["No such article zzz", "No article"], ["Offline example", "could not be reached"]]) {
await keys(page, "h h h"); await keys(page, "h h h");
await command(page, `/link w:${title}`); await command(page, `/link w:${title}`);
await keys(page, "Enter"); await keys(page, "Enter");
await expect(page.locator(".wiki-pane").last().locator(".wiki-problem")).toContainText(says); await expect(page.locator(".wiki-pane.active").locator(".wiki-problem")).toContainText(says);
} }
// Refused or slow, Wikipedia gets a plain message, and the reader is told once (only once) how to make it fast. // Refused or slow, Wikipedia gets a plain message, and the reader is told once (only once) how to make it fast.
await keys(page, "h h h"); await keys(page, "h h h");
await command(page, "/link w:Rate limited example"); await command(page, "/link w:Rate limited example");
await keys(page, "Enter"); await keys(page, "Enter");
await expect(page.locator(".wiki-pane").last().locator(".wiki-problem")).toContainText("fewer requests"); await expect(page.locator(".wiki-pane.active").locator(".wiki-problem")).toContainText("fewer requests");
await expect(page.locator(".status .message")).toContainText("IE_WIKI_CONTACT"); await expect(page.locator(".status .message")).toContainText("IE_WIKI_CONTACT");
expect(await page.evaluate(() => localStorage.getItem("ie:wiki-hint"))).toBe("true"); expect(await page.evaluate(() => localStorage.getItem("ie:wiki-hint"))).toBe("true");
await keys(page, "h h h"); await keys(page, "h h h");
await command(page, "/link w:Slow article"); await command(page, "/link w:Slow article");
await keys(page, "Enter"); await keys(page, "Enter");
await expect(page.locator(".wiki-pane").last().locator(".wiki-wait")).toContainText("Loading"); await expect(page.locator(".wiki-pane.active").locator(".wiki-wait")).toContainText("Loading");
await expect(page.locator(".wiki-pane").last().locator(".wiki-head h2")).toHaveText("Slow article", { timeout: 10_000 }); await expect(page.locator(".wiki-pane.active").locator(".wiki-head h2")).toHaveText("Slow article", { timeout: 10_000 });
await expect(page.locator(".status .message")).not.toContainText("IE_WIKI_CONTACT"); await expect(page.locator(".status .message")).not.toContainText("IE_WIKI_CONTACT");
await keys(page, "h h h"); await keys(page, "h h h");
await command(page, "/unlink"); await command(page, "/unlink");
+14 -11
View File
@@ -41,11 +41,11 @@ test("the library is the first pane, and a document opens in the next; reload an
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
expect(await paneTitles(page)).toEqual(["Library", "Infinispand"]); expect(await paneTitles(page)).toEqual(["Library", "Infinispand"]);
await expect(page.locator(".pane.doc .abstract.seed.folded")).toBeVisible(); await expect(page.locator(".pane.doc .abstract.seed.folded")).toBeVisible();
await keys(page, "j l"); // the next document: its pane replaces the first one's await keys(page, "j l"); // the next document: its pane opens beside the first one's, below it in the same column
expect(await paneTitles(page)).toEqual(["Library", "A mind made of text"]); expect(await paneTitles(page)).toEqual(["Library", "Infinispand", "A mind made of text"]);
await keys(page, "l l"); // into its first section, and open that await keys(page, "l l"); // into its first section, and open that
const third = await paneTitles(page); const third = await paneTitles(page);
expect(third).toHaveLength(3); expect(third).toHaveLength(4);
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");
@@ -54,12 +54,13 @@ test("the library is the first pane, and a document opens in the next; reload an
await page.keyboard.press("m"); await page.keyboard.press("m");
await page.keyboard.type("tides"); await page.keyboard.type("tides");
await page.keyboard.press("Enter"); await page.keyboard.press("Enter");
expect(await paneTitles(page)).toEqual(["Library", "The tides"]); // From the menu a document opens in place of the one open, not beside it.
expect(await paneTitles(page)).toEqual(["Library", "Infinispand", "The tides"]);
await expect(page).toHaveURL(/\/doc\/tides$/); await expect(page).toHaveURL(/\/doc\/tides$/);
await page.goBack(); await page.goBack();
await expect.poll(() => paneTitles(page)).toEqual(third); await expect.poll(() => paneTitles(page)).toEqual(third);
await page.goForward(); await page.goForward();
await expect.poll(() => paneTitles(page)).toEqual(["Library", "The tides"]); await expect.poll(() => paneTitles(page)).toEqual(["Library", "Infinispand", "The tides"]);
}); });
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 }) => {
@@ -144,9 +145,9 @@ test("j and k move among siblings, and the strip follows", async ({ page }) => {
expect(await focusedTitle(page)).toBe("Levels of a node"); expect(await focusedTitle(page)).toBe("Levels of a node");
await keys(page, "j j j j j j"); await keys(page, "j j j j j j");
expect(await focusedTitle(page)).toBe("Deeper, not longer"); expect(await focusedTitle(page)).toBe("Deeper, not longer");
// A click on a row does what l does: focus it and show its pane. // A click on a row does what l does: focus it and show its pane, beside the one already open there.
await page.locator(".pane .row", { hasText: "Generation on demand" }).click(); await page.locator(".pane .row", { hasText: "Generation on demand" }).click();
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]); expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth", "Generation on demand"]);
expect(await focusedTitle(page)).toBe("Generation on demand"); expect(await focusedTitle(page)).toBe("Generation on demand");
}); });
@@ -179,11 +180,13 @@ test("in panes everything is reachable with the mouse: rows, headings, marked sp
await expect(page.locator(".pane .anchor.on")).toHaveCount(1); await expect(page.locator(".pane .anchor.on")).toHaveCount(1);
await anchor.click(); await anchor.click();
await expect(page.locator(".pane .anchor.on")).toHaveCount(0); await expect(page.locator(".pane .anchor.on")).toHaveCount(0);
// A pane's heading focuses its node, leaving the trail as it is; a click on the focused row whose pane is showing closes that pane. // A pane's heading focuses its node, leaving the trail as it is; a click on the focused row whose pane is showing keeps it; its x closes it.
await page.locator(".pane-head", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane-head", { hasText: "Borrowed from Gwern" }).click();
expect(await focusedTitle(page)).toBe("Borrowed from Gwern"); expect(await focusedTitle(page)).toBe("Borrowed from Gwern");
expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]); expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]);
await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click();
expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]);
await page.locator('.pane[data-pane-index="1"] .pane-ctl .pane-btn.close').click();
expect(await paneTitles(page)).toEqual(["Infinispand"]); expect(await paneTitles(page)).toEqual(["Infinispand"]);
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();
@@ -243,9 +246,9 @@ test("generation in a pane: a note on a sentence streams in; a leaf gets section
await idle(page); await idle(page);
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 pane of its own, at the end of the focused branch
await expect(page.locator(".strip .pane")).toHaveCount(5); await expect.poll(async () => (await state(page, (s) => s.snap.nodes[s.trail[s.trail.length - 1].id]?.title))).toBe("First part of Downward: rendered children");
expect((await paneTitles(page)).at(-1)).toBe("First part of Downward: rendered children"); expect(await paneTitles(page)).toContain("First part of Downward: rendered children");
}); });
test("editing in a pane: c, type, Esc", async ({ page }) => { test("editing in a pane: c, type, Esc", async ({ page }) => {
+3 -1
View File
@@ -107,10 +107,12 @@ test("a library of over 5,000 nodes in 100 more documents: keypress → paint an
const panes = stats(await keySamples(page)); const panes = stats(await keySamples(page));
// ---- forks: four documents opened side by side from the library pane, each three panes deep (document, part, leaf) ---- // ---- forks: four documents opened side by side from the library pane, each three panes deep (document, part, leaf) ----
// A fresh view: the panes opened above stay open (opens go beside), and would be restored here.
await page.evaluate(() => localStorage.clear());
await page.goto("/doc/scale-document-90"); await page.goto("/doc/scale-document-90");
await ready(page); await ready(page);
await paced(page, "l l l l"); await paced(page, "l l l l");
for (let d = 1; d < 4; d++) await paced(page, "h h j Shift+Enter l l l l"); for (let d = 1; d < 4; d++) await paced(page, "h h j Enter l l l l");
await idle(page); await idle(page);
// The twelve panes' Related lists are fetched as they are first drawn: let them arrive, so what is timed is moving between forks. // The twelve panes' Related lists are fetched as they are first drawn: let them arrive, so what is timed is moving between forks.
await page.waitForTimeout(1000); await page.waitForTimeout(1000);
+4 -9
View File
@@ -507,8 +507,8 @@ export function App() {
if (!store.ready) return <div class="loading">Loading…</div>; if (!store.ready) return <div class="loading">Loading…</div>;
const panes = store.panes; const panes = store.panes;
// Shift-, Ctrl- or Cmd-click (and a middle click) opens a fork: beside what is open, not instead of it. // A click opens beside what is open (so do Ctrl-, Cmd- and middle clicks); a Shift-click in its place.
const onClick = (e: MouseEvent) => store.withFork(e.shiftKey || e.ctrlKey || e.metaKey || e.button === 1, () => click(e)); const onClick = (e: MouseEvent) => store.withReplace(e.shiftKey, () => click(e));
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;
@@ -588,7 +588,7 @@ export function App() {
return; return;
} }
// A drag selection inside one body becomes the focus range. // A drag selection inside one body becomes the focus range.
if (selection && !selection.isCollapsed && !store.forking) { if (selection && !selection.isCollapsed && !store.replacing) {
const a = locate(selection.anchorNode, selection.anchorOffset); const a = locate(selection.anchorNode, selection.anchorOffset);
const b = locate(selection.focusNode, selection.focusOffset); const b = locate(selection.focusNode, selection.focusOffset);
if (a && b && a.id === b.id && a.at !== b.at) { if (a && b && a.id === b.id && a.at !== b.at) {
@@ -626,12 +626,7 @@ export function App() {
if (row) { if (row) {
const id = row.dataset.row as NodeId; const id = row.dataset.row as NodeId;
if (panes && id !== store.top) { if (panes && id !== store.top) {
// In panes a click shows the row's pane: focus it and open it next. On the focused row whose pane is showing, it closes that pane. // In panes a click shows the row's pane: focus it and open it next (or focus it where it is open).
const next = store.trail[paneIndex + 1];
if (!store.forking && store.focus.node === id && store.focus.grain === "node" && next?.kind === "node" && next.id === id) {
store.closeRow(paneIndex, id);
return;
}
store.paneAt = paneIndex; store.paneAt = paneIndex;
store.go(id); store.go(id);
store.open.add(id); store.open.add(id);
+3 -3
View File
@@ -117,7 +117,7 @@ export function DocsPanel() {
e.preventDefault(); e.preventDefault();
// The selection as it is now: the filter may have changed since this was drawn. // The selection as it is now: the filter may have changed since this was drawn.
const now = store.menuSelected(); const now = store.menuSelected();
if (now) store.openDoc(now.node); if (now) store.openDoc(now.node, true);
} else if (k === "Escape" || k === "Tab") { } else if (k === "Escape" || k === "Tab") {
e.preventDefault(); e.preventDefault();
m.focus = "list"; m.focus = "list";
@@ -161,7 +161,7 @@ export function DocsPanel() {
(document.activeElement as HTMLElement | null)?.blur(); (document.activeElement as HTMLElement | null)?.blur();
store.emit(); store.emit();
}} }}
onDblClick={() => store.openDoc(d.node)} onDblClick={() => store.openDoc(d.node, true)}
> >
<div class="line"> <div class="line">
<span class="title">{d.title || "Untitled"}</span> <span class="title">{d.title || "Untitled"}</span>
@@ -170,7 +170,7 @@ export function DocsPanel() {
<div class="sub">{d.excerpt || "No text yet."}</div> <div class="sub">{d.excerpt || "No text yet."}</div>
{selected && ( {selected && (
<div class="actions"> <div class="actions">
{d.node !== current && <button onClick={act(() => store.openDoc(d.node))}>open</button>} {d.node !== current && <button onClick={act(() => store.openDoc(d.node, true))}>open</button>}
<button onClick={act(() => store.menuPrompt("rename"))}>rename</button> <button onClick={act(() => store.menuPrompt("rename"))}>rename</button>
<button onClick={act(() => store.menuPrompt("duplicate"))}>save as</button> <button onClick={act(() => store.menuPrompt("duplicate"))}>save as</button>
<button onClick={act(() => store.exportDocument(d.node))}>export .md</button> <button onClick={act(() => store.exportDocument(d.node))}>export .md</button>
+284 -107
View File
@@ -18,11 +18,11 @@
import { Component, type ComponentChildren } from "preact"; import { Component, type ComponentChildren } from "preact";
import { useEffect, useLayoutEffect, useRef } 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 type { Placed } from "./forks";
import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes"; import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes";
import { ACROSS, DOWN, mark, offsets, reveal, starts, stick, unmark, whole } from "./stack";
import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links"; import { 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 { kidClass, refKey, store, type Aux, type Back, type Pane as PaneNode, type PaneRef } from "./store"; import { kidClass, refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store";
import { WikiView } from "./Wiki"; import { WikiView } from "./Wiki";
import { article } from "./wiki"; import { article } from "./wiki";
@@ -93,6 +93,7 @@ function Chrome({ props, title, mark }: { props: PaneProps; title: string; mark?
{title} {title}
</span> </span>
</div> </div>
<div class="grip" data-grip={tid} title="Drag to move this pane up or down its column" />
<div class="tabline" data-spine={props.index} title={title}> <div class="tabline" data-spine={props.index} title={title}>
{mark} {mark}
<span class="tabtitle">{title}</span> <span class="tabtitle">{title}</span>
@@ -226,10 +227,12 @@ 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 pane keeps in a column while all its panes fit; below it, the column folds all but one into tabs. */ /** The least height a pane keeps in a column while all its panes fit; below it, the column stacks them. */
export const PANE_MIN = 260; export const PANE_MIN = 260;
/** A folded pane's tab. */ /** A covered pane's tab, the strip a pane leaves down a crowded column (as a spine does across). */
export const TAB = 30; export const TAB = 30;
/** How long the mouse rests on a covered pane before it peeks out. */
export const PEEK_MS = 200;
/** /**
* Heights for the panes of one column of height h, from what each needs to show all it holds: * Heights for the panes of one column of height h, from what each needs to show all it holds:
@@ -257,22 +260,22 @@ const paneEls = (el: HTMLElement) => {
const kidsKey = (t: PaneNode) => `${t.pick}:${t.kids.map((k) => refKey(k.ref)).join(",")}`; 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 strip = useRef<HTMLDivElement>(null); const strip = useRef<HTMLDivElement>(null);
const svg = useRef<SVGSVGElement>(null); const svg = useRef<SVGSVGElement>(null);
const followed = useRef(""); const followed = useRef("");
/** Per column, the pane last on the focused branch there: the one a folded column keeps open when the branch is elsewhere. */ /** Per column, the pane last on the focused branch there: the one a crowded column shows whole when the branch is elsewhere. */
const lastIn = useRef(new Map<number, number>()); const lastIn = useRef(new Map<number, number>());
/** 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. */ /** Each column's sticky left edge, in px, as last set. */
const lefts = useRef<number[]>([]); const lefts = useRef<number[]>([]);
const frame = useRef(0); const frame = useRef(0);
/** A pending layout of the columns other than the active pane's. */ /** A pending reveal in the columns other than the active pane's. */
const later = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const later = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
/** What each pane last needed to show all it holds. */
const needs = useRef(new Map<number, number>());
/** The pane each crowded column was last scrolled to show whole. */
const shown = useRef(new Map<HTMLElement, number>());
/** Each column's panes when last laid out. */ /** Each column's panes when last laid out. */
const laid = useRef(new Map<HTMLElement, string>()); const laid = useRef(new Map<HTMLElement, string>());
/** The layout of the latest render (a pending one uses it). */ /** The layout of the latest render (a pending one uses it). */
@@ -280,21 +283,18 @@ export function Panes() {
/** The active pane's column when the strip last followed it. */ /** The active pane's column when the strip last followed it. */
const lastCol = useRef(-1); const lastCol = useRef(-1);
const placed = store.panesPlaced;
const branch = store.branchNodes; const branch = store.branchNodes;
const onBranch = new Set(branch.map((n) => n.id)); const onBranch = new Set(branch.map((n) => n.id));
const activeId = branch[store.paneAt]?.id; const activeId = branch[store.paneAt]?.id;
const cols = new Map<number, Spot[]>(); const cols = store.paneColumns;
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); const order = [...cols.keys()].sort((a, b) => a - b);
/** /**
* Lay out the columns: each column's sticky left edge (every column before it leaves a spine, or * Lay out the stacks (stack.ts). Across: each column stuck a spine after the one before (a pinned
* the whole of a pinned pane's column), and the heights of the panes in each column with several. * pane's column, its whole width). Down: a column with several panes divides its height among
* them, a pane taking what its text needs; when they do not all fit, it becomes a stack of its
* own, each pane stuck a tab below the one before (a pinned one, its height) and the column
* scrolled to show whole the pane on the focused branch, or the one last on it there.
*/ */
const layout = (all = false) => { const layout = (all = false) => {
const el = strip.current; const el = strip.current;
@@ -305,103 +305,101 @@ export function Panes() {
const activeCol = activeId === undefined ? null : paneEls(el).get(activeId)?.parentElement; const activeCol = activeId === undefined ? null : paneEls(el).get(activeId)?.parentElement;
const w = colEls[0].offsetWidth; const w = colEls[0].offsetWidth;
const spine = colEls[0].querySelector<HTMLElement>(".spine")?.offsetWidth ?? 0; 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. // 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); setAttr(el, "data-flush", el.offsetHeight - el.clientHeight < 1);
let left = 0; lefts.current = offsets(
lefts.current = colEls.map((c, i) => { colEls.map(() => w),
// Far enough left that the columns after it can still all be scrolled to. colEls.map((c) => c.hasAttribute("data-pinned")),
const l = Math.round(Math.min(left, Math.max(i * spine, view - w - (n - 1 - i) * spine))); spine,
if (c.style.left !== `${l}px`) c.style.left = `${l}px`; el.clientWidth,
left += c.hasAttribute("data-pinned") ? w : spine; );
return l; stick(colEls, lefts.current, ACROSS);
}); let deferred = false;
for (const c of colEls) { for (const c of colEls) {
const ps = [...c.children] as HTMLElement[]; const ps = [...c.children].filter((p): p is HTMLElement => p.classList.contains("pane"));
if (ps.length < 2) { if (ps.length < 2) {
for (const p of ps) { for (const p of ps) if (p.style.height) (p.style.height = ""), (p.style.flex = ""), (p.style.top = "");
setAttr(p, "data-tab", false); c.classList.remove("crowded");
if (p.style.height) (p.style.height = ""), (p.style.flex = ""); unmark(ps);
}
continue; continue;
} }
const h = c.clientHeight; const h = c.clientHeight;
const col = Number(c.dataset.col); const col = Number(c.dataset.col);
const pad = (() => { const sc = ps[0].querySelector<HTMLElement>(".pane-scroll")!;
const s = ps.find((p) => !p.hasAttribute("data-tab"))?.querySelector<HTMLElement>(".pane-scroll"); const cs = getComputedStyle(sc);
if (!s) return 60; const pad = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + 1;
const cs = getComputedStyle(s);
return parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + 1;
})();
const tids = ps.map((p) => Number(p.dataset.tid)); const tids = ps.map((p) => Number(p.dataset.tid));
// What each pane needs to show all it holds; a buried pane is not laid out, so it keeps what it last needed.
const need = ps.map((p, i) => { const need = ps.map((p, i) => {
const body = p.hasAttribute("data-tab") ? null : p.querySelector<HTMLElement>(".pane-body"); if (p.hasAttribute("data-buried") && needs.current.has(tids[i])) return needs.current.get(tids[i])!;
if (body) needs.current.set(tids[i], body.offsetHeight + pad); const n = p.querySelector<HTMLElement>(".pane-body")!.offsetHeight + pad;
return needs.current.get(tids[i]) ?? PANE_MIN; needs.current.set(tids[i], n);
return n;
}); });
const pinned = ps.map((p) => p.classList.contains("pinned")); const pinned = ps.map((p) => p.classList.contains("pinned"));
const fits = need.reduce((s, x) => s + Math.min(x, PANE_MIN), 0) <= h; const crowded = need.reduce((s, x) => s + Math.min(x, PANE_MIN), 0) > h;
let heights: number[]; let heights: number[];
let tab: boolean[]; let tops: number[] = [];
if (fits) { if (!crowded) heights = fill(h, need);
tab = ps.map(() => false); else {
heights = fill(h, need); // Each pane what its text needs, up to the column less a tab for each other pane; a pinned one, at most a third of it, but its least.
} else { const pin = need.map((x, i) => (pinned[i] ? Math.min(x, Math.max(PANE_MIN, Math.floor(h / 3))) : 0));
// 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 free = h - pin.reduce((s, x) => s + x, 0) - (pinned.filter((x) => !x).length - 1) * TAB;
const here = tids.find((t) => onBranch.has(t)); heights = need.map((x, i) => (pinned[i] ? pin[i] : Math.min(x, Math.max(PANE_MIN, free))));
const keep = here ?? (tids.includes(lastIn.current.get(col)!) ? lastIn.current.get(col)! : tids[0]); tops = offsets(heights, pinned, TAB, h);
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. c.classList.toggle("crowded", crowded);
ps.forEach((p, i) => {
if (p.style.height !== `${heights[i]}px`) (p.style.height = `${heights[i]}px`), (p.style.flex = "none");
});
if (crowded) stick(ps, tops, DOWN);
else for (const p of ps) p.style.top = "";
// The pane to show whole: on the focused branch, or the one last on it here.
const here = tids.find((t) => onBranch.has(t)) ?? (tids.includes(lastIn.current.get(col)!) ? lastIn.current.get(col)! : tids[0]);
const k = tids.indexOf(here);
const st = starts(heights);
const want = crowded ? reveal(c.scrollTop, h, st[k], heights[k], tops[k], st[st.length - 1] + heights[heights.length - 1] - h) : 0;
// As the focus moves, the active pane's column scrolls at once and the others once the keys pause (each brings whole panes into view, which costs a frame's painting); any other change, at once.
const sig = tids.map((t, i) => `${t}${pinned[i] ? "^" : ""}`).join(); const sig = tids.map((t, i) => `${t}${pinned[i] ? "^" : ""}`).join();
const same = laid.current.get(c) === sig; const same = laid.current.get(c) === sig;
laid.current.set(c, sig); laid.current.set(c, sig);
if (!all && same && c !== activeCol && ps.some((p, i) => p.hasAttribute("data-tab") !== tab[i])) { const moved = shown.current.get(c) !== here;
later.current = setTimeout(() => { if (Math.abs(c.scrollTop - want) > 1 && !all && same && moved && c !== activeCol) deferred = true;
latest.current(true); else {
schedule(); if (Math.abs(c.scrollTop - want) > 1) c.scrollTop = want;
}, 150); shown.current.set(c, here);
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");
});
} }
if (deferred)
later.current = setTimeout(() => {
latest.current(true);
measure();
schedule();
}, 150);
// The focused branch's panes, marked without redrawing them. // 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 [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); for (const [col, ps] of cols) for (const x of ps) if (onBranch.has(x.node.id)) lastIn.current.set(col, x.node.id);
}; };
/** /**
* Mark how far each column is covered by the next. Any overlap gives the column above a shadow * Mark how far each item is covered by the next, across the strip and down each crowded column
* edge (data-over); once too little of it is left to read its own heading, its panes show as * (stack.ts): an overlapped item gives the one over it a shadow edge (data-over); one with too
* spines with their titles (data-covered). * little left to read its heading shows its spine or tab (data-covered).
*/ */
const measure = () => { const measure = () => {
const el = strip.current; const el = strip.current;
if (!el) return; if (!el) return;
const colEls = el.querySelectorAll<HTMLElement>(":scope > .col"); const colEls = [...el.querySelectorAll<HTMLElement>(":scope > .col")];
if (!colEls.length) return; mark(el, colEls, ACROSS, false, colEls[0]?.querySelector<HTMLElement>(".spine")?.offsetWidth ?? 0);
const w = colEls[0].offsetWidth; for (const c of colEls) if (c.classList.contains("crowded")) mark(c, [...c.querySelectorAll<HTMLElement>(":scope > .pane")], DOWN, true, TAB);
const xs = [...colEls].map((c) => c.getBoundingClientRect().left);
colEls.forEach((c, i) => {
const visible = i + 1 < xs.length ? xs[i + 1] - xs[i] : w;
setAttr(c, "data-covered", visible < w * 0.4);
setAttr(colEls[i + 1], "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's column is * selection or link. Horizontally, the strip scrolls as little as it can so that pane's column is
* fully visible and, when there is room, so is the column beside it: for a row whose pane is * whole and, when there is room, so is the column beside it: for a row whose pane is showing,
* showing, that pane's; otherwise the one before. * that pane's; otherwise the one before. Up and down a column it stays still while the pane looked
* at is whole.
*/ */
const follow = () => { const follow = () => {
const el = strip.current; const el = strip.current;
@@ -426,20 +424,18 @@ export function Panes() {
const colOf = (p: HTMLElement | undefined) => (p ? colEls.indexOf(p.parentElement as HTMLElement) : -1); const colOf = (p: HTMLElement | undefined) => (p ? colEls.indexOf(p.parentElement as HTMLElement) : -1);
const w = colEls[0].offsetWidth; const w = colEls[0].offsetWidth;
const view = el.clientWidth; const view = el.clientWidth;
const max = el.scrollWidth - view;
const L = lefts.current; const L = lefts.current;
const b = colOf(panes[Math.min(panes.length - 1, showing ? at + 1 : at)]); const b = colOf(panes[Math.min(panes.length - 1, showing ? at + 1 : at)]);
if (b < 0) return; 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 here = colOf(panes[at]);
const was = lastCol.current; const was = lastCol.current;
lastCol.current = here; 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; if (here === was && whole(el.scrollLeft, view, b * w, w, L[b] ?? 0)) return;
let a = b > 0 && (showing || f.grain === "node") ? b - 1 : b; // Column i starts at i·w: show b whole, and the one before it too when both fit.
// 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 a = b > 0 && (showing || f.grain === "node") ? b - 1 : b;
const lo = (b + 1) * w - view; const both = reveal(el.scrollLeft, view, a * w, (b + 1 - a) * w, L[a] ?? 0, max);
if (lo > a * w - (L[a] ?? 0)) a = b; const target = whole(both, view, b * w, w, L[b] ?? 0) && whole(both, view, a * w, w, L[a] ?? 0) ? both : reveal(el.scrollLeft, view, b * w, w, L[b] ?? 0, max);
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)));
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" });
}; };
@@ -464,7 +460,10 @@ export function Panes() {
const el = strip.current!; const el = strip.current!;
const wrap = el.parentElement!; const wrap = el.parentElement!;
const onScroll = (e: Event) => { const onScroll = (e: Event) => {
if (e.target === el) measure(); const t = e.target as HTMLElement;
if (t === el || t.classList?.contains("col")) measure();
// What peeks is placed for where things were: put it back (one waiting to peek still may).
if (peeked) hide();
schedule(); schedule();
}; };
const onResize = () => { const onResize = () => {
@@ -474,17 +473,168 @@ export function Panes() {
measure(); measure();
schedule(); schedule();
}; };
// Panes scroll on their own: their scroll events are caught on the way down. // Panes and crowded columns scroll on their own: their scroll events are caught on the way down.
wrap.addEventListener("scroll", onScroll, { passive: true, capture: true }); wrap.addEventListener("scroll", onScroll, { passive: true, capture: true });
// The strip changes size with the window and when the history panel opens or closes. // 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); document.fonts?.ready.then(onResize);
/*
* Peeking: a pane the stacks have covered, wholly or in part (its column across the strip, or
* the pane down a crowded column), slides out over its neighbours while the mouse rests on it
* (after PEEK_MS, so passing across does not flicker), raised and, if it runs past the column's
* foot, lifted into view; nothing else moves. A click makes it the active pane, which uncovers
* it for good. Not for touch, the keyboard, or while dragging.
*/
let peeked: HTMLElement | null = null;
let pending: HTMLElement | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
function hide() {
if (!peeked) return;
peeked.removeAttribute("data-peek");
peeked.style.transform = "";
peeked = null;
}
function unpeek() {
clearTimeout(timer);
pending = null;
hide();
}
const peekable = (pane: HTMLElement): HTMLElement | null => {
const col = pane.parentElement as HTMLElement;
if (col.hasAttribute("data-covered") || (col.nextElementSibling as HTMLElement | null)?.hasAttribute("data-over")) return col;
if (!col.classList.contains("crowded")) return null;
const r = pane.getBoundingClientRect();
const c = col.getBoundingClientRect();
if (pane.hasAttribute("data-covered") || (pane.nextElementSibling as HTMLElement | null)?.hasAttribute("data-over") || r.bottom > c.bottom + 1) return pane;
return null;
};
const peek = (it: HTMLElement) => {
peeked = it;
it.setAttribute("data-peek", "");
if (it.classList.contains("pane")) {
const r = it.getBoundingClientRect();
const c = (it.parentElement as HTMLElement).getBoundingClientRect();
const dy = Math.max(c.top - r.top, Math.min(0, c.bottom - r.bottom));
if (dy) it.style.transform = `translateY(${Math.round(dy)}px)`;
}
};
const onMove = (e: PointerEvent) => {
if (e.pointerType !== "mouse" || e.buttons || drag) return;
const pane = (e.target as HTMLElement).closest<HTMLElement>(".pane");
const it = pane && (pane === peeked || pane.parentElement === peeked ? peeked : peekable(pane));
if (it === peeked && it) return;
if (it === pending && it) return;
unpeek();
if (!it) return;
pending = it;
timer = setTimeout(() => {
if (pending !== it) return;
pending = null;
const pane = it.classList.contains("pane") ? it : it.querySelector<HTMLElement>(".pane");
if (pane && peekable(pane)) peek(it);
}, PEEK_MS);
};
el.addEventListener("pointermove", onMove);
el.addEventListener("pointerleave", unpeek);
window.addEventListener("keydown", unpeek, true);
/*
* Dragging a pane up or down its column, by its grip (the band above its title, beside the pin
* and the x) or its tab: a line shows where it will go; Esc cancels. The column's order is then
* its own (forks.ts `reorder`), kept with the panes.
*/
let drag: { tid: number; col: HTMLElement; y0: number; on: boolean; before: number | null; line: HTMLElement | null } | null = null;
let swallow = false;
const onDown = (e: PointerEvent) => {
if (e.button !== 0) return;
const t = e.target as HTMLElement;
if (t.closest("[data-close], [data-pin]")) return;
const handle = t.closest<HTMLElement>("[data-grip], .tabline");
const pane = handle?.closest<HTMLElement>(".pane");
const col = pane?.parentElement as HTMLElement | undefined;
if (!handle || !pane || !col || col.children.length < 2) return;
drag = { tid: Number(pane.dataset.tid), col, y0: e.clientY, on: false, before: null, line: null };
handle.setPointerCapture(e.pointerId);
};
const onDrag = (e: PointerEvent) => {
if (!drag) return;
if (!drag.on) {
if (Math.abs(e.clientY - drag.y0) < 5) return;
drag.on = true;
unpeek();
wrap.classList.add("dragging");
drag.line = document.createElement("div");
drag.line.className = "drop-line";
wrap.appendChild(drag.line);
}
const others = [...drag.col.querySelectorAll<HTMLElement>(":scope > .pane")].filter((p) => Number(p.dataset.tid) !== drag!.tid);
const c = drag.col.getBoundingClientRect();
const tops = others.map((p) => Math.max(c.top, Math.min(c.bottom, p.getBoundingClientRect().top)));
const ends = others.map((p, i) => Math.min(tops[i + 1] ?? c.bottom, Math.max(c.top, Math.min(c.bottom, p.getBoundingClientRect().bottom))));
const i = others.findIndex((_, k) => e.clientY < (tops[k] + ends[k]) / 2);
drag.before = i < 0 ? null : Number(others[i].dataset.tid);
const y = i < 0 ? (ends[ends.length - 1] ?? c.top) : tops[i];
const box = wrap.getBoundingClientRect();
Object.assign(drag.line!.style, { left: `${c.left - box.left}px`, width: `${c.width}px`, top: `${y - box.top - 1}px` });
};
const end = (keep: boolean) => {
if (!drag) return;
const d = drag;
drag = null;
d.line?.remove();
wrap.classList.remove("dragging");
if (d.on) {
swallow = true;
setTimeout(() => (swallow = false), 0);
if (keep) store.reorderPane(d.tid, d.before);
}
};
const onUp = () => end(true);
const onCancel = () => end(false);
const onKey = (e: KeyboardEvent) => {
if (drag?.on && e.key === "Escape") {
e.stopImmediatePropagation();
e.preventDefault();
end(false);
}
};
// The click that ends a drag is not a click on the pane.
const onClick = (e: MouseEvent) => {
if (!swallow) return;
swallow = false;
e.stopPropagation();
e.preventDefault();
};
// A press elsewhere puts a peeking pane back; on it, the click goes through to it (and makes it the active pane), and then it goes back.
const onPress = (e: PointerEvent) => !(peeked && peeked.contains(e.target as Node)) && unpeek();
const afterClick = () => peeked && requestAnimationFrame(unpeek);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointerdown", onPress);
el.addEventListener("click", afterClick);
el.addEventListener("pointermove", onDrag);
el.addEventListener("pointerup", onUp);
el.addEventListener("pointercancel", onCancel);
window.addEventListener("keydown", onKey, true);
window.addEventListener("click", onClick, true);
return () => { return () => {
cancelAnimationFrame(frame.current); cancelAnimationFrame(frame.current);
clearTimeout(later.current); clearTimeout(later.current);
clearTimeout(timer);
wrap.removeEventListener("scroll", onScroll, { capture: true }); wrap.removeEventListener("scroll", onScroll, { capture: true });
sizes.disconnect(); sizes.disconnect();
el.removeEventListener("pointermove", onMove);
el.removeEventListener("pointerleave", unpeek);
window.removeEventListener("keydown", unpeek, true);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointerdown", onPress);
el.removeEventListener("click", afterClick);
el.removeEventListener("pointermove", onDrag);
el.removeEventListener("pointerup", onUp);
el.removeEventListener("pointercancel", onCancel);
window.removeEventListener("keydown", onKey, true);
window.removeEventListener("click", onClick, true);
}; };
}, []); }, []);
@@ -549,12 +699,14 @@ function underline(s: HTMLElement, r: DOMRect): number {
const cs = getComputedStyle(s); const cs = getComputedStyle(s);
const fs = parseFloat(cs.fontSize) || 16; const fs = parseFloat(cs.fontSize) || 16;
if (s.matches(".anchor")) return r.bottom - 0.08 * fs - 0.5; if (s.matches(".anchor")) return r.bottom - 0.08 * fs - 0.5;
let d = descents.get(cs.font); const font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
let d = descents.get(font);
if (d === undefined) { if (d === undefined) {
measurer ??= document.createElement("canvas").getContext("2d"); measurer ??= document.createElement("canvas").getContext("2d");
if (measurer) measurer.font = cs.font; if (measurer) measurer.font = font;
d = measurer?.measureText("x").fontBoundingBoxDescent ?? 0.25 * fs; d = measurer?.measureText("x").fontBoundingBoxDescent ?? 0.3 * fs;
descents.set(cs.font, d); // Kept once the face has arrived; measured before, it is the fallback's.
if (document.fonts?.check(font) !== false) descents.set(font, d);
} }
const off = parseFloat(cs.textUnderlineOffset); const off = parseFloat(cs.textUnderlineOffset);
return r.bottom - d + (Number.isFinite(off) ? off : 0.1 * fs) + 0.5; return r.bottom - d + (Number.isFinite(off) ? off : 0.1 * fs) + 0.5;
@@ -596,28 +748,36 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
const pcol = pe?.parentElement; const pcol = pe?.parentElement;
const ccol = ce?.parentElement; const ccol = ce?.parentElement;
if (!pe || !ce || !pcol || !ccol || pcol.hasAttribute("data-covered") || ccol.hasAttribute("data-covered")) continue; if (!pe || !ce || !pcol || !ccol || pcol.hasAttribute("data-covered") || ccol.hasAttribute("data-covered")) continue;
const left = ccol.getBoundingClientRect().left; const ccolBox = ccol.getBoundingClientRect();
// Where it arrives: just before the child's title, or its tab's. const left = ccolBox.left;
// Where it arrives: just before the child's title, or its tab's; below a crowded column's foot, at the foot.
const cbox = ce.getBoundingClientRect(); const cbox = ce.getBoundingClientRect();
let ey: number; let ey: number;
if (ce.hasAttribute("data-tab")) ey = cbox.top + TAB / 2; let lost = false;
if (ce.hasAttribute("data-covered")) ey = cbox.top + TAB / 2;
else { else {
const scroll = ce.querySelector<HTMLElement>(".pane-scroll")!.getBoundingClientRect(); const scroll = ce.querySelector<HTMLElement>(".pane-scroll")!.getBoundingClientRect();
const tr = ce.querySelector<HTMLElement>(".pane-head h2, .top h1, .wiki-head h2")?.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; ey = tr && tr.bottom > scroll.top + 4 ? Math.max(scroll.top + 6, tr.top + Math.min(tr.height, 32) / 2) : scroll.top + 14;
} }
if (ey > ccolBox.bottom - 4) {
ey = ccolBox.bottom - 4;
lost = true;
}
// 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. // 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 pbox = pe.getBoundingClientRect();
const textRight = Math.min(pbox.right - 33, left - 2); const textRight = Math.min(pbox.right - 33, left - 2);
let sx = textRight; let sx = textRight;
let sy: number; let sy: number;
let under: { x: number; y: number } | undefined; let under: { x: number; y: number } | undefined;
let lost = false; if (pe.hasAttribute("data-covered")) {
if (pe.hasAttribute("data-tab")) {
sy = pbox.top + TAB / 2; sy = pbox.top + TAB / 2;
lost = true; lost = true;
} else { } else {
const sc = pe.querySelector<HTMLElement>(".pane-scroll")!.getBoundingClientRect(); // What of the pane shows: its own scroll box, less what the pane after it in a crowded column covers, down to the column's foot.
const box = pe.querySelector<HTMLElement>(".pane-scroll")!.getBoundingClientRect();
const nextTop = pcol.classList.contains("crowded") ? (pe.nextElementSibling as HTMLElement | null)?.getBoundingClientRect().top : undefined;
const sc = { top: box.top, bottom: Math.min(box.bottom, nextTop ?? Infinity, pcol.getBoundingClientRect().bottom) };
const cands = pe.querySelectorAll<HTMLElement>(`.${kidClass(refKey(x.node.ref))}`); const cands = pe.querySelectorAll<HTMLElement>(`.${kidClass(refKey(x.node.ref))}`);
let src: HTMLElement | undefined; let src: HTMLElement | undefined;
for (const c of cands) { for (const c of cands) {
@@ -671,7 +831,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
} }
for (const g of [...lanesUsed.keys()]) if (!gutters.has(g)) lanesUsed.delete(g); for (const g of [...lanesUsed.keys()]) if (!gutters.has(g)) lanesUsed.delete(g);
const fx = (n: number) => Math.round(n * 2) / 2; const fx = (n: number) => Math.round(n * 2) / 2;
const out: string[] = []; const out: { key: string; from: number; to: number; lane: number; cls: string; d: string }[] = [];
edges.sort((a, b) => Number(a.on) - Number(b.on)); edges.sort((a, b) => Number(a.on) - Number(b.on));
for (const e of edges) { for (const e of edges) {
const i = lane.get(e)!; const i = lane.get(e)!;
@@ -694,8 +854,25 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
`C${fx(g)} ${fx(e.ey - sg * r2 * (1 - k))} ${fx(g + r2 - k * r2)} ${fx(e.ey)} ${fx(g + r2)} ${fx(e.ey)}` + `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)}`; `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}"/>`); out.push({ key: `${e.from}>${e.to}`, from: e.from, to: e.to, lane: i, cls: `${e.on ? "on" : ""}${e.lost ? " lost" : ""}`, d });
} }
const html = out.join(""); // Each curve keeps its element, changed only where it changed, so only what moved is painted again.
if (svg.innerHTML !== html) svg.innerHTML = html; const had = new Map<string, SVGPathElement>();
for (const p of svg.querySelectorAll<SVGPathElement>("path")) had.set(p.dataset.key!, p);
out.forEach((c, k) => {
let p = had.get(c.key);
had.delete(c.key);
if (!p) {
p = document.createElementNS("http://www.w3.org/2000/svg", "path");
p.dataset.key = c.key;
p.dataset.from = String(c.from);
p.dataset.to = String(c.to);
}
if (p.getAttribute("d") !== c.d) p.setAttribute("d", c.d);
if (p.getAttribute("class") !== c.cls) p.setAttribute("class", c.cls);
if (p.dataset.lane !== String(c.lane)) p.dataset.lane = String(c.lane);
// In drawing order: the focused branch's last, on top.
if (svg.children[k] !== p) svg.insertBefore(p, svg.children[k] ?? null);
});
for (const p of had.values()) p.remove();
} }
+12 -12
View File
@@ -15,11 +15,11 @@ 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 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"], ["q", "in panes: close the active pane (the one under the heavy rule, whatever it shows) and every pane opened from it, except pinned ones; the focus goes back to where it was opened from. A pane's x does the same. Moving left never closes anything"],
["P", "in panes: pin or unpin the active pane (or its pin, top right). A pinned pane stays where it is when a pane it came from closes, is never replaced by a plain open, and never folds into a tab or a spine"], ["P", "in panes: pin or unpin the active pane (or its pin, top right). A pinned pane stays where it is when a pane it came from closes, is never replaced by a Shift open, and is never covered, in its column or along the strip"],
["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"], ["Enter l", "in panes: open into the next column, beside what is open there (so does a click, and a Ctrl-, Cmd- or middle click); on something open already, focus it"],
["[ ]", "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"], ["Shift+Enter", "in panes: open in place of the focused branch's pane in the next column (so does a Shift-click)"],
], ["[ ]", "in panes: the pane above / below in the same column (back where you were in it, or at its head); at the top or bottom nothing moves. A crowded column stacks its panes as the strip stacks columns, covered to a tab; resting the mouse on a covered pane peeks it out; its grip or tab drags it up or down. A faint curve runs from where each pane was opened to its title"], ],
], ],
[ [
"Links", "Links",
@@ -41,7 +41,7 @@ export const HELP: [string, [string, string][]][] = [
"Expand", "Expand",
[ [
["e", "go deeper: open → open children → generate"], ["e", "go deeper: open → open children → generate"],
["Enter", "on a section: toggle. On a selection: open its note, or step into it"], ["Enter", "on a section: toggle (in panes: open its pane, or focus it where it is open). On a selection: open its note, or step into it"],
["H L", "shrink / grow the selection by one unit"], ["H L", "shrink / grow the selection by one unit"],
["d y x c", "on a selection: define · why · example · challenge"], ["d y x c", "on a selection: define · why · example · challenge"],
[":", "on a selection: ask your own question about it"], [":", "on a selection: ask your own question about it"],
@@ -237,7 +237,7 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
// The filter box is not focused (a key typed before it took focus, or after a click // The filter box is not focused (a key typed before it took focus, or after a click
// elsewhere in the panel): keys still mean what they would there. // elsewhere in the panel): keys still mean what they would there.
if (k === "Escape" || k === "Tab") m.focus = "list"; if (k === "Escape" || k === "Tab") m.focus = "list";
else if (k === "Enter") return d && (e.preventDefault(), store.openDoc(d.node)); else if (k === "Enter") return d && (e.preventDefault(), store.openDoc(d.node, true));
else if (k === "ArrowDown" || k === "ArrowUp") return e.preventDefault(), store.menuMove(k === "ArrowDown" ? 1 : -1); else if (k === "ArrowDown" || k === "ArrowUp") return e.preventDefault(), store.menuMove(k === "ArrowDown" ? 1 : -1);
else if (k.length === 1) return e.preventDefault(), store.menuFilter(m.filter + k); else if (k.length === 1) return e.preventDefault(), store.menuFilter(m.filter + k);
else return; else return;
@@ -265,7 +265,7 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
store.menuMove(-1); store.menuMove(-1);
break; break;
case "Enter": case "Enter":
if (d) store.openDoc(d.node); if (d) store.openDoc(d.node, true);
break; break;
case "/": case "/":
m.focus = "filter"; m.focus = "filter";
@@ -347,11 +347,11 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
} }
// An Enter after a Tab that is waiting for its article to arrive waits with it. // An Enter after a Tab that is waiting for its article to arrive waits with it.
if (store.aux && store.holdKey(k, e.shiftKey)) return done(); if (store.aux && store.holdKey(k, e.shiftKey)) return done();
// Shift+Enter opens a fork: whatever Enter opens, it opens beside what is there. // Enter opens beside what is in the next column; Shift+Enter in place of the focused branch's pane there.
const fork = k === "Enter" && e.shiftKey; const replace = k === "Enter" && e.shiftKey;
// Words selected in an article's text take the same keys as words of a node. // Words selected in an article's text take the same keys as words of a node.
if (store.aux && !store.inArticleText) { if (store.aux && !store.inArticleText) {
if (store.withFork(fork, () => auxKey(k, e.shiftKey)) || commonKey(k, hooks)) return done(); if (store.withReplace(replace, () => auxKey(k, e.shiftKey)) || commonKey(k, hooks)) return done();
const why = store.aux.kind === "wiki" ? store.articleRefuses(k, false) : null; const why = store.aux.kind === "wiki" ? store.articleRefuses(k, false) : null;
if (why) (store.say(why), done()); if (why) (store.say(why), done());
return; return;
@@ -394,7 +394,7 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
break; break;
case "Enter": case "Enter":
case " ": case " ":
store.withFork(fork, () => { store.withReplace(replace, () => {
if (selecting) store.enterOrExpand(); if (selecting) store.enterOrExpand();
else if (store.snap.nodes[store.focus.node]?.kind === "note" && store.targetOf(store.focus.node)) store.followOwn(); else if (store.snap.nodes[store.focus.node]?.kind === "note" && store.targetOf(store.focus.node)) store.followOwn();
else store.toggle(); else store.toggle();
+7 -3
View File
@@ -8,6 +8,8 @@ export const LANE_PITCH = 4;
export const LANE_FIRST = 5; export const LANE_FIRST = 5;
export const LANE_LAST = 29; export const LANE_LAST = 29;
export const LANES = Math.floor((LANE_LAST - LANE_FIRST) / LANE_PITCH) + 1; export const LANES = Math.floor((LANE_LAST - LANE_FIRST) / LANE_PITCH) + 1;
/** Up to this many curves in a gutter, every lane is tried for each; past it, only the neighbouring lanes. */
const MOVES = 8;
/** /**
* How many times curves in one gutter cross, for an order of lanes (rightmost first): a lead-out * How many times curves in one gutter cross, for an order of lanes (rightmost first): a lead-out
@@ -46,12 +48,14 @@ export function laneOrder<T extends { key: string; sy: number; ey: number }>(edg
const at = order.findIndex((o) => rule.indexOf(o) > r); const at = order.findIndex((o) => rule.indexOf(o) > r);
order.splice(at < 0 ? order.length : at, 0, e); 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). // Move one curve to another lane while that removes crossings: a few curves per gutter, every place
// tried; many (past MOVES), only neighbours swapped, which stays cheap enough for every frame.
let best = crossings(order); let best = crossings(order);
for (let pass = 0, better = true; better && pass < order.length; pass++) { const far = order.length <= MOVES;
for (let pass = 0, better = best > 0; better && pass < order.length; pass++) {
better = false; better = false;
for (let i = 0; i < order.length && best; i++) for (let i = 0; i < order.length && best; i++)
for (let j = 0; j < order.length; j++) { for (let j = far ? 0 : i + 1; j < (far ? order.length : Math.min(order.length, i + 2)); j++) {
if (j === i) continue; if (j === i) continue;
const moved = order.slice(); const moved = order.slice();
moved.splice(j, 0, ...moved.splice(i, 1)); moved.splice(j, 0, ...moved.splice(i, 1));
+108
View File
@@ -0,0 +1,108 @@
/**
* Stacking, after Andy Matuschak's notes, along either axis of the panes view (Panes.tsx). Items
* stand side by side in a scrolling box, each stuck (position: sticky) a strip's width after the one
* before, so that a later item slides over an earlier one and leaves it a strip: across the strip,
* the columns, leaving spines; down a crowded column, its panes, leaving tabs. A pinned item leaves
* its whole size instead, so nothing after it covers it. How far each item is covered sets its
* state: overlapped (a shadow edge on the item over it), covered (only its strip is worth showing),
* and the box scrolls as little as it can to show the item looked at whole.
*
* This module is that model and its computation, for both axes; Panes.tsx sizes the items (a
* column is a pane's width; a pane in a crowded column, what its text needs up to the column's
* height less a tab for each other pane) and applies what comes back.
*/
export interface Axis {
/** The sticky inset, and the start and end of a box along the axis. */
start: "left" | "top";
end: "right" | "bottom";
size: "offsetWidth" | "offsetHeight";
client: "clientWidth" | "clientHeight";
scroll: "scrollLeft" | "scrollTop";
scrollSize: "scrollWidth" | "scrollHeight";
}
/** Across: the columns of the strip. */
export const ACROSS: Axis = { start: "left", end: "right", size: "offsetWidth", client: "clientWidth", scroll: "scrollLeft", scrollSize: "scrollWidth" };
/** Down: the panes of a crowded column. */
export const DOWN: Axis = { start: "top", end: "bottom", size: "offsetHeight", client: "clientHeight", scroll: "scrollTop", scrollSize: "scrollHeight" };
/** An item covered to less than this share of its size shows only its strip (spine or tab). */
export const COVERED = 0.4;
/**
* Each item's sticky offset: every item before it leaves its strip, a pinned one its whole size;
* never so far that the items after it could not all still be scrolled to.
*/
export function offsets(sizes: number[], pinned: boolean[], strip: number, view: number): number[] {
const n = sizes.length;
let at = 0;
return sizes.map((s, i) => {
const o = Math.round(Math.min(at, Math.max(i * strip, view - s - (n - 1 - i) * strip)));
at += pinned[i] ? s : strip;
return o;
});
}
/** Where each item begins when nothing is stuck: one after another. */
export const starts = (sizes: number[]) => sizes.map((_, i) => sizes.slice(0, i).reduce((a, b) => a + b, 0));
/**
* How covered each item is, from where each begins on screen now, its size and where the box ends:
* an item shows up to where the next begins (or the box's end); overlapped when any of it is
* hidden, covered when less than COVERED of it shows, buried when no more than its strip does (what
* is under the strip need not be painted).
*/
export function coverage(at: number[], sizes: number[], end: number, strip = 0): { over: boolean[]; covered: boolean[]; buried: boolean[] } {
const shown = at.map((a, i) => Math.max(0, Math.min(at[i + 1] ?? Infinity, end) - a));
return { over: shown.map((s, i) => s < sizes[i] - 1), covered: shown.map((s, i) => s < sizes[i] * COVERED), buried: shown.map((s) => s <= strip + 2) };
}
/**
* The scroll, as near the present one as it can be, that shows an item whole: its far edge inside
* the box, and itself not yet stuck under the items before it.
*/
export function reveal(scroll: number, view: number, start: number, size: number, stuck: number, max: number): number {
return Math.max(0, Math.min(max, Math.min(Math.max(scroll, start + size - view), start - stuck)));
}
/** Whether an item is shown whole at this scroll. */
export const whole = (scroll: number, view: number, start: number, size: number, stuck: number) => scroll >= start + size - view - 1 && scroll <= start - stuck + 1;
const setAttr = (el: Element | undefined, name: string, on: boolean) => {
if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name);
};
/** Stick a box's items at their offsets. */
export function stick(items: HTMLElement[], offs: number[], axis: Axis) {
items.forEach((el, i) => {
const v = `${offs[i]}px`;
if (el.style[axis.start] !== v) el.style[axis.start] = v;
});
}
/** Clear the marks of items no longer stacked. */
export function unmark(items: Element[]) {
for (const el of items) {
setAttr(el, "data-covered", false);
setAttr(el, "data-over", false);
setAttr(el, "data-buried", false);
}
}
/** Mark a box's items with how covered they are now (data-over, data-covered); `edge`: whether the box's far edge covers too (down a column it does; across, a column beyond the window is simply further on). */
export function mark(box: HTMLElement, items: HTMLElement[], axis: Axis, edge: boolean, strip: number) {
if (!items.length) return;
const at = items.map((el) => el.getBoundingClientRect()[axis.start]);
const { over, covered, buried } = coverage(
at,
items.map((el) => el[axis.size]),
edge ? box.getBoundingClientRect()[axis.start] + box[axis.client] : Infinity,
strip,
);
items.forEach((el, i) => {
setAttr(el, "data-covered", covered[i]);
setAttr(el, "data-buried", buried[i]);
// The shadow edge is drawn by the item over an overlapped one.
setAttr(items[i + 1], "data-over", over[i] && i + 1 < items.length);
});
}
+43 -29
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, 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 { all, besideInColumn, close as closeIn, columns as columnsOf, reorder, 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";
@@ -290,10 +290,10 @@ class Store {
get tree(): Pane | null { get tree(): Pane | null {
return focused(this.forest); 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 Shift open (Shift+Enter, Shift-click) runs: it opens in place of what is in the next column instead of beside it. */
forking = false; replacing = false;
private toldForks = false; private toldReplace = false;
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 memo: { forest: Forest<PaneRef, Back> | null; nodes: Pane[]; trail: PaneRef[]; placed?: Placed<PaneRef, Back>[]; cols?: Map<number, 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.forest !== this.forest) { if (this.memo.forest !== this.forest) {
const nodes = path(this.tree); const nodes = path(this.tree);
@@ -301,11 +301,16 @@ class Store {
} }
return this.memo; return this.memo;
} }
/** Every pane, with its column, in the order panes stand in a column. */ /** Every pane, with its column, tree by tree, depth first. */
get panesPlaced(): Placed<PaneRef, Back>[] { get panesPlaced(): Placed<PaneRef, Back>[] {
const m = this.branch; const m = this.branch;
return (m.placed ??= all(this.forest)); return (m.placed ??= all(this.forest));
} }
/** The panes of each column, top to bottom (forks.ts `columns`). */
get paneColumns(): Map<number, Placed<PaneRef, Back>[]> {
const m = this.branch;
return (m.cols ??= columnsOf(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;
@@ -555,11 +560,12 @@ class Store {
/** /**
* 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 pinned pane stays beside it); * focused. Otherwise it opens beside what is there, a new pane in the next column; a Shift open
* a fork (`forking`) opens it beside that, below in the next column. Returns the pane it is in. * (`replacing`) opens it in place of the focused branch's pane there instead (a pinned pane stays
* beside it). Returns the pane it is in.
*/ */
openPane(i: number, ref: PaneRef): number { openPane(i: number, ref: PaneRef): number {
this.setForest(openIn(this.forest, i, ref, this.forking, sameRef)); this.setForest(openIn(this.forest, i, ref, !this.replacing, 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);
@@ -572,18 +578,18 @@ class Store {
this.closePane(kid.id); this.closePane(kid.id);
} }
/** 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 beside what is there, or in its place (Shift). In the column there is only the one way, and the status line says so once. */
withFork<T>(fork: boolean, fn: () => T): T { withReplace<T>(replace: boolean, fn: () => T): T {
if (fork && !this.panes && !this.toldForks) { if (replace && !this.panes && !this.toldReplace) {
this.toldForks = true; this.toldReplace = true;
this.say("Forks (Shift+Enter, Shift- or Ctrl-click) open side by side in the panes view; in one column this opens as usual."); this.say("Shift+Enter and Shift-click open in place of the pane to the right in the panes view; in one column this opens as usual.");
} }
const was = this.forking; const was = this.replacing;
this.forking = fork && this.panes; this.replacing = replace && this.panes;
try { try {
return fn(); return fn();
} finally { } finally {
this.forking = was; this.replacing = was;
} }
} }
@@ -713,6 +719,15 @@ class Store {
this.land(i); this.land(i);
} }
/** A pane dragged up or down its column, to just above another (or to the bottom). */
reorderPane(id: number, before: number | null) {
const f = reorder(this.forest, id, before);
if (f === this.forest) return;
this.setForest(f);
this.saveView();
this.emit();
}
/** P (on the active pane) or a pane's pin: pin or unpin it. */ /** P (on the active pane) or a pane's pin: pin or unpin it. */
togglePanePin(id = this.branchNodes[this.paneAt]?.id) { togglePanePin(id = this.branchNodes[this.paneAt]?.id) {
if (!this.panes) return this.say("Panes are pinned in the panes view (v)."); if (!this.panes) return this.say("Panes are pinned in the panes view (v).");
@@ -1352,7 +1367,8 @@ class Store {
} }
/** Open a document: hoist to it in the column, show it in the next pane in panes. */ /** Open a document: hoist to it in the column, show it in the next pane in panes. */
openDoc(id: NodeId) { /** Open a document: from its row in the library, beside what is open; from the menu, a command or an address (`nav`), in place of it. */
openDoc(id: NodeId, nav = false) {
const s = this.doc.snap(); const s = this.doc.snap();
if (!s.nodes[id]) return; if (!s.nodes[id]) return;
void this.links.loadDoc(id); void this.links.loadDoc(id);
@@ -1365,7 +1381,7 @@ class Store {
this.open.add(id); this.open.add(id);
this.focus = { node: id, grain: "node" }; this.focus = { node: id, grain: "node" };
this.syncTrail(); this.syncTrail();
if (s.nodes[id].parent === this.top) this.openPane(this.paneAt, { kind: "node", id }); if (s.nodes[id].parent === this.top) this.withReplace(nav || this.replacing, () => this.openPane(this.paneAt, { kind: "node", id }));
} else this.hoist = id; } else this.hoist = id;
this.focus = { node: id, grain: "node" }; this.focus = { node: id, grain: "node" };
this.saveView(); this.saveView();
@@ -1552,12 +1568,10 @@ class Store {
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. // 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(); 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 opens its pane, or focuses it where it is open already: closing is q's, or the pane's x.
if (this.panes) { if (this.panes) {
this.syncTrail(); this.syncTrail();
const n = this.branchNodes[this.paneAt]; return this.setOpen(id, true);
const k = n ? n.kids.findIndex((c) => c.ref.kind === "node" && c.ref.id === id) : -1;
if ((k >= 0 && k !== n.pick) || this.forking) return this.setOpen(id, true);
} }
this.setOpen(id, !this.isOpen(id)); this.setOpen(id, !this.isOpen(id));
} }
@@ -2537,7 +2551,7 @@ class Store {
this.held = null; this.held = null;
if (art?.state !== "ready") return; if (art?.state !== "ready") return;
for (const k of h.keys) { for (const k of h.keys) {
if (k === "Enter" || k === "S-Enter") this.withFork(k === "S-Enter", () => (this.inArticleText ? this.enterArticle() : this.auxActivate())); if (k === "Enter" || k === "S-Enter") this.withReplace(k === "S-Enter", () => (this.inArticleText ? this.enterArticle() : this.auxActivate()));
else if (k === "i") this.descend(); else if (k === "i") this.descend();
else this.auxTab(k === "Tab" ? 1 : -1); else this.auxTab(k === "Tab" ? 1 : -1);
} }
@@ -3062,7 +3076,7 @@ class Store {
if (!title) return this.say("A new document needs a title: /new <title>"); if (!title) return this.say("A new document needs a title: /new <title>");
this.docWrite(() => { this.docWrite(() => {
const id = createDoc(this.doc, title, this.user); const id = createDoc(this.doc, title, this.user);
this.openDoc(id); this.openDoc(id, true);
this.say(`Created “${clip(title, 60)}”: c writes its opening text, a adds a section.`); this.say(`Created “${clip(title, 60)}”: c writes its opening text, a adds a section.`);
}); });
} }
@@ -3084,7 +3098,7 @@ class Store {
if (!title) return this.say("The copy needs a title."); if (!title) return this.say("The copy needs a title.");
this.docWrite(() => { this.docWrite(() => {
const copy = duplicateDoc(this.doc, id, title, this.user); const copy = duplicateDoc(this.doc, id, title, this.user);
this.openDoc(copy); this.openDoc(copy, true);
this.say(`Saved a copy as “${clip(title, 60)}”; this is the copy.`); this.say(`Saved a copy as “${clip(title, 60)}”; this is the copy.`);
}); });
} }
@@ -3144,7 +3158,7 @@ class Store {
const slug = freeSlug(file.name.replace(/\.(md|markdown|txt)$/i, ""), new Set(documents(s).map((d) => s.nodes[d].slug))); const slug = freeSlug(file.name.replace(/\.(md|markdown|txt)$/i, ""), new Set(documents(s).map((d) => s.nodes[d].slug)));
try { try {
const id = importDoc(this.doc, text, file.name, { creator: this.user, slug }); const id = importDoc(this.doc, text, file.name, { creator: this.user, slug });
this.openDoc(id); this.openDoc(id, true);
this.say(`Imported ${file.name} as “${clip(this.doc.snap().nodes[id].title, 60)}”.`); this.say(`Imported ${file.name} as “${clip(this.doc.snap().nodes[id].title, 60)}”.`);
// Imported text is scanned like any other writing: by a background job, once the server has it. // Imported text is scanned like any other writing: by a background job, once the server has it.
if (this.settings.autolink !== "off") void this.whenSynced().then(() => this.linkJob("doc", id, true)); if (this.settings.autolink !== "off") void this.whenSynced().then(() => this.linkJob("doc", id, true));
@@ -3165,7 +3179,7 @@ class Store {
all.find((x) => x.slug === q) ?? all.find((x) => x.title.toLowerCase() === q) ?? all.find((x) => x.title.toLowerCase().startsWith(q)) ?? all.find((x) => x.slug === q) ?? all.find((x) => x.title.toLowerCase() === q) ?? all.find((x) => x.title.toLowerCase().startsWith(q)) ??
all.find((x) => `${x.title} ${x.slug}`.toLowerCase().includes(q)); all.find((x) => `${x.title} ${x.slug}`.toLowerCase().includes(q));
if (!d) return this.say(`No document matches “${name}”. m lists them.`); if (!d) return this.say(`No document matches “${name}”. m lists them.`);
this.openDoc(d.node); this.openDoc(d.node, true);
this.say(`Opened “${clip(d.title, 60)}”.`); this.say(`Opened “${clip(d.title, 60)}”.`);
} }
@@ -3384,7 +3398,7 @@ class Store {
this.aux = null; this.aux = null;
this.colWiki = null; this.colWiki = null;
const s = this.snap; const s = this.snap;
if (s.library && s.nodes[id]?.parent === s.root) return this.openDoc(id); if (s.library && s.nodes[id]?.parent === s.root) return this.openDoc(id, true);
this.reveal(id); this.reveal(id);
this.focus = { node: id, grain: "node" }; this.focus = { node: id, grain: "node" };
this.saveView(); this.saveView();
+35 -6
View File
@@ -334,6 +334,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
--spine: 2.1rem; --spine: 2.1rem;
--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));
--tab: 30px;
--shade: rgb(0 0 0 / 0.2); --shade: rgb(0 0 0 / 0.2);
--pane-rule: #d9d9d9; --pane-rule: #d9d9d9;
--curve: rgb(0 0 0 / 0.17); --curve: rgb(0 0 0 / 0.17);
@@ -386,19 +387,46 @@ 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. */ /*
* Down a crowded column the panes stack as the columns do across the strip (stack.ts): each stuck
* a tab below the one before, a later one sliding up over an earlier along a hairline (a shadow
* there costs too much painting, with many panes) and, covered to its tab, its title on one line,
* as a covered column shows its spine.
*/
.col.crowded { overflow-y: auto; overscroll-behavior-y: contain; scrollbar-width: thin; scrollbar-color: var(--hair) transparent; }
.col.crowded > .pane { position: sticky; }
.col.crowded > .pane[data-over]::before { content: ""; position: absolute; z-index: 4; top: 0; left: 0; right: 0; height: 1px; background: var(--rule); }
.tabline { .tabline {
display: none; align-items: center; gap: 0.4em; height: 100%; padding: 0 3.4rem 0 var(--spine); cursor: pointer; position: absolute; z-index: 2; top: 0; left: 0; right: 0; height: var(--tab); display: flex; align-items: center; gap: 0.4em;
padding: 0 3.4rem 0 var(--spine); background: inherit; border-bottom: 1px solid var(--pane-rule); opacity: 0; pointer-events: none; cursor: pointer; transition: opacity 0.12s;
font-family: var(--sans); font-size: 0.74rem; letter-spacing: 0.02em; color: var(--dim); white-space: nowrap; 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 .tabtitle { overflow: hidden; text-overflow: ellipsis; }
.tabline:hover { color: var(--fg); } .tabline:hover { color: var(--fg); }
.pane[data-tab] > .tabline { display: flex; } .col.crowded > .pane[data-covered] > .tabline { opacity: 1; pointer-events: auto; }
.pane[data-tab] > .pane-scroll, .pane[data-tab] > .spine { display: none; } @media (prefers-reduced-motion: reduce) {
.tabline { transition: none; }
}
/* A pane or column covered down to its tab or spine has nothing else on show: it is not painted, until it peeks. */
.col[data-buried]:not([data-peek]) .pane-scroll, .col.crowded > .pane[data-buried]:not([data-peek]) > .pane-scroll { content-visibility: hidden; }
/* Peeking: a covered pane or column, the mouse resting on it, raised over its neighbours whole. */
.col[data-peek], .pane[data-peek] { z-index: 6; box-shadow: 0 3px 18px 0 var(--shade); }
.col[data-peek] .spine, .col.crowded > .pane[data-peek] > .tabline { opacity: 0; pointer-events: none; }
/* Dragging a pane in its column: its grip, quiet until pointed at; the line where it will go. */
.grip { position: absolute; z-index: 3; top: 0; left: var(--spine); right: 3.6rem; height: 1.15rem; cursor: grab; touch-action: none; user-select: none; -webkit-user-select: none; }
.grip::before { content: ""; position: absolute; left: 50%; top: 0.42rem; width: 1.1rem; margin-left: -0.55rem; height: 3px; border-top: 1px solid var(--faint); border-bottom: 1px solid var(--faint); opacity: 0; transition: opacity 0.12s; }
.col.split .grip:hover::before { opacity: 0.8; }
.col:not(.split) .grip, .col.crowded > .pane[data-covered] > .grip { display: none; }
.tabline { touch-action: none; }
.panes.dragging, .panes.dragging * { cursor: grabbing !important; user-select: none; }
.drop-line { position: absolute; z-index: 7; height: 2px; background: var(--link); pointer-events: 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. */ /* 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-ctl { position: absolute; z-index: 3; top: 0.25rem; right: 0.3rem; display: flex; gap: 0.05rem; }
.pane[data-tab] > .pane-ctl { top: 2px; } .col.crowded > .pane[data-covered] > .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 { 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-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:hover .pane-btn { color: var(--faint); }
@@ -416,7 +444,8 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.pane.on-branch:not(.active)::after { height: 1px; background: var(--faint); } .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. */ /* 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; } /* A layer of its own, so that drawing a curve again does not paint the panes under it again. */
.curves { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 2; pointer-events: none; overflow: hidden; will-change: transform; }
.curves path { fill: none; stroke: var(--curve); stroke-width: 1; } .curves path { fill: none; stroke: var(--curve); stroke-width: 1; }
.curves path.on { stroke: var(--curve-on); } .curves path.on { stroke: var(--curve-on); }
.curves path.lost { stroke-dasharray: 1 3; } .curves path.lost { stroke-dasharray: 1 3; }
+37
View File
@@ -0,0 +1,37 @@
/** The stacking shared by the panes view's strip and its crowded columns (src/ui/stack.ts). */
import { describe, expect, it } from "vitest";
import { coverage, offsets, reveal, starts, whole } from "../src/ui/stack";
describe("stack", () => {
it("sticks each item a strip after the one before, a pinned one its whole size, never past where the rest can still be reached", () => {
expect(offsets([700, 700, 700, 700], [false, false, false, false], 40, 1920)).toEqual([0, 40, 80, 120]);
expect(offsets([700, 700, 700, 700], [false, true, false, false], 40, 1920)).toEqual([0, 40, 740, 780]);
// Two pinned columns would push the last out of reach: it stays where the window ends.
expect(offsets([700, 700, 700, 700], [true, true, false, false], 40, 1920).at(-1)).toBe(1920 - 700);
// Down a column: tabs.
expect(offsets([300, 500, 400], [false, false, false], 30, 900)).toEqual([0, 30, 60]);
});
it("an item is overlapped where the next begins before it ends, and covered when less than 40% of it shows", () => {
const { over, covered } = coverage([0, 40, 480], [700, 700, 700], Infinity);
expect(over).toEqual([true, true, false]);
expect(covered).toEqual([true, false, false]);
// Down a column the box's foot covers too.
expect(coverage([0, 300], [300, 600], 600).covered).toEqual([false, false]);
expect(coverage([0, 500], [300, 600], 600).over).toEqual([false, true]);
});
it("scrolls as little as it can to show an item whole", () => {
const sizes = [700, 700, 700, 700];
const at = starts(sizes);
expect(at).toEqual([0, 700, 1400, 2100]);
// The last column whole: its far edge in view.
expect(reveal(0, 1920, at[3], 700, 120, 880)).toBe(880);
// Already whole: no move.
expect(reveal(500, 1920, at[2], 700, 80, 880)).toBe(500);
// Column 1 uncovered: not yet stuck under column 0.
expect(reveal(880, 1920, at[1], 700, 40, 880)).toBe(660);
expect(whole(660, 1920, at[1], 700, 40)).toBe(true);
expect(whole(880, 1920, at[1], 700, 40)).toBe(false);
});
});