Web pages: a link to any address opens as an article, as Wikipedia's do

A url link now opens in the app instead of the browser. The server fetches
the page (robots.txt honoured, public addresses only, size and time caps),
keeps a snapshot on disk until it is reloaded, and cuts it into a lead and
sections: by its headings, else by pseudo-headings, else in chunks, or by a
model when asked (s), within a daily budget. The pane has its own amber
ground, the author and date in its head when the page gives them, and the
source in its foot. W opens the original, R reads it again. See
docs/pages.md.

Pictures and videos are kept, in web pages and in Wikipedia articles:
pictures through the server (only addresses seen in a page that was read),
videos as a still that loads the player on a click.

A section that is only a link (a target, no text, no sections) opens as
its article at once, and L opens a target to the right of the node's own
pane, never under it.

Article text is sized to read like the reader's own.

Panes: a pane that already has all its column can give beside the others'
tabs no longer peeks over them on hover, and the curves of tabs under a
peeking pane are no longer drawn over it. The keypress timing test judges
each of its two passes on its own, so a stall from outside the app does
not fail it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Fable 5.2 committed 2026-11-18 13:44:13 -05:00
1 parent a3f25fbdcc
commit f8c6576ea1
58 files changed
+8606 -367

No files matched your search

+36 -12
View File
@@ -10,21 +10,21 @@ import { LinkCard, LinkPicker, LinksPanel, NodeBacklinks, NodeRelated, TargetRow
import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
import { Panes } from "./Panes";
import { PaneMap, Trail } from "./Pages";
import { PANES_MIN_WIDTH, store, type Aux } from "./store";
import { WikiPage, WikiView } from "./Wiki";
import { PANES_MIN_WIDTH, rowId, store, type Aux } from "./store";
import { ArticlePage, ArticleView } from "./Web";
import { Usage } from "./Usage";
import { FirstRun, Hints, Key, MenuHost, SelBar, closeMenu, dragged, hideBar, locate, locateIn, menuAt, pointedPane, setCard, setPrompt, showBar, touch, wtextRow, type Hint } from "./Mouse";
import { press } from "./press";
function Page() {
if (store.colWiki) return <WikiPage />;
if (store.colWiki) return <ArticlePage />;
const kids = sections(store.snap, store.top);
return (
<article class={store.preview ? "preview" : ""}>
<TopMatter id={store.top} />
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={store.top} />
{store.articleUnder(store.top) ? <WikiView host={`n${store.top}`} /> : <TargetRow id={store.top} />}
{store.articleUnder(store.top) ? <ArticleView host={`n${store.top}`} /> : <TargetRow id={store.top} />}
<NodeBacklinks id={store.top} />
<NodeRelated id={store.top} />
</article>
@@ -411,13 +411,22 @@ function StatusLine() {
? [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 auxTo = store.aux ? store.auxTarget(store.aux) : null;
// Where a focused link in an article's text goes, as Enter's hint names it: the article, or the page's host.
const auxToName = !auxTo ? "" : auxTo.kind === "wiki" ? `“${clip(auxTo.title, 40)}”` : clip(hostOf(auxTo.kind === "url" ? auxTo.url : ""), 40);
const hint: Hint = store.aux
? store.aux.kind === "wiki"
? store.aux.kind === "wiki" && store.onWeb
? store.inArticleText
? auxTo
? [["Enter", `opens ${auxToName}`], ["W", "the original"], ["Escape", "widen"]]
: [["H L", "select less, more"], ["Escape", "widen"]]
: ["web page · j k rows", ["l", "open"], ["h", "back"], ["i", "select words"], ["Tab", "links"], ["W", "the original"], ...(store.panes ? [["q", "close"] as [string, string]] : [])]
: store.aux.kind === "wiki"
? store.inArticleText
? store.articleNoteHere()
? [["Enter", "open/enter the note"], ["e", "toggle"], ["D", "delete note"], ["Tab", "next"]]
: store.auxLink(store.aux)
? [["Enter", `opens “${clip(store.auxLink(store.aux)!.title, 40)}”`], "e d y x c annotate", ["W", "on wikipedia.org"]]
: auxTo
? [["Enter", `opens ${auxToName}`], "e d y x c annotate", ["W", auxTo.kind === "wiki" ? "on wikipedia.org" : "the original"]]
: [...lensHint, ["Escape", "widen"]]
: ["Wikipedia · j k rows", ["l", "open"], ["h", "back"], ["i", "select words"], ["Tab", "links and notes"], ["W", "on wikipedia.org"], ...(store.panes ? [["q", "close"] as [string, string]] : [])]
: store.aux.kind === "target" ? [["Enter", "opens what this is about"]]
@@ -431,7 +440,7 @@ function StatusLine() {
? [["Enter", `opens the note with ${store.targetOf(commentary)!.kind === "wiki" ? "its article" : "what it links to"}`], ["e", "shows the note here"], ["D", "delete note"], ["w", "retarget"]]
: noteHere
? store.snap.nodes[noteHere].ref
? [["Enter", "open the link"], ["w", "retarget"], ["D", "remove"], ...(store.snap.nodes[noteHere].ref!.kind === "wiki" ? [["W", "on Wikipedia"] as [string, string]] : [])]
? [["Enter", "open the link"], ["w", "retarget"], ["D", "remove"], ...(store.snap.nodes[noteHere].ref!.kind === "wiki" ? [["W", "on Wikipedia"] as [string, string]] : store.snap.nodes[noteHere].ref!.kind === "url" ? [["W", "the original"] as [string, string]] : [])]
: [["Enter", "open/enter"], ["e", "toggle"], ["D", "delete note"], ["w", "link it"]]
: [...lensHint, ["w", "link"]]
: st.up || st.down
@@ -569,7 +578,7 @@ export function App() {
// Only when the focus, the page or the mode has changed: a render for something that arrived
// in the background (a list fetched, a scan's suggestions) leaves the page where the reader
// scrolled it. The panes keep their own focus in view (Panes.tsx).
const key = JSON.stringify([f, store.aux, store.mode, store.panes, store.top, store.colWiki?.title]);
const key = JSON.stringify([f, store.aux, store.mode, store.panes, store.top, store.colWiki?.title, store.colWiki?.url]);
const moved = key !== shownFocus;
shownFocus = key;
// Another pane opened or gone to (as pages, another page): no preview stays over it.
@@ -617,23 +626,38 @@ export function App() {
// A covered pane's spine brings that pane back by focusing it.
const spine = target.closest<HTMLElement>("[data-spine]");
if (spine) return store.land(Number(spine.dataset.spine));
// Article text: a link to another article opens it next; a link out leaves in a new tab (the HTML says so); nothing else navigates.
// Article text: a link to another article opens it next (in the link's own language, a web
// page's links say theirs), as does a web page's link to another page; a link out leaves in a
// new tab (the HTML says so); nothing else navigates.
const a = target.closest<HTMLAnchorElement>("a");
if (a && host) {
if (a.dataset.wiki) {
e.preventDefault();
store.paneAt = paneIndex;
const h = store.wikiHost(host);
return store.follow({ kind: "wiki", title: a.dataset.wiki, lang: h?.lang ?? store.wiki.lang });
return store.follow({ kind: "wiki", title: a.dataset.wiki, lang: a.dataset.wikiLang ?? h?.lang ?? store.wiki.lang });
}
if (a.dataset.url && target.closest(".wiki-text")) {
e.preventDefault();
store.paneAt = paneIndex;
return store.follow({ kind: "url", url: a.dataset.url });
}
if (!/^https?:/.test(a.getAttribute("href") ?? "")) e.preventDefault();
return;
}
// A figure: what its data-full names, in a new tab: a web page's image itself, a Wikipedia
// picture's File page (its author and licence). A video's facade plays instead (Wiki.tsx).
const img = host ? target.closest<HTMLImageElement>(".wiki-text img[data-full]") : null;
if (img) {
e.preventDefault();
window.open(img.dataset.full!, "_blank", "noopener,noreferrer");
return;
}
if (a && target.closest(".wattr")) return;
const wrow = target.closest<HTMLElement>("[data-wrow], [data-sense]");
if (wrow && host) {
store.paneAt = paneIndex;
const id = Number(wrow.dataset.wrow);
const id = rowId(wrow.dataset.wrow);
const ss = wrow.dataset.sense;
if (ss) return store.follow({ kind: "wiki", title: ss, lang: store.wikiHost(host)?.lang ?? store.wiki.lang });
store.setFocus(store.focus, { kind: "wiki", host, row: { t: "sec", id } } as Aux);
+36 -8
View File
@@ -7,12 +7,13 @@ import { Fragment, createContext } from "preact";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { ownerSection, resolveNode } from "../core/links";
import { isLibraryRoot, isLink, label, topOf, type NodeId, type Snap } from "../core/model";
import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref";
import { describeTarget, hostOf, parseTarget, validateRef, wikiRefOf, wikiTitle, type Ref } from "../core/ref";
import { clip, plain } from "../core/text";
import { kidClass, sameAux, store, type Aux } from "./store";
import type { LinkRow, Status, Sugg } from "./linker";
import { Hints } from "./Mouse";
import { press } from "./press";
import { cachedSummary, pageTitle, readDate } from "./web";
import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion } from "./wiki";
const MARK: Record<Ref["kind"], string> = { wiki: "W", node: "§", url: "↗" };
@@ -62,15 +63,25 @@ export function Attribution({ a }: { a: Attr }) {
);
}
/** What a target is, briefly: an article's summary, a node's title, where it is and first lines, a page's host. */
/**
* What a target is, briefly: an article's summary, a node's title, where it is and first lines; a
* page's title, site, author, date and first sentence when the server has read it before (its cache
* alone is asked: a card never makes the site be read), else its host and address.
*/
export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
if (r.kind === "url") {
const sum = cachedSummary(r.url);
const s = sum.state === "ready" ? sum.value : null;
// The site is the card's head; the line under the title is who wrote it and when.
const line = s ? [s.author, s.published && readDate(s.published)].filter(Boolean).join(" · ") : "";
return (
<div class="lcard l-url">
<div class="lhead">
<span class="lmark l-url">↗</span> {hostOf(r.url)}
<span class="lmark l-url">↗</span> {s?.site ?? hostOf(r.url)}
</div>
{r.title && <div class="ltitle">{r.title}</div>}
{(s?.title || r.title) && <div class="ltitle">{s?.title || r.title}</div>}
{line && <div class="lsub lbyline">{line}</div>}
{s?.sentence && <div class="lbody">{compact ? clip(s.sentence, 200) : s.sentence}</div>}
<div class="lsub">{clip(r.url, 90)}</div>
</div>
);
@@ -125,7 +136,7 @@ export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
export function LinkPreview({ id }: { id: NodeId }) {
const n = store.snap.nodes[id];
if (!n?.ref) return null;
const next = n.ref.kind === "wiki" ? "Enter opens the article · W opens it on Wikipedia" : n.ref.kind === "node" ? "Enter goes there · Back returns" : "Enter opens the page in a new tab";
const next = n.ref.kind === "wiki" ? "Enter opens the article · W opens it on Wikipedia" : n.ref.kind === "node" ? "Enter goes there · Back returns" : "Enter opens the page here · W opens the original in a new tab";
return (
<span class={`inset lpreview l-${n.ref.kind}${store.focus.node === id ? " focused" : ""}`} data-node={id}>
<LinkCard r={n.ref} />
@@ -332,8 +343,11 @@ export function LinkPicker() {
const choices: Choice[] = [];
if (/^https?:\/\/\S+$/i.test(text)) {
// An address of a Wikipedia article is that article.
const article = wikiRefOf(text);
try {
choices.push({ group: "Address", label: hostOf(text), sub: text, ref: validateRef({ kind: "url", url: text }) });
if (article?.kind === "wiki") choices.push({ group: "Wikipedia", label: article.title, sub: text, ref: article });
else choices.push({ group: "Address", label: hostOf(text), sub: text, ref: validateRef({ kind: "url", url: text }) });
} catch {
/* not an address after all */
}
@@ -343,10 +357,23 @@ export function LinkPicker() {
choices.push(...libraryChoices(text, spot.node));
choices.push(...(wiki?.list ?? []).map(articleChoice));
const sel = Math.min(i, choices.length - 1);
// A bare address: its page's title is read now, as part of this choice, and kept in the link
// (never later, never because the page was opened). Slow or failing, the link is made without one.
const [reading, setReading] = useState<string | null>(null);
const apply = (c: Choice | undefined) => {
if (!c) return;
if (!c || reading) return;
const ref = c.ref;
if (c.group === "Address" && ref.kind === "url" && !ref.title) {
setReading(ref.url);
void pageTitle(ref.url).then((title) => {
if (store.picker !== spot) return; // Esc while it was read: nothing is linked
store.closePicker();
store.applyTarget(spot, title ? { ...ref, title } : ref);
});
return;
}
store.closePicker();
store.applyTarget(spot, c.ref);
store.applyTarget(spot, ref);
};
const existing = spot.existing ? store.snap.nodes[spot.existing]?.ref : spot.range ? undefined : store.snap.nodes[spot.node]?.ref;
return (
@@ -373,6 +400,7 @@ export function LinkPicker() {
{!choices.length && <li class="none">{text ? "Nothing matches yet." : "Type to search."}</li>}
{text && !wiki && wikiConfig().mode !== "off" && !/^https?:/i.test(text) && <li class="none">Asking Wikipedia…</li>}
{wiki?.problem && <li class="none problem">Wikipedia: {wiki.problem}</li>}
{reading && <li class="none reading">Reading the page's title… (Esc leaves it unlinked)</li>}
</ul>
</div>
</div>
+24 -9
View File
@@ -12,9 +12,10 @@ import { createPortal } from "preact/compat";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { isLibraryRoot, label, staleness, topOf, type NodeId } from "../core/model";
import { plain } from "../core/text";
import { articleRowEntries, barItems, nodeEntries, paneEntries, selectionEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx } from "./actions";
import { articleRowEntries, barItems, nodeEntries, paneEntries, selectionEntries, tidy, webPageEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx } from "./actions";
import { press } from "./press";
import { store, type WRow } from "./store";
import { rowId, store, type WRow } from "./store";
import { canArrange, pageName, siteOf } from "./web";
// ---- where a pointer is, in the text ----
@@ -55,7 +56,7 @@ export function pointedPane(target: HTMLElement) {
}
/** The row of an article's text an element is in: its head or a section. */
export const wtextRow = (wtext: HTMLElement) => (wtext.dataset.wtext === "head" ? { t: "head" } : { t: "sec", id: Number(wtext.dataset.wtext) }) as WRow;
export const wtextRow = (wtext: HTMLElement) => (wtext.dataset.wtext === "head" ? { t: "head" } : { t: "sec", id: rowId(wtext.dataset.wtext) }) as WRow;
/** The text position under a point. */
function caretAt(x: number, y: number): { node: Node; offset: number } | null {
@@ -126,7 +127,7 @@ function selCtx(): SelCtx {
const text = plain(store.selectedText() ?? "");
const s = store.snap;
const a = store.aux;
if (a?.kind === "wiki") return { text, article: true, link: store.auxLink(a) ? "wiki" : undefined, note: !!store.articleNoteHere(), panes: store.panes, pages: store.pages };
if (a?.kind === "wiki") return { text, article: true, web: store.onWeb, link: store.auxTarget(a)?.kind as "wiki" | "url" | undefined, note: !!store.articleNoteHere(), panes: store.panes, pages: store.pages };
const f = store.focus;
const id = store.noteAt(f.range);
const r = id ? store.targetOf(id) : undefined;
@@ -156,15 +157,29 @@ function menuHere(where: Where): Entry[] {
const pinned = !!store.branchNodes[store.paneAt]?.pinned;
const moves = store.paneMoves();
if (a?.kind === "wiki") {
const h = store.wikiHost(a.host);
if (store.panes && (where === "pane" || a.row.t === "head")) return paneEntries(a.host.startsWith("n") ? { node: nodeCtx(a.host.slice(1) as NodeId), pinned, ...moves } : { article: h?.title, pinned, ...moves }, act);
if (a.row.t === "sec" || a.row.t === "sense") return articleRowEntries(h?.title ?? "Wikipedia", store.panes, act, store.pages);
const h = store.viewHost(a.host);
const title = h?.src === "web" ? pageName(h.url) : h?.title;
const web = h?.src === "web";
const arrange = canArrange();
if (store.panes && (where === "pane" || a.row.t === "head")) {
if (!a.host.startsWith("n")) return paneEntries({ article: title, web, arrange, pinned, ...moves }, act);
const id = a.host.slice(1) as NodeId;
// A section shown as its article: its own items, then the page's or the article's.
return paneEntries({ node: nodeCtx(id), ...(store.linkOnly(id) ? { article: title ?? "", web, arrange } : {}), pinned, ...moves }, act);
}
if (a.row.t === "sec" || a.row.t === "sense") return articleRowEntries(title ?? "Wikipedia", store.panes, act, store.pages, web, arrange);
// A web page's head, in the column or under a node: what can be done to the page.
if (web && a.row.t === "head") return tidy([{ t: "head", text: title ?? siteOf(h.url) }, ...webPageEntries(act, arrange)]);
return [];
}
if (a) return [];
const id = store.focus.node;
if (!store.snap.nodes[id]) return [];
if (where === "pane" && store.panes) return paneEntries({ node: nodeCtx(id), pinned, ...moves }, act);
if (where === "pane" && store.panes) {
const h = store.linkOnly(id) && store.paneHead(id) ? store.viewHost(`n${id}`) : null;
const article = h ? (h.src === "web" ? pageName(h.url) : h.title) : undefined;
return paneEntries({ node: nodeCtx(id), ...(h ? { article, web: h.src === "web", arrange: canArrange() } : {}), pinned, ...moves }, act);
}
return nodeEntries(nodeCtx(id), act);
}
@@ -209,7 +224,7 @@ function focusAt(target: HTMLElement, x: number, y: number): Where | null {
const wrow = target.closest<HTMLElement>("[data-wrow]");
if (host && wrow) {
intoPane();
store.setFocus(store.focus, { kind: "wiki", host, row: { t: "sec", id: Number(wrow.dataset.wrow) } });
store.setFocus(store.focus, { kind: "wiki", host, row: { t: "sec", id: rowId(wrow.dataset.wrow) } });
return "auto";
}
// A link's or a note's words.
+4 -2
View File
@@ -8,6 +8,7 @@ import { streamView } from "../core/marks";
import { ownerSection } from "../core/links";
import { ChoiceRows, LinkMark, useForkMark, LinkPreview, NodeBacklinks, NodeRelated, SuggestionCard, TargetRow, articleChoice, sectionChoice, useWikiSuggest, type Choice } from "./Links";
import { store, type Pending } from "./store";
import { ArticleView } from "./Web";
// ---- inline text ----
@@ -402,10 +403,11 @@ function SectionView({ id }: { id: NodeId }) {
<Row id={id} open={open} leaf={leaf} editing={editing} />
{open && (
<div class="content">
{isPrompt(snap, id) ? <Abstract id={id} /> : <NodeBody id={id} />}
{/* A section that is only a link is shown as its article, under its row: no empty text above it. */}
{store.linkOnly(id) ? null : isPrompt(snap, id) ? <Abstract id={id} /> : <NodeBody id={id} />}
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={id} />
<TargetRow id={id} />
{store.articleUnder(id) ? <ArticleView host={`n${id}`} /> : <TargetRow id={id} />}
<NodeBacklinks id={id} />
<NodeRelated id={id} />
</div>
+11 -3
View File
@@ -9,16 +9,24 @@ import { label } from "../core/model";
import { store, type PaneRef } from "./store";
import { mapStep, rails, type Rail } from "./pages";
import { article } from "./wiki";
import { article as webArticle, siteOf } from "./web";
/** What a pane is called: its node's title, or its article's (a section of one by its heading). */
/** What a pane is called: its node's title, or its article's or web page's (a section of one by its heading). */
function paneTitle(p: PaneRef): string {
if (p.kind === "node") return store.snap.nodes[p.id] ? label(store.snap, p.id) : "…";
if (p.kind === "web") {
const w = webArticle(p.url);
const sec = p.sec !== undefined && w.state === "ready" ? w.value.sections.find((x) => x.id === p.sec) : undefined;
return sec ? sec.heading : w.state === "ready" ? w.value.title : siteOf(p.url);
}
const a = article(p.title, p.lang);
const sec = p.sec !== undefined && a.state === "ready" ? a.value.sections.find((x) => x.id === p.sec) : undefined;
return sec ? sec.heading : a.state === "ready" ? a.value.title : p.title;
}
export const W = () => <b class="wmark">W</b>;
/** The mark of a web page's pane, as W marks an article's. */
export const U = () => <b class="wmark umark">↗</b>;
/** Up to this many panes in a column, a trail step shows a dot for each; beyond, their number. */
const STACK_DOTS = 4;
@@ -82,7 +90,7 @@ export function Trail() {
store.toPane(n.id);
}}
>
{n.ref.kind === "wiki" && <W />}
{n.ref.kind === "wiki" ? <W /> : n.ref.kind === "web" ? <U /> : null}
<span class="trail-t">{t}</span>
{d && <Stack i={d.i} n={d.n} />}
</button>
@@ -208,7 +216,7 @@ export function PaneMap() {
<RailLine key={k} r={r} step={step} hue={hues.get(r.tid)} on={branch.has(r.tid)} />
))}
<button type="button" class="map-go" aria-current={id === active ? "page" : undefined} onClick={() => (store.showMap(false), store.toPane(id))}>
{x.node.ref.kind === "wiki" && <W />}
{x.node.ref.kind === "wiki" ? <W /> : x.node.ref.kind === "web" ? <U /> : null}
<span class="map-t">{paneTitle(x.node.ref)}</span>
{orphan && <span class="map-sub">its source closed</span>}
</button>
+112 -34
View File
@@ -1,7 +1,7 @@
/**
* The panes view: panes side by side, in the manner of Andy Matuschak's notes. It starts as the
* path down from the top node; a link followed from a pane opens its target in the next pane
* (a node from anywhere in the library, a Wikipedia article, a section of one), replacing what was to the
* (a node from anywhere in the library, a Wikipedia article or a web page, a section of one), replacing what was to the
* right. Moving back left closes nothing: the panes stay until something else is opened from an
* earlier pane, or q or a pane's × closes them. Earlier columns stay at the left as narrow spines
* when later ones slide over them.
@@ -22,11 +22,13 @@ import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes";
import { ACROSS, DOWN, crowds, fill, fit, folded, mark, offsets, release, resize, reveal, setAttr, share, starts, stick, unmark, whole } from "./stack";
import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links";
import { pageAt, paneOfPage } from "./pages";
import { Close, Pin, W } from "./Pages";
import { Close, Pin, U, W } from "./Pages";
import { Abstract, Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter, isPrompt } from "./Node";
import { kidClass, refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store";
import { WikiView } from "./Wiki";
import { ArticleView, WebView } from "./Web";
import { article } from "./wiki";
import { article as webArticle, siteOf } from "./web";
interface PaneProps {
t: PaneNode;
@@ -56,7 +58,7 @@ const key = (p: PaneProps) => `${refKey(p.p)}|${p.t.hue}|${p.index}|${p.kids}|${
class Pane extends Component<PaneProps> {
shouldComponentUpdate(next: PaneProps) {
if (key(next) !== key(this.props)) return true;
if (next.p.kind === "wiki") return true;
if (next.p.kind !== "node") return true;
return store.paneDirty(next.p.id) || !!store.targetOf(next.p.id) || store.linkedFrom(next.p.id).length > 0;
}
componentDidMount() {
@@ -71,7 +73,7 @@ class Pane extends Component<PaneProps> {
}
render() {
const p = this.props.p;
return <PaneCtx.Provider value={this.props.t.id}>{p.kind === "node" ? <NodePane {...this.props} id={p.id} /> : <WikiPane {...this.props} />}</PaneCtx.Provider>;
return <PaneCtx.Provider value={this.props.t.id}>{p.kind === "node" ? <NodePane {...this.props} id={p.id} /> : p.kind === "web" ? <WebPane {...this.props} /> : <WikiPane {...this.props} />}</PaneCtx.Provider>;
}
}
@@ -177,6 +179,30 @@ function NodePane(props: PaneProps & { id: NodeId }) {
const kid = t.kids[t.pick];
const showing = kid?.ref.kind === "node" && store.continuesFrom(kid.ref, props.p) ? kid.ref.id : undefined;
const forked = new Set(t.kids.flatMap((k, j) => (j !== t.pick && k.ref.kind === "node" && store.continuesFrom(k.ref, props.p) ? [k.ref.id] : [])));
// A section that is only a link is shown as its article: the pane reads as an article pane (one
// head, the article's; its ground), and the node's own commands are on that head and on its row.
if (!top && store.linkOnly(id)) {
const web = store.isWeb(`n${id}`);
return (
<article class={`pane link-pane${web ? " web" : ""}${jump ? " jumped" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`} {...paneAttrs(props, id)}>
<Chrome props={props} title={label(snap, id)} mark={web ? <U /> : <W />} />
<div class="pane-scroll">
<div class="pane-body">
<Orphaned on={props.orphan} />
{jump && <div class="pane-from">{ancestors(snap, id).reverse().map((a) => label(snap, a)).join(" › ")}</div>}
{editing && (
<div class="link-rename" data-node={id}>
<TitleEditor id={id} />
</div>
)}
<ArticleView host={`n${id}`} own headFocused={focused} />
<NodeBacklinks id={id} />
<NodeRelated id={id} />
</div>
</div>
</article>
);
}
return (
<article
class={`pane${top ? " root" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`}
@@ -207,7 +233,7 @@ function NodePane(props: PaneProps & { id: NodeId }) {
</ul>
)}
<PendingSections id={id} />
{store.articleUnder(id) ? <WikiView host={`n${id}`} /> : <TargetRow id={id} />}
{store.articleUnder(id) ? <ArticleView host={`n${id}`} /> : <TargetRow id={id} />}
<NodeBacklinks id={id} />
<NodeRelated id={id} />
</div>
@@ -236,6 +262,27 @@ function WikiPane(props: PaneProps) {
);
}
/** A web page's pane: an article pane with the page's view in it (Web.tsx). */
function WebPane(props: PaneProps) {
const { p, index } = props;
if (p.kind !== "web") return null;
const a = webArticle(p.url);
const sec = p.sec && a.state === "ready" ? a.value.sections.find((x) => x.id === p.sec) : undefined;
const page = a.state === "ready" ? a.value.title : siteOf(p.url);
const title = sec ? `${sec.heading} · ${page}` : page;
return (
<article class={`pane wiki-pane web${p.from ? " jumped" : ""}${paneClass(props)}`} {...paneAttrs(props, refKey(p))}>
<Chrome props={props} title={title} mark={<U />} />
<div class="pane-scroll">
<div class="pane-body">
<Orphaned on={props.orphan} />
<WebView host={props.off ? `f${props.t.id}` : `p${index}`} />
</div>
</div>
</article>
);
}
function PaneRow({ id, showing, forked, active }: { id: NodeId; showing: boolean; forked: boolean; active: boolean }) {
const snap = store.snap;
const n = snap.nodes[id];
@@ -683,7 +730,7 @@ export function Panes() {
if (!panes.length) return;
const next = store.trail[at + 1];
const a0 = store.aux;
const showing = store.showingFocus() || (a0?.kind === "wiki" && a0.row.t === "sec" && next?.kind === "wiki" && next.sec === a0.row.id);
const showing = store.showingFocus() || (a0?.kind === "wiki" && a0.row.t === "sec" && !!next && next.kind !== "node" && next.sec === a0.row.id);
if (store.mode !== "edit") {
const pane = panes[at];
nearestY(pane?.querySelector(".sel, .wfocus, .node.focused > .row, .wrow.focused > .row, .backlinks li.focused, .target-row.focused, .wiki-head.focused, .pane-head.focused, .focused"));
@@ -907,10 +954,20 @@ export function Panes() {
pending = null;
hide();
}
/** Where in its column a pane may peek while the others keep their tabs: below a tab for each pane above it, above a tab for each below. */
const tabRoom = (pane: HTMLElement) => {
const col = pane.parentElement as HTMLElement;
const c = col.getBoundingClientRect();
const ps = [...col.children].filter((p) => p.classList.contains("pane"));
const i = ps.indexOf(pane);
return { top: c.top + i * TAB, bottom: c.bottom - (ps.length - 1 - i) * TAB };
};
/**
* How tall a pane would be shown whole (what its text needs, up to its column's height), if it is
* cut off now (0 if not): shown shorter than that for any reason, covered by the pane after it, given
* too small a share of its column, or running past the column's foot.
* How tall a pane would be shown at its fullest, if it is cut off now (0 if not): what its text
* needs, if that fits in its column; if not (it scrolls however tall it is), the column less a tab
* for each other pane, so a pane given that already does not cover the others' tabs for a few more
* lines. Cut off: shown shorter than that for any reason, covered by the pane after it, given too
* small a share of its column, or running past the column's foot.
*/
const cutOff = (pane: HTMLElement): number => {
const col = pane.parentElement as HTMLElement;
@@ -920,8 +977,9 @@ export function Panes() {
const shown = Math.max(0, Math.min(r.bottom, c.bottom, next) - Math.max(r.top, c.top));
const sc = pane.querySelector<HTMLElement>(".pane-scroll")!;
const cs = getComputedStyle(sc);
const need = needs.current.get(Number(pane.dataset.tid)) ?? pane.querySelector<HTMLElement>(".pane-body")!.offsetHeight + parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + 1;
const full = Math.min(Math.ceil(need), Math.floor(c.height));
const need = Math.ceil(needs.current.get(Number(pane.dataset.tid)) ?? pane.querySelector<HTMLElement>(".pane-body")!.offsetHeight + parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + 1);
const room = tabRoom(pane);
const full = need <= Math.floor(c.height) ? need : Math.floor(room.bottom - room.top);
return shown < full - 2 ? full : 0;
};
/** What must come out for a pane to show whole: its column, if later columns cover it; the pane, if it is cut off down its column. */
@@ -940,15 +998,18 @@ export function Panes() {
it.setAttribute("data-peek", "");
if (it === pane) {
// As tall as it needs, without moving the panes around it (the extra height takes no room), then lifted into the column.
// (Never shorter: a covered pane may be laid out as tall already, and its column's scroll must not move.)
const full = cutOff(it);
if (full) {
const h = it.offsetHeight;
const h = it.offsetHeight;
if (full > h) {
it.style.setProperty("--peek-h", `${full}px`);
it.style.setProperty("--peek-extra", `${Math.max(0, full - h)}px`);
it.style.setProperty("--peek-extra", `${full - h}px`);
it.setAttribute("data-peek-h", "");
}
// Clear of the other panes' tabs, if it fits between them; else anywhere in its column.
const r = it.getBoundingClientRect();
const c = (it.parentElement as HTMLElement).getBoundingClientRect();
const room = tabRoom(it);
const c = r.height <= room.bottom - room.top + 1 ? room : (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)`;
}
@@ -1832,16 +1893,22 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
const holes = peeked.map((p) => local(p.getBoundingClientRect()));
const bar = el.querySelector<HTMLElement>(".pane > .selbar");
const barHole = bar && bar.style.visibility !== "hidden" ? [local(bar.getBoundingClientRect())] : [];
const owned = (id: number) => {
/** Whether a curve's pane is in what peeks: in a pane that peeks (it is that pane), or only in a column that peeks (another pane in it). */
const owner = (id: number): "pane" | "col" | null => {
const p = els.get(id);
return !!p && peeked.some((q) => q.contains(p));
if (!p) return null;
const by = peeked.filter((q) => q.contains(p));
return by.some((q) => q.classList.contains("pane")) ? "pane" : by.length ? "col" : null;
};
const { under, over } = layers(svg, area, [...holes, ...barHole], barHole);
// A column peeking with one of its panes: its other panes' curves are over the column but not over that pane, which may cover their tabs.
const paneHoles = peeked.flatMap((p, i) => (p.classList.contains("pane") ? [holes[i]] : []));
const { under, mid, over } = layers(svg, area, [...holes, ...barHole], [...paneHoles, ...barHole], barHole);
// Each curve keeps its element, changed only where it changed, so only what moved is painted again.
const had = new Map<string, SVGPathElement>();
for (const p of svg.querySelectorAll<SVGPathElement>("path")) had.set(p.dataset.key!, p);
const at = new Map<Element, number>([
[under, 0],
[mid, 0],
[over, 0],
]);
out.forEach((c) => {
@@ -1858,7 +1925,8 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
if (p.dataset.lane !== String(c.lane)) p.dataset.lane = String(c.lane);
if ((p.dataset.hue ?? "") !== c.hue) c.hue ? (p.dataset.hue = c.hue) : delete p.dataset.hue;
// In drawing order, the focused branch's last, on top; over what peeks if it belongs to it.
const g = owned(c.from) || owned(c.to) ? over : under;
const by = [owner(c.from), owner(c.to)];
const g = by.includes("pane") ? over : by.includes("col") ? mid : under;
const k = at.get(g)!;
at.set(g, k + 1);
if (g.children[k] !== p) g.insertBefore(p, g.children[k] ?? null);
@@ -1871,20 +1939,16 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
}
/**
* The curves' two layers: those under what peeks (with holes where it is, and where the selection
* bar is), and those over it (its own; a hole only for the bar). Made once; the holes kept as asked.
* The curves' three layers: those under what peeks (with holes where it is, and where the selection
* bar is); those of a peeking column's other panes, over the column but under a pane of it that
* peeks too (holes where that pane is, and the bar); and those over it all (what peeks' own; a hole
* only for the bar). Made once; the holes kept as asked.
*/
function layers(svg: SVGSVGElement, area: DOMRect, holes: { x: number; y: number; w: number; h: number }[], barHoles: { x: number; y: number; w: number; h: number }[]) {
function layers(svg: SVGSVGElement, area: DOMRect, holes: { x: number; y: number; w: number; h: number }[], midHoles: { x: number; y: number; w: number; h: number }[], barHoles: { x: number; y: number; w: number; h: number }[]) {
const NS = "http://www.w3.org/2000/svg";
let defs = svg.querySelector("defs");
if (!defs) {
defs = document.createElementNS(NS, "defs");
for (const id of ["ie-curve-holes", "ie-curve-bar"]) {
const m = document.createElementNS(NS, "mask");
m.id = id;
m.setAttribute("maskUnits", "userSpaceOnUse");
defs.appendChild(m);
}
const clip = document.createElementNS(NS, "clipPath");
clip.id = "ie-curve-area";
clip.appendChild(document.createElementNS(NS, "rect"));
@@ -1893,16 +1957,29 @@ function layers(svg: SVGSVGElement, area: DOMRect, holes: { x: number; y: number
const shown = document.createElementNS(NS, "g");
shown.setAttribute("clip-path", "url(#ie-curve-area)");
svg.appendChild(shown);
for (const c of ["under", "over"]) {
const g = document.createElementNS(NS, "g");
g.setAttribute("class", c);
shown.appendChild(g);
}
}
// Each part made if missing (a drawing an earlier build of the page began has fewer layers).
for (const id of ["ie-curve-holes", "ie-curve-mid", "ie-curve-bar"]) {
if (defs.querySelector(`#${id}`)) continue;
const m = document.createElementNS(NS, "mask");
m.id = id;
m.setAttribute("maskUnits", "userSpaceOnUse");
defs.appendChild(m);
}
const shown = svg.querySelector<SVGGElement>("g[clip-path]")!;
["under", "mid", "over"].forEach((c, i) => {
let g = shown.querySelector<SVGGElement>(`:scope > g.${c}`);
if (!g) {
g = document.createElementNS(NS, "g");
g.setAttribute("class", c);
}
if (shown.children[i] !== g) shown.insertBefore(g, shown.children[i] ?? null);
});
// Only over the strip.
const r = svg.querySelector("#ie-curve-area rect")!;
for (const [k, v] of Object.entries({ x: area.left, y: area.top, width: area.width, height: area.height })) if (r.getAttribute(k) !== String(v)) r.setAttribute(k, String(v));
const under = svg.querySelector<SVGGElement>("g.under")!;
const mid = svg.querySelector<SVGGElement>("g.mid")!;
const over = svg.querySelector<SVGGElement>("g.over")!;
const fill = (id: string, g: SVGGElement, hs: typeof holes) => {
const m = svg.querySelector<SVGMaskElement>(`#${id}`)!;
@@ -1926,8 +2003,9 @@ function layers(svg: SVGSVGElement, area: DOMRect, holes: { x: number; y: number
g.setAttribute("mask", `url(#${id})`);
};
fill("ie-curve-holes", under, holes);
fill("ie-curve-mid", mid, midHoles);
fill("ie-curve-bar", over, barHoles);
return { under, over };
return { under, mid, over };
}
/** The words, rows and links the panes were opened from, coloured as pages (pageMarks). */
+227
View File
@@ -0,0 +1,227 @@
/**
* A web page shown as an article view, the way Wiki.tsx shows a Wikipedia article: its lead is
* its text, its sections are rows (in a pane a section opens as the next pane; on the column's page
* it opens in place), its links are Tab stops (one to an article opens the article, in the link's
* own language; one to another page opens that page), and its figures show through the server's
* media route. It is never stored in the library: it comes from /api/page/article, read once by
* the server and kept in its cache (server/page.ts).
*
* It takes the article views' structure and classes (`.wiki`, `.wiki-head`, `.wiki-text`, `.wrows`)
* with a `.web` modifier: an amber ground and a ↗ at the head instead of Wikipedia's W, so it is
* always clear whose text this is. Its head names the site, the title and who wrote it; its foot
* says where it is from, when it was read and what was changed. A page that cannot be shown says
* why in plain words and offers the original. Nothing is written on it: annotations are for
* Wikipedia's text and the reader's own. What a model made of it at the reader's request (s) is
* marked as the model's: its summary above the lead (the page's own opening still follows), a
* line when the sections are the model's, and the foot.
*/
import { useContext } from "preact/hooks";
import { clip, type Range } from "../core/text";
import { PaneCtx, useForkMark } from "./Links";
import { sameAux, store, type WRow } from "./store";
import { Blocks, Problem, WikiPage, WikiView, backLabel } from "./Wiki";
import { articleText } from "./wiki";
import { article, attributionText, byline, cachedSummary, sectionsUnder, siteOf, webKey, type WebArticle, type WebProblem } from "./web";
/**
* What an article view under a node is drawn as. `own`: the view is its pane's own (a section that
* is only a link, shown as its article), not an inset under the node's text. `headFocused`: its
* head is focused because the node is (that pane's head, as a node's pane has).
*/
export interface ViewOpts {
own?: boolean;
headFocused?: boolean;
}
/** Any article view by its host: a web page's, or Wikipedia's. */
export function ArticleView({ host, ...o }: { host: string } & ViewOpts) {
return store.isWeb(host) ? <WebView host={host} {...o} /> : <WikiView host={host} {...o} />;
}
/** The column's article page, Wikipedia's or a web page's. */
export function ArticlePage() {
if (!store.colWiki?.url) return <WikiPage />;
return (
<article class="wiki-page web">
<WebView host="col" />
<p class="wiki-back">h at the top, or Back, returns to “{clip(backLabel(), 40)}”.</p>
</article>
);
}
/** A piece of the page's text (the lead or a section) as text the keys select in, as an article's is; it carries no annotations. */
function WebText({ host, row, html }: { host: string; row: WRow; html: string }) {
const at = articleText(html, true);
const a = store.aux;
const here = a?.kind === "wiki" && a.host === host && sameAux({ ...a, grain: undefined, range: undefined }, { kind: "wiki", host, row });
const sel = here && a.grain && a.range ? { grain: a.grain, range: a.range } : null;
const link: Range | null = sel && at.links.some((l) => l.range[0] === sel.range[0] && l.range[1] === sel.range[1]) ? sel.range : null;
const fork = useForkMark();
return (
<div class="wiki-text" data-wtext={row.t === "sec" ? row.id : "head"}>
<Blocks bs={at.blocks} c={{ text: at.text, notes: [], sel, link, fork }} />
</div>
);
}
/** The ↗ and the site that mark a web page's text, its title, and its byline (author · site · date, only what the page gives). */
function Head({ url, title, sub, line, focused, mark }: { url: string; title: string; sub?: string; line?: string; focused: boolean; mark?: string }) {
return (
<header class={`wiki-head${focused ? " focused" : ""}${mark ? ` ${mark}` : ""}`}>
<div class="wiki-brand">
<span class="wmark umark">↗</span> {siteOf(url)}
</div>
<h2>
{title}
{sub && <span class="wsub"> › {sub}</span>}
</h2>
{line && <p class="web-byline">{line}</p>}
</header>
);
}
/** The line every view of a page's text ends with: where it is from, who wrote it, when it was read, what was changed, and the original. */
function Attribution({ a }: { a: WebArticle["attribution"] }) {
return (
<p class="wattr">
{attributionText(a)}{" "}
<a href={a.url} target="_blank" rel="noopener noreferrer">the original</a>
</p>
);
}
/** The summary a model wrote of the page, set apart and labelled so it is never taken for the page's own words. */
function ModelSummary({ m }: { m: NonNullable<WebArticle["model"]> }) {
return (
<aside class="web-model" data-model-summary>
<p class="web-model-label">Summary written by a model{m.by ? ` (${m.by})` : ""} from the page's openings, at your request; not the author's words</p>
<p class="web-model-text">{m.summary}</p>
{m.note && <p class="web-model-label">{m.note}</p>}
</aside>
);
}
/** A page that is not shown: what is known of it, why, and the original in a new tab. */
function Unusable({ url, p }: { url: string; p: WebProblem }) {
return (
<>
{p.description && <p class="wiki-desc">{p.description}</p>}
<Problem message={p.message} />
<p class="web-open">
<a href={url} target="_blank" rel="noopener noreferrer" data-original>
Open in a new tab
</a>{" "}
· W does the same
</p>
</>
);
}
/** The title a page goes by before it has arrived: the link's own, else its site. */
function knownTitle(host: string, url: string): string {
const h = store.viewHost(host);
const r = h?.embedded ? store.targetOf(h.embedded) : undefined;
if (r?.kind === "url" && r.title) return r.title;
if (host === "col" && store.colWiki?.url === url && store.colWiki.title !== siteOf(url)) return store.colWiki.title;
return siteOf(url);
}
/** One web page's view. `host` says which (see Aux in store.ts). */
export function WebView({ host, own, headFocused }: { host: string } & ViewOpts) {
const tid = useContext(PaneCtx);
const fork = useForkMark();
const h = store.viewHost(host);
if (h?.src !== "web") return null;
// Under a node, the page opened in a pane of its own (L) is marked at this head, where its curve starts.
const mark = h.embedded ? fork?.(webKey(h.url)) : undefined;
const a = store.aux;
const at = (row: WRow) => (row.t === "head" && !!headFocused) || (!!a && a.kind === "wiki" && a.host === host && !a.grain && sameAux(a, { kind: "wiki", host, row }));
const cls = `wiki web${h.embedded && !own ? " embedded" : ""}`;
// Under a section, folded: what the server's cache knows of it (never a request to the site), until l opens it.
if (store.folded(h.embedded)) {
const sum = cachedSummary(h.url);
const s = sum.state === "ready" ? sum.value : null;
return (
<section class={`${cls} folded${at({ t: "head" }) ? " focused" : ""}`} data-host={host}>
<Head url={h.url} title={s?.title ?? knownTitle(host, h.url)} line={s ? byline(s) : undefined} focused={at({ t: "head" })} mark={mark} />
{s?.description && <p class="wiki-summary">{s.description}</p>}
<p class="wiki-more">l reads the page here · L opens it in a pane of its own · W the original</p>
</section>
);
}
const art = article(h.url);
if (art.state === "loading") {
return (
<section class={cls} data-host={host}>
<Head url={h.url} title={knownTitle(host, h.url)} focused={at({ t: "head" })} mark={mark} />
<p class="wiki-wait">Reading the page…</p>
</section>
);
}
if (art.state === "failed") {
return (
<section class={`${cls} unusable`} data-host={host} data-reason={art.reason}>
<Head url={h.url} title={art.title ?? knownTitle(host, h.url)} line={art.site && art.site !== siteOf(h.url) ? art.site : undefined} focused={at({ t: "head" })} mark={mark} />
<Unusable url={h.url} p={art} />
</section>
);
}
const v = art.value;
const at0 = v.attribution;
const sec = h.sec !== null ? v.sections.find((x) => x.id === h.sec) : undefined;
const line = byline({ author: at0.author, site: at0.site, published: at0.published });
// A section the page no longer has: its pane is closed as the page arrives (store.livePane); never the lead in its place.
if (h.sec !== null && !sec) {
return (
<section class={cls} data-host={host}>
<Head url={h.url} title={v.title} line={line} focused={at({ t: "head" })} mark={mark} />
<Problem message="This section is no longer in the page." />
</section>
);
}
// A section open as a pane to the right is marked: the picked child "showing", another fork "forked".
const showing = (id: string): string | undefined => (store.panes ? store.kidMark(tid, (r) => r.kind === "web" && r.sec === id && webKey(r.url) === webKey(h.url)) : undefined);
return (
<section class={cls} data-host={host} data-outline={v.outline}>
<Head url={h.url} title={v.title} sub={sec?.heading} line={line} focused={at({ t: "head" })} mark={mark} />
{at0.stale && <p class="wiki-wait">The page no longer answers; this is the copy read before. R tries again.</p>}
{!sec && v.model?.summary && <ModelSummary m={v.model} />}
{sec || v.lead ? <WebText host={host} row={{ t: "head" }} html={sec ? sec.html : v.lead} /> : null}
{!sec && v.outline === "model" && <p class="web-model-label web-arranged">Sections arranged by a model at your request; the page has no headings of its own.</p>}
<Rows article={v} host={host} parent={h.sec} nested={!!h.nested} at={at} showing={showing} />
<Attribution a={at0} />
</section>
);
}
function Rows(props: { article: WebArticle; host: string; parent: string | null; nested: boolean; at: (r: WRow) => boolean; showing: (id: string) => string | undefined }) {
const { article: v, host, parent, nested, at, showing } = props;
const kids = sectionsUnder(v, parent);
if (!kids.length) return null;
return (
<ul class={`wrows${parent ? " nested" : ""}`}>
{kids.map((x) => {
const row: WRow = { t: "sec", id: x.id };
const open = nested && store.secOpen(host, x.id);
const leaf = !sectionsUnder(v, x.id).length;
const mark = showing(x.id);
return (
<li key={x.id} class={`wrow${at(row) ? " focused" : ""}${open ? " open" : ""}${mark ? ` ${mark}` : ""}`}>
<div class="row" data-wrow={x.id}>
<span class="mark">{open ? "▾" : leaf && !x.html ? "·" : "▸"}</span>
<span class="title">{x.heading}</span>
</div>
{open && (
<div class="content">
<WebText host={host} row={row} html={x.html} />
<Rows {...props} parent={x.id} />
</div>
)}
</li>
);
})}
</ul>
);
}
+96 -17
View File
@@ -10,18 +10,21 @@
* text ends with its attribution.
*/
import { h, type ComponentChildren } from "preact";
import { useContext } from "preact/hooks";
import { useContext, useEffect, useRef, useState } from "preact/hooks";
import type { NodeId } from "../core/model";
import { wikiKey } from "../core/ref";
import { clip, type Range } from "../core/text";
import { PLAYER_ALLOW, PLAYER_SANDBOX, embedSrc } from "../core/video";
import type { Block } from "./articleText";
import { Attribution, Backlinks, PaneCtx, useForkMark } from "./Links";
import { NodeBody, NoteView, type VNote } from "./Node";
import { sameAux, store, type WRow } from "./store";
import { article, articleText, known, revisionUrl, sectionsUnder, sensesOf, summary, type Article } from "./wiki";
import { webKey } from "./web";
type Para = Extract<Block, { k: "para" }>;
interface Ctx {
/** What drawing a piece of article text needs besides its blocks (a web page's too: Web.tsx). */
export interface Ctx {
text: string;
notes: VNote[];
sel: { grain: string; range: Range } | null;
@@ -60,16 +63,85 @@ function ArticleTextView({ host, row, sec, html, article, lang }: { host: string
);
}
function Blocks({ bs, c }: { bs: Block[]; c: Ctx }) {
export function Blocks({ bs, c }: { bs: Block[]; c: Ctx }) {
return (
<>
{bs.map((b, i) =>
b.k === "para" ? <APara key={i} b={b} c={c} /> : b.k === "raw" ? <div key={i} class="wraw" dangerouslySetInnerHTML={{ __html: b.html }} /> : h(b.tag, { key: i, ...Object.fromEntries(b.attrs) }, <Blocks bs={b.kids} c={c} />),
b.k === "para" ? (
<APara key={i} b={b} c={c} />
) : b.k === "raw" ? (
<div key={i} class="wraw" dangerouslySetInnerHTML={{ __html: b.html }} />
) : b.tag === "figure" && b.attrs.some(([k, v]) => k === "class" && v === "video") ? (
<VideoFigure key={i} b={b} c={c} />
) : (
h(b.tag, { key: i, ...Object.fromEntries(b.attrs) }, <Blocks bs={b.kids} c={c} />)
),
)}
</>
);
}
type El = Extract<Block, { k: "el" }>;
/** A video box's shape: the nearest of a few common ones to the video's own (16:9 when unknown), as a class, since the text may carry no style attribute. */
const SHAPES: [string, number][] = [["r21-9", 21 / 9], ["r16-9", 16 / 9], ["r3-2", 3 / 2], ["r4-3", 4 / 3], ["r1-1", 1], ["r3-4", 3 / 4], ["r9-16", 9 / 16]];
function shape(size: { width?: string; height?: string }): string {
const r = size.width && size.height ? Number(size.width) / Number(size.height) : 16 / 9;
return SHAPES.reduce((best, s) => (Math.abs(Math.log(s[1] / r)) < Math.abs(Math.log(best[1] / r)) ? s : best))[0];
}
/**
* A video's facade (src/core/video.ts): its still and a play mark, its caption under them, and on
* Wikipedia a link to its File page, which credits it. Nothing plays or loads from elsewhere until
* the click; then a <video controls preload="none"> with the checked source (started, since the
* reader asked), or an iframe to the one player address for the checked id, takes the still's
* place. Both are made here from the data attributes the cleaning let through, never from the
* page's own markup.
*/
function VideoFigure({ b, c }: { b: El; c: Ctx }) {
const [playing, setPlaying] = useState(false);
const ref = useRef<HTMLVideoElement>(null);
const a = Object.fromEntries(b.attrs) as Record<string, string | undefined>;
const still = b.kids.find((k): k is Extract<Block, { k: "raw" }> => k.k === "raw");
const stillSrc = still && /^<img src="([^"]*)"/.exec(still.html)?.[1]?.replace(/&amp;/g, "&");
const rest = b.kids.filter((k) => k !== still);
const player = a["data-embed"] && a["data-id"] ? embedSrc(a["data-embed"], a["data-id"]) : null;
const size = a["data-width"] && a["data-height"] && !player ? { width: a["data-width"], height: a["data-height"] } : {};
const caption = rest.map((k) => (k.k === "para" ? c.text.slice(k.s, k.e) : k.k === "el" ? k.kids.map((x) => (x.k === "para" ? c.text.slice(x.s, x.e) : "")).join(" ") : "")).join(" ").trim();
useEffect(() => {
if (playing) void ref.current?.play().catch(() => {});
}, [playing]);
const play = (e: Event) => {
e.preventDefault();
e.stopPropagation();
setPlaying(true);
};
return (
<figure {...a} class={`video${a["data-embed"] ? " embed" : ""}${playing ? " playing" : ""}`}>
{!playing ? (
<div class={`video-box ${shape(size)}`} role="button" aria-label={`Play video${caption ? `: ${caption}` : ""}`} onClick={play}>
{still && <div class="wraw" dangerouslySetInnerHTML={{ __html: still.html }} />}
<span class="video-play" aria-hidden="true">▶</span>
</div>
) : player ? (
<div class="video-box r16-9">
<iframe src={player} title={caption || "Video"} sandbox={PLAYER_SANDBOX} allow={PLAYER_ALLOW} referrerpolicy="no-referrer" />
</div>
) : (
<div class={`video-box ${shape(size)}`}>
<video ref={ref} src={a["data-video"]} controls preload="none" {...size} {...(stillSrc ? { poster: stillSrc } : {})} />
</div>
)}
<Blocks bs={rest} c={c} />
{a["data-file"] && (
<a class="video-credit" href={a["data-file"]} target="_blank" rel="noopener noreferrer">
File page: author and licence ↗
</a>
)}
</figure>
);
}
/** One paragraph, cut where its inline elements, annotations, the selection and the focused link begin and end; a formula is never cut. */
function APara({ b, c }: { b: Para; c: Ctx }) {
const clipTo = (r: Range): Range | null => (r[0] < b.e && r[1] > b.s ? [Math.max(r[0], b.s), Math.min(r[1], b.e)] : null);
@@ -101,7 +173,8 @@ function APara({ b, c }: { b: Para; c: Ctx }) {
);
for (const m of [...run.marks].reverse()) {
const attrs = Object.fromEntries(m.attrs);
const cls = m.tag === "a" ? [c.link && meets(c.link, x, y, false) && "wfocus", c.fork && attrs["data-wiki"] && c.fork(`w:${attrs["data-wiki"]}`)].filter(Boolean).join(" ") : "";
const fork = c.fork && (attrs["data-wiki"] ? c.fork(`w:${attrs["data-wiki"]}`) : attrs["data-url"] ? c.fork(webKey(attrs["data-url"])) : "");
const cls = m.tag === "a" ? [c.link && meets(c.link, x, y, false) && "wfocus", fork].filter(Boolean).join(" ") : "";
el = h(m.tag, { key: x, ...attrs, class: cls || undefined }, el);
}
out.push(el);
@@ -150,9 +223,9 @@ const detachedIn = (article: Article, lang: string, sec: number) =>
store.annotations(article, lang).detached.filter((d) => d.sec === sec || (sec === 0 && d.sec === null)).map((d) => d.id);
/** The W that marks Wikipedia's text, and the title. */
function Head({ title, sub, focused }: { title: string; sub?: string; focused: boolean }) {
function Head({ title, sub, focused, mark }: { title: string; sub?: string; focused: boolean; mark?: string }) {
return (
<header class={`wiki-head${focused ? " focused" : ""}`}>
<header class={`wiki-head${focused ? " focused" : ""}${mark ? ` ${mark}` : ""}`}>
<div class="wiki-brand">
<span class="wmark">W</span> Wikipedia
</div>
@@ -164,25 +237,30 @@ function Head({ title, sub, focused }: { title: string; sub?: string; focused: b
);
}
function Problem({ message }: { message: string }) {
export function Problem({ message }: { message: string }) {
return <p class="wiki-problem">{message}</p>;
}
/** One article view. `host` says which (see Aux in store.ts); a pane passes its index. */
export function WikiView({ host }: { host: string }) {
export function WikiView({ host, own, headFocused }: { host: string; own?: boolean; headFocused?: boolean }) {
const tid = useContext(PaneCtx);
const fork = useForkMark();
const h = store.wikiHost(host);
if (!h) return null;
// Under a node, the article opened in a pane of its own (L) is marked at this head, where its curve starts.
const mark = h.embedded ? fork?.(`w:${h.title}`) : undefined;
const a = store.aux;
const at = (row: WRow) => !!a && a.kind === "wiki" && a.host === host && !a.grain && sameAux(a, { kind: "wiki", host, row });
const at = (row: WRow) => (row.t === "head" && !!headFocused) || (!!a && a.kind === "wiki" && a.host === host && !a.grain && sameAux(a, { kind: "wiki", host, row }));
const embedded = h.embedded;
// Its pane's own view (a section that is only a link, shown as its article), not an inset under a node's text.
const inset = embedded && !own ? " embedded" : "";
// Under a node, folded: its summary only, until l unfolds the article.
if (store.folded(embedded)) {
const sum = summary(h.title, h.lang);
return (
<section class={`wiki embedded folded${at({ t: "head" }) ? " focused" : ""}`} data-host={host}>
<Head title={sum.state === "ready" ? sum.value.title : h.title} focused={at({ t: "head" })} />
<Head title={sum.state === "ready" ? sum.value.title : h.title} focused={at({ t: "head" })} mark={mark} />
{sum.state === "loading" && <p class="wiki-wait">Loading the summary…</p>}
{sum.state === "failed" && <Problem message={sum.message} />}
{sum.state === "ready" && (
@@ -202,8 +280,8 @@ export function WikiView({ host }: { host: string }) {
// While the article loads, a summary already at hand is shown at once.
const have = known(h.title, h.lang);
return (
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
<Head title={have?.title ?? h.title} focused={at({ t: "head" })} />
<section class={`wiki${inset}`} data-host={host}>
<Head title={have?.title ?? h.title} focused={at({ t: "head" })} mark={mark} />
{have && <p class="wiki-summary">{have.extract}</p>}
{art.state === "loading" ? <p class="wiki-wait">Loading the article from Wikipedia…</p> : <Problem message={art.message} />}
{have && <Attribution a={have.attribution} />}
@@ -216,8 +294,8 @@ export function WikiView({ host }: { host: string }) {
// A section open as a pane to the right is marked: the picked child "showing", another fork "forked".
const showing = (id: number): string | undefined => (store.panes ? store.kidMark(tid, (r) => r.kind === "wiki" && r.title === h.title && r.sec === id) : undefined);
return (
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
<Head title={v.title} sub={sec?.heading} focused={at({ t: "head" })} />
<section class={`wiki${inset}`} data-host={host}>
<Head title={v.title} sub={sec?.heading} focused={at({ t: "head" })} mark={mark} />
{art.stale && <p class="wiki-wait">Wikipedia could not be reached; this is the copy kept from before.</p>}
<Detached ids={detachedIn(v, h.lang, h.sec)} article={v} lang={h.lang} />
<ArticleTextView host={host} row={{ t: "head" }} sec={h.sec} html={sec ? sec.html : v.lead} article={v} lang={h.lang} />
@@ -237,7 +315,7 @@ function Rows(props: { article: Article; host: string; lang: string; parent: num
<ul class={`wrows${parent ? " nested" : ""}`}>
{kids.map((x) => {
const row: WRow = { t: "sec", id: x.id };
const open = nested && store.colOpen.has(x.id);
const open = nested && store.secOpen(host, x.id);
const leaf = !sectionsUnder(v, x.id).length;
return (
<li key={x.id} class={`wrow${at(row) ? " focused" : ""}${open ? " open" : ""}${showing(x.id) ? ` ${showing(x.id)}` : ""}`}>
@@ -298,7 +376,8 @@ export function WikiPage() {
);
}
function backLabel(): string {
/** What h returns to from the column's article page. */
export function backLabel(): string {
const c = store.colWiki;
if (!c) return "";
if (c.stack.length) return c.stack[c.stack.length - 1].title;
+26 -8
View File
@@ -71,8 +71,10 @@ const quote = (s: string, n = 60) => {
export interface SelCtx {
/** The words, for Copy and the menu's head. */
text: string;
/** In Wikipedia's text: no linking by hand, no Related. */
/** In Wikipedia's text (or a web page's): no linking by hand, no Related. */
article: boolean;
/** In a web page's text: nothing is written on it, so no lenses either. */
web?: boolean;
/** A link on exactly these words: where it goes. */
link?: "wiki" | "node" | "url";
/** A note (with text of its own) on exactly these words. */
@@ -100,6 +102,7 @@ function lenses(act: Act): Item[] {
/** The selection bar: the lenses, then linking (not in an article). Its ⋯ opens `selectionEntries`. */
export function barItems(c: SelCtx, act: Act): Item[][] {
if (c.web) return [[key(act, c.link ? "Open the link" : "Open the original", c.link ? "Enter" : "W", { short: c.link ? "open" : "original" })]];
const ls = lenses(act);
return c.article ? [ls] : [ls, [key(act, "Link to…", "w", { short: "link…" })]];
}
@@ -114,14 +117,15 @@ export function selectionEntries(c: SelCtx, act: Act): Entry[] {
c.link && key(act, c.panes && !c.pages ? "Open the link beside" : "Open the link", "Enter"),
c.link && c.panes && key(act, "Open it in place", "Enter", { keyText: "⇧⏎", shift: true, sub: "instead of the pane there" }),
c.link === "wiki" && key(act, "Open on wikipedia.org", "W"),
(c.link === "url" || (c.web && !c.link)) && key(act, "Open the original", "W", { sub: "in a new tab" }),
c.note && key(act, "Open the note", "Enter"),
c.suggestion && key(act, `Link to ${c.suggestion}`, "y", { sub: "a suggested link" }),
c.suggestion && key(act, "Decline the suggestion", "n"),
(c.link || c.note) && !c.article && key(act, c.link ? "Retarget…" : "Link it…", "w"),
(c.link || c.note) && key(act, c.link && !c.note ? "Remove the link" : "Delete the note", "D", c.link && !c.note ? { sub: "and do not link these words again here" } : {}),
(c.link || c.note) && !c.web && key(act, c.link && !c.note ? "Remove the link" : "Delete the note", "D", c.link && !c.note ? { sub: "and do not link these words again here" } : {}),
c.link && c.note && !c.article && { t: "item", label: "Remove the link, keep the note", keyText: "/unlink", run: () => act.command("/unlink") },
SEP,
...lenses(act),
...(c.web ? [] : lenses(act)),
SEP,
!c.article && !c.link && !c.note && key(act, "Link to…", "w"),
related.length > 0 && head("Link to a related section"),
@@ -196,16 +200,30 @@ export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
interface PaneCtx {
/** A node's pane: its node; none for an article's. */
node?: NodeCtx;
/** An article's pane: its title. */
/** An article's pane: its title. With `node`, the pane of a section shown as its article: the node's items, then the article's. */
article?: string;
/** The article is a web page (its original is at its own address, not on wikipedia.org). */
web?: boolean;
/** A web page: whether a model may arrange it here (false: the item is shown, disabled). */
arrange?: boolean;
pinned: boolean;
/** Whether it can move up, or down, its column (another pane is above it, or below). */
above?: boolean;
below?: boolean;
}
/** What can be done to a web page itself: open the original, have a model arrange it (s), read it again (R). */
export function webPageEntries(act: Act, arrange = true): Entry[] {
return [
key(act, "Open the original", "W", { sub: "in a new tab" }),
key(act, "Arrange with a model", "s", arrange ? { sub: "a summary; sections for a page divided by length" } : { disabled: true, sub: "no model, or turned off on this server" }),
key(act, "Read it again", "R", { sub: "Reload: the page is otherwise kept as first read" }),
];
}
export function paneEntries(c: PaneCtx, act: Act): Entry[] {
const own = c.node ? nodeEntries(c.node, act) : [head(c.article ?? "Wikipedia"), key(act, "Open on wikipedia.org", "W")];
const page = c.web ? webPageEntries(act, c.arrange !== false) : [key(act, "Open on wikipedia.org", "W")];
const own = c.node ? [...nodeEntries(c.node, act), ...(c.article !== undefined ? [SEP, head(c.article), ...page] : [])] : [head(c.article ?? "Wikipedia"), ...page];
return tidy([
...own,
SEP,
@@ -227,13 +245,13 @@ export function paneEntries(c: PaneCtx, act: Act): Entry[] {
]);
}
/** A row of an article (a section, a sense): open it. */
export function articleRowEntries(title: string, panes: boolean, act: Act, pages = false): Entry[] {
/** A row of an article (a section, a sense) or of a web page: open it; on a web page, what can be done to the page. */
export function articleRowEntries(title: string, panes: boolean, act: Act, pages = false, web = false, arrange = true): Entry[] {
return tidy([
head(title),
key(act, panes && !pages ? "Open beside" : "Open", "Enter"),
panes && key(act, "Open in place", "Enter", { keyText: "⇧⏎", shift: true, sub: "instead of the pane there" }),
key(act, "Open on wikipedia.org", "W"),
...(web ? [SEP, ...webPageEntries(act, arrange)] : [key(act, "Open on wikipedia.org", "W")]),
]);
}
+16 -9
View File
@@ -7,8 +7,9 @@
* list entries and block quotes, with everything inline in them (links, italics, bold, sub- and
* superscripts, code). An inline formula counts as its glyphs' text and is selected and drawn
* whole: a selection that touches it highlights all of it. What is not: tables and preformatted
* blocks, which are shown as they are but carry no offsets. Whitespace is collapsed as the browser
* collapses it. Citation markers and the rest are gone already (server/wikiHtml.ts). A section's
* blocks, which are shown as they are but carry no offsets. A figure (an image and its caption,
* or a video's facade and its caption) is shown as it is, and its caption is text like a paragraph's. Whitespace is
* collapsed as the browser collapses it. Citation markers and the rest are gone already (server/wikiHtml.ts). A section's
* text is its own: nothing spans two sections.
*/
import type { Range } from "../core/text";
@@ -42,15 +43,18 @@ export type Block =
| { k: "el"; tag: string; attrs: [string, string][]; kids: Block[] }
| { k: "raw"; html: string };
/** A link in the text: to an article (`lang` when it names its own, as a web page's links do), or to another web page. */
export type TextLink = { range: Range; title: string; lang?: string } | { range: Range; url: string; title?: undefined };
export interface ArticleText {
text: string;
blocks: Block[];
/** The links to other articles, in reading order. */
links: { range: Range; title: string }[];
/** The links to other articles and pages, in reading order. */
links: TextLink[];
}
const STRUCT = new Set(["ul", "ol", "li", "dl", "dt", "dd", "blockquote"]);
const OPAQUE = new Set(["table", "pre", "hr"]);
const STRUCT = new Set(["ul", "ol", "li", "dl", "dt", "dd", "blockquote", "figure", "figcaption"]);
const OPAQUE = new Set(["table", "pre", "hr", "img"]);
const attrsOf = (n: DomLike): [string, string][] => Array.from(n.attributes ?? [], (a) => [a.name, a.value]);
const same = (a: Mark[], b: Mark[]) => a.length === b.length && a.every((m, i) => m === b[i]);
@@ -138,7 +142,7 @@ export function buildText(root: DomLike): ArticleText {
visit(root);
flush();
// A link is the runs inside one <a data-wiki>.
// A link is the runs inside one <a data-wiki> (or, in a web page's text, <a data-url>).
const links: ArticleText["links"] = [];
const seen = new Map<Mark, number>();
const walk = (bs: Block[]) => {
@@ -146,13 +150,16 @@ export function buildText(root: DomLike): ArticleText {
if (b.k === "el") walk(b.kids);
if (b.k !== "para") continue;
for (const r of b.runs) {
const a = r.marks.find((m) => m.tag === "a" && m.attrs.some(([k]) => k === "data-wiki"));
const a = r.marks.find((m) => m.tag === "a" && m.attrs.some(([k]) => k === "data-wiki" || k === "data-url"));
if (!a) continue;
const i = seen.get(a);
if (i !== undefined) links[i].range[1] = r.e;
else {
seen.set(a, links.length);
links.push({ range: [r.s, r.e], title: a.attrs.find(([k]) => k === "data-wiki")![1] });
const at = (k: string) => a.attrs.find(([n]) => n === k)?.[1];
const title = at("data-wiki");
const lang = at("data-wiki-lang");
links.push(title !== undefined ? { range: [r.s, r.e], title, ...(lang ? { lang } : {}) } : { range: [r.s, r.e], url: at("data-url")! });
}
}
}
+27 -6
View File
@@ -2,6 +2,9 @@
import { inArticles } from "../core/article";
import { store } from "./store";
/** The keys that act on a node, which on the head of a section shown as its article (Store.linkHead) act on that section rather than on the article. */
const NODE_KEYS = new Set(["r", "w", "D", "a", "A", "c", "e", "J", "K", ">", "<", "p", "M", "z", "b", "o", "O"]);
export const HELP: [string, [string, string][]][] = [
[
"Move",
@@ -40,10 +43,12 @@ export const HELP: [string, [string, string][]][] = [
"Links",
[
["", "W marks a Wikipedia link, § another note in the library, ↗ a web page; a dotted underline is a note, both together a note that also links"],
["Enter", "on a link: open it (panes: the next pane; column: a preview, Enter again opens it). On a note that also links, or a note and a link on the same words: one page, the note's text above the article"],
["w", "on a selection: link it (library, Wikipedia or an address); on a link: retarget it; on a node: give the node a target"],
["L", "on a node: open its own target"],
["W", "open the focused article on wikipedia.org, in a new tab"],
["Enter", "on a link: open it (panes: the next pane; column: a preview, Enter again opens it). A web page opens like an article: its lead, then its sections as rows (an address on wikipedia.org opens as the article). On a note that also links, or a note and a link on the same words: one page, the note's text above the article"],
["w", "on a selection: link it (library, Wikipedia or an address); on a link: retarget it; on a node: give the node a target. A section with a target and nothing else of its own is shown as its article: opened, its pane reads as the article (in one column, the article opens under its row); on that pane's head r w D a c act on the section, and a or c makes it a section like any other"],
["L", "on a node: open its own target (in panes, to the right of the node's pane when that is open)"],
["W", "open the focused article on wikipedia.org, or a web page (or a link to one) at its own address, in a new tab"],
["s", "on a web page: have the model summarise it, and arrange a page divided only by length into sections of its choosing (a page with headings of its own keeps them). Only when asked, within the server's daily limit of calls (EX_PAGE_CALLS); the summary is shown above the lead, marked as the model's, and the foot says what the model did. Pressed again on the same text, it costs no call"],
["R", "on a web page: read it again (a page is otherwise kept as first read). Unchanged text keeps what the model made of it; a page that no longer answers keeps the copy read before, marked stale; one that could not be shown is asked again"],
["D", "on a link: remove it, and decline its words in that node so it is not made again (u undoes). Also in the right-click menu: Remove the link"],
["y n", "on a suggested link (a faint dashed underline; Tab reaches it): link it / decline it (a declined phrase is not suggested again in that node)"],
["S", "the links list of the node you are on and everything under it (on the library root, the whole library): every link found or made, with who decided and the reviewer's reason. 1 2 3 show or hide linked · rejected · pending (rejected is hidden at first); j k move (the words are selected in the text); y links (also a rejected one: you overrule); n declines, or on a link removes it for good; Y links all the pending shown; Enter goes to the words; Esc closes"],
@@ -329,11 +334,27 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
// On a Wikipedia view, a target or a "Linked from" row, the keys mean what they would on rows
// (unless the focus is an annotation shown in it, which is a node like any other).
const onAnnotation = !!store.snap.nodes[store.focus.node]?.wanchor || inArticles(store.snap, store.focus.node);
if (!store.aux && !onAnnotation && ((store.panes && store.trail[store.paneAt]?.kind === "wiki") || (!store.panes && store.colWiki))) {
if (!store.aux && !onAnnotation && ((store.panes && (store.trail[store.paneAt]?.kind ?? "node") !== "node") || (!store.panes && store.colWiki))) {
store.aux = { kind: "wiki", host: store.panes ? `p${store.paneAt}` : "col", row: { t: "head" } };
}
// The head of a pane that is a section shown as its article is the article's head; the keys that
// act on a node (rename, retarget, delete, add a section, edit its text…) act on that section there.
const lone = store.focus.node;
if (!store.aux && !onAnnotation && store.panes && store.focus.grain === "node" && lone !== store.top && store.paneHead(lone) && store.linkOnly(lone)) {
store.aux = { kind: "wiki", host: `n${lone}`, row: { t: "head" } };
}
const head = store.linkHead;
if (head && NODE_KEYS.has(k)) {
store.aux = null;
store.focus = { node: head, grain: "node" };
}
// 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();
// On a web page, its rows or its text: R reads it again, s has the model arrange it.
if (store.onWeb && (k === "R" || k === "s")) {
void (k === "R" ? store.reloadWebPage() : store.arrangeWebPage());
return done();
}
// Enter opens beside what is in the next column; Shift+Enter in place of the focused branch's pane there.
const replace = k === "Enter" && e.shiftKey;
// Words selected in an article's text take the same keys as words of a node.
@@ -541,7 +562,7 @@ function libsKey(k: string): boolean {
function commonKey(k: string, hooks: KeyHooks): boolean {
switch (k) {
case "W":
store.openOnWikipedia();
store.openOriginal();
return true;
case "q":
if (store.panes) store.closePane();
+445 -114
View File
@@ -10,7 +10,7 @@
*/
import { UndoManager } from "loro-crdt";
import {
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, isLibraryRoot, isLink, isStale, label, notesOf, sections,
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, isLibraryRoot, isLink, isStale, label, linkOnly, notesOf, sections,
staleness, topOf, tops, type NodeId, type Op, type Snap,
} from "../core/model";
import { FormatError, serializeDoc } from "../core/format";
@@ -23,9 +23,10 @@ import {
import { clip, formFor, plain, rangeAt, sentences, slugify, words, type Form, type Range } from "../core/text";
import { applyLinks, linkIndex, nodeRef, ownerSection, resolveNode } from "../core/links";
import { annotationsOf, articleNodes, inArticles, makeAnchor, reanchor, type ArticleKey } from "../core/article";
import { describeTarget, formatTarget, hostOf, parseTargetLoose, wikiKey, type Ref } from "../core/ref";
import { asOpened, describeTarget, formatTarget, hostOf, parseTargetLoose, wikiKey, type Ref } from "../core/ref";
import { article as wikiArticle, articleText, cachedExtract, sectionPath, sectionsUnder, sectionTexts, configureWiki, sensesOf as wikiSenses, wikiUrl, type Article, type WikiConfig } from "./wiki";
import type { ArticleText } from "./articleText";
import { arrangePage, article as webArticle, canArrange, configurePages, knownArticle, reloadPage, sectionsUnder as webSectionsUnder, siteOf, webKey, type PagesConfig } from "./web";
import { LENSES } from "../llm/prompts";
import {
cascade, commitArticleNote, commitExpansion, deepen, reconcile, resolveConflicts, runAgent, scanContradictions, streamArticleNote, streamExpansion,
@@ -55,11 +56,13 @@ export type Mode = "normal" | "edit" | "command" | "history" | "help" | "jump" |
* A pane of the panes view. The panes are a tree of forks (forks.ts) whose focused branch is the
* trail: it starts with the path down from the top node, and a link followed from a pane opens its
* target in the next pane, so it may hold a node from anywhere in the library, a Wikipedia article or a section
* of one. `from` is where a jump was made from, which h returns to.
* of one, or a web page or a section of one (`sec` is the page's own id for it: "h3", "p2", "c1").
* `from` is where a jump was made from, which h returns to.
*/
export type PaneRef =
| { kind: "node"; id: NodeId; from?: Back }
| { kind: "wiki"; title: string; lang: string; sec?: number; from?: Back };
| { kind: "wiki"; title: string; lang: string; sec?: number; from?: Back }
| { kind: "web"; url: string; sec?: string; from?: Back };
export interface Back {
focus: Focus;
aux: Aux | null;
@@ -73,24 +76,50 @@ export const kidClass = (key: string) => {
for (let i = 0; i < key.length; i++) h = ((h * 33) ^ key.charCodeAt(i)) >>> 0;
return `k${h.toString(36)}`;
};
/** Whether two panes show the same thing (a node, or an article or one of its sections). */
const sameRef = (a: PaneRef, b: PaneRef): boolean =>
a.kind === b.kind && (a.kind === "node" ? a.id === (b as { id: NodeId }).id : a.title === (b as { title: string }).title && a.sec === (b as { sec?: number }).sec);
/** What a pane shows, as a key: `n:<node id>`, or `w:<title>` with `#<section>`. A link's target has the same key as the pane it opens. */
export const refKey = (p: PaneRef): string => (p.kind === "node" ? `n:${p.id}` : `w:${p.title}${p.sec !== undefined ? `#${p.sec}` : ""}`);
/**
* What a pane shows, as a key: `n:<node id>`; `w:<title>` with `#<section>`; or `u:<address>` (as
* compared for sameness: no fragment, no trailing slash) with `#<section>`. A link's target has the
* same key as the pane it opens.
*/
export const refKey = (p: PaneRef): string => (p.kind === "node" ? `n:${p.id}` : p.kind === "web" ? webKey(p.url, p.sec) : `w:${p.title}${p.sec !== undefined ? `#${p.sec}` : ""}`);
/** Whether two panes show the same thing (a node, an article or one of its sections, a web page or one of its sections). */
const sameRef = (a: PaneRef, b: PaneRef): boolean => {
if (a.kind === "node" && b.kind === "node") return a.id === b.id;
if (a.kind === "wiki" && b.kind === "wiki") return a.title === b.title && a.sec === b.sec;
if (a.kind === "web" && b.kind === "web") return refKey(a) === refKey(b);
return false;
};
const errText = (err: unknown) => (err instanceof Error ? err.message : String(err));
const isPaneRef = (r: unknown): r is PaneRef => {
const o = r as Record<string, unknown> | null;
return !!o && typeof o === "object" && ((o.kind === "node" && typeof o.id === "string") || (o.kind === "wiki" && typeof o.title === "string" && typeof o.lang === "string"));
if (!o || typeof o !== "object") return false;
if (o.kind === "node") return typeof o.id === "string";
if (o.kind === "wiki") return typeof o.title === "string" && typeof o.lang === "string";
return o.kind === "web" && typeof o.url === "string" && /^https?:\/\//i.test(o.url) && (o.sec === undefined || (typeof o.sec === "string" && /^[a-z]\d+$/.test(o.sec)));
};
/** A row of a Wikipedia view: its head (the lead), a section, a sense of a disambiguation page, a "Mentioned in" entry. */
export type WRow = { t: "head" } | { t: "sec"; id: number } | { t: "sense"; i: number } | { t: "back"; i: number };
/**
* Focus on something that is not a library node: a row of a Wikipedia view (`host` says which:
* `p<i>` the article in pane i, `n<id>` the article under a node, `col` the article page of the
* column), or words in the text that row shows (a grain and a range, as in a node's body: a
* A row of an article view: its head (the lead), a section, a sense of a disambiguation page, a
* "Mentioned in" entry. A section's id is a number in a Wikipedia article, a string ("h3") in a web page.
*/
export type WRow = { t: "head" } | { t: "sec"; id: number | string } | { t: "sense"; i: number } | { t: "back"; i: number };
/** A section row's id as a data attribute gives it back: a web page's ids start with a letter. */
export const rowId = (s: string | undefined): number | string => (s && /^\d+$/.test(s) ? Number(s) : (s ?? ""));
/**
* What an article view shows (Store.viewHost): a Wikipedia article or a web page, where it starts
* (`sec`: the lead, 0 or null, or a section), and how. `embedded`: under that node; `nested`: its
* sections open in place (the column) rather than as panes; `mentions`: "Mentioned in" is listed.
*/
export type ViewHost =
| { src: "wiki"; title: string; lang: string; sec: number; embedded?: NodeId; nested?: boolean; mentions?: boolean }
| { src: "web"; url: string; sec: string | null; embedded?: NodeId; nested?: boolean };
/**
* Focus on something that is not a library node: a row of an article view, Wikipedia's or a web
* page's (`host` says which view: `p<i>` the one in pane i, `f<id>` one in a pane off the focused
* branch, `n<id>` the one under a node, `col` the column's article page; Store.viewHost says what
* it shows), or words in the text that row shows (a grain and a range, as in a node's body: a
* sentence, words, a link or an annotation's words), a node's target, or a "Linked from" row. The
* node focus stays where it was, so leaving the aux focus returns to it.
* node focus stays where it was, so leaving the aux focus returns to it. `kind: "wiki"` is any
* article view; what only Wikipedia's text allows (annotations) asks Store.wikiHost.
*/
export type Aux =
| { kind: "wiki"; host: string; row: WRow; grain?: "sentence" | "word"; range?: Range }
@@ -98,11 +127,12 @@ export type Aux =
| { kind: "back"; of: NodeId; index: number };
/** A row in a pane or in the column: a section, or an aux row. */
export type Row = { node: NodeId } | { aux: Aux };
/** The column's article page, opened from a link, with the way back. */
/** The column's article page, opened from a link, with the way back: a Wikipedia article, or with `url` a web page. */
export interface ColWiki {
title: string;
lang: string;
stack: { title: string; lang: string; aux: Aux | null }[];
url?: string;
stack: { title: string; lang: string; url?: string; aux: Aux | null }[];
back: { focus: Focus; hoist: NodeId | null; aux: Aux | null };
}
/** The link picker: what is typed, and what it applies to. */
@@ -116,6 +146,8 @@ export interface Picker {
}
export const sameAux = (a: Aux | null, b: Aux | null): boolean => JSON.stringify(a) === JSON.stringify(b);
/** Why the keys that write (e d y x c :, D) do nothing on a web page's text. */
const WEB_TEXT = "A web page's text is shown as it is: notes on its words are not kept here (annotations are for Wikipedia articles and your own text). Its links open with Enter; W opens the original.";
/** Page layout: one column with a margin, or panes side by side. Auto picks panes on wide windows. */
export type View = "auto" | "column" | "panes";
/** Where a fork's colour shows in the panes view: along its curves and title rules, across its panes' tops, down their left edges, or nowhere. */
@@ -325,8 +357,8 @@ class Store {
}
aux: Aux | null = null;
colWiki: ColWiki | null = null;
/** Sections of the column's article page that are open. */
colOpen = new Set<number>();
/** Sections open in place in the column (its article page, an article under a node), as `<host> <id>` (secOpen). */
colOpen = new Set<string>();
/** Nodes whose article is unfolded beneath them in their pane. */
expanded = new Set<NodeId>();
picker: Picker | null = null;
@@ -496,7 +528,9 @@ class Store {
continuesFrom(p: PaneRef | undefined, q: PaneRef | undefined): boolean {
if (!p || !q || p.from) return false;
if (p.kind === "node") return q.kind === "node" && this.snap.nodes[p.id]?.parent === q.id && this.snap.nodes[p.id].kind === "section";
return p.sec !== undefined && (q.kind === "wiki" ? q.title === p.title : this.targetOf(q.id)?.kind === "wiki");
if (p.sec === undefined) return false;
if (q.kind === "node") return this.viewHost(`n${q.id}`)?.src === (p.kind === "wiki" ? "wiki" : "web");
return p.kind === "wiki" ? q.kind === "wiki" && q.title === p.title : q.kind === "web" && webKey(q.url) === webKey(p.url);
}
/** Pane i of the focused branch holds a focus (see holdsIn); a continuation's head only while it is the active pane. */
@@ -514,7 +548,7 @@ class Store {
const s = this.snap;
const n = s.nodes[f.node];
// An annotation is held by the pane showing its article.
if (p && n && inArticles(s, f.node)) return this.shows(p.kind === "wiki" ? host : `n${p.id}`, f.node);
if (p && n && inArticles(s, f.node)) return this.shows(p.kind !== "node" ? host : `n${p.id}`, f.node);
if (!p || p.kind !== "node" || !n) return false;
if (f.grain !== "node" || n.kind === "note") return ownerSection(s, f.node) === p.id || f.node === p.id;
if (f.node === p.id) return head || !this.continuesFrom(p, q);
@@ -538,7 +572,7 @@ class Store {
syncTrail() {
if (!this.panes || !this.session) return;
const s = this.snap;
let f = prune(this.forest, (p) => p.kind === "wiki" || !!s.nodes[p.id]);
let f = prune(this.forest, this.livePane);
if (!rooted(f, { kind: "node", id: this.top }, sameRef)) f = withBranch(f, this.pathRefs(), sameRef);
this.forest = f;
this.paneAt = Math.max(0, Math.min(this.paneAt, this.trail.length - 1));
@@ -557,6 +591,17 @@ class Store {
this.paneAt = at >= 0 ? at : this.trail.length - 1;
}
/**
* Whether a pane still shows something: its node exists; a web page's section is still in the
* page (once the page is here: a section id it no longer has is closed, not shown as the lead).
*/
private livePane = (p: PaneRef): boolean => {
if (p.kind === "node") return !!this.snap.nodes[p.id];
if (p.kind === "wiki" || p.sec === undefined) return true;
const a = knownArticle(p.url);
return a?.state !== "ready" || a.value.sections.some((x) => x.id === p.sec);
};
/**
* Open something to the right of pane i. If it is already open there, as any fork, that fork is
* focused. Otherwise it opens beside what is there, a new pane in the next column; a Shift open
@@ -616,10 +661,11 @@ class Store {
return new Map(n.kids.map((k, j) => [refKey(k.ref), { picked: j === n.pick, many: n.kids.length > 1 }]));
}
/** A link's target by the key of the pane it opens (refKey); none for a web page or a node that is gone. */
targetKey(r: Ref): string | undefined {
/** A link's target by the key of the pane it opens (refKey); none for a node that is gone. */
targetKey(target: Ref): string | undefined {
const r = asOpened(target);
if (r.kind === "wiki") return `w:${r.title}`;
if (r.kind !== "node") return undefined;
if (r.kind === "url") return webKey(r.url);
const id = resolveNode(this.snap, r);
return id ? `n:${id}` : undefined;
}
@@ -711,8 +757,7 @@ class Store {
if (!here.kids.length) return this.say("Nothing opened from this pane yet: Enter or l on a row or link opens it to the right.");
const f = this.focus;
const a = this.aux;
const key =
a?.kind === "wiki" && a.row.t === "sec" ? refKey({ kind: "wiki", title: this.wikiHost(a.host)?.title ?? "", lang: "", sec: a.row.id }) : !a && f.grain === "node" ? refKey({ kind: "node", id: f.node }) : this.selectionTargetKey();
const key = a?.kind === "wiki" && a.row.t === "sec" ? this.secKey(a.host, a.row.id) : !a && f.grain === "node" ? refKey({ kind: "node", id: f.node }) : this.selectionTargetKey();
const k = here.kids.find((c) => refKey(c.ref) === key) ?? here.kids[here.pick];
this.goPane(k.id);
}
@@ -765,8 +810,8 @@ class Store {
if (ref.from && ref.from.pane === i) return this.restore(ref.from);
this.paneAt = i;
if (ref.kind === "node" && q?.kind === "node" && this.continuesFrom(ref, q) && this.snap.nodes[ref.id]) return this.setFocus({ node: ref.id, grain: "node" });
if (ref.kind === "wiki" && ref.sec !== undefined && q) {
const host = q.kind === "wiki" ? `p${i}` : `n${q.id}`;
if (ref.kind !== "node" && ref.sec !== undefined && q) {
const host = q.kind !== "node" ? `p${i}` : `n${q.id}`;
return this.setFocus(q.kind === "node" ? { node: q.id, grain: "node" } : this.focus, { kind: "wiki", host, row: { t: "sec", id: ref.sec } });
}
this.land(i);
@@ -841,14 +886,14 @@ class Store {
paneRows(i: number): Row[] {
const p = this.trail[i];
if (!p) return [];
if (p.kind === "wiki") return this.wikiRows(`p${i}`).map((row) => ({ aux: { kind: "wiki", host: `p${i}`, row } }));
if (p.kind !== "node") return this.wikiRows(`p${i}`).map((row) => ({ aux: { kind: "wiki", host: `p${i}`, row } }));
const s = this.snap;
if (!s.nodes[p.id]) return [];
const rows: Row[] = sections(s, p.id).map((node) => ({ node }));
return [...rows, ...this.auxRows(p.id)];
}
/** Under a node: its target (in panes a Wikipedia target is the article itself, unfolded on l), then "Linked from". */
/** Under a node: its target (in panes the article itself, unfolded on l, or shown at once for a section that is only a link), then "Linked from". */
private auxRows(id: NodeId): Row[] {
const r = this.targetOf(id);
const rows: Row[] = [];
@@ -908,39 +953,92 @@ class Store {
auxValid(a: Aux): boolean {
if (a.kind !== "wiki") return !!this.snap.nodes[a.of];
if (a.host === "col") return !!this.colWiki;
if (a.host.startsWith("p")) return this.trail[+a.host.slice(1)]?.kind === "wiki";
if (a.host.startsWith("p")) return (this.trail[+a.host.slice(1)]?.kind ?? "node") !== "node";
if (a.host.startsWith("f")) return false;
return !!this.snap.nodes[a.host.slice(1) as NodeId];
}
/**
* The article a Wikipedia host shows, and how. `p<i>` is the article pane at column i of the
* focused branch, `f<id>` an article pane off it (by its id in the tree of forks).
* What an article view shows, and how (see Aux for the hosts): a Wikipedia article or a web
* page. `p<i>` is the article pane at column i of the focused branch, `f<id>` an article pane off
* it (by its id in the tree of forks), `n<id>` the target under a node, `col` the column's page.
*/
wikiHost(host: string): { title: string; lang: string; sec: number; embedded?: NodeId; nested?: boolean; mentions?: boolean } | null {
if (host === "col") return this.colWiki ? { title: this.colWiki.title, lang: this.colWiki.lang, sec: 0, nested: true, mentions: true } : null;
viewHost(host: string): ViewHost | null {
if (host === "col") {
const c = this.colWiki;
if (!c) return null;
return c.url ? { src: "web", url: c.url, sec: null, nested: true } : { src: "wiki", title: c.title, lang: c.lang, sec: 0, nested: true, mentions: true };
}
if (host.startsWith("p") || host.startsWith("f")) {
const p = host.startsWith("p") ? this.trail[+host.slice(1)] : this.forkNode(+host.slice(1))?.node.ref;
return p?.kind === "wiki" ? { title: p.title, lang: p.lang, sec: p.sec ?? 0, mentions: p.sec === undefined } : null;
if (p?.kind === "web") return { src: "web", url: p.url, sec: p.sec ?? null };
return p?.kind === "wiki" ? { src: "wiki", title: p.title, lang: p.lang, sec: p.sec ?? 0, mentions: p.sec === undefined } : null;
}
const id = host.slice(1) as NodeId;
const r = this.targetOf(id);
const t = this.targetOf(id);
const r = t && asOpened(t);
// In the column its sections open in place, as on the article page.
return r?.kind === "wiki" ? { title: r.title, lang: r.lang, sec: 0, embedded: id, nested: !this.panes } : null;
if (r?.kind === "url") return { src: "web", url: r.url, sec: null, embedded: id, nested: !this.panes };
return r?.kind === "wiki" ? { src: "wiki", title: r.title, lang: r.lang, sec: 0, embedded: id, nested: !this.panes } : null;
}
/** The Wikipedia article a host shows (viewHost), or null for a web page or nothing: what annotations, senses and "Mentioned in" need. */
wikiHost(host: string): Extract<ViewHost, { src: "wiki" }> | null {
const h = this.viewHost(host);
return h?.src === "wiki" ? h : null;
}
/** Whether an article view is a web page's. */
isWeb(host: string): boolean {
return this.viewHost(host)?.src === "web";
}
/** The key of the pane a section row of a view opens (refKey). */
secKey(host: string, id: number | string): string {
const h = this.viewHost(host);
if (!h) return "";
return h.src === "web" ? webKey(h.url, String(id)) : refKey({ kind: "wiki", title: h.title, lang: h.lang, sec: Number(id) });
}
/**
* Whether the article under a node is folded to its summary. A section about an article opens on
* its own text, with the article folded until l; a note's text is a commentary on the article, so
* the article is there in full beneath it.
* the article is there in full beneath it; a section that is only a link is shown as its article.
*/
folded(id: NodeId | undefined): boolean {
return !!id && this.snap.nodes[id]?.kind === "section" && !this.expanded.has(id);
return !!id && this.snap.nodes[id]?.kind === "section" && !this.expanded.has(id) && !this.linkOnly(id);
}
/** Whether a node shows its Wikipedia target as the article itself: always in a pane; in the column, under a note opened as a page. */
/**
* Whether a section is shown as its article (core linkOnly: a Wikipedia or web target, no text and
* no sections of its own): its pane reads as the article's, and in the column the article is
* under its row. Not while its text is being written, or written for it: then it is a node like any other.
*/
linkOnly(id: NodeId): boolean {
if (!linkOnly(this.snap, id) || (this.edit?.node === id && this.edit.field === "body")) return false;
for (const p of this.pending.values()) if (p.node === id) return false;
return true;
}
/** A section shown as its article whose head the focus is on (in panes, that article is its pane): the keys that act on a node act on it there. */
get linkHead(): NodeId | null {
const a = this.aux;
if (a?.kind !== "wiki" || a.grain || a.row.t !== "head" || !a.host.startsWith("n")) return null;
const id = a.host.slice(1) as NodeId;
return this.linkOnly(id) ? id : null;
}
/** Whether a node shows its target, a Wikipedia article or a web page, as the article itself: always in a pane; in the column, under a note opened as a page, or under a section that is only a link. */
articleUnder(id: NodeId): boolean {
return this.targetOf(id)?.kind === "wiki" && (this.panes || (id === this.top && this.snap.nodes[id].kind === "note"));
return !!this.viewHost(`n${id}`) && (this.panes || (id === this.top && this.snap.nodes[id].kind === "note") || this.linkOnly(id));
}
/** Whether a section of an article view is open in place (on the column's page, or under a node in the column). */
secOpen(host: string, id: number | string): boolean {
return this.colOpen.has(`${host} ${id}`);
}
openSec(host: string, id: number | string) {
this.colOpen.add(`${host} ${id}`);
}
/**
@@ -982,15 +1080,27 @@ class Store {
}
/**
* The rows of a Wikipedia view: its head, then its sections (in a pane, the sections directly
* The rows of an article view: its head, then its sections (in a pane, the sections directly
* under what it shows, since a section opens as the next pane; on the column's page, nested and
* opened in place), a disambiguation page's senses, and "Mentioned in".
* opened in place), a disambiguation page's senses, and "Mentioned in" (a web page has neither).
*/
wikiRows(host: string): WRow[] {
const h = this.wikiHost(host);
const h = this.viewHost(host);
if (!h) return [];
const rows: WRow[] = [{ t: "head" }];
if (this.folded(h.embedded)) return rows;
if (h.src === "web") {
const a = webArticle(h.url);
if (a.state !== "ready") return rows;
const visit = (parent: string | null) => {
for (const x of webSectionsUnder(a.value, parent)) {
rows.push({ t: "sec", id: x.id });
if (h.nested && this.secOpen(host, x.id)) visit(x.id);
}
};
visit(h.sec);
return rows;
}
const a = wikiArticle(h.title, h.lang);
if (a.state === "ready") {
if (a.value.disambiguation && h.sec === 0) {
@@ -1000,7 +1110,7 @@ class Store {
const visit = (parent: number) => {
for (const x of sectionsUnder(a.value, parent)) {
rows.push({ t: "sec", id: x.id });
if (h.nested && this.colOpen.has(x.id)) visit(x.id);
if (h.nested && this.secOpen(host, x.id)) visit(x.id);
}
};
visit(h.sec);
@@ -1035,13 +1145,18 @@ class Store {
/**
* Open a target. In panes it opens in the next pane and the focus goes into it; in the column a
* node is gone to (Back returns) and an article opens as a page of its own (h or Back returns).
* A web page opens in a new tab.
* node is gone to (Back returns) and an article or a web page opens as a page of its own (h or
* Back returns). An address of a Wikipedia article opens as that article. W opens the original.
*/
follow(r: Ref) {
follow(target: Ref) {
const r = asOpened(target);
if (r.kind === "url") {
window.open(r.url, "_blank", "noopener,noreferrer");
return this.say(`Opened ${r.url} in a new tab.`);
if (this.panes) {
const from = this.backHere();
this.paneAt = this.openPane(this.paneAt, { kind: "web", url: r.url, from });
return this.setFocus(this.focus, { kind: "wiki", host: `p${this.paneAt}`, row: { t: "head" } });
}
return this.openColWiki(r.title ?? siteOf(r.url), "", true, r.url);
}
if (r.kind === "node") {
const id = resolveNode(this.snap, r);
@@ -1066,12 +1181,13 @@ class Store {
this.openColWiki(r.title, r.lang, true);
}
/** The column's article page. A further article from it stacks on it; h goes back one. */
openColWiki(title: string, lang: string, push: boolean) {
if (this.colWiki) this.colWiki.stack.push({ title: this.colWiki.title, lang: this.colWiki.lang, aux: this.aux });
/** The column's article page (with `url`, a web page). A further article from it stacks on it; h goes back one. */
openColWiki(title: string, lang: string, push: boolean, url?: string) {
if (this.colWiki) this.colWiki.stack.push({ title: this.colWiki.title, lang: this.colWiki.lang, url: this.colWiki.url, aux: this.aux });
else this.colWiki = { title, lang, stack: [], back: { focus: this.focus, hoist: this.hoist, aux: this.aux } };
this.colWiki.title = title;
this.colWiki.lang = lang;
this.colWiki.url = url;
this.colOpen.clear();
this.aux = { kind: "wiki", host: "col", row: { t: "head" } };
if (push && this.ready) window.history.pushState(null, "", this.here());
@@ -1087,6 +1203,7 @@ class Store {
if (prev) {
c.title = prev.title;
c.lang = prev.lang;
c.url = prev.url;
this.colOpen.clear();
this.aux = prev.aux ?? { kind: "wiki", host: "col", row: { t: "head" } };
} else {
@@ -1162,7 +1279,7 @@ class Store {
}
setLibrary(library);
this.library = library;
let state: { user: string; llm: LLM["kind"]; model: string | null; library?: string; title?: string; libraries?: LibraryInfo[]; branches?: { name: string }[]; wiki?: WikiConfig; linkJob?: JobState | null; web?: { on: boolean; searches: number; fetches: number } } | null = null;
let state: { user: string; llm: LLM["kind"]; model: string | null; library?: string; title?: string; libraries?: LibraryInfo[]; branches?: { name: string }[]; wiki?: WikiConfig; pages?: PagesConfig; linkJob?: JobState | null; web?: { on: boolean; searches: number; fetches: number } } | null = null;
try {
const res = await fetch(libApi("/state"));
if (res.status === 404) {
@@ -1182,6 +1299,7 @@ class Store {
if (state?.wiki) this.wiki = state.wiki;
this.web = state?.web ?? { on: false, searches: 0, fetches: 0 };
if (state?.linkJob?.state === "running") this.links.job = state.linkJob;
configurePages(state?.pages, () => this.pageArrived());
configureWiki(state?.wiki, () => (this.replayHeld(), this.emit()), () => {
// Once per browser: why Wikipedia is slow, and what makes it fast.
if (lsGet("ie:wiki-hint", false)) return;
@@ -1459,9 +1577,11 @@ class Store {
this.emit();
}
/** The window's title: the article on the column's article page, else the node the reader is on. */
/** The window's title: the article (or web page) 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) || "Explicata";
const c = this.colWiki;
const page = c?.url ? webArticle(c.url) : null;
document.title = c ? (c.url ? `${page?.state === "ready" ? page.value.title : c.title} · ${siteOf(c.url)}` : `${c.title} · Wikipedia`) : label(this.snap, this.activeNode) || "Explicata";
}
/** Every edit is saved as it is made; this says whether the server has it yet. */
@@ -1491,7 +1611,7 @@ class Store {
this.hoist = v.hoist && s.nodes[v.hoist] ? v.hoist : null;
this.focus = v.focus && s.nodes[v.focus.node] ? v.focus : { node: this.top, grain: "node" };
// The forest of forks; a view saved before orphans has one tree, and before forks only its trail, which loads as one branch.
this.forest = prune(restoreForest<PaneRef, Back>(v, isPaneRef), (p) => p.kind === "wiki" || !!s.nodes[p.id]);
this.forest = prune(restoreForest<PaneRef, Back>(v, isPaneRef), this.livePane);
this.paneAt = Math.min(v.paneAt ?? 0, Math.max(0, this.trail.length - 1));
this.aux = null;
this.repairView();
@@ -1519,6 +1639,7 @@ class Store {
/** The address of what is on screen: the focused node, so a reload, a link or Back lands on it again. */
here(): string {
if (!this.panes && this.colWiki?.url) return inLibrary(this.library, `/u/${encodeURIComponent(this.colWiki.url)}`);
if (!this.panes && this.colWiki) return inLibrary(this.library, `/w/${this.colWiki.lang}/${encodeURIComponent(this.colWiki.title.replace(/ /g, "_"))}`);
const s = this.snap;
// An annotation has no address of its own: the address stays on what shows its article.
@@ -1643,9 +1764,22 @@ class Store {
this.markEntry(!named);
}
/** Show what a path within the library names (`/`, `/n/<id>`, `/w/<lang>/<title>`): on boot, and on Back and Forward. */
/** Show what a path within the library names (`/`, `/n/<id>`, `/w/<lang>/<title>`, `/u/<address>`): on boot, and on Back and Forward. */
navigate(path: string, history: "replace" | "none") {
const s = this.snap;
// A web page of the column has an address of its own too: the page's, encoded whole.
const u = /^\/u\/(.+)$/.exec(path);
let url: string | null = null;
try {
url = u ? decodeURIComponent(u[1]) : null;
} catch {
/* not an address */
}
if (url && /^https?:\/\/\S+$/i.test(url) && !this.panes) {
if (this.colWiki?.url !== url) this.openColWiki(siteOf(url), "", false, url);
if (history === "replace") window.history.replaceState(window.history.state, "", this.here());
return this.emit();
}
// An article page of the column has an address of its own, so Back returns to it and from it.
const w = /^\/w\/([a-z][a-z0-9-]{1,15})\/(.+)$/.exec(path);
if (w && !this.panes) {
@@ -1656,7 +1790,7 @@ class Store {
/* keep it as it came */
}
title = title.replace(/_/g, " ");
if (this.colWiki?.title !== title) this.openColWiki(title, w[1], false);
if (this.colWiki?.title !== title || this.colWiki.url) this.openColWiki(title, w[1], false);
if (history === "replace") window.history.replaceState(window.history.state, "", this.here());
return this.emit();
}
@@ -1664,7 +1798,7 @@ class Store {
this.colWiki = null;
this.aux = null;
}
const named = w ? ({ node: s.root } as const) : resolve(s, path);
const named = w || u ? ({ node: s.root } as const) : resolve(s, path);
const found = "node" in named && inArticles(s, named.node) ? ({ node: s.root } as const) : named;
if ("missing" in found || isLibraryRoot(s, found.node)) {
if ("missing" in found) this.say(`There is no ${found.missing.replace(/^no /, "")} here. Showing the library.`);
@@ -1842,6 +1976,8 @@ class Store {
if (!this.isOpen(f.node)) return this.setOpen(f.node, true);
const kids = sections(s, f.node);
if (kids.length) this.setFocus({ node: kids[0], grain: "node" });
// A section shown as its article: into the article, at its head.
else if (!this.panes && this.linkOnly(f.node)) this.focusRow({ aux: { kind: "wiki", host: `n${f.node}`, row: { t: "head" } } });
}
/** Enter on a selection: open the note anchored there, step into it if it is open, or ask for one. */
@@ -1958,13 +2094,13 @@ class Store {
const a = this.aux;
if (a?.kind === "wiki") {
// In an article: into its text, as in a node's body.
if (a.row.t === "sec" && this.wikiHost(a.host)?.nested && !this.colOpen.has(a.row.id)) this.colOpen.add(a.row.id);
if (a.row.t === "sec" && this.viewHost(a.host)?.nested) this.openSec(a.host, a.row.id);
const sel = this.selecting();
if (!sel && a.row.t === "head" && this.auxArticle(a)?.state === "loading") {
this.held = { aux: a, keys: [...(this.held && sameAux(this.held.aux, a) ? this.held.keys : []), "i"] };
return this.say("The article is still loading; i selects in it when it arrives.");
}
if (!sel) return this.say(a.row.t === "sec" ? "l opens the section; i then selects in its text." : a.row.t !== "head" ? "Nothing to select here." : this.folded(this.wikiHost(a.host)?.embedded) ? "l unfolds the article; i then selects in it." : "The article is still loading.");
if (!sel) return this.say(a.row.t === "sec" ? "l opens the section; i then selects in its text." : a.row.t !== "head" ? "Nothing to select here." : this.folded(this.viewHost(a.host)?.embedded) ? "l unfolds the article; i then selects in it." : this.auxArticle(a)?.state === "failed" ? "Nothing of it is shown here to select in." : "The article is still loading.");
const unit = sel.grain === "node" ? sentences(sel.text)[0] : sel.grain === "sentence" ? words(sel.text, sel.range)[0] : undefined;
if (unit) sel.set(sel.grain === "node" ? "sentence" : "word", unit);
else if (sel.grain === "node") this.say("This part of the article has no text to select.");
@@ -2200,6 +2336,7 @@ class Store {
remove() {
if (!this.writable()) return;
if (this.onWeb) return this.say(WEB_TEXT);
const s = this.snap;
const sel = this.articleSelection();
if (sel) {
@@ -2544,6 +2681,7 @@ class Store {
if (verb.startsWith("/") && builtin[verb.slice(1)]) return builtin[verb.slice(1)]();
const lens = LENSES.find((l) => l === text.toLowerCase());
if (this.inArticleText) return this.expandArticle(lens ?? "elaborate", lens ? undefined : text);
if (this.onWeb) return this.say(WEB_TEXT);
if (this.aux?.kind === "wiki") return this.say("Select words of the article first (i), then : asks about them. The editor works on your own nodes.");
if (this.focus.grain !== "node") {
// A question about the selection becomes a note answering it.
@@ -2554,13 +2692,37 @@ class Store {
// ---- keys on aux rows: Wikipedia views, targets, "Linked from" ----
/** The article text an aux focus is in: the lead or the section its row shows, with the article. None while it loads, or on a row that shows no text. */
/** Whether the aux focus is on a web page's view, where nothing is written (no annotations: the library has no place for them). */
get onWeb(): boolean {
return this.aux?.kind === "wiki" && this.isWeb(this.aux.host);
}
/**
* The text an aux focus on an article view is in, Wikipedia's or a web page's: the lead or the
* section its row shows (articleText; a web page's cleaned as one), and the language its article
* links default to. None while it loads, or on a row that shows no text.
*/
private auxText(a: Aux | null): { at: ArticleText; lang: string } | null {
if (a?.kind !== "wiki") return null;
const h = this.viewHost(a.host);
if (h?.src !== "web") {
const spot = this.auxSpot(a);
return spot && { at: spot.at, lang: spot.lang };
}
const art = webArticle(h.url);
if (art.state !== "ready") return null;
const sec = a.row.t === "head" ? (this.folded(h.embedded) ? undefined : h.sec) : a.row.t === "sec" && h.nested && this.secOpen(a.host, a.row.id) ? String(a.row.id) : undefined;
const html = sec === undefined ? undefined : sec === null ? art.value.lead : art.value.sections.find((x) => x.id === sec)?.html;
return html === undefined ? null : { at: articleText(html, true), lang: this.wiki.lang };
}
/** The article text an aux focus is in: the lead or the section its row shows, with the article. None while it loads, on a row that shows no text, or on a web page. */
private auxSpot(a: Aux | null): Spot | null {
if (a?.kind !== "wiki") return null;
const h = this.wikiHost(a.host);
const art = h ? wikiArticle(h.title, h.lang) : null;
if (!h || art?.state !== "ready") return null;
const sec = a.row.t === "head" ? (this.folded(h.embedded) ? -1 : h.sec) : a.row.t === "sec" && h.nested && this.colOpen.has(a.row.id) ? a.row.id : -1;
const sec = a.row.t === "head" ? (this.folded(h.embedded) ? -1 : h.sec) : a.row.t === "sec" && h.nested && this.secOpen(a.host, a.row.id) ? Number(a.row.id) : -1;
const html = sec === 0 ? art.value.lead : art.value.sections.find((x) => x.id === sec)?.html;
return sec < 0 || html === undefined ? null : { at: articleText(html), sec, article: art.value, lang: h.lang, host: a.host };
}
@@ -2576,21 +2738,32 @@ class Store {
this.held = { aux: a, keys: [...(this.held && sameAux(this.held.aux, a) ? this.held.keys : []), delta > 0 ? "Tab" : "S-Tab"] };
return this.say("The article is still loading; Tab goes to its first link when it arrives.");
}
if (art?.state === "failed") return this.say(`The article could not be loaded: ${art.message}`);
if (art?.state === "failed") return this.say(`${this.isWeb(a.host) ? "The page is not shown here" : "The article could not be loaded"}: ${art.message}`);
const spot = this.auxSpot(a);
const spans = spot ? this.spansIn(spot) : [];
if (!spans.length) return this.say(a.row.t === "head" || a.row.t === "sec" ? "No links to other articles or notes here." : "");
const seen = new Set<string>();
const spans = spot ? this.spansIn(spot) : (this.auxText(a)?.at.links.map((l) => l.range) ?? []).filter((r) => !seen.has(r.join()) && !!seen.add(r.join()));
if (!spans.length) return this.say(a.row.t === "head" || a.row.t === "sec" ? (spot ? "No links to other articles or notes here." : "No links here.") : "");
const at = a.range?.[0] ?? (delta > 0 ? -1 : Infinity);
const next = delta > 0 ? spans.find((r) => r[0] > at) ?? spans[0] : [...spans].reverse().find((r) => r[0] < at) ?? spans[spans.length - 1];
this.setFocus(this.focus, { ...a, grain: "word", range: next });
}
/** The article a focused link inside an article names: the link whose words are exactly the selection. */
auxLink(a: Aux): { title: string; lang: string } | null {
/**
* Where a focused link in an article's text goes, the link whose words are exactly the selection:
* an article (in the link's own language, else the text's), or another web page.
*/
auxTarget(a: Aux): Ref | null {
if (a.kind !== "wiki" || !a.range) return null;
const spot = this.auxSpot(a);
const l = spot?.at.links.find((x) => x.range[0] === a.range![0] && x.range[1] === a.range![1]);
return l && spot ? { title: l.title, lang: spot.lang } : null;
const t = this.auxText(a);
const l = t?.at.links.find((x) => x.range[0] === a.range![0] && x.range[1] === a.range![1]);
if (!l || !t) return null;
return "url" in l ? asOpened({ kind: "url", url: l.url }) : { kind: "wiki", title: l.title, lang: l.lang ?? t.lang };
}
/** The article a focused link inside an article names (auxTarget), when it names one. */
auxLink(a: Aux): { title: string; lang: string } | null {
const r = this.auxTarget(a);
return r?.kind === "wiki" ? { title: r.title, lang: r.lang } : null;
}
// ---- annotating articles (src/core/article.ts) ----
@@ -2650,7 +2823,7 @@ class Store {
private selecting(): { text: string; grain: Grain; range?: Range; set: (grain: Grain, range?: Range) => void } | null {
const a = this.aux;
if (a?.kind === "wiki") {
const spot = this.auxSpot(a);
const spot = this.auxText(a);
if (!spot) return null;
return {
text: spot.at.text,
@@ -2666,6 +2839,7 @@ class Store {
/** e d y x c and : on words of an article: open the annotation already there, or have one written. */
private expandArticle(lens: string, question?: string) {
if (this.onWeb) return this.say(WEB_TEXT);
const sel = this.articleSelection();
if (!sel) return this.say("Select words first: i, then e d y x c or :. An article itself is never deepened or rewritten.");
const existing = this.annotationAt(sel.spot, sel.range);
@@ -2680,11 +2854,11 @@ class Store {
/** Enter on words of an article: an annotation opens, and Enter again steps into it; a link opens its article; anything else is expanded. */
private enterArticle() {
const sel = this.articleSelection()!;
const note = this.annotationAt(sel.spot, sel.range);
const sel = this.articleSelection();
const note = sel && this.annotationAt(sel.spot, sel.range);
if (!note) {
const link = this.auxLink(sel.a);
return link ? this.follow({ kind: "wiki", title: link.title, lang: link.lang }) : this.expandArticle("elaborate");
const link = this.aux && this.auxTarget(this.aux);
return link ? this.follow(link) : this.expandArticle("elaborate");
}
if (this.open.has(note)) return this.setFocus({ node: note, grain: "node" });
this.open.add(note);
@@ -2767,8 +2941,9 @@ class Store {
/** The views that could show an annotation: the article page, a pane's article, the article under a pane's node or the column's top. */
private hosts(): string[] {
if (!this.panes) return this.colWiki ? ["col"] : this.articleUnder(this.top) ? [`n${this.top}`] : [];
return this.trail.flatMap((p, i) => (p.kind === "wiki" ? [`p${i}`] : this.articleUnder(p.id) ? [`n${p.id}`] : []));
// In the column: the article page, or each article shown under a node (the top's, a section's that is only a link).
if (!this.panes) return this.colWiki ? ["col"] : [...new Set(this.columnRows().flatMap((r) => ("aux" in r && r.aux.kind === "wiki" && r.aux.row.t === "head" ? [r.aux.host] : [])).concat(this.articleUnder(this.top) ? [`n${this.top}`] : []))];
return this.trail.flatMap((p, i) => (p.kind !== "node" ? [`p${i}`] : this.articleUnder(p.id) ? [`n${p.id}`] : []));
}
/** Whether a view shows the article an annotation (or a note inside one) is on. */
@@ -2781,7 +2956,7 @@ class Store {
/** The view showing the article an annotation is on, the focused pane's first. */
private hostOf(id: NodeId): string | undefined {
const p = this.panes ? this.trail[this.paneAt] : undefined;
const mine = p ? (p.kind === "wiki" ? `p${this.paneAt}` : `n${p.id}`) : undefined;
const mine = p ? (p.kind !== "node" ? `p${this.paneAt}` : `n${p.id}`) : undefined;
return mine && this.shows(mine, id) ? mine : this.hosts().find((h) => this.shows(h, id));
}
@@ -2798,7 +2973,7 @@ class Store {
if (!p) return this.setFocus(node, { kind: "wiki", host, row: { t: "head" } });
const h = this.wikiHost(host)!;
const row: WRow = p.sec === h.sec ? { t: "head" } : { t: "sec", id: p.sec };
if (row.t === "sec") this.colOpen.add(p.sec);
if (row.t === "sec") this.openSec(host, p.sec);
this.setFocus(node, { kind: "wiki", host, row, grain: "word", range: p.range });
}
@@ -2835,7 +3010,7 @@ class Store {
/** A click or a drag in an article's text: the sentence at a point, or the words dragged over. */
selectInArticle(host: string, row: WRow, range: Range, grain: "sentence" | "word") {
const a: Aux = { kind: "wiki", host, row };
const spot = this.auxSpot(a);
const spot = this.auxText(a);
if (!spot) return this.setFocus(this.focus, a);
const all = sentences(spot.at.text);
const r: Range = grain === "sentence" ? all.find((x) => range[0] >= x[0] && range[0] <= x[1]) ?? all[rangeAt(all, range[0])] : range;
@@ -2854,8 +3029,16 @@ class Store {
else this.emit();
}
/** Why a key that works on a node does nothing on Wikipedia's text, for the status line; null for a key that does work there. */
/** Why a key that works on a node does nothing on Wikipedia's text (or a web page's), for the status line; null for a key that does work there. */
articleRefuses(k: string, selecting: boolean): string | null {
if (this.onWeb) {
if (["r", "a", "A", "J", "K", ">", "<", "p", "b", "o", "O", "z", "f"].includes(k) && !(selecting && (k === "J" || k === "K"))) return "A web page's text is shown as it is: it cannot be edited, renamed, moved, locked, reconciled or rewritten here. R reads it again; s has a model arrange it.";
if (["e", "d", "y", "x", "c", "D", ":"].includes(k)) return WEB_TEXT;
if (k === "w") return "Words of a web page cannot be linked from here; W opens the original in a new tab.";
if (k === "S" || k === "n") return "Link suggestions are for your own text, not a web page's.";
if (/^[1-5]$/.test(k)) return "Related is listed under your own nodes, not under a web page.";
return null;
}
const own = "Wikipedia's text is shown as it is: it cannot be edited, renamed, moved, locked, reconciled or rewritten here. Annotations on it can: i selects words, e d y x c writes one.";
if (["r", "a", "A", "J", "K", ">", "<", "p", "R", "b", "o", "O", "z"].includes(k) && !(selecting && (k === "J" || k === "K"))) return own;
if (k === "c" && !selecting) return "Wikipedia's text cannot be edited here. Select words (i) and press c to challenge them, or e d y x to annotate them.";
@@ -2868,11 +3051,123 @@ class Store {
return null;
}
/** The article an aux focus shows, as loaded so far. */
/** The article (or web page) an aux focus shows, as loaded so far. */
private auxArticle(a: Aux) {
if (a.kind !== "wiki") return null;
const h = this.wikiHost(a.host);
return h ? wikiArticle(h.title, h.lang) : null;
const h = this.viewHost(a.host);
return !h ? null : h.src === "web" ? webArticle(h.url) : wikiArticle(h.title, h.lang);
}
/**
* A web page has arrived (or failed): a pane on a section it no longer has closes (livePane), the
* keys that waited for it are done, and the column's page takes its title.
*/
private pageArrived() {
const closed = this.pruneSections();
if (closed) this.say(closed === 1 ? "A pane showed a section this web page no longer has; it is closed." : `${closed} panes showed sections this web page no longer has; they are closed.`);
this.replayHeld();
if (this.colWiki?.url) this.setTitle();
this.emit();
}
/**
* Close the panes on sections a web page no longer has (after it arrived, was read again or was
* arranged: its section ids are namespaced by outline, so a pane on a part by length, "c2", does
* not survive the model's sections), and move a focus on such a row up to the page's head.
* Returns how many panes closed.
*/
private pruneSections(): number {
let closed = 0;
if (this.panes && this.session) {
const was = this.forest;
const before = this.panesPlaced.length;
this.syncTrail();
if (this.forest !== was) {
closed = Math.max(1, before - this.panesPlaced.length);
this.saveView();
this.aux = null;
this.land(Math.min(this.paneAt, this.trail.length - 1));
}
}
const a = this.aux;
const h = a?.kind === "wiki" ? this.viewHost(a.host) : null;
if (a?.kind === "wiki" && h?.src === "web" && a.row.t === "sec") {
const art = knownArticle(h.url);
if (art?.state === "ready" && !art.value.sections.some((x) => x.id === (a as { row: { id: string | number } }).row.id)) this.aux = { kind: "wiki", host: a.host, row: { t: "head" } };
}
return closed;
}
/** Actions on a web page waiting for the server, by its key: one at a time per page. */
private acting = new Set<string>();
/** The web page the focus is on (its view's address), or why there is none. */
private focusedPage(): { url: string; title: string } | string {
const a = this.aux;
const h = a?.kind === "wiki" ? this.viewHost(a.host) : null;
if (h?.src !== "web") return "Not on a web page.";
const art = webArticle(h.url);
return { url: h.url, title: art.state === "ready" ? art.value.title : art.state === "failed" && art.title ? art.title : siteOf(h.url) };
}
/**
* R on a web page: read it again. Unchanged text keeps what a model made of it; a page that no
* longer answers keeps the copy read before, marked stale; one that could not be shown is asked
* again at once. Panes on sections it no longer has close.
*/
async reloadWebPage() {
const p = this.focusedPage();
if (typeof p === "string") return this.say(p);
const k = webKey(p.url);
if (this.acting.has(k)) return this.say(`Still waiting for ${siteOf(p.url)}…`);
this.acting.add(k);
this.say(`Reading ${siteOf(p.url)} again…`);
try {
const r = await reloadPage(p.url);
const closed = this.pruneSections();
const panes = closed ? ` ${closed === 1 ? "A pane on a section it no longer has is" : `${closed} panes on sections it no longer has are`} closed.` : "";
if (!r.ok) this.say(`${clip(p.title, 50)} could not be read again: ${r.message}${panes}`);
else if (r.stale) this.say(`${clip(p.title, 50)} no longer answers (${clip(r.stale, 120)}); the copy read before is kept.${panes}`);
else this.say(`Read ${clip(r.article.title, 50)} again${r.article.model ? `; ${r.article.model.sections ? "the model's arrangement" : "the model's summary"} is kept, the text being unchanged` : ""}.${panes}`);
if (this.colWiki?.url) this.setTitle();
} finally {
this.acting.delete(k);
this.emit();
}
}
/**
* s on a web page: have a model summarise it, and arrange a page divided only by length into
* sections (a page with headings of its own keeps them). Always this explicit request, POST,
* within the server's daily budget; a page already arranged as it reads costs no call. Panes on
* the old parts close: the model's sections have ids of their own (m1, m2…).
*/
async arrangeWebPage() {
const p = this.focusedPage();
if (typeof p === "string") return this.say(p);
const art = webArticle(p.url);
if (art.state === "loading") return this.say("The page is still loading; s arranges it once it is here.");
if (art.state === "failed") return this.say("This page is not shown here, so there is nothing to arrange. R reads it again.");
if (!canArrange()) return this.say(this.generating ? "Arranging pages with a model is turned off on this server (EX_PAGES_ARRANGE=off)." : "No model is configured on this server, so pages cannot be arranged.");
const k = webKey(p.url);
if (this.acting.has(k)) return this.say(`Still waiting for the model on ${clip(p.title, 40)}…`);
this.acting.add(k);
const what = art.value.outline === "chunks" ? "arrange" : "summarise";
this.say(`Asking the model to ${what} ${clip(p.title, 50)}…`);
try {
const r = await arrangePage(p.url);
if (!r.ok) return this.say(`Not arranged: ${r.message}`);
const closed = this.pruneSections();
const panes = closed ? ` ${closed === 1 ? "A pane on one of its old parts is" : `${closed} panes on its old parts are`} closed.` : "";
const n = r.article.sections.length;
const again = r.called ? "" : " (as before: no new call)";
if (r.arranged === "sections") this.say(`Arranged by the model into ${n} sections${again}; its summary is above the lead.${panes}`);
else if (r.note) this.say(`${r.note} Its summary is above the lead${again}.`);
else this.say(`Summarised by the model${again}: the summary is above the lead; the page keeps its own sections.`);
} finally {
this.acting.delete(k);
this.emit();
}
}
/** Keys pressed on an article that was still loading, to be done once it has (Tab, then perhaps Enter). */
@@ -2915,13 +3210,14 @@ class Store {
return r ? this.follow(r) : undefined;
}
if (a.kind === "back") return this.openLinking(this.linkedFrom(a.of)[a.index]);
const h = this.wikiHost(a.host);
const h = this.viewHost(a.host);
if (!h) return;
const link = this.auxLink(a);
if (link) return this.follow({ kind: "wiki", title: link.title, lang: link.lang });
const link = this.auxTarget(a);
if (link) return this.follow(link);
const row = a.row;
if (row.t === "back") return this.openLinking(this.mentionsOf(h.lang, this.hostArticle(a.host)!.title)[row.i]);
if (row.t === "sense") {
if ((row.t === "back" || row.t === "sense") && h.src !== "wiki") return;
if (row.t === "back" && h.src === "wiki") return this.openLinking(this.mentionsOf(h.lang, this.hostArticle(a.host)!.title)[row.i]);
if (row.t === "sense" && h.src === "wiki") {
const ss = wikiSenses(h.title, h.lang);
if (ss.state === "ready" && ss.value[row.i]) this.follow({ kind: "wiki", title: ss.value[row.i].title, lang: h.lang });
return;
@@ -2933,21 +3229,23 @@ class Store {
}
return this.move(1);
}
if (row.t !== "sec") return;
// A section: in a pane it opens as the next pane (l again steps into it); on the column's page, in place.
if (h.nested) {
if (!this.colOpen.has(row.id)) {
this.colOpen.add(row.id);
if (!this.secOpen(a.host, row.id)) {
this.openSec(a.host, row.id);
return this.emit();
}
return this.move(1);
}
const i = this.paneAt;
const next = this.trail[i + 1];
if (next?.kind === "wiki" && next.title === h.title && next.sec === row.id) {
const ref: PaneRef = h.src === "web" ? { kind: "web", url: h.url, sec: String(row.id) } : { kind: "wiki", title: h.title, lang: h.lang, sec: Number(row.id) };
if (next && sameRef(next, ref)) {
this.paneAt = i + 1;
return this.setFocus(this.focus, { kind: "wiki", host: `p${i + 1}`, row: { t: "head" } });
}
this.openPane(i, { kind: "wiki", title: h.title, lang: h.lang, sec: row.id });
this.openPane(i, ref);
if (this.pages) this.land(i + 1);
}
@@ -2956,16 +3254,27 @@ class Store {
const a = this.aux;
if (!a) return;
if (a.kind !== "wiki") return this.setFocus({ node: a.of, grain: "node" });
const h = this.wikiHost(a.host);
const h = this.viewHost(a.host);
if (a.row.t !== "head") {
// On the column's page an open section's subsection steps out to the section first.
const art = h ? wikiArticle(h.title, h.lang) : null;
const sec = a.row.t === "sec" && art?.state === "ready" ? art.value.sections.find((x) => x.id === (a.row as { id: number }).id) : undefined;
const row: WRow = h?.nested && sec?.parent ? { t: "sec", id: sec.parent } : { t: "head" };
const id = a.row.t === "sec" ? a.row.id : undefined;
const art = h ? (h.src === "web" ? webArticle(h.url) : wikiArticle(h.title, h.lang)) : null;
const sections: { id: number | string; parent: number | string | null }[] = art?.state === "ready" ? art.value.sections : [];
const parent = id === undefined ? undefined : sections.find((x) => x.id === id)?.parent;
const row: WRow = h?.nested && parent ? { t: "sec", id: parent } : { t: "head" };
return this.setFocus(this.focus, { ...a, row });
}
if (a.host === "col") return this.closeColWiki();
if (a.host.startsWith("n")) return this.setFocus({ node: a.host.slice(1) as NodeId, grain: "node" });
if (a.host.startsWith("n")) {
const id = a.host.slice(1) as NodeId;
// The head of a pane that is a section shown as its article is that pane's head: h goes back as from a node's pane.
if (this.panes && id !== this.top && this.paneHead(id) && this.linkOnly(id)) {
this.aux = null;
this.focus = { node: id, grain: "node" };
return this.out();
}
return this.setFocus({ node: id, grain: "node" });
}
// The head of an article pane: back where it was opened from, or to the row it continues.
const i = +a.host.slice(1);
const p = this.trail[i];
@@ -2973,29 +3282,38 @@ class Store {
if (i === 0) return;
this.paneAt = i - 1;
const q = this.trail[i - 1];
if (p?.kind === "wiki" && p.sec !== undefined) {
const host = q.kind === "wiki" ? `p${i - 1}` : `n${q.id}`;
if (p && p.kind !== "node" && p.sec !== undefined) {
const host = q.kind !== "node" ? `p${i - 1}` : `n${q.id}`;
return this.setFocus(q.kind === "node" ? { node: q.id, grain: "node" } : this.focus, { kind: "wiki", host, row: { t: "sec", id: p.sec } });
}
if (q.kind === "node") this.setFocus({ node: q.id, grain: "node" });
else this.setFocus(this.focus, { kind: "wiki", host: `p${i - 1}`, row: { t: "head" } });
}
/** W: the focused article (or the article a focused link names) on Wikipedia itself, in a new tab. */
openOnWikipedia() {
/**
* W: the original of what is focused, in a new tab: the focused article (or the article a focused
* link names) on Wikipedia itself; a web page (or a link to one) at its own address.
*/
openOriginal() {
const a = this.aux;
let target: { title: string; lang: string } | null = a ? this.auxLink(a) : null;
let target: Ref | null = a ? this.auxTarget(a) : null;
if (!target && a?.kind === "wiki") {
const h = this.viewHost(a.host);
const k = this.hostArticle(a.host);
if (k) target = { title: k.title, lang: k.lang };
if (h?.src === "web") target = { kind: "url", url: h.url };
else if (k) target = { kind: "wiki", title: k.title, lang: k.lang };
}
if (!target) {
const f = this.focus;
const note = f.grain !== "node" ? this.noteAt(f.range) : undefined;
const r = this.targetOf(note ?? (a?.kind === "target" ? a.of : f.node));
if (r?.kind === "wiki") target = { title: r.title, lang: r.lang };
if (r && r.kind !== "node") target = asOpened(r);
}
if (!target) return this.say("No Wikipedia article here.");
if (target?.kind === "url") {
window.open(target.url, "_blank", "noopener,noreferrer");
return this.say(`Opened ${hostOf(target.url)} in a new tab.`);
}
if (target?.kind !== "wiki") return this.say("No Wikipedia article or web page here.");
window.open(wikiUrl(target.title, target.lang), "_blank", "noopener,noreferrer");
this.say(`Opened “${target.title}” on Wikipedia in a new tab.`);
}
@@ -3024,7 +3342,7 @@ class Store {
const f = this.focus;
const s = this.snap;
const n = s.nodes[f.node];
if (this.aux || !n) return null;
if ((this.aux && !this.linkHead) || !n) return null;
if (f.grain !== "node" && f.range) return { node: f.node, range: f.range, existing: this.noteAt(f.range), text: plain(n.body.slice(f.range[0], f.range[1])).trim() };
return { node: f.node, text: n.title || plain(label(s, f.node)).replace(/^“|”$/g, "") };
}
@@ -3093,10 +3411,23 @@ class Store {
this.say("Unlinked. u to undo.");
}
/** L on a node: open its own target (a section about an article, a note that also links). */
/**
* L on a node: open its own target (a section about an article, a note that also links). Where the
* node's own pane is open, the target opens to the right of it, whether the focus is on its head
* or on its row in the pane before: never beside it, in the same column.
*/
followOwn() {
const r = this.targetOf(this.focus.node);
const id = this.focus.node;
const r = this.targetOf(id);
if (!r) return this.say("This node has no target. w gives it one.");
if (this.panes) {
this.syncTrail();
const kid = this.paneHead(id) ? undefined : this.branchNodes[this.paneAt]?.kids.find((k) => k.ref.kind === "node" && k.ref.id === id);
if (kid) {
this.forest = focusIn(this.forest, kid.id);
this.paneAt += 1;
}
}
this.follow(r);
}
+63 -8
View File
@@ -21,6 +21,9 @@
/* Wikipedia's text sits on its own ground, so it is never mistaken for the reader's. */
--wiki-bg: #f2f5f8;
--wiki-rule: #c9d3dd;
/* A web page's text sits on an amber ground: neither the reader's nor Wikipedia's. */
--web-bg: #fbf1dc;
--web-rule: #e3d3ad;
--serif: "Source Serif 4 Variable", "Source Serif 4", "Apple Garamond", "Baskerville", "Libre Baskerville", "Times New Roman", serif;
--sans: "Source Sans 3 Variable", "Source Sans 3", "Lucida Sans Unicode", "Helvetica", sans-serif;
--mono: "IBM Plex Mono", "Liberation Mono", "Consolas", monospace;
@@ -48,6 +51,8 @@
--link: #8fb1d8;
--wiki-bg: #182029;
--wiki-rule: #34414f;
--web-bg: #30240f;
--web-rule: #57452a;
}
}
@@ -647,12 +652,15 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.lcard .lbody { margin-top: 0.3rem; }
.popup .lcard + .lcard, .popup .body + .lcard { margin-top: 0.5rem; padding-top: 0.45rem; border-top: 1px solid var(--hair); }
.popup:has(.l-wiki) { background: var(--wiki-bg); border-color: var(--wiki-rule); }
.popup:has(.l-url) { background: var(--web-bg); border-color: var(--web-rule); }
.wattr { margin: 0.5rem 0 0; font-family: var(--sans); font-size: 0.6rem; line-height: 1.4; color: var(--faint); text-align: left; text-indent: 0; }
.wattr a { color: inherit; text-decoration: underline 1px dotted; text-underline-offset: 0.15em; }
.lpreview.l-wiki { background: var(--wiki-bg); border-left-color: var(--wiki-rule); }
.lpreview.l-url { background: var(--web-bg); border-left-color: var(--web-rule); }
.lpreview .lnext { margin: 0.35rem 0 0; }
.target-row { margin: 0.9rem 0 0.4rem; padding: 0.45rem 0.7rem; border-left: 2px solid var(--wiki-rule); cursor: pointer; }
.target-row.l-wiki { background: var(--wiki-bg); }
.target-row.l-url { background: var(--web-bg); border-left-color: var(--web-rule); }
.target-row.focused { border-left-color: var(--fg); background: var(--sel); }
/* "Linked from" and "Mentioned in". */
@@ -672,12 +680,15 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.picker li .t { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 55%; }
/* ---- Wikipedia (src/ui/Wiki.tsx) ----
* Its own ground, its own face (the bundled sans), a W at its head, its licence at its foot.
* Its own ground, its own face (the bundled sans, sized to read like the reader's own text), a W
* at its head, its licence at its foot.
*/
.wiki { font-family: var(--sans); color: var(--soft); }
.pane.wiki-pane { background: var(--wiki-bg); }
.wiki-pane .spine span { color: var(--dim); }
.wiki-pane .spine .wmark { font-weight: 600; }
/* An article's pane, and the pane of a section shown as its article (a section that is only a link: Panes.tsx). */
.pane.wiki-pane, .pane.link-pane { background: var(--wiki-bg); }
:is(.wiki-pane, .link-pane) .spine span { color: var(--dim); }
:is(.wiki-pane, .link-pane) .spine .wmark { font-weight: 600; }
.link-rename { margin: 0 0 0.6rem; }
.wiki-head { margin: 0 0 0.8rem; padding-bottom: 0.35rem; border-bottom: 1px solid var(--wiki-rule); cursor: pointer; }
.wiki-head.focused { border-bottom-color: var(--fg); }
.wiki-head.focused h2 { text-decoration: underline 1px solid var(--faint); text-underline-offset: 0.2em; }
@@ -686,7 +697,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.wiki-brand .wmark { display: inline-block; border: 1px solid var(--wiki-rule); border-radius: 2px; padding: 0 0.22em; line-height: 1.25; background: var(--bg); }
.wiki-head h2 { margin: 0.15rem 0 0; font-family: var(--sans); font-size: 1.28rem; font-weight: 600; line-height: 1.2; color: var(--fg); letter-spacing: -0.005em; }
.wiki-head .wsub { font-weight: 400; color: var(--dim); }
.wiki-text { font-size: 0.82rem; line-height: 1.55; }
.wiki-text { font-size: 0.95rem; line-height: 1.55; }
.wiki-text p { margin: 0 0 0.65em; }
.wiki-text ul, .wiki-text ol { margin: 0 0 0.65em; padding-left: 1.3em; }
.wiki-text dl dd { margin-left: 1.2em; }
@@ -701,7 +712,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
/* Annotations in an article are the library's own notes: its dotted underline, its serif face, set off from Wikipedia's text. */
.wiki-text .gloss, .wiki-text .inset, .wdetached .inset { font-family: var(--serif); text-align: left; }
.wiki-text .gloss { color: var(--fg); font-size: 0.98em; }
.wiki-text .inset, .wdetached .inset { display: block; margin: 0.35rem 0 0.75rem 1.2em; padding: 0.35rem 0.75rem; font-size: 0.86rem; line-height: 1.45; background: var(--bg); color: var(--fg); border-left: 2px dotted var(--faint); }
.wiki-text .inset, .wdetached .inset { display: block; margin: 0.35rem 0 0.75rem 1.2em; padding: 0.35rem 0.75rem; font-size: 0.95rem; line-height: 1.45; background: var(--bg); color: var(--fg); border-left: 2px dotted var(--faint); }
.wiki-text .inset.focused, .wdetached .inset.focused { border-left: 2px solid var(--fg); }
.wiki-text .gloss.focused { background: var(--sel); }
.wdetached { margin: 0 0 0.6rem; }
@@ -710,12 +721,12 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.wdetached .meta a { color: inherit; text-decoration: underline 1px dotted; text-underline-offset: 0.15em; }
.wiki-text .wmath.sel { outline: 1px solid var(--sel-strong); }
.wiki-desc { margin: -0.4rem 0 0.6rem; font-size: 0.74rem; color: var(--dim); font-style: italic; }
.wiki-summary { margin: 0 0 0.5rem; font-size: 0.82rem; line-height: 1.55; }
.wiki-summary { margin: 0 0 0.5rem; font-size: 0.95rem; line-height: 1.55; }
.wiki-more, .wiki-wait, .wiki-back { margin: 0.3rem 0; font-size: 0.66rem; color: var(--faint); letter-spacing: 0.02em; }
.wiki-problem { margin: 0.4rem 0; padding: 0.4rem 0.6rem; border-left: 2px solid var(--attn); background: var(--bg); font-size: 0.78rem; color: var(--soft); }
.wrows { list-style: none; margin: 0.9rem 0 0; padding: 0.5rem 0 0; border-top: 1px solid var(--wiki-rule); }
.wrows.nested { margin: 0.3rem 0 0; border-top: 0; padding-top: 0; }
.wrow .row { font-size: 0.86rem; }
.wrow .row { font-size: 0.95rem; }
.wrow.focused > .row { background: var(--sel); }
.wrow.focused > .row .mark { color: var(--fg); }
.wrow.open > .row > .title { font-weight: 600; }
@@ -739,6 +750,49 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
/* The column's article page. */
.wiki-page { background: var(--wiki-bg); padding: 1.2rem 1.4rem 1.4rem; border: 1px solid var(--wiki-rule); }
/* ---- web pages (src/ui/Web.tsx) ----
* An article view in every way but its ground and its mark: the .web modifier makes Wikipedia's
* tokens the web's amber ones wherever a view (a pane, the column's page, an inset) draws them.
*/
.web { --wiki-bg: var(--web-bg); --wiki-rule: var(--web-rule); }
.web .wiki-brand { text-transform: none; letter-spacing: 0.02em; font-size: 0.66rem; }
.umark { font-family: var(--sans); font-weight: 400; }
.web-byline { margin: 0.15rem 0 0; font-size: 0.7rem; color: var(--dim); }
.web-open { margin: 0.5rem 0; font-size: 0.78rem; }
.web-open a { color: inherit; text-decoration: underline 1px solid var(--link); text-underline-offset: 0.16em; }
.web-open a::after { content: "↗"; font-size: 0.7em; vertical-align: 0.45em; color: var(--link); margin-left: 0.05em; }
/* A figure: never wider than its pane nor taller than most of the window, its box kept from the image's own width and height before it loads, its caption under it. */
.wiki-text figure { margin: 0.5em 0 0.9em; max-width: 100%; }
.wiki-text figure > .wraw { line-height: 0; }
.wiki-text figure img { display: block; max-width: 100%; height: auto; max-height: 70vh; object-fit: contain; object-position: left top; cursor: zoom-in; }
.wiki-text figcaption { margin-top: 0.3em; font-size: 0.72rem; line-height: 1.4; color: var(--dim); }
/* A video's facade (src/core/video.ts): its still, or a dark box, with a play mark, in a box of the video's own shape (the nearest common one; 16:9 unknown, and for a player), never wider than the pane nor taller than most of the window. A click puts the player in its place. */
.wiki-text figure.video { width: 100%; }
.wiki-text .video-box { position: relative; width: 100%; background: #14161a; line-height: 0; overflow: hidden; }
.wiki-text .video-box[role="button"] { cursor: pointer; }
.wiki-text .video-box.r21-9 { aspect-ratio: 21 / 9; max-width: calc(70vh * 21 / 9); }
.wiki-text .video-box.r16-9 { aspect-ratio: 16 / 9; max-width: calc(70vh * 16 / 9); }
.wiki-text .video-box.r3-2 { aspect-ratio: 3 / 2; max-width: calc(70vh * 3 / 2); }
.wiki-text .video-box.r4-3 { aspect-ratio: 4 / 3; max-width: calc(70vh * 4 / 3); }
.wiki-text .video-box.r1-1 { aspect-ratio: 1; max-width: 70vh; }
.wiki-text .video-box.r3-4 { aspect-ratio: 3 / 4; max-width: calc(70vh * 3 / 4); }
.wiki-text .video-box.r9-16 { aspect-ratio: 9 / 16; max-width: calc(70vh * 9 / 16); }
.wiki-text .video-box > .wraw { width: 100%; height: 100%; }
.wiki-text .video-box img, .wiki-text .video-box video, .wiki-text .video-box iframe { display: block; width: 100%; height: 100%; max-height: none; border: 0; object-fit: contain; object-position: center; background: #14161a; cursor: inherit; }
.wiki-text figure.video.embed .video-box img { object-fit: cover; }
.wiki-text .video-play { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 3rem; height: 3rem; border-radius: 50%; background: rgb(0 0 0 / 0.62); color: #fff; box-shadow: 0 0 0 2px rgb(255 255 255 / 0.85); font: 1.15rem/3rem var(--sans); text-align: center; text-indent: 0.15rem; pointer-events: none; }
.wiki-text .video-box[role="button"]:hover .video-play { background: rgb(0 0 0 / 0.85); }
.wiki-text .video-credit { display: inline-block; margin-top: 0.15em; font-family: var(--sans); font-size: 0.66rem; color: var(--faint); }
/* What a model made of a page (s): set apart from the page's text, and labelled. */
.web-model { margin: 0.2rem 0 0.8rem; padding: 0.45rem 0.7rem; border-left: 2px dashed var(--web-rule); background: color-mix(in srgb, var(--bg) 45%, transparent); }
.web-model-label { margin: 0 0 0.2rem; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.02em; color: var(--faint); }
.web-model-text { margin: 0; font-size: 0.95rem; line-height: 1.55; }
.web-arranged { margin: 0.6rem 0 0.2rem; }
@media (prefers-color-scheme: dark) {
/* Most images are drawn for a light page: a light plate behind them. */
.wiki-text figure img { background: #f3efe6; }
}
/* ---- end links and Wikipedia ---- */
/* Suggested links: a faint dashed underline, distinct from a link's solid one and a note's dotted one. */
@@ -1105,4 +1159,5 @@ html { scroll-padding-top: 48px; }
/* A long press on a link (touch): what it opens, above its menu. */
.menu-card { padding: 0.5rem 1rem 0.6rem; border-bottom: 1px solid var(--hair); font-family: var(--serif); font-size: 0.82rem; line-height: 1.45; max-height: 40vh; overflow-y: auto; }
.menu-card:has(.l-wiki) { background: var(--wiki-bg); }
.menu-card:has(.l-url) { background: var(--web-bg); }
/* ---- end pages ---- */
+229
View File
@@ -0,0 +1,229 @@
/**
* Web pages in the browser: what the server's /api/page routes return (server/page.ts), kept per
* address so a pane, the column's page and a node's inset showing one page share one request. In
* the manner of wiki.ts: nothing blocks; a view asks for a page and draws whatever state it is in
* (loading, ready, not shown and why), and is told to draw again when that changes.
*
* Only a page the reader opens is asked for. An inset folded under a section, and a link's card,
* ask the server's cache alone (summary &cached=1), which never reads the site. The page's HTML
* arrives sanitised and is cleaned again where it is drawn (wiki.ts articleText, with `web` set).
* Two actions the reader takes on a page replace what is kept here: Reload (read it again) and
* Arrange (a model's summary, and sections for a page divided only by length).
*/
import type { WebArticle, WebSection, WebSummary, WebUnusable } from "../../server/page";
import { normUrl } from "../llm/web";
export type { WebArticle, WebSection, WebSummary, WebUnusable };
/** Why a page is not shown: the server's reason and its words, with what it knew of the page. */
export type WebProblem = Pick<WebUnusable, "message" | "title" | "description" | "site"> & { reason: WebUnusable["reason"] | "uncached" };
type Loadable<T> = { state: "loading" } | { state: "ready"; value: T; cached: boolean } | ({ state: "failed"; at: number } & WebProblem);
/** A failure that may pass (the site down, the server unreachable) is asked again after this long. */
const RETRY_MS = 20_000;
/** Reasons that stand for this page load: the site answered, and answered no (the server keeps them a day). */
const LASTING = new Set<WebProblem["reason"]>(["robots", "refused", "type", "empty", "too-large", "off", "uncached"]);
/** What the server said about web pages when the page loaded (EX_PAGES). */
export interface PagesConfig {
mode: "live" | "mock" | "off";
/** Whether a model may arrange a page here (a model, and EX_PAGES_ARRANGE not off). */
arrange?: boolean;
}
let config: PagesConfig = { mode: "live" };
let onChange: () => void = () => {};
export function configurePages(c: Partial<PagesConfig> | undefined, changed: () => void) {
if (c) config = { ...config, ...c };
onChange = changed;
}
const articles = new Map<string, Loadable<WebArticle>>();
const summaries = new Map<string, Loadable<WebSummary>>();
/** The words for each reason, where the server gave none. */
const PLAIN: Record<WebProblem["reason"], string> = {
robots: "The site asks programs like this one not to read this page.",
refused: "The site refused to let this program read the page.",
type: "This address is not a web page that can be shown here.",
empty: "The page has too little text to show here.",
"too-large": "The page is too large to read here.",
offline: "The site could not be reached. It is tried again in a little while.",
error: "The page could not be read.",
off: "Reading web pages is turned off on this server (EX_PAGES=off).",
uncached: "This page has not been read yet.",
};
async function get<T>(path: string, field: string): Promise<{ ok: true; value: T; cached: boolean } | ({ ok: false } & WebProblem)> {
if (config.mode === "off") return { ok: false, reason: "off", message: PLAIN.off };
try {
const res = await fetch(path);
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (res.ok && body.ok) return { ok: true, value: body[field] as T, cached: !!body.cached };
const reason = (typeof body.reason === "string" && body.reason in PLAIN ? body.reason : "error") as WebProblem["reason"];
const str = (k: string) => (typeof body[k] === "string" && body[k] ? { [k]: body[k] as string } : {});
return { ok: false, reason, message: typeof body.message === "string" && body.message ? body.message : res.status === 400 ? "This is not an address that can be read." : PLAIN[reason], ...str("title"), ...str("description"), ...str("site") };
} catch {
return { ok: false, reason: "offline", message: "The local server could not be reached." };
}
}
function load<T>(cache: Map<string, Loadable<T>>, key: string, path: string, field: string): Loadable<T> {
const have = cache.get(key);
if (have && (have.state !== "failed" || LASTING.has(have.reason) || Date.now() - have.at < RETRY_MS)) return have;
cache.set(key, { state: "loading" });
void get<T>(path, field).then((r) => {
cache.set(key, r.ok ? { state: "ready", value: r.value, cached: r.cached } : { state: "failed", at: Date.now(), ...stripOk(r) });
onChange();
});
return cache.get(key)!;
}
const stripOk = <P extends { ok: false }>({ ok: _, ...rest }: P) => rest;
/** A page as a lead and sections: read once by the server, kept in its cache until Reload. */
export function article(url: string): Loadable<WebArticle> {
return load(articles, normUrl(url), `/api/page/article?url=${encodeURIComponent(url)}`, "article");
}
/** A page as far as it has been asked for, without asking for it. */
export const knownArticle = (url: string): Loadable<WebArticle> | undefined => articles.get(normUrl(url));
/** A page's title, site, author and first sentence, from the server's cache only: never a request to the site. */
export function cachedSummary(url: string): Loadable<WebSummary> {
const a = articles.get(normUrl(url));
if (a?.state === "ready") return { state: "ready", value: summaryOf(a.value), cached: true };
return load(summaries, normUrl(url), `/api/page/summary?url=${encodeURIComponent(url)}&cached=1`, "summary");
}
function summaryOf(a: WebArticle): WebSummary {
const at = a.attribution;
return { url: a.url, requested: a.requested, title: a.title, site: at.site, author: at.author, published: at.published, description: a.description, sentence: firstSentence(a.lead || a.sections[0]?.html || "") };
}
const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", nbsp: " " };
/** The first sentence of some HTML's text, at most 300 characters, as the server's summary gives it (shown as text, never as HTML). */
export function firstSentence(html: string): string {
const text = html
.replace(/<figure[\s\S]*?<\/figure>/gi, " ")
.replace(/<[^>]*>/g, " ")
.replace(/&(amp|lt|gt|quot|#39|nbsp);/g, (_, e: string) => ENTITIES[e])
.replace(/\s+/g, " ")
.trim();
const m = /^.+?[.!?](?=\s+["“'(\p{Lu}\d]|$)/u.exec(text);
const s = m ? m[0] : text;
return s.length > 300 ? `${s.slice(0, 299).replace(/\s+\S*$/, "")}…` : s;
}
// ---- what the reader does to a page ----
/** What an action on a page came to: the page as it now is, or why not, in words. */
export type Acted<X = object> = ({ ok: true; article: WebArticle } & X) | { ok: false; reason: string; message: string };
async function post<X>(route: "reload" | "arrange", url: string): Promise<Acted<X>> {
if (config.mode === "off") return { ok: false, reason: "off", message: PLAIN.off };
try {
const res = await fetch(`/api/page/${route}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ url }) });
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (res.ok && body.ok && body.article) {
articles.set(normUrl(url), { state: "ready", value: body.article as WebArticle, cached: false });
summaries.delete(normUrl(url));
return body as unknown as Acted<X>;
}
const reason = typeof body.reason === "string" ? body.reason : "error";
const message = typeof body.message === "string" && body.message ? body.message : `The server answered ${res.status}.`;
// A page that still cannot be shown: shown as such, with the new reason.
if (route === "reload" && reason in PLAIN) articles.set(normUrl(url), { state: "failed", at: Date.now(), reason: reason as WebProblem["reason"], message, ...strs(body, "title", "description", "site") });
return { ok: false, reason, message };
} catch {
return { ok: false, reason: "offline", message: "The local server could not be reached." };
}
}
const strs = (body: Record<string, unknown>, ...ks: string[]) => Object.fromEntries(ks.filter((k) => typeof body[k] === "string" && body[k]).map((k) => [k, body[k] as string]));
/** Read a page again (R). `stale`: it no longer answers, and the last copy is kept (with why). */
export const reloadPage = (url: string) => post<{ stale?: string }>("reload", url);
/** Have a model summarise a page, and arrange one divided only by length into sections (s). Never reads the page again. */
export const arrangePage = (url: string) => post<{ called: boolean; arranged: "sections" | "summary"; note?: string }>("arrange", url);
/** How long the link picker waits for a page's title before linking without one. */
const TITLE_WAIT_MS = 2500;
/**
* A page's own title, for the link picker's "Address": the reader has just chosen this page, so
* the server reads it now (and keeps it, so opening it next is immediate). Null when it gives
* none (only its host), cannot be read, or takes longer than `wait`.
*/
export async function pageTitle(url: string, wait = TITLE_WAIT_MS): Promise<string | null> {
if (config.mode === "off") return null;
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), wait);
try {
const res = await fetch(`/api/page/summary?url=${encodeURIComponent(url)}`, { signal: ac.signal });
const body = (await res.json().catch(() => ({}))) as { summary?: { title?: unknown }; title?: unknown };
const t = body.summary?.title ?? body.title;
if (typeof t !== "string") return null;
const title = t.replace(/\s+/g, " ").trim().slice(0, 300);
return title && title !== siteOf(url) ? title : null;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/** Whether the server lets a model arrange pages. */
export const canArrange = () => config.arrange !== false;
/** What a pane showing a web page (or a section of one) goes by, as a key: `u:<address>`, `#<section>` after it. */
export const webKey = (url: string, sec?: string) => `u:${normUrl(url)}${sec ? `#${sec}` : ""}`;
/** The sections directly under one (null: the top level). */
export function sectionsUnder(a: WebArticle, parent: string | null): WebSection[] {
return a.sections.filter((x) => x.parent === parent);
}
/** What a page goes by: its title once it has arrived, else its site. */
export function pageName(url: string): string {
const a = article(url);
return a.state === "ready" ? a.value.title : siteOf(url);
}
/** A page's host, as the head shows it: without "www.". */
export function siteOf(url: string): string {
try {
return new URL(url).host.replace(/^www\./, "");
} catch {
return url;
}
}
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
/** An ISO date (or date and time) for reading: "9 Aug 2000", the day as the page wrote it (no time zone moves it); else as it came. */
export function readDate(iso: string): string {
const m = /^(\d{4})-(\d{2})(?:-(\d{2}))?/.exec(iso.trim());
if (!m || +m[2] < 1 || +m[2] > 12) return iso;
return `${m[3] ? `${+m[3]} ` : ""}${MONTHS[+m[2] - 1]} ${m[1]}`;
}
/** The head's byline: author, site and date, only those the page gives. */
export function byline(a: { author?: string; site?: string; published?: string }): string {
return [a.author, a.site, a.published && readDate(a.published)].filter(Boolean).join(" · ");
}
/** The footer's sentence: where the text is from, who wrote it, when it was read, and what was changed. */
export function attributionText(at: WebArticle["attribution"]): string {
const parts = [`From “${at.title}”`];
if (at.author) parts[0] += ` by ${at.author}`;
parts[0] += `, ${at.site}`;
if (at.published) parts[0] += `, published ${readDate(at.published)}`;
const read = readDate(at.retrieved);
const adapted = at.adapted.length ? ` Adapted: ${at.adapted.join("; ")}.` : "";
return `${parts[0]}. ${at.stale ? `The page no longer answers; last read ${read}.` : `Read ${read}.`}${adapted}`;
}
+80 -19
View File
@@ -7,10 +7,13 @@
* Article HTML arrives sanitised by the server (server/wiki.ts). It is cleaned again here before it
* is put into the page, because it came from outside: only an allowlist of elements and
* attributes survives, and every link either names an article (data-wiki) or opens a new tab.
* Pictures survive only from the app's own image route (Wikipedia's or a web page's), and a video
* only as the fixed facade of src/core/video.ts, with checked values.
*/
import type { Attribution, FullArticle as Article, Sense, Summary, TitleSuggestion as Suggestion } from "../../server/wiki";
import type { SectionText } from "../core/article";
import { wikiKey, wikiTitle } from "../core/ref";
import { validId } from "../core/video";
import { buildText, type ArticleText } from "./articleText";
export type { Article, Attribution, Suggestion };
@@ -155,49 +158,107 @@ const ATTRS = new Set(["colspan", "rowspan", "start", "data-wiki", "data-wiki-fr
/** Elements whose content goes with them. */
const DROP = new Set(["script", "style", "iframe", "object", "embed", "svg", "link", "meta", "base", "form", "template", "noscript", "video", "audio", "img", "picture", "figure", "source", "canvas", "title", "head", "input", "button", "select", "textarea"]);
/** Figures, each an image from the app's own media route and its caption (server/pageHtml.ts, server/wikiHtml.ts), or a video's facade. */
const FIGURE_KEEP = new Set(["figure", "figcaption", "img"]);
/** The only images shown in a web page's text: those the server proxies for a page it read (it is not an open proxy, and the page's CSP allows nothing else). */
export const MEDIA_ROUTE = "/api/page/media?u=";
/** The same for Wikipedia's text: pictures on upload.wikimedia.org that an article read here shows. */
export const WIKI_MEDIA_ROUTE = "/api/wiki/media?u=";
const FILE_PAGE = /^https:\/\/[a-z][a-z0-9-]{1,15}\.wikipedia\.org\/wiki\/[^\s"<>]+$/;
const LANG = /^[a-z][a-z0-9-]{1,15}$/;
const http = (u: string | undefined) => !!u && /^https?:\/\/[^\s]+$/i.test(u);
/**
* What of an allowlisted element survives the cleaning: its attributes, in the order they are set,
* or null when the element goes, content and all. A figure's image is kept with a fixed set of
* attributes when it comes from the media route (`data-full`: what a click opens, the image itself
* on a web page, its File page on Wikipedia). A video's facade keeps its class and checked data
* attributes, nothing else. `web`: a web page's text, where a link may name another page
* (data-url, opened as a pane) or an article in its own language (data-wiki-lang), images come
* from /api/page/media, and a video may be any https file or a YouTube or Vimeo player; in
* Wikipedia's, images come from /api/wiki/media and a video's file from upload.wikimedia.org.
*/
export function cleanAttrs(tag: string, attrs: [string, string][], web = false): [string, string][] | null {
const get = (k: string) => attrs.find(([n]) => n === k)?.[1];
const digits = (k: string) => (/^\d{1,5}$/.test(get(k) ?? "") ? get(k)! : null);
if (tag === "img") {
const src = get("src");
if (!src?.startsWith(web ? MEDIA_ROUTE : WIKI_MEDIA_ROUTE)) return null;
const out: [string, string][] = [["src", src], ["alt", get("alt") ?? ""]];
for (const k of ["width", "height"]) if (digits(k)) out.push([k, digits(k)!]);
out.push(["loading", "lazy"], ["decoding", "async"]);
if (http(get("data-full"))) out.push(["data-full", get("data-full")!]);
return out;
}
if (tag === "figure" && get("class") === "video") {
const out: [string, string][] = [];
const embed = get("data-embed") ?? "";
const id = get("data-id") ?? "";
const video = get("data-video") ?? "";
if (web && validId(embed, id)) out.push(["data-embed", embed], ["data-id", id]);
else if (web ? /^https:\/\/[^\s"<>]+$/.test(video) : /^https:\/\/upload\.wikimedia\.org\/[^\s"<>]+$/.test(video)) out.push(["data-video", video]);
// Not a video this app can play: an empty figure, which shows its caption.
if (!out.length) return [];
if (digits("data-width") && digits("data-height")) out.push(["data-width", digits("data-width")!], ["data-height", digits("data-height")!]);
if (FILE_PAGE.test(get("data-file") ?? "")) out.push(["data-file", get("data-file")!]);
return [["class", "video"], ...out];
}
if (FIGURE_KEEP.has(tag)) return [];
const out = attrs.filter(([k]) => ATTRS.has(k));
if (tag !== "a") return out;
const href = get("href");
const wiki = get("data-wiki");
const lang = web && LANG.test(get("data-wiki-lang") ?? "") ? get("data-wiki-lang")! : null;
const page = web && wiki === undefined && http(get("data-url")) ? get("data-url")! : null;
if (lang) out.push(["data-wiki-lang", lang]);
if (page) out.push(["data-url", page]);
if (wiki !== undefined) out.push(["href", `https://${lang ?? config.lang}.wikipedia.org/wiki/${encodeURIComponent(wiki.replace(/ /g, "_"))}`]);
else if (page ?? (href && /^https?:\/\//i.test(href))) out.push(["href", page ?? href!], ["target", "_blank"], ["rel", "noopener noreferrer nofollow"]);
return out;
}
/**
* Clean article HTML once more, in an inert document (DOMParser runs no script and loads nothing):
* allowlisted elements and attributes only, wiki links kept as data-wiki, other links only if
* http(s) and then in a new tab without an opener.
* allowlisted elements and attributes only (cleanAttrs), wiki links kept as data-wiki, other links
* only if http(s) and then in a new tab without an opener.
*/
function cleanHtml(html: string): string {
function cleanHtml(html: string, web: boolean): string {
const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
const walk = (el: Element) => {
for (const child of [...el.children]) {
const tag = child.localName;
if (DROP.has(tag)) {
const extra = FIGURE_KEEP.has(tag);
if (DROP.has(tag) && !extra) {
child.remove();
continue;
}
walk(child);
if (!KEEP.has(tag)) {
if (!KEEP.has(tag) && !extra) {
child.replaceWith(...child.childNodes);
continue;
}
const href = tag === "a" ? child.getAttribute("href") : null;
for (const a of [...child.attributes]) if (!ATTRS.has(a.name)) child.removeAttribute(a.name);
if (tag === "a") {
if (child.hasAttribute("data-wiki")) child.setAttribute("href", `https://${config.lang}.wikipedia.org/wiki/${encodeURIComponent(child.getAttribute("data-wiki")!.replace(/ /g, "_"))}`);
else if (href && /^https?:\/\//i.test(href)) {
child.setAttribute("href", href);
child.setAttribute("target", "_blank");
child.setAttribute("rel", "noopener noreferrer nofollow");
}
const attrs = cleanAttrs(tag, [...child.attributes].map((a): [string, string] => [a.name, a.value]), web);
if (!attrs) {
child.remove();
continue;
}
for (const a of [...child.attributes]) child.removeAttribute(a.name);
for (const [k, v] of attrs) child.setAttribute(k, v);
}
};
walk(doc.body);
return doc.body.innerHTML;
}
/** A piece of article HTML as text to select in (articleText.ts). Remembered per string. */
/** A piece of article HTML as text to select in (articleText.ts); `web` for a web page's (cleanAttrs). Remembered per string. */
const texts = new Map<string, ArticleText>();
export function articleText(html: string): ArticleText {
let out = texts.get(html);
export function articleText(html: string, web = false): ArticleText {
const key = web ? `\u0000${html}` : html;
let out = texts.get(key);
if (out) return out;
out = buildText(new DOMParser().parseFromString(`<body>${cleanHtml(html)}</body>`, "text/html").body);
out = buildText(new DOMParser().parseFromString(`<body>${cleanHtml(html, web)}</body>`, "text/html").body);
if (texts.size > 400) texts.delete(texts.keys().next().value as string);
texts.set(html, out);
texts.set(key, out);
return out;
}