The libraries panel, on the left: the library's name in the top bar (or m) opens it; j k, Enter opens (where it was left), n new, r rename, D delete after y; by mouse a click on a row, its ⋯ or a right-click; the column moves over and the panes narrow beside it, on a phone it covers the page. A page whose library was deleted while it was away says so and offers the others instead of showing "offline"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 02:53:58 -05:00
1 parent f888525808
commit 037c13b549
10 files changed
+993 -44

No files matched your search

+340 -5
View File
@@ -1,13 +1,16 @@
/**
* Several libraries, from the page: every address names its library (`/l/<id>`), `/` opens the one
* last used, :/library lists, makes and opens them (a page load), a new library starts with its root
* last used, :/library makes and opens them (a page load), a new library starts with its root
* alone, nothing of one library is found from another (the jump box, nearby and Related, a node's
* address), and each library keeps its own view. The panel that lists them is step 4's; these
* tests use the command and the API. They make their own libraries and delete them at the end: the
* other specs share the first.
* address), and each library keeps its own view. The libraries panel (m, or the library's name in
* the top bar): opening and closing it by key, click and a press outside, its rows, making,
* renaming and deleting a library from it by key and by mouse, the last one refusing, switching
* with each library's view kept, the panes beside it with their curves, a phone's width, and a page
* whose library was deleted while it was away. The tests make their own libraries and delete them
* at the end: the other specs share the first.
*/
import { expect, test, type Page } from "@playwright/test";
import { command, keys, libraryId, settle, state } from "./helpers";
import { autoLayout, command, curveFaults, keys, libraryId, settle, state } from "./helpers";
const ready = (page: Page) => page.waitForFunction(() => (globalThis as any).__ie?.ready);
const status = (page: Page) => page.locator(".status .message");
@@ -108,3 +111,335 @@ test("rename and delete over the API; an unknown library's address goes to the f
const last = await page.request.delete(`/api/libraries/${first}`);
expect(last.status()).toBe(409);
});
// ---- the libraries panel ----
const panel = (page: Page) => page.locator(".panel.left[data-libraries]");
const trigger = (page: Page) => page.locator(".docbar .lib-name");
const rows = (page: Page) => panel(page).locator(".lib-row[data-lib]");
const row = (page: Page, title: string) => panel(page).locator(".lib-row[data-lib]", { has: page.locator(".lib-t", { hasText: title }) });
const titles = (page: Page) => rows(page).locator(".lib-t").allTextContents();
const loaded = (page: Page) => expect(panel(page)).not.toHaveAttribute("data-loading", /./);
const frames = (page: Page) => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
/** Until the strip and its panes have stopped scrolling (a pane opened slides into view), then two frames for the curves. */
async function still(page: Page) {
await page.waitForFunction(
() =>
new Promise((r) => {
const at = () => [document.querySelector(".strip")!, ...document.querySelectorAll(".strip > .col, .strip .pane-scroll")].map((el) => `${el.scrollLeft},${el.scrollTop},${Math.round(el.getBoundingClientRect().left)},${Math.round(el.getBoundingClientRect().width)}`).join();
const x = at();
setTimeout(() => r(at() === x), 250);
}),
);
await frames(page);
}
const api = async (page: Page) => ((await (await page.request.get("/api/libraries")).json()).libraries as { id: string; title: string; nodes: number }[]);
const focusTitle = (page: Page) => state(page, (s) => s.snap.nodes[s.focus.node]?.title as string);
test("the library's name opens the panel; a second click, m, Esc or a press outside closes it", async ({ page }) => {
await page.goto("/");
await ready(page);
await expect(trigger(page)).toHaveText("Library");
await expect(trigger(page)).toHaveAttribute("aria-expanded", "false");
// A click opens it, on the left, and the page makes room.
await trigger(page).click();
await expect(panel(page)).toBeVisible();
await expect(trigger(page)).toHaveAttribute("aria-expanded", "true");
await expect(page.locator(".app")).toHaveClass(/with-left/);
const box = (await panel(page).boundingBox())!;
expect(box.x).toBe(0);
// It hangs below the top bar: the name that opened it stays where it was, clear of it.
const bar = (await trigger(page).boundingBox())!;
expect(box.y).toBeGreaterThanOrEqual(bar.y + bar.height - 1);
const article = (await page.locator("article").boundingBox())!;
expect(article.x).toBeGreaterThanOrEqual(box.x + box.width);
await expect(page.locator(".status .grain")).toHaveText("libraries");
await expect(page.locator(".status .message")).toContainText("open");
// A second click on the name closes it, and does not open it again.
await trigger(page).click();
await expect(panel(page)).toHaveCount(0);
await page.waitForTimeout(150);
await expect(panel(page)).toHaveCount(0);
await expect(page.locator(".app")).not.toHaveClass(/with-left/);
// m opens and closes it; so does Esc.
await keys(page, "m");
await expect(panel(page)).toBeVisible();
await keys(page, "m");
await expect(panel(page)).toHaveCount(0);
await keys(page, "m");
await expect(panel(page)).toBeVisible();
await keys(page, "Escape");
await expect(panel(page)).toHaveCount(0);
// The top bar's menu offers it too.
await page.locator(".docbar .tool", { hasText: "menu" }).click();
await page.locator(".menu .mi", { hasText: "Libraries…" }).click();
await expect(panel(page)).toBeVisible();
// A press outside closes it, and the click does nothing else: the row under it is not opened.
const openBefore = await state(page, (s) => s.open.size);
await page.locator("article .row", { hasText: "Octopus minds" }).click();
await expect(panel(page)).toHaveCount(0);
expect(await state(page, (s) => s.open.size)).toBe(openBefore);
// While it is open the keys are its own: j does not move the page's focus.
const before = await focusTitle(page);
await keys(page, "m j j Escape");
expect(await focusTitle(page)).toBe(before);
// The help lists it.
await keys(page, "?");
await expect(page.locator(".help")).toContainText("the libraries panel");
await keys(page, "Escape");
});
test("the panel lists every library with its size, marks the one open here, and will not delete the last", async ({ page }) => {
const first = await libraryId(page);
expect((await api(page)).map((l) => l.id)).toEqual([first]);
await page.goto("/");
await ready(page);
await keys(page, "m");
await loaded(page);
expect(await titles(page)).toEqual(["Library"]);
const mine = row(page, "Library");
await expect(mine).toHaveClass(/current/);
await expect(mine).toHaveClass(/selected/);
await expect(mine.locator(".lib-mark")).toHaveText("●");
// Its size, as the library's own byline counts it.
const byline = (await page.locator(".top .byline").textContent())!;
const count = /(\d[\d,]*) nodes/.exec(byline)![1];
await expect(mine.locator(".sub")).toHaveText(`${count} nodes · open here`);
// D refuses, saying why; its menu offers Delete disabled.
await keys(page, "D");
await expect(page.locator(".lib-confirm")).toHaveCount(0);
await expect(status(page)).toContainText("The last library cannot be deleted");
await mine.click({ button: "right" });
await expect(page.locator(".menu .mi", { hasText: "Delete…" })).toHaveAttribute("aria-disabled", "true");
await expect(page.locator(".menu .mi", { hasText: "Open here already" })).toHaveAttribute("aria-disabled", "true");
await keys(page, "Escape");
// The server agrees.
expect((await page.request.delete(`/api/libraries/${first}`)).status()).toBe(409);
// A click on this page's own library just closes the panel.
await mine.locator(".lib-t").click();
await expect(panel(page)).toHaveCount(0);
await expect(page).toHaveURL(new RegExp(`/l/${first}$`));
});
test("from the panel: n makes a library and opens it, r renames inline, D asks and y deletes; switching keeps each library's view", async ({ page }) => {
const first = await libraryId(page);
await page.goto("/");
await ready(page);
// Leave the first library somewhere: Octopus minds open, the focus on it.
await keys(page, "/");
await page.keyboard.type("Octopus minds");
await page.keyboard.press("Enter");
await expect.poll(() => focusTitle(page)).toBe("Octopus minds");
await keys(page, "Enter");
await expect.poll(() => state(page, (s) => s.open.has(s.focus.node))).toBe(true);
// n: a name, typed in the panel; Enter makes the library and opens it (a page load).
await keys(page, "m");
await keys(page, "n");
const box = panel(page).locator(".lib-input");
await expect(box).toBeFocused();
// An empty name is refused; Esc leaves it.
await page.keyboard.press("Enter");
await expect(status(page)).toContainText("Give it a name");
await page.keyboard.press("Escape");
await expect(box).toHaveCount(0);
await expect(panel(page)).toBeVisible();
await keys(page, "n");
await page.keyboard.type("Scratch");
await page.keyboard.press("Enter");
await page.waitForURL((u) => /^\/l\/[0-9a-z]+$/.test(u.pathname) && !u.pathname.endsWith(first));
await ready(page);
const scratch = await lib(page);
await expect(page.locator(".top h1")).toHaveText("Scratch");
await expect(trigger(page)).toHaveText("Scratch");
// Somewhere of its own here: a section, focused.
await keys(page, "a");
await page.keyboard.type("A scratch section");
await page.keyboard.press("Enter");
await expect.poll(() => focusTitle(page)).toBe("A scratch section");
await page.waitForFunction(() => (globalThis as any).__ie.synced());
// The panel lists both, in order, this one marked; j k move.
await keys(page, "m");
await loaded(page);
expect(await titles(page)).toEqual(["Library", "Scratch"]);
await expect(row(page, "Scratch")).toHaveClass(/current/);
await expect(row(page, "Scratch").locator(".sub")).toHaveText("1 node · open here");
await keys(page, "k");
await expect(row(page, "Library")).toHaveClass(/selected/);
await keys(page, "j");
await expect(row(page, "Scratch")).toHaveClass(/selected/);
// r renames inline: this page's own library, so its root's title follows.
await keys(page, "r");
await expect(box).toHaveValue("Scratch");
await page.keyboard.press("End");
await page.keyboard.type(" pad");
await page.keyboard.press("Enter");
await expect(row(page, "Scratch pad")).toHaveCount(1);
await expect(trigger(page)).toHaveText("Scratch pad");
await expect(page.locator(".top h1")).toHaveText("Scratch pad");
// Enter on the other row opens it, by a page load, where it was left.
await keys(page, "k Enter");
await page.waitForURL(new RegExp(`/l/${first}`));
await ready(page);
await expect.poll(() => focusTitle(page)).toBe("Octopus minds");
expect(await state(page, (s) => s.open.has(s.focus.node))).toBe(true);
// And back by a click on its row: there too.
await trigger(page).click();
await row(page, "Scratch pad").locator(".lib-t").click();
await page.waitForURL(new RegExp(`/l/${scratch}`));
await ready(page);
await expect.poll(() => focusTitle(page)).toBe("A scratch section");
// Rename by the mouse: a right-click on a row, Rename…; Esc in the box leaves the name as it was.
await keys(page, "m");
await row(page, "Library").click({ button: "right" });
await page.locator(".menu .mi", { hasText: "Rename…" }).click();
await expect(box).toHaveValue("Library");
await page.keyboard.press("Escape");
await expect(row(page, "Library")).toHaveCount(1);
expect((await api(page)).find((l) => l.id === first)!.title).toBe("Library");
// D asks first, saying where the files go; n keeps it.
const doomed = (await (await page.request.post("/api/libraries", { data: { title: "Doomed" } })).json()).library.id as string;
await keys(page, "Escape m");
await loaded(page);
expect(await titles(page)).toEqual(["Library", "Scratch pad", "Doomed"]);
await keys(page, "j D");
await expect(row(page, "Doomed").locator(".lib-confirm")).toContainText("libraries/.deleted/");
await expect(status(page)).toContainText("delete “Doomed”?");
// While it asks, j moves nothing.
await keys(page, "k");
await expect(row(page, "Doomed")).toHaveClass(/selected/);
await keys(page, "n");
await expect(page.locator(".lib-confirm")).toHaveCount(0);
expect((await api(page)).some((l) => l.id === doomed)).toBe(true);
// y deletes it: gone from the list and the server, and the panel says where its files went.
await keys(page, "D y");
await expect(row(page, "Doomed")).toHaveCount(0);
await expect(panel(page).locator(".lib-note")).toContainText(`libraries/.deleted/${doomed}-`);
expect((await api(page)).some((l) => l.id === doomed)).toBe(false);
await expect(row(page, "Scratch pad")).toHaveClass(/selected/);
// Deleting the library open here, by the mouse (its ⋯, Delete…, then the y button): the page goes to the first.
await row(page, "Scratch pad").hover();
await row(page, "Scratch pad").locator("[data-lib-more]").click();
await page.locator(".menu .mi", { hasText: "Delete…" }).click();
await row(page, "Scratch pad").locator(".lib-confirm .key[data-key=y]").click();
await page.waitForURL(new RegExp(`/l/${first}$`));
await ready(page);
await expect(status(page)).toContainText("Deleted “Scratch pad”");
expect((await api(page)).map((l) => l.id)).toEqual([first]);
});
test("in the panes view the panel narrows the panes, and the curves follow it there and back", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await autoLayout(page);
const other = (await (await page.request.post("/api/libraries", { data: { title: "Beside" } })).json()).library.id as string;
await page.goto("/");
await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready);
await page.locator(".pane .row", { hasText: "Infinispand" }).first().dispatchEvent("click");
await page.locator(".pane .row", { hasText: "Expansion by depth" }).first().dispatchEvent("click");
await expect(page.locator(".strip .pane")).toHaveCount(3);
await still(page);
expect(await curveFaults(page), "before").toEqual([]);
expect(await page.locator(".curves path:not(.foot):not(.frame)").count()).toBeGreaterThan(0);
const strip = (await page.locator(".strip").boundingBox())!;
await keys(page, "m");
await expect(panel(page)).toBeVisible();
const p = (await panel(page).boundingBox())!;
// The panes start where the panel ends; the top bar runs on above both.
await expect.poll(async () => Math.round((await page.locator(".panes").boundingBox())!.x)).toBe(Math.round(p.x + p.width));
expect(Math.round((await page.locator(".docbar").boundingBox())!.x)).toBe(0);
await expect.poll(async () => Math.round((await page.locator(".strip").boundingBox())!.width)).toBe(Math.round(strip.width - p.width));
await still(page);
expect(await curveFaults(page), "with the panel").toEqual([]);
// With the history panel open on the right as well: the panes between the two.
await keys(page, "Escape g");
await trigger(page).click();
await expect(panel(page)).toBeVisible();
await expect(page.locator(".panel:not(.left)")).toBeVisible();
const right = (await page.locator(".panel:not(.left)").boundingBox())!;
await expect.poll(async () => { const b = (await page.locator(".panes").boundingBox())!; return Math.round(b.x + b.width); }).toBe(Math.round(right.x));
await still(page);
expect(await curveFaults(page), "between two panels").toEqual([]);
// The panel has the keys over the history panel's; closed, history has them again.
await keys(page, "Escape");
await expect(panel(page)).toHaveCount(0);
expect(await state(page, (s) => s.mode)).toBe("history");
await keys(page, "Escape");
await expect.poll(async () => Math.round((await page.locator(".strip").boundingBox())!.width)).toBe(Math.round(strip.width));
await still(page);
expect(await curveFaults(page), "after").toEqual([]);
expect((await page.request.delete(`/api/libraries/${other}`)).ok()).toBe(true);
});
test("on a phone the panel covers the page instead of squeezing the column", async ({ browser }) => {
const port = new URL(test.info().project.use.baseURL!).port;
const ctx = await browser.newContext({ viewport: { width: 390, height: 800 }, hasTouch: true, isMobile: true, baseURL: `http://localhost:${port}` });
const page = await ctx.newPage();
const other = (await (await page.request.post("/api/libraries", { data: { title: "Pocket" } })).json()).library.id as string;
await page.goto("/");
await ready(page);
const article = (await page.locator("article").boundingBox())!;
await trigger(page).tap();
await expect(panel(page)).toBeVisible();
await loaded(page);
const p = (await panel(page).boundingBox())!;
expect(p.x).toBe(0);
expect(Math.round(p.width)).toBe(390);
// The column under it is as it was.
const after = (await page.locator("article").boundingBox())!;
expect([after.x, after.width]).toEqual([article.x, article.width]);
expect(await titles(page)).toEqual(["Library", "Pocket"]);
// A row's ⋯ shows without hovering; a tap on the name closes the panel.
await expect(row(page, "Pocket").locator("[data-lib-more]")).toBeVisible();
await trigger(page).tap();
await expect(panel(page)).toHaveCount(0);
// A tap on a row opens that library.
await trigger(page).tap();
await row(page, "Pocket").locator(".lib-t").tap();
await page.waitForURL(new RegExp(`/l/${other}`));
await ready(page);
await expect(page.locator(".top h1")).toHaveText("Pocket");
expect((await page.request.delete(`/api/libraries/${other}`)).ok()).toBe(true);
await ctx.close();
});
test("a page whose library was deleted while it was away says so and offers the others", async ({ page }) => {
const first = await libraryId(page);
const away = (await (await page.request.post("/api/libraries", { data: { title: "Away" } })).json()).library.id as string;
// The page cannot hear the server: its notice stream fails, as when the machine slept.
let cut = true;
await page.route(/\/events$/, (r) => (cut ? r.abort() : r.continue()));
await page.goto(`/l/${away}`);
await ready(page);
await expect(page.locator(".top h1")).toHaveText("Away");
// Deleted meanwhile, elsewhere; the page missed the notice.
expect((await page.request.delete(`/api/libraries/${away}`)).ok()).toBe(true);
// An edit goes nowhere: the server has no such library (a 404), and the page says so instead of "offline".
await keys(page, "a");
await page.keyboard.type("Written after");
await page.keyboard.press("Enter");
await expect(page.locator(".save-state")).toHaveText("deleted · not saved");
await expect(status(page)).toContainText("This library has been deleted");
await expect(panel(page)).toBeVisible();
await expect(panel(page).locator(".lib-gone")).toContainText("deleted on the server");
await loaded(page);
expect(await titles(page)).toEqual(["Library"]);
await keys(page, "Enter");
await page.waitForURL(new RegExp(`/l/${first}`));
await ready(page);
// The same when the page learns it from its notice stream coming back (no edit made).
const again = (await (await page.request.post("/api/libraries", { data: { title: "Away again" } })).json()).library.id as string;
cut = true;
await page.goto(`/l/${again}`);
await ready(page);
await expect(page.locator(".top h1")).toHaveText("Away again");
expect((await page.request.delete(`/api/libraries/${again}`)).ok()).toBe(true);
cut = false;
await expect(page.locator(".save-state")).toHaveText("deleted · not saved", { timeout: 15_000 });
await expect(panel(page)).toBeVisible();
});
+15 -4
View File
@@ -5,7 +5,7 @@ import { clip, plain } from "../core/text";
import { hostOf } from "../core/ref";
import { nodeRef } from "../core/links";
import { HELP, handleKey } from "./keys";
import { DocBar } from "./Menu";
import { DocBar, LibrariesPanel } from "./Menu";
import { LinkCard, LinkPicker, LinksPanel, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
import { Panes } from "./Panes";
@@ -402,6 +402,16 @@ function StatusLine() {
? [`${store.reviewRows().findIndex((x) => x.key === row.key) + 1}/${store.reviewRows().length} ${row.status}`, ...(row.status !== "linked" ? [["y", "link"] as [string, string]] : []), ...(row.status !== "rejected" ? [["n", row.status === "linked" ? "remove" : "decline"] as [string, string]] : []), ["j", "next"], ["Enter", "go"], ["Escape", "close"]]
: ["links list", ["1", "linked"], ["2", "rejected"], ["3", "pending"], ["Escape", "close"]]
: null;
// The libraries panel: its keys, or the question a deletion waits on.
const lp = store.libs;
const libsHint: Hint | null =
lp && !store.status
? lp.confirm
? [`delete “${clip(store.libraries.find((l) => l.id === lp.confirm)?.title ?? "", 40)}”?`, ["y", "delete"], ["n", "keep"]]
: lp.edit
? [lp.edit.kind === "new" ? "the new library's name" : "the library's new name", "⏎ keeps it", ["Escape", "leave it"]]
: ["j k", ["Enter", "open"], ["n", "new"], ["r", "rename"], ["D", "delete"], ["Escape", "close"]]
: null;
const hint: Hint = store.aux
? store.aux.kind === "wiki"
? store.inArticleText
@@ -430,9 +440,9 @@ function StatusLine() {
: [];
return (
<footer class="status">
<span class={`grain ${store.aux ? "aux" : f.grain}`}>{store.preview ? "history" : store.mode === "review" ? "review" : store.aux ? (store.aux.kind === "wiki" ? "article" : store.aux.kind === "back" ? "linked" : "target") : f.grain}</span>
<span class={`grain ${lp ? "aux" : store.aux ? "aux" : f.grain}`}>{lp ? "libraries" : store.preview ? "history" : store.mode === "review" ? "review" : store.aux ? (store.aux.kind === "wiki" ? "article" : store.aux.kind === "back" ? "linked" : "target") : f.grain}</span>
<span class="path">{path}</span>
<span class="message">{reviewing ? <Hints hint={reviewing} /> : store.status || (hint.length ? <Hints hint={hint} /> : <FirstRun />)}</span>
<span class="message">{libsHint ? <Hints hint={libsHint} /> : reviewing ? <Hints hint={reviewing} /> : store.status || (hint.length ? <Hints hint={hint} /> : <FirstRun />)}</span>
<span class="right">
{store.links.job?.state === "running" && (
<span class="job" title={store.jobText(store.links.job)}>
@@ -730,7 +740,7 @@ export function App() {
};
return (
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "review" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "review" ? " with-panel" : ""}${store.libs ? " with-left" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
<main
class="page"
onClick={onClick}
@@ -746,6 +756,7 @@ export function App() {
)}
{panes ? <Panes /> : <Page />}
</main>
<LibrariesPanel />
{store.mode === "history" && <HistoryPanel verdict={verdict} />}
{store.mode === "review" && <LinksPanel />}
{store.mode === "help" && <Help />}
+184 -7
View File
@@ -1,28 +1,48 @@
/** The top bar: where the reader is (the library's name) and whether it is saved, with undo and the menu. */
import { topEntries } from "./actions";
import { act, showMenu } from "./Mouse";
/**
* The top bar: where the reader is (the library's name, which opens the libraries panel) and
* whether it is saved, with undo and the menu; and the libraries panel, on the left.
*/
import { useLayoutEffect, useRef } from "preact/hooks";
import { libraryEntries, topEntries } from "./actions";
import { nodeCount } from "./libraries";
import { Hints, Key, act, showMenu, type Hint } from "./Mouse";
import { press } from "./press";
import { store } from "./store";
/** A press on a tool keeps the focus where it was (the keys stay with the page). */
const keep = (e: MouseEvent) => e.preventDefault();
const SAVE_LABEL = { saved: "saved", saving: "saving…", offline: "offline · kept in this browser", foreign: "not saved · reload the page" };
const SAVE_LABEL = { saved: "saved", saving: "saving…", offline: "offline · kept in this browser", foreign: "not saved · reload the page", deleted: "deleted · not saved" };
const SAVE_TITLE = {
saved: "Every edit is saved as you make it. The server has all of them.",
saving: "Every edit is saved as you make it. The latest are on their way to the server.",
offline: "The server cannot be reached. Edits are kept in this browser and sent when it can.",
foreign: "The server now holds a different library than this page.",
deleted: "The server no longer has this library: it was deleted, and its files moved aside. Open another from the libraries (m).",
};
export function DocBar() {
const state = store.saveState();
const snap = store.snap;
return (
<nav class="docbar">
<span class="lib-name" title="The library">
{snap.nodes[snap.root].title || "Library"}
</span>
<button
type="button"
class="tool lib-name"
data-libs-trigger
aria-haspopup="dialog"
aria-expanded={store.libs ? "true" : "false"}
title="The libraries: open, make, rename or delete one (m)"
onMouseDown={keep}
onClick={(e) => {
e.stopPropagation();
store.toggleLibraries();
}}
>
<span class="lib-title">{snap.nodes[snap.root].title || "Library"}</span>
<span class={`chev${store.libs ? " up" : ""}`} />
</button>
<span class={`save-state ${state}`} title={SAVE_TITLE[state]}>
{SAVE_LABEL[state]}
</span>
@@ -53,3 +73,160 @@ export function DocBar() {
</nav>
);
}
// ---- the libraries panel ----
/**
* The libraries, on the left: each a tree of its own, with its name, its size and which one this
* page holds. j k move, Enter opens (a page load), n names a new one, r renames, D deletes after a
* y; Esc, m or the library's name in the top bar closes it, and so does a press anywhere outside it
* (that press does nothing else). It hangs below the top bar, so the name that opened it stays
* where it was; beside it the page makes room (the column moves over, the panes narrow), and on a
* phone it covers the page.
*/
export function LibrariesPanel() {
const p = store.libs;
const ref = useRef<HTMLElement>(null);
// Below the top bar, wherever the view puts it.
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const place = () => {
const bar = document.querySelector(".docbar")?.getBoundingClientRect();
el.style.top = `${Math.max(0, Math.round(bar?.bottom ?? 0))}px`;
};
place();
window.addEventListener("resize", place);
return () => window.removeEventListener("resize", place);
});
useLayoutEffect(() => {
ref.current?.querySelector(".lib-row.selected")?.scrollIntoView({ block: "nearest" });
});
// A press outside closes it, as a press outside closes a menu; the click it begins does nothing
// else (so a press on the library's name closes it, and its click does not open it again).
useLayoutEffect(() => {
if (!p) return;
const outside = (e: PointerEvent) => {
const t = e.target as HTMLElement;
if (ref.current?.contains(t) || t.closest?.(".menu, .overlay, .help")) return;
store.closeLibraries();
const swallow = (c: MouseEvent) => (c.stopPropagation(), c.preventDefault());
window.addEventListener("click", swallow, { capture: true, once: true });
setTimeout(() => window.removeEventListener("click", swallow, { capture: true }), 800);
};
document.addEventListener("pointerdown", outside, true);
return () => document.removeEventListener("pointerdown", outside, true);
}, [p]);
if (!p) return null;
const rows = store.libRows();
const only = store.libraries.length <= 1;
const menuFor = (id: string, at: HTMLElement | { x: number; y: number }) => {
store.libSelect(id);
const l = rows.find((x) => x.id === id);
if (!l) return;
showMenu(libraryEntries({ title: l.title, current: id === store.library && !store.gone, last: only }, act), at);
};
const head: Hint = [["n", "new"], ["Escape", "close"]];
return (
<aside class="panel left libraries" ref={ref} data-libraries data-loading={p.loading ? "1" : undefined} aria-label="Libraries">
<div class="panel-head">
<span>Libraries{p.loading ? " …" : ""}</span>
<span class="keys">
<Hints hint={head} />
</span>
</div>
{store.gone && <div class="verdict lib-gone">This library was deleted on the server, and its files moved aside; what was edited here since is not saved. Open another:</div>}
{p.note && <div class="lib-note">{p.note}</div>}
<div class="lib-list" role="listbox" aria-label="Libraries">
{rows.map((l) => {
const current = l.id === store.library;
const selected = l.id === p.sel;
const renaming = p.edit?.kind === "rename" && p.edit.id === l.id;
const confirming = p.confirm === l.id;
return (
<div
key={l.id}
class={`item lib-row${selected ? " selected" : ""}${current ? " current" : ""}`}
role="option"
aria-selected={selected}
data-lib={l.id}
onClick={(e) => {
e.stopPropagation();
if (renaming || confirming || (e.target as HTMLElement).closest("button, input")) return;
store.libSelect(l.id);
press("Enter");
}}
onContextMenu={(e) => {
if (e.shiftKey || renaming) return;
e.preventDefault();
menuFor(l.id, { x: e.clientX, y: e.clientY });
}}
>
<div class="line">
<span class="lib-mark">{current ? "●" : "○"}</span>
{renaming ? <NameBox initial={l.title} /> : <span class="lib-t">{l.title}</span>}
{!renaming && (
<button type="button" class="more" data-lib-more title="Open, rename or delete (right-click works too)" aria-haspopup="menu" onMouseDown={keep} onClick={(e) => (e.stopPropagation(), menuFor(l.id, e.currentTarget as HTMLElement))}>
⋯
</button>
)}
</div>
<div class="sub">
{nodeCount(l.nodes)}
{current ? (store.gone ? " · deleted" : " · open here") : ""}
</div>
{confirming && (
<div class="lib-confirm" role="alertdialog" aria-label={`Delete ${l.title}?`}>
<p>
Delete “{l.title}”{current ? ", the library open here" : ""}? Its files are moved, unchanged, to <code>libraries/.deleted/</code> in the server's data folder,
from where it can be restored by hand; <kbd>u</kbd> cannot bring it back.
</p>
<Hints hint={[["y", "delete"], ["n", "keep"]]} />
</div>
)}
</div>
);
})}
{!rows.length && <p class="lempty">{p.loading ? "Asking the server…" : "No other library."}</p>}
{p.edit?.kind === "new" ? (
<div class="item lib-row lib-new selected">
<div class="line">
<span class="lib-mark">+</span>
<NameBox initial="" />
</div>
<div class="sub">a new library, its root alone; it opens once made</div>
</div>
) : (
<div class="lib-add">
<Key k="n" what="new library…" />
</div>
)}
</div>
</aside>
);
}
/** The name being typed in the panel: Enter keeps it (a new library is made and opened), Esc leaves it. */
function NameBox({ initial }: { initial: string }) {
return (
<input
class="title-editor lib-input"
aria-label={initial ? "The library's new name" : "The new library's name"}
placeholder="Name of the new library"
defaultValue={initial}
maxLength={200}
ref={(el) => {
if (el && document.activeElement !== el) {
el.focus();
el.select();
}
}}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Escape") (e.preventDefault(), store.libCancel());
else if (e.key === "Enter") (e.preventDefault(), void store.libSubmit((e.target as HTMLInputElement).value));
}}
onClick={(e) => e.stopPropagation()}
/>
);
}
+23
View File
@@ -251,6 +251,7 @@ export function topEntries(c: TopCtx, act: Act): Entry[] {
const auto = (v: TopCtx["autolink"], label: string): Choice => ({ label, on: c.autolink === v, run: () => act.command(`/autolink ${v}`) });
const setting = (label: string, name: string, on: boolean, sub?: string): Item => ({ t: "item", label, sub, keyText: `/${name}`, checked: on, run: () => act.command(`/${name} ${on ? "off" : "on"}`) });
return tidy([
key(act, "Libraries…", "m", { sub: "open, make, rename or delete one" }),
key(act, "Jump to a section…", "/"),
key(act, "History and branches", "g"),
SEP,
@@ -273,6 +274,28 @@ export function topEntries(c: TopCtx, act: Act): Entry[] {
]);
}
// ---- a row of the libraries panel ----
export interface LibCtx {
title: string;
/** The library this page holds. */
current: boolean;
/** The only library: it cannot be deleted. */
last: boolean;
}
/** A library's row (its ⋯, a right-click): open, rename, delete; and a new library. Each presses the panel's key for the row it selected. */
export function libraryEntries(c: LibCtx, act: Act): Entry[] {
return tidy([
head(c.title),
c.current ? key(act, "Open here already", "Enter", { disabled: true }) : key(act, "Open", "Enter", { sub: "loads the page" }),
key(act, "Rename…", "r"),
key(act, "Delete…", "D", c.last ? { disabled: true, sub: "the last library cannot be deleted" } : { sub: "asks first; its files are kept aside" }),
SEP,
key(act, "New library…", "n"),
]);
}
/** The page's own `Act`: keys through the key handler, commands through the command bar's handler. */
export function pageAct(hooks: { command(text: string): void; prompt(prefill: string): void }): Act {
return {
+76 -4
View File
@@ -29,7 +29,8 @@ export const HELP: [string, [string, string][]][] = [
["", "a click on a sentence selects it, and a bar over it offers expand · define · why · example · challenge · ask · link, each with its key (on a phone, at the foot of the screen, × puts it away); a drag selects words, a double click a word"],
["", "right-click (a long press on a phone) on words, a row, a link, a note or a pane: what can be done with it, Copy first. Shift+right-click is the browser's own menu"],
["", "⋯ by a row, a pane's pin, a page's byline or a note (shown when pointed at): the same menu. A stale flag, clicked, offers what to do about it"],
["", "the top bar: the library's name, undo, redo, and menu: jump, history, links, layout and settings. A key named in the status line or a panel's head is a button that presses it"],
["", "the top bar: the library's name (it opens the libraries panel), undo, redo, and menu: libraries, jump, history, links, layout and settings. A key named in the status line or a panel's head is a button that presses it"],
["", "in the libraries panel a click on a row opens that library; its ⋯ (or a right-click) offers open, rename, delete and a new library; a press outside the panel closes it"],
],
],
[
@@ -85,10 +86,16 @@ export const HELP: [string, [string, string][]][] = [
],
],
[
"The library",
"Libraries",
[
["", "everything is a node of one tree, whose root is the library: the first page. Any node can be moved under any other (M, > <), copied (/duplicate), saved to a file (/export) or given a file's tree under it (/import); each acts on the node you are on, with everything under it. The ⋯ menu of any node offers the same"],
["", "there can be several libraries, each a tree of its own with its own address (/l/…): nothing links, moves or is found from one to another (export, then import, carries a tree across). :/library lists them, :/library name opens one, :/library new name makes one"],
["", "there can be several libraries, each a tree of its own with its own address (/l/…): nothing links, moves or is found from one to another (export, then import, carries a tree across)"],
["m", "the libraries panel, on the left (so does a click on the library's name in the top bar; m, Esc or a press outside closes it): every library with its size, ● the one open here"],
["j k", "in the panel: move"],
["Enter", "in the panel: open the library (a page load; each library opens where it was left)"],
["n", "in the panel: a new library: type its name, Enter makes it (its root alone) and opens it"],
["r", "in the panel: rename the library (Enter keeps the name, Esc leaves it)"],
["D", "in the panel: delete the library, after y (n keeps it). Its files are moved, unchanged, to libraries/.deleted/ in the server's data folder, from where it can be restored by hand; u cannot. The last library cannot be deleted"],
],
],
[
@@ -122,7 +129,7 @@ export const HELP: [string, [string, string][]][] = [
["/duplicate title", "save the node you are on, with everything under it, as a copy just after it (titled \"… (copy)\" unless given one); the copy has the focus"],
["/export", "save the node you are on, with everything under it, to a .md file (on the library root, the whole library)"],
["/import", "read a .md file into the node you are on, as its last child (on the library root, a new top-level node)"],
["/library [name]", "list the libraries; with a name, open that library (a page load); /library new name makes one and opens it. Libraries are separate trees: nothing links, moves or is found across them"],
["/library [name]", "the libraries panel (m); with a name, open that library (a page load); /library new name makes one and opens it"],
["/link target", "link the selection (or the node): w:Title, /Top title/Section (titles from the library root), an address, or a Wikipedia title"],
["/unlink", "remove the link on the selection (for good: its words are declined; a note that also links keeps its text), or the node's own target"],
["/autolink review|suggest|on|off", "after an edit: the model reviews what was found and links what it approves (review, the default with a model; u undoes, S lists every decision), suggest everything for you to decide (suggest; what review does without a model, or when the model fails or its limit is reached), link the scanner's sure ones unreviewed (on), or look for nothing (off)"],
@@ -181,6 +188,12 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
return;
}
// The libraries panel has the keys while it is open, over any other panel.
if (store.libs) {
if (libsKey(k)) done();
return;
}
if (store.mode === "history") {
const items = store.panel();
const item = items[store.historyIndex];
@@ -457,6 +470,62 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
done();
}
/**
* Keys in the libraries panel. A deletion waiting for its answer takes only y and n (or Esc); a
* name being typed has its own box, which keeps its keys. Returns whether the key was taken.
*/
function libsKey(k: string): boolean {
const p = store.libs!;
if (p.confirm) {
switch (k) {
case "y":
void store.libConfirm();
return true;
case "n":
case "Escape":
store.libCancel();
return true;
default:
return false;
}
}
switch (k) {
case "j":
case "ArrowDown":
store.libStep(1);
return true;
case "k":
case "ArrowUp":
store.libStep(-1);
return true;
case "Enter":
case "l":
store.libOpen();
return true;
case "n":
case "a":
store.libEdit("new");
return true;
case "r":
store.libEdit("rename");
return true;
case "D":
store.libDelete();
return true;
case "Escape":
case "m":
case "q":
case "h":
store.closeLibraries();
return true;
case "?":
store.setMode("help");
return true;
default:
return false;
}
}
/** Keys that mean the same on a node and on an aux row. Returns whether the key was taken. */
function commonKey(k: string, hooks: KeyHooks): boolean {
switch (k) {
@@ -485,6 +554,9 @@ function commonKey(k: string, hooks: KeyHooks): boolean {
case "g":
store.openHistory();
return true;
case "m":
store.openLibraries();
return true;
case "/":
store.setMode("jump");
return true;
+49
View File
@@ -0,0 +1,49 @@
/**
* The libraries panel's state, as pure functions (the store holds it, the panel in Menu.tsx draws
* it, keys.ts and the mouse drive it). A row is chosen by its library's id, not its place, so a
* list fetched again under the reader keeps the row they were on.
*/
import type { LibraryInfo } from "./api";
export interface LibPanel {
/** The library whose row is selected. */
sel: string;
/** A name being typed: for a new library, or a library being renamed. */
edit: { kind: "new" } | { kind: "rename"; id: string } | null;
/** The library whose deletion waits for y. */
confirm: string | null;
/** The list is being fetched again (it shows the last one meanwhile). */
loading: boolean;
/** What the panel last did that the reader should be able to read whole (where a deleted library went). */
note?: string;
}
/** A panel opened on this page's library (or the first, if the list does not have it). */
export function openPanel(list: LibraryInfo[], current: string): LibPanel {
return { sel: list.some((l) => l.id === current) ? current : (list[0]?.id ?? current), edit: null, confirm: null, loading: true };
}
/** The row `d` steps from the selected one, held at the ends. */
export function step(list: LibraryInfo[], sel: string, d: number): string {
if (!list.length) return sel;
const i = list.findIndex((l) => l.id === sel);
const at = i < 0 ? 0 : Math.max(0, Math.min(list.length - 1, i + d));
return list[at].id;
}
/** After a fetch: the same library if it is still listed, else the row that stood where it was (or the last). */
export function keep(before: LibraryInfo[], after: LibraryInfo[], sel: string): string {
if (after.some((l) => l.id === sel)) return sel;
if (!after.length) return sel;
const i = before.findIndex((l) => l.id === sel);
return after[Math.max(0, Math.min(after.length - 1, i))].id;
}
/** Where a deleted library went, as the data folder names it (`libraries/.deleted/<id>-<time>`), from the server's full path. */
export function deletedPlace(movedTo: string): string {
const m = /(libraries[\\/]\.deleted[\\/][^\\/]+)[\\/]?$/.exec(movedTo);
return m ? m[1].replace(/\\/g, "/") : movedTo;
}
/** How a library's size reads in its row. */
export const nodeCount = (n: number) => `${n} node${n === 1 ? "" : "s"}`;
+45 -3
View File
@@ -19,6 +19,8 @@ export interface SessionHooks {
connection(up: boolean): void;
/** The server holds a different library than this page (its data directory was replaced). */
foreign(): void;
/** The server has no such library any more: it was deleted, perhaps while this page could not hear of it. */
gone(): void;
/** Any other notice from the server (a link job's progress). */
message?(msg: Record<string, unknown>): void;
}
@@ -87,7 +89,10 @@ export class Session {
private async fetchBranch(name: string): Promise<Doc | null> {
const res = await fetch(libApi(`/branch/${encodeURIComponent(name)}`));
if (!res.ok) return null;
if (!res.ok) {
if (res.status === 404 && (await failure(res)).message.startsWith("no library")) this.vanished();
return null;
}
if (res.headers.get("x-library") !== this.library) {
this.lost();
return null;
@@ -177,7 +182,9 @@ export class Session {
});
if (!res.ok) {
if (res.status === 409) this.lost();
throw await failure(res);
const err = await failure(res);
if (res.status === 404 && err.message.startsWith("no library")) this.vanished();
throw err;
}
const theirs = decodeVV(res.headers.get("x-vv")!);
report = mergeUpdate(doc, new Uint8Array(await res.arrayBuffer()), theirs);
@@ -201,6 +208,14 @@ export class Session {
this.hooks.foreign();
}
/** The library is gone from the server: stop sending, and say so once. */
vanished() {
if (this.foreign) return;
this.foreign = true;
this.disconnect();
this.hooks.gone();
}
/** Listen for other writers. */
connect() {
if (this.events || this.foreign) return;
@@ -215,10 +230,37 @@ export class Session {
// Back after an outage (or just connected): exchange whatever either side missed.
void this.syncAll();
};
events.onerror = () => this.hooks.connection(false);
events.onerror = () => {
this.hooks.connection(false);
// A refused connection is tried again by the browser; an answer that is not a stream (a 404
// for a library deleted while this page was away) ends it for good. Ask why, and go on
// listening unless the library is gone.
if (events.readyState === EventSource.CLOSED && this.events === events) {
this.events = null;
void this.probe();
}
};
this.events = events;
}
/** After the notice stream ended: whether the library is still there (then listen again), gone, or the server unreachable (ask again later). */
private async probe(wait = 1000) {
if (this.foreign) return;
let status = 0;
let message = "";
try {
const res = await fetch(libApi("/state"));
status = res.status;
if (!res.ok) message = (await failure(res)).message;
} catch {
/* unreachable */
}
if (this.foreign) return;
if (status === 404 && message.startsWith("no library")) return this.vanished();
if (status >= 200 && status < 300) return this.connect();
setTimeout(() => void this.probe(Math.min(wait * 2, 30_000)), wait);
}
disconnect() {
this.events?.close();
this.events = null;
+161 -17
View File
@@ -33,6 +33,7 @@ import {
import type { LLM } from "../llm/types";
import { DEFAULT_LIMITS, wantsResearch } from "../llm/web";
import { createLibrary, deleteLibrary, libApi, listLibraries, renameLibrary, setLibrary, type LibraryInfo } from "./api";
import { deletedPlace, keep, openPanel, step, type LibPanel } from "./libraries";
import { remoteLLM } from "./remote";
import { Session } from "./session";
import { refreshAfterCalls } from "./usage";
@@ -275,10 +276,13 @@ class Store {
}
/** Set at a keypress; cleared when the resulting frame has been painted. */
t0: { what: string; at: number } | null = null;
/** Replicas of pre-library documents whose edits never reached the server. */
/** The library this page holds (its id, as in its address), and every library the server has, as it last said. */
library = "";
libraries: LibraryInfo[] = [];
/** The libraries panel (m, or the library's name in the top bar), while it is open. */
libs: LibPanel | null = null;
/** The server no longer has this page's library (deleted, perhaps while this page was away): nothing more is sent. */
gone = false;
/** The panes as a forest of forks (forks.ts); its focused branch is `trail`, and `paneAt` is the pane on it that holds the focus: the active pane. */
forest: Forest<PaneRef, Back> = { trees: [], at: 0 };
@@ -1164,13 +1168,10 @@ class Store {
this.emit();
},
foreign: () => this.say("The server now holds a different library than this page. Edits here are no longer sent; reload the page."),
gone: () => this.libraryGone(),
message: (msg) => {
if (msg.linkJob) this.jobUpdate(msg.linkJob as JobState);
if (msg.library === "deleted") {
this.session.foreign = true;
this.session.disconnect();
this.say("This library has been deleted (the server moved its files aside). Edits here are no longer sent; go to / for another library.");
}
if (msg.library === "deleted") this.session.vanished();
},
});
await this.session.load((state?.branches ?? []).map((b) => b.name), this.online);
@@ -1178,7 +1179,14 @@ class Store {
this.repo.current = this.repo.branches.has(branch) ? branch : "main";
this.restoreView();
this.undoManager();
this.navigate(splitLibrary(location.pathname).part, "replace");
// Opened from the libraries panel (or :/library): where it was left in this browser, not its root.
const switched = sessionStorage.getItem("ie:switch") === library;
sessionStorage.removeItem("ie:switch");
const at = splitLibrary(location.pathname).part;
if (switched && (at === "/" || at === "")) {
window.history.replaceState(null, "", this.here());
this.setTitle();
} else this.navigate(at, "replace");
this.ready = true;
this.prefetchLinks(this.focus.node);
const flash = sessionStorage.getItem("ie:flash");
@@ -1221,9 +1229,11 @@ class Store {
return this.libraries;
}
/** Open another library: a page load, so nothing of this one stays in memory. */
/** Open another library: a page load, so nothing of this one stays in memory. It opens where it was left in this browser. */
switchLibrary(id: string) {
this.session?.flush();
this.saveView();
sessionStorage.setItem("ie:switch", id);
location.assign(inLibrary(id, "/"));
}
@@ -1254,15 +1264,22 @@ class Store {
}
}
/** Delete a library: the server moves its files aside; the last one cannot go. Deleting this one goes to the first other. */
/**
* Delete a library: the server moves its directory, whole, to libraries/.deleted/ in its data
* folder, from where it can be brought back by hand; the last one cannot go. Deleting this
* page's library goes to the first other.
*/
async deleteLibrary(id: string): Promise<boolean> {
const title = this.libraries.find((l) => l.id === id)?.title ?? id;
try {
await deleteLibrary(id);
const { movedTo } = await deleteLibrary(id);
const said = `Deleted “${title}”; its files are kept in ${deletedPlace(movedTo)} in the server's data folder (the README says how to restore it).`;
const left = await this.listLibraries();
if (this.libs) this.libs.note = said;
if (id === this.library) {
sessionStorage.setItem("ie:flash", "Deleted the library; its files were moved aside on the server.");
sessionStorage.setItem("ie:flash", said);
this.switchLibrary(left[0].id);
} else this.say("Deleted the library; its files were moved aside on the server.");
} else this.say(said);
return true;
} catch (err) {
this.say(`Could not delete the library: ${(err as Error).message}`);
@@ -1271,29 +1288,156 @@ class Store {
}
/**
* :/library: with no name, list the libraries; with a name (or id), switch to it; `new <name>`
* :/library: with no name, the libraries panel; with a name (or id), switch to it; `new <name>`
* makes one and switches to it.
*/
async libraryCommand(arg: string) {
const list = await this.listLibraries().catch(() => this.libraries);
const words = arg.trim();
if (!words) return this.say(`Libraries: ${list.map((l) => `${l.id === this.library ? "▸ " : ""}${l.title} (${l.nodes} nodes)`).join(" · ")}. :/library <name> opens one, :/library new <name> makes one.`);
if (!words) return this.openLibraries();
const made = /^new\s+(.+)$/.exec(words);
if (made) return void this.createLibrary(made[1], true);
const list = await this.listLibraries().catch(() => this.libraries);
const lower = words.toLowerCase();
const hit = list.find((l) => l.id === words) ?? list.find((l) => l.title.toLowerCase() === lower) ?? list.find((l) => l.title.toLowerCase().startsWith(lower));
if (!hit) return this.say(`No library “${words}”. :/library lists them.`);
if (!hit) return this.say(`No library “${words}”. m lists them.`);
if (hit.id === this.library) return this.say(`This is “${hit.title}”.`);
this.switchLibrary(hit.id);
}
/** The server has no such library any more (deleted while this page was away, or just now): say so, and offer the others. */
private libraryGone() {
if (this.gone) return;
this.gone = true;
this.online = false;
this.openLibraries();
this.say("This library has been deleted on the server (its files were moved aside). Edits made here are no longer sent: open another library.");
}
// ---- the libraries panel ----
/** m, or the library's name in the top bar: the panel listing the libraries, fetched again as it opens. */
openLibraries() {
const panel = openPanel(this.libraries, this.library);
this.libs = panel;
this.status = "";
this.emit();
const before = this.libraries;
listLibraries()
.then((list) => {
this.libraries = list;
if (this.libs === panel) panel.sel = keep(before, list, panel.sel);
})
.catch((err) => this.libs === panel && this.say(`Could not list the libraries (${(err as Error).message}); showing the list as it last was.`))
.finally(() => {
panel.loading = false;
this.emit();
});
}
closeLibraries() {
if (!this.libs) return;
this.libs = null;
this.emit();
}
toggleLibraries() {
if (this.libs) this.closeLibraries();
else this.openLibraries();
}
/** The libraries the panel lists: the server's, without this page's library once it is gone. */
libRows(): LibraryInfo[] {
return this.gone ? this.libraries.filter((l) => l.id !== this.library) : this.libraries;
}
libSelect(id: string) {
if (!this.libs || this.libs.edit) return;
this.libs.sel = id;
this.libs.confirm = null;
this.emit();
}
libStep(d: number) {
if (!this.libs || this.libs.edit || this.libs.confirm) return;
this.libs.sel = step(this.libRows(), this.libs.sel, d);
this.status = "";
this.emit();
}
/** Enter: open the selected library (a page load); on this page's own, just close the panel. */
libOpen() {
const p = this.libs;
if (!p || p.edit || p.confirm) return;
if (p.sel === this.library && !this.gone) return this.closeLibraries();
if (!this.libRows().some((l) => l.id === p.sel)) return;
this.switchLibrary(p.sel);
}
/** n: name a new library (it opens once made); r: rename the selected one. */
libEdit(kind: "new" | "rename") {
const p = this.libs;
if (!p || p.edit || p.confirm) return;
if (kind === "rename" && !this.libRows().some((l) => l.id === p.sel)) return;
p.edit = kind === "new" ? { kind } : { kind, id: p.sel };
this.status = "";
this.emit();
}
libCancel() {
const p = this.libs;
if (!p) return;
p.edit = null;
p.confirm = null;
this.emit();
}
/** The name typed in the panel: Enter makes the new library (and opens it) or renames. */
async libSubmit(text: string) {
const p = this.libs;
const edit = p?.edit;
if (!p || !edit) return;
const name = text.replace(/\s+/g, " ").trim();
if (!name) return this.say("Give it a name, or Esc to leave it.");
if (edit.kind === "rename" && this.libraries.find((l) => l.id === edit.id)?.title === name) return this.libCancel();
p.edit = null;
this.emit();
if (edit.kind === "new") await this.createLibrary(name, true);
else await this.renameLibrary(edit.id, name);
}
/** D: ask to delete the selected library (y deletes it); the last one cannot be deleted. */
libDelete() {
const p = this.libs;
if (!p || p.edit || p.confirm) return;
const rows = this.libRows();
if (!rows.some((l) => l.id === p.sel)) return;
if (this.libraries.length <= 1) return this.say("The last library cannot be deleted: make another first (n).");
p.confirm = p.sel;
this.status = "";
this.emit();
}
/** y: delete the library waiting for it. */
async libConfirm() {
const p = this.libs;
const id = p?.confirm;
if (!p || !id) return;
p.confirm = null;
const before = this.libraries;
if (await this.deleteLibrary(id)) {
if (this.libs === p && id !== this.library) p.sel = keep(before, this.libraries, id);
}
this.emit();
}
/** The window's title: the article on the column's article page, else the node the reader is on. */
private setTitle() {
document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : label(this.snap, this.activeNode) || "Infinispand";
}
/** Every edit is saved as it is made; this says whether the server has it yet. */
saveState(): "saved" | "saving" | "offline" | "foreign" {
saveState(): "saved" | "saving" | "offline" | "foreign" | "deleted" {
if (this.gone) return "deleted";
if (this.session.foreign) return "foreign";
if (!this.online) return "offline";
return this.session.synced() ? "saved" : "saving";
+49 -3
View File
@@ -66,7 +66,9 @@ body {
.app { min-height: 100vh; }
.loading, .fatal { max-width: 34em; margin: 20vh auto; padding: 0 20px; font-family: var(--sans); color: var(--dim); }
.page { max-width: calc(var(--col) + var(--gap) + var(--margin) + 40px); margin: 0 auto; padding: 44px 20px 30vh; }
/* The page's widest: the column, its gap and the margin for notes (only the column where no margin fits). */
:root { --page-w: calc(var(--col) + var(--gap) + var(--margin) + 40px); }
.page { max-width: var(--page-w); margin: 0 auto; padding: 44px 20px 30vh; }
article { width: min(100%, var(--col)); }
/* ---- the top of the page ---- */
@@ -160,7 +162,7 @@ article { width: min(100%, var(--col)); }
/* Below the width where a margin fits, notes fall into the column. */
@media (max-width: 1139px) {
.page { max-width: calc(var(--col) + 40px); }
:root { --page-w: calc(var(--col) + 40px); }
.sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
}
.with-panel .sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
@@ -595,7 +597,10 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
* edit yet; undo, redo and the menu on the right.
*/
.docbar { display: flex; align-items: baseline; gap: 0.9em; width: min(100%, var(--col)); margin: -30px 0 16px; min-width: 0; font-family: var(--sans); font-size: 0.66rem; color: var(--faint); letter-spacing: 0.02em; }
.lib-name { min-width: 0; max-width: 75%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dim); }
/* The library's name is the button that opens the libraries panel, with the menu's chevron (turned up while the panel is open). */
.docbar .lib-name { display: inline-flex; align-items: baseline; min-width: 0; max-width: 75%; white-space: nowrap; }
.lib-name .lib-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.docbar .tool .chev.up { transform: rotate(180deg); }
.save-state { white-space: nowrap; }
.save-state.offline, .save-state.deleted { color: var(--attn); }
.view-panes .docbar { flex: none; width: auto; margin: 0; padding: 0.3rem 0.9rem 0.25rem; border-bottom: 1px solid var(--hair); }
@@ -877,3 +882,44 @@ html { scroll-padding-top: 48px; }
.status .q { display: inline; }
}
/* ---- end mouse ---- */
/* ---- the libraries panel (src/ui/Menu.tsx) ----
* On the left, hanging from the top bar so the library's name that opens it stays put: one row per
* library (● the one open here), its size, and a ⋯. Beside it the page makes room: the column moves
* over (notes fold into it where the margin no longer fits), the panes narrow; on a phone it covers
* the page instead of squeezing the column.
*/
:root { --left-w: min(300px, 85vw); }
.panel.left { left: 0; right: auto; width: var(--left-w); border-left: 0; border-right: 3px double var(--rule); }
.lib-list { padding-top: 0.35rem; }
.lib-row .line { align-items: baseline; }
.lib-mark { flex: none; width: 1em; color: var(--dim); }
.lib-t { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.lib-row.current .lib-t { font-weight: 600; }
.lib-row .sub { padding-left: 1.6em; }
.lib-row .more { margin-left: auto; align-self: center; }
.lib-row:hover .more, .lib-row.selected .more { opacity: 1; }
.lib-row .lib-input { flex: 1; min-width: 0; font-size: inherit; }
.lib-confirm { margin: 0.35rem 0 0.15rem 1.6em; padding: 0.35rem 0.55rem 0.4rem; background: var(--wash); border-left: 2px solid var(--attn); cursor: default; }
.lib-confirm p { margin: 0 0 0.3rem; color: var(--soft); }
.lib-confirm code { font-family: var(--mono); font-size: 0.92em; }
.lib-note { margin-top: 0.6rem; padding: 0.4rem 0.6rem; background: var(--wash); border-left: 2px solid var(--rule); color: var(--soft); overflow-wrap: anywhere; }
.lib-add { margin: 0.55rem 0.45rem 0; color: var(--faint); }
@media (hover: none) {
.lib-row .more { opacity: 1; padding: 0.45em 0.6em; margin: -0.3em -0.4em -0.3em auto; }
}
@media (min-width: 721px) {
/* The column moves over just enough to clear the panel, its top bar left where it was. */
.with-left:not(.view-panes) .page { --shift: max(20px, calc(var(--left-w) + 28px - max(0px, (100vw - var(--page-w)) / 2))); padding-left: var(--shift); }
.with-left:not(.view-panes) .docbar { margin-left: calc(20px - var(--shift)); width: min(calc(100% + var(--shift) - 20px), var(--col)); }
.with-left.with-panel:not(.view-panes) article { max-width: calc(100vw - min(440px, 92vw) - var(--left-w) - 56px); }
/* The panes narrow beside it; the top bar runs on above both. */
.view-panes.with-left .page > :not(.docbar) { margin-left: var(--left-w); }
}
@media (min-width: 721px) and (max-width: 1739px) {
.with-left .sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
}
@media (max-width: 720px) {
.panel.left { width: auto; right: 0; border-right: 0; }
}
/* ---- end libraries panel ---- */
+51 -1
View File
@@ -1,7 +1,9 @@
/** What the mouse offers (src/ui/actions.ts): every item does what its key does, and the bar, the ⋯ menus and the right-click menu are built from one place. */
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { articleRowEntries, barItems, nodeEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
import { articleRowEntries, barItems, libraryEntries, nodeEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
import { deletedPlace, keep, nodeCount, openPanel, step } from "../src/ui/libraries";
import type { LibraryInfo } from "../src/ui/api";
/** An Act that records what was asked of it. */
function recorder() {
@@ -38,6 +40,7 @@ describe("actions", () => {
...items(paneEntries({ article: "Octopus", pinned: true }, act)),
...items(articleRowEntries("Octopus", true, act)),
...items(topEntries(top({ canRedo: true }), act)),
...items(libraryEntries({ title: "Work", current: false, last: false }, act)),
];
const keyed = all.filter((i) => i.key);
expect(keyed.length).toBeGreaterThan(50);
@@ -169,4 +172,51 @@ describe("actions", () => {
const h = { t: "head", text: "x" } as const;
expect(tidy([s, h, s, false, s, null, h, s, ""]).map((e) => e.t)).toEqual(["head", "sep", "head"]);
});
it("a library's row offers open, rename and delete, with new; this page's own cannot be opened again, and the last cannot be deleted", () => {
const { act, calls } = recorder();
const other = libraryEntries({ title: "Work", current: false, last: false }, act);
expect(labels(other)).toEqual(["# Work", "Open", "Rename…", "Delete…", "--", "New library…"]);
expect(items(other).map((i) => i.key)).toEqual(["Enter", "r", "D", "n"]);
find(other, "Delete…").run();
expect(calls).toEqual(["press D"]);
const mine = libraryEntries({ title: "Library", current: true, last: true }, act);
expect(find(mine, "Open here already").disabled).toBe(true);
expect(find(mine, "Delete…").disabled).toBe(true);
expect(find(mine, "Delete…").sub).toContain("last library");
expect(find(topEntries(top(), act), "Libraries…").key).toBe("m");
});
});
describe("the libraries panel's state", () => {
const lib = (id: string, title = id): LibraryInfo => ({ id, title, created: "", nodes: 0, branches: ["main"] });
const list = [lib("a"), lib("b"), lib("c")];
it("opens on this page's library, else the first", () => {
expect(openPanel(list, "b")).toMatchObject({ sel: "b", edit: null, confirm: null, loading: true });
expect(openPanel(list, "gone").sel).toBe("a");
expect(openPanel([], "x").sel).toBe("x");
});
it("steps by rows, held at the ends", () => {
expect(step(list, "a", 1)).toBe("b");
expect(step(list, "c", 1)).toBe("c");
expect(step(list, "a", -1)).toBe("a");
expect(step(list, "missing", 1)).toBe("a");
expect(step([], "a", 1)).toBe("a");
});
it("keeps the row a fetch still lists, else takes the one that stood where it was", () => {
expect(keep(list, [lib("c"), lib("b")], "b")).toBe("b");
expect(keep(list, [lib("a"), lib("c")], "b")).toBe("c");
expect(keep(list, [lib("a"), lib("b")], "c")).toBe("b");
expect(keep(list, [], "b")).toBe("b");
});
it("says where a deleted library went as the data folder names it, and counts nodes", () => {
expect(deletedPlace("/home/x/.data/libraries/.deleted/k06dp45g64-20261117-074500")).toBe("libraries/.deleted/k06dp45g64-20261117-074500");
expect(deletedPlace("C:\\data\\libraries\\.deleted\\abc-1")).toBe("libraries/.deleted/abc-1");
expect(deletedPlace("elsewhere")).toBe("elsewhere");
expect([nodeCount(0), nodeCount(1), nodeCount(2)]).toEqual(["0 nodes", "1 node", "2 nodes"]);
});
});