Panes: one controller for the listeners, shared helpers for repeated lookups

- The panes' effect registered 25 listeners and removed each by hand;
  they share an AbortController now.
- One relayout() for the four places that laid out, measured and drew;
  one uncurve() for "curves off" and the start of the pages' marks (so
  schedule just calls curves(), which goes to pageMarks as pages);
  one handleAt() for the mouse and touch drags' handle lookup (the
  close/pin/⋯ checks before it could never match inside a grip or tab);
  ruleOf() for the rule a pane's head draws, written three times;
  setAttr from stack.ts instead of a copy; paneOfPage for the desktop
  column's pane to show, the same rule; the pin, close and W icons from
  Pages.tsx instead of copies in Chrome.
- The curves' `box` offset was a constant zero subtracted everywhere.
- Gone: glideTo's ms parameter (never passed), the "lifting" class
  (nothing reads it), Axis fields nothing reads, a dead branch in the
  map's rails, a linear search per pane in forks reorder, a stale and a
  superseded comment. Exports used only in their own file are not
  exported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 16:25:27 -05:00
1 parent 5d6b7a8215
commit 3aa8778427
5 files changed
+128 -170

No files matched your search

+7 -6
View File
@@ -11,17 +11,17 @@ import { mapStep, rails, type Rail } from "./pages";
import { article } from "./wiki"; import { article } from "./wiki";
/** 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 (a section of one by its heading). */
export function paneTitle(p: PaneRef): string { function paneTitle(p: PaneRef): string {
if (p.kind === "node") return store.snap.nodes[p.id] ? label(store.snap, p.id) : "…"; if (p.kind === "node") return store.snap.nodes[p.id] ? label(store.snap, p.id) : "…";
const a = article(p.title, p.lang); 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; 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; return sec ? sec.heading : a.state === "ready" ? a.value.title : p.title;
} }
const W = () => <b class="wmark">W</b>; export const W = () => <b class="wmark">W</b>;
/** Up to this many panes in a column, a trail step shows a dot for each; beyond, their number. */ /** Up to this many panes in a column, a trail step shows a dot for each; beyond, their number. */
export const STACK_DOTS = 4; const STACK_DOTS = 4;
/** /**
* How many panes the page of a step holds, when more than one: a dot for each, top to bottom as they * How many panes the page of a step holds, when more than one: a dot for each, top to bottom as they
@@ -107,12 +107,13 @@ export function Trail() {
); );
} }
const Pin = () => ( /** A pane's pin and close icons (here and in Panes.tsx). */
export const Pin = () => (
<svg viewBox="0 0 12 12" aria-hidden="true"> <svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M4 1.5h4M4.6 1.5v3.6L2.8 7.2h6.4L7.4 5.1V1.5M6 7.2V11" /> <path d="M4 1.5h4M4.6 1.5v3.6L2.8 7.2h6.4L7.4 5.1V1.5M6 7.2V11" />
</svg> </svg>
); );
const Close = () => ( export const Close = () => (
<svg viewBox="0 0 12 12" aria-hidden="true"> <svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M3 3l6 6M9 3l-6 6" /> <path d="M3 3l6 6M9 3l-6 6" />
</svg> </svg>
@@ -134,7 +135,7 @@ function RailLine({ r, step, hue, on }: { r: Rail; step: number; hue?: number; o
? { left: `${x}px`, width: `${markAt(r.level + 1, step) + MARK - x}px`, top: 0, height: "50%" } ? { left: `${x}px`, width: `${markAt(r.level + 1, step) + MARK - x}px`, top: 0, height: "50%" }
: r.kind === "pass" : r.kind === "pass"
? { left: `${x}px`, top: 0, bottom: 0 } ? { left: `${x}px`, top: 0, bottom: 0 }
: { left: `${r.kind === "down" ? lineAt(r.level, step) : x}px`, top: "50%", bottom: 0 }; : { left: `${x}px`, top: "50%", bottom: 0 };
return <span class={`rail r-${r.kind}${on ? " strong" : ""}`} data-hue={hue} data-rail={r.kind} data-to={r.tid} style={style} aria-hidden="true" />; return <span class={`rail r-${r.kind}${on ? " strong" : ""}`} data-hue={hue} data-rail={r.kind} data-to={r.tid} style={style} aria-hidden="true" />;
} }
+102 -140
View File
@@ -19,9 +19,10 @@ import { Component, type ComponentChildren } from "preact";
import { useEffect, useLayoutEffect, useRef } from "preact/hooks"; import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import { ancestors, label, sections, staleness, type NodeId } from "../core/model"; import { ancestors, label, sections, staleness, type NodeId } from "../core/model";
import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes"; import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes";
import { ACROSS, DOWN, crowds, fill, fit, folded, mark, offsets, release, resize, reveal, starts, stick, unmark, whole } from "./stack"; import { ACROSS, DOWN, crowds, fill, fit, folded, mark, offsets, release, resize, reveal, setAttr, starts, stick, unmark, whole } from "./stack";
import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links"; import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links";
import { pageAt, paneOfPage } from "./pages"; import { pageAt, paneOfPage } from "./pages";
import { Close, Pin, W } from "./Pages";
import { Abstract, Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter, isPrompt } from "./Node"; import { Abstract, Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter, isPrompt } from "./Node";
import { kidClass, refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store"; import { kidClass, refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store";
import { WikiView } from "./Wiki"; import { WikiView } from "./Wiki";
@@ -87,8 +88,7 @@ function watchHead(tid: number) {
const pane = document.querySelector<HTMLElement>(`.strip .pane[data-tid="${tid}"]`); const pane = document.querySelector<HTMLElement>(`.strip .pane[data-tid="${tid}"]`);
if (!pane || typeof IntersectionObserver === "undefined") return; if (!pane || typeof IntersectionObserver === "undefined") return;
const scroll = pane.querySelector<HTMLElement>(":scope > .pane-scroll"); const scroll = pane.querySelector<HTMLElement>(":scope > .pane-scroll");
const head = pane.querySelector<HTMLElement>(HEADS); const target = ruleOf(pane);
const target = head?.matches(".top") ? head.querySelector("h1") : head;
const w = watched.get(tid); const w = watched.get(tid);
if (w && w.target === target && w.tab === TAB) return; if (w && w.target === target && w.tab === TAB) return;
w?.io.disconnect(); w?.io.disconnect();
@@ -125,14 +125,15 @@ const paneClass = (props: PaneProps) => `${props.active ? " active" : ""}${props
function Chrome({ props, title, mark }: { props: PaneProps; title: string; mark?: ComponentChildren }) { function Chrome({ props, title, mark }: { props: PaneProps; title: string; mark?: ComponentChildren }) {
const tid = props.t.id; const tid = props.t.id;
const pinned = !!props.t.pinned; const pinned = !!props.t.pinned;
const close = () => (
<span role="button" class="pane-btn close" data-close={tid} title="Close this pane and what was opened from it (q)" aria-label="Close">
<Close />
</span>
);
return ( return (
<> <>
<div class="spine" data-spine={props.index} title={title}> <div class="spine" data-spine={props.index} title={title}>
<span role="button" class="pane-btn close" data-close={tid} title="Close this pane and what was opened from it (q)" aria-label="Close"> {close()}
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M3 3l6 6M9 3l-6 6" />
</svg>
</span>
<span class="spine-title"> <span class="spine-title">
{mark} {mark}
{mark && " "} {mark && " "}
@@ -149,15 +150,9 @@ function Chrome({ props, title, mark }: { props: PaneProps; title: string; mark?
⋯ ⋯
</span> </span>
<span role="button" class={`pane-btn pin${pinned ? " on" : ""}`} data-pin={tid} title={pinned ? "Unpin this pane (P)" : "Pin this pane: it stays when what opened it closes, and never folds away (P)"} aria-label={pinned ? "Unpin" : "Pin"}> <span role="button" class={`pane-btn pin${pinned ? " on" : ""}`} data-pin={tid} title={pinned ? "Unpin this pane (P)" : "Pin this pane: it stays when what opened it closes, and never folds away (P)"} aria-label={pinned ? "Unpin" : "Pin"}>
<svg viewBox="0 0 12 12" aria-hidden="true"> <Pin />
<path d="M4 1.5h4M4.6 1.5v3.6L2.8 7.2h6.4L7.4 5.1V1.5M6 7.2V11" />
</svg>
</span>
<span role="button" class="pane-btn close" data-close={tid} title="Close this pane and what was opened from it (q)" aria-label="Close">
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="M3 3l6 6M9 3l-6 6" />
</svg>
</span> </span>
{close()}
</div> </div>
</> </>
); );
@@ -229,7 +224,7 @@ function WikiPane(props: PaneProps) {
const title = sec ? `${sec.heading} · ${p.title}` : a.state === "ready" ? a.value.title : p.title; const title = sec ? `${sec.heading} · ${p.title}` : a.state === "ready" ? a.value.title : p.title;
return ( return (
<article class={`pane wiki-pane${p.from ? " jumped" : ""}${paneClass(props)}`} {...paneAttrs(props, `w:${p.title}${p.sec ? `#${p.sec}` : ""}`)}> <article class={`pane wiki-pane${p.from ? " jumped" : ""}${paneClass(props)}`} {...paneAttrs(props, `w:${p.title}${p.sec ? `#${p.sec}` : ""}`)}>
<Chrome props={props} title={title} mark={<b class="wmark">W</b>} /> <Chrome props={props} title={title} mark={<W />} />
<div class="pane-scroll"> <div class="pane-scroll">
<div class="pane-body"> <div class="pane-body">
<Orphaned on={props.orphan} /> <Orphaned on={props.orphan} />
@@ -267,7 +262,7 @@ const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(pre
* a link, the trail, the map, Back): short, easing out. The browser's smooth scroll takes twice as * a link, the trail, the map, Back): short, easing out. The browser's smooth scroll takes twice as
* long or more, at its own pace; a finger's swipe keeps the browser's own snapping. * long or more, at its own pace; a finger's swipe keeps the browser's own snapping.
*/ */
export const GLIDE_MS = 140; const GLIDE_MS = 140;
/** The strip's glide under way: its frame. */ /** The strip's glide under way: its frame. */
const glides = new WeakMap<HTMLElement, number>(); const glides = new WeakMap<HTMLElement, number>();
/** Whether the strip is gliding (its scroll events are its own, not a finger's). */ /** Whether the strip is gliding (its scroll events are its own, not a finger's). */
@@ -281,15 +276,15 @@ function stopGlide(el: HTMLElement) {
el.removeAttribute("data-gliding"); el.removeAttribute("data-gliding");
} }
/** Glide the strip to a scroll offset, easing out (a cubic), without snapping on the way (data-gliding), landing exactly there. */ /** Glide the strip to a scroll offset, easing out (a cubic), without snapping on the way (data-gliding), landing exactly there. */
function glideTo(el: HTMLElement, to: number, done: () => void, ms = GLIDE_MS) { function glideTo(el: HTMLElement, to: number, done: () => void) {
stopGlide(el); stopGlide(el);
const from = el.scrollLeft; const from = el.scrollLeft;
if (ms <= 0 || Math.abs(to - from) < 1) return void ((el.scrollLeft = to), done()); if (Math.abs(to - from) < 1) return void ((el.scrollLeft = to), done());
el.setAttribute("data-gliding", ""); el.setAttribute("data-gliding", "");
let t0 = -1; let t0 = -1;
const step = (now: number) => { const step = (now: number) => {
if (t0 < 0) t0 = now - 1000 / 60; if (t0 < 0) t0 = now - 1000 / 60;
const p = Math.min(1, (now - t0) / ms); const p = Math.min(1, (now - t0) / GLIDE_MS);
el.scrollLeft = from + (to - from) * (1 - (1 - p) ** 3); el.scrollLeft = from + (to - from) * (1 - (1 - p) ** 3);
if (p < 1) return void glides.set(el, requestAnimationFrame(step)); if (p < 1) return void glides.set(el, requestAnimationFrame(step));
glides.delete(el); glides.delete(el);
@@ -318,40 +313,35 @@ function nearestY(el: Element | null | false) {
*/ */
function ruleShows(p: HTMLElement, col: DOMRect, next: number): boolean { function ruleShows(p: HTMLElement, col: DOMRect, next: number): boolean {
if (p.hasAttribute("data-buried")) return false; if (p.hasAttribute("data-buried")) return false;
const head = p.querySelector<HTMLElement>(HEADS); const rule = ruleOf(p)?.getBoundingClientRect();
const rule = (head?.matches(".top") ? head.querySelector<HTMLElement>("h1") : head)?.getBoundingClientRect();
if (!rule) return false; if (!rule) return false;
const r = p.getBoundingClientRect(); const r = p.getBoundingClientRect();
const sc = p.querySelector<HTMLElement>(":scope > .pane-scroll")!.getBoundingClientRect(); const sc = p.querySelector<HTMLElement>(":scope > .pane-scroll")!.getBoundingClientRect();
return rule.bottom > Math.max(r.top, col.top, sc.top) + TAB && rule.bottom <= Math.min(next, col.bottom, sc.bottom); return rule.bottom > Math.max(r.top, col.top, sc.top) + TAB && rule.bottom <= Math.min(next, col.bottom, sc.bottom);
} }
const setAttr = (el: Element | undefined, name: string, on: boolean) => {
if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name);
};
/** The least height a pane keeps in a column while all its panes fit; below it, the column stacks them. */ /** The least height a pane keeps in a column while all its panes fit; below it, the column stacks them. */
export const PANE_MIN = 260; const PANE_MIN = 260;
/** A covered pane's tab, the strip a pane leaves down a crowded column (as a spine does across): as pages, a finger's height (PAGE_TAB). Set as the panes are drawn. */ /** A covered pane's tab, the strip a pane leaves down a crowded column (as a spine does across): as pages, a finger's height (PAGE_TAB). Set as the panes are drawn. */
export let TAB = 30; let TAB = 30;
const DESK_TAB = 30; const DESK_TAB = 30;
export const PAGE_TAB = 44; const PAGE_TAB = 44;
/** As pages, how long a finger is held still on a pane's tab or the band above its title to pick the pane up. */ /** As pages, how long a finger is held still on a pane's tab or the band above its title to pick the pane up. */
export const HOLD_MS = 380; const HOLD_MS = 380;
/** The touch drag's move handler (Panes' effect sets it); the handles call it from their own, blocking, touchmove listeners. */ /** The touch drag's move handler (Panes' effect sets it); the handles call it from their own, blocking, touchmove listeners. */
let handleMove: ((e: TouchEvent) => void) | null = null; let handleMove: ((e: TouchEvent) => void) | null = null;
const onHandleMove = (e: TouchEvent) => handleMove?.(e); const onHandleMove = (e: TouchEvent) => handleMove?.(e);
/** How long the mouse rests on a covered pane before it peeks out. */ /** How long the mouse rests on a covered pane before it peeks out. */
export const PEEK_MS = 200; const PEEK_MS = 200;
/** As pages, how far a finger moves on a pane's handle before its direction is known: up or down resizes the pane, sideways is the browser's (the page turns). */ /** As pages, how far a finger moves on a pane's handle before its direction is known: up or down resizes the pane, sideways is the browser's (the page turns). */
export const LOCK_PX = 8; const LOCK_PX = 8;
/** As pages, a pane sized by hand left less than this much taller than its tab folds to it when the finger lifts. */ /** As pages, a pane sized by hand left less than this much taller than its tab folds to it when the finger lifts. */
export const FOLD_SNAP = 40; const FOLD_SNAP = 40;
/** As pages, how long a released edge takes to come to rest at a fold, easing out. */ /** As pages, how long a released edge takes to come to rest at a fold, easing out. */
export const SNAP_MS = 120; const SNAP_MS = 120;
/** As pages, two taps on a pane's handle this close together put its page back to the automatic sizes. */ /** As pages, two taps on a pane's handle this close together put its page back to the automatic sizes. */
export const DOUBLE_TAP_MS = 320; const DOUBLE_TAP_MS = 320;
/** /**
* As pages, a page sized by hand (Panes' touch handlers, stack.ts `resize`): each pane's height * As pages, a page sized by hand (Panes' touch handlers, stack.ts `resize`): each pane's height
@@ -511,7 +501,7 @@ export function Panes() {
const col = Number(c.dataset.col); const col = Number(c.dataset.col);
const tids = ps.map((p) => Number(p.dataset.tid)); const tids = ps.map((p) => Number(p.dataset.tid));
// The pane to show whole: on the focused branch, or the one last on it here. // The pane to show whole: on the focused branch, or the one last on it here.
const here = tids.find((t) => onBranch.has(t)) ?? (tids.includes(lastIn.current.get(col)!) ? lastIn.current.get(col)! : tids[0]); const here = paneOfPage(tids, onBranch, lastIn.current.get(col))!;
const sig = tids.map((t, i) => `${t}${ps[i].classList.contains("pinned") ? "^" : ""}`).join(); const sig = tids.map((t, i) => `${t}${ps[i].classList.contains("pinned") ? "^" : ""}`).join();
// As pages, a page too short for a tab for each of its panes is never sized by hand (its handles scroll it). // As pages, a page too short for a tab for each of its panes is never sized by hand (its handles scroll it).
c.classList.toggle("tight", pages && ps.length * TAB > h); c.classList.toggle("tight", pages && ps.length * TAB > h);
@@ -578,11 +568,7 @@ export function Panes() {
} }
} }
if (deferred) if (deferred)
later.current = setTimeout(() => { later.current = setTimeout(relayout, 150);
latest.current(true);
measure();
schedule();
}, 150);
// The focused branch's panes, marked without redrawing them. // The focused branch's panes, marked without redrawing them.
for (const [id, p] of paneEls(el)) p.classList.toggle("on-branch", onBranch.has(id)); for (const [id, p] of paneEls(el)) p.classList.toggle("on-branch", onBranch.has(id));
for (const [col, ps] of cols) for (const x of ps) if (onBranch.has(x.node.id)) lastIn.current.set(col, x.node.id); for (const [col, ps] of cols) for (const x of ps) if (onBranch.has(x.node.id)) lastIn.current.set(col, x.node.id);
@@ -682,10 +668,15 @@ export function Panes() {
if (!frame.current) if (!frame.current)
frame.current = requestAnimationFrame(() => { frame.current = requestAnimationFrame(() => {
frame.current = 0; frame.current = 0;
if (store.pages) pageMarks(strip.current, svg.current); curves(strip.current, svg.current);
else curves(strip.current, svg.current);
}); });
}; };
/** Lay out every column again, measure, and draw. */
const relayout = () => {
latest.current(true);
measure();
schedule();
};
/** Where each newly opened pane came from in its parent, down the parent's text (its column's order goes by it). */ /** Where each newly opened pane came from in its parent, down the parent's text (its column's order goes by it). */
const sources = () => { const sources = () => {
@@ -724,11 +715,7 @@ export function Panes() {
measure(); measure();
schedule(); schedule();
if (typeof ResizeObserver !== "undefined") { if (typeof ResizeObserver !== "undefined") {
bodies.current ??= new ResizeObserver(() => { bodies.current ??= new ResizeObserver(relayout);
latest.current(true);
measure();
schedule();
});
for (const b of strip.current?.querySelectorAll(".pane-body") ?? []) if (!watchedBodies.current.has(b)) (watchedBodies.current.add(b), bodies.current.observe(b)); for (const b of strip.current?.querySelectorAll(".pane-body") ?? []) if (!watchedBodies.current.has(b)) (watchedBodies.current.add(b), bodies.current.observe(b));
} }
// As pages, a step from pane to pane is a step in the browser's history. // As pages, a step from pane to pane is a step in the browser's history.
@@ -738,6 +725,9 @@ export function Panes() {
useEffect(() => { useEffect(() => {
const el = strip.current!; const el = strip.current!;
const wrap = el.parentElement!; const wrap = el.parentElement!;
// Every listener added below goes when the panes do.
const ac = new AbortController();
const signal = ac.signal;
/* /*
* As pages, a swipe ends on a page: its pane becomes the active one (the one on the focused * As pages, a swipe ends on a page: its pane becomes the active one (the one on the focused
* branch there, else the one last on it, else the first), so the page on screen is always the * branch there, else the one last on it, else the first), so the page on screen is always the
@@ -771,11 +761,11 @@ export function Panes() {
// A finger on the strip takes it from a glide, where it is. // A finger on the strip takes it from a glide, where it is.
if (e.type === "touchstart") (stopGlide(el), (programmatic.current = false)); if (e.type === "touchstart") (stopGlide(el), (programmatic.current = false));
}; };
el.addEventListener("touchstart", onTouch, { passive: true }); el.addEventListener("touchstart", onTouch, { passive: true, signal });
// Its end heard on the window: a touch whose target leaves the page (a pane that closed) ends there too. // Its end heard on the window: a touch whose target leaves the page (a pane that closed) ends there too.
window.addEventListener("touchend", onTouch, { passive: true, capture: true }); window.addEventListener("touchend", onTouch, { passive: true, capture: true, signal });
window.addEventListener("touchcancel", onTouch, { passive: true, capture: true }); window.addEventListener("touchcancel", onTouch, { passive: true, capture: true, signal });
if (ends) el.addEventListener("scrollend", settle); if (ends) el.addEventListener("scrollend", settle, { signal });
const onScroll = (e: Event) => { const onScroll = (e: Event) => {
const t = e.target as HTMLElement; const t = e.target as HTMLElement;
if (t === el && store.pages) { if (t === el && store.pages) {
@@ -798,7 +788,7 @@ export function Panes() {
schedule(); schedule();
}; };
// Panes and crowded columns scroll on their own: their scroll events are caught on the way down. // Panes and crowded columns scroll on their own: their scroll events are caught on the way down.
wrap.addEventListener("scroll", onScroll, { passive: true, capture: true }); wrap.addEventListener("scroll", onScroll, { passive: true, capture: true, signal });
// While anything animates, the curves are drawn every frame, so they follow it. // While anything animates, the curves are drawn every frame, so they follow it.
let moving = 0; let moving = 0;
const tick = () => { const tick = () => {
@@ -813,10 +803,10 @@ export function Panes() {
moving = Math.max(0, moving - 1); moving = Math.max(0, moving - 1);
if (!moving) schedule(); if (!moving) schedule();
}; };
window.addEventListener(GEOMETRY, schedule); window.addEventListener(GEOMETRY, schedule, { signal });
wrap.addEventListener("transitionrun", onRun); wrap.addEventListener("transitionrun", onRun, { signal });
wrap.addEventListener("transitionend", onEnd); wrap.addEventListener("transitionend", onEnd, { signal });
wrap.addEventListener("transitioncancel", onEnd); wrap.addEventListener("transitioncancel", onEnd, { signal });
// The strip changes size with the window and when the history panel opens or closes. // The strip changes size with the window and when the history panel opens or closes.
const sizes = new ResizeObserver(onResize); const sizes = new ResizeObserver(onResize);
sizes.observe(el); sizes.observe(el);
@@ -924,9 +914,9 @@ export function Panes() {
if (now.length) peek(pane, now); if (now.length) peek(pane, now);
}, PEEK_MS); }, PEEK_MS);
}; };
el.addEventListener("pointermove", onMove); el.addEventListener("pointermove", onMove, { signal });
el.addEventListener("pointerleave", unpeek); el.addEventListener("pointerleave", unpeek, { signal });
window.addEventListener("keydown", unpeek, true); window.addEventListener("keydown", unpeek, { capture: true, signal });
/* /*
* Dragging a pane up or down its column, by its grip (the band above its title, beside the pin * Dragging a pane up or down its column, by its grip (the band above its title, beside the pin
@@ -936,14 +926,18 @@ export function Panes() {
*/ */
let drag: { tid: number; col: HTMLElement; y0: number; on: boolean; before: number | null; line: HTMLElement | null; touch?: boolean } | null = null; let drag: { tid: number; col: HTMLElement; y0: number; on: boolean; before: number | null; line: HTMLElement | null; touch?: boolean } | null = null;
let swallow = false; let swallow = false;
/** The grip or tab pressed, its pane and its column, when the column has other panes to move among. */
const handleAt = (t: EventTarget | null) => {
const handle = (t as HTMLElement).closest<HTMLElement>("[data-grip], .tabline");
const pane = handle?.closest<HTMLElement>(".pane");
const col = pane?.parentElement;
return handle && pane && col && col.children.length > 1 ? { handle, pane, col } : null;
};
const onDown = (e: PointerEvent) => { const onDown = (e: PointerEvent) => {
if (e.button !== 0 || (e.pointerType === "touch" && store.pages)) return; if (e.button !== 0 || (e.pointerType === "touch" && store.pages)) return;
const t = e.target as HTMLElement; const h = handleAt(e.target);
if (t.closest("[data-close], [data-pin]")) return; if (!h) return;
const handle = t.closest<HTMLElement>("[data-grip], .tabline"); const { handle, pane, col } = h;
const pane = handle?.closest<HTMLElement>(".pane");
const col = pane?.parentElement as HTMLElement | undefined;
if (!handle || !pane || !col || col.children.length < 2) return;
drag = { tid: Number(pane.dataset.tid), col, y0: e.clientY, on: false, before: null, line: null }; drag = { tid: Number(pane.dataset.tid), col, y0: e.clientY, on: false, before: null, line: null };
handle.setPointerCapture(e.pointerId); handle.setPointerCapture(e.pointerId);
}; };
@@ -1032,7 +1026,6 @@ export function Panes() {
if (!h || !store.pages || !h.pane.isConnected) return; if (!h || !store.pages || !h.pane.isConnected) return;
drag = { tid: Number(h.pane.dataset.tid), col: h.col, y0: h.y, on: false, before: null, line: null, touch: true }; drag = { tid: Number(h.pane.dataset.tid), col: h.col, y0: h.y, on: false, before: null, line: null, touch: true };
startDrag(); startDrag();
wrap.classList.add("lifting");
h.pane.setAttribute("data-lifted", ""); h.pane.setAttribute("data-lifted", "");
ghost = document.createElement("div"); ghost = document.createElement("div");
ghost.className = "drag-ghost"; ghost.className = "drag-ghost";
@@ -1113,7 +1106,7 @@ export function Panes() {
const col = Number(r.col.dataset.col); const col = Number(r.col.dataset.col);
const m = hands.get(col); const m = hands.get(col);
// Dropped while the finger was down (its panes changed): laid out automatically. // Dropped while the finger was down (its panes changed): laid out automatically.
if (!m) return void (latest.current(true), measure(), schedule()); if (!m) return relayout();
tids.forEach((t, k) => m.sizes.set(t, to[k])); tids.forEach((t, k) => m.sizes.set(t, to[k]));
const from = r.now; const from = r.now;
cancelAnimationFrame(snapping); cancelAnimationFrame(snapping);
@@ -1147,9 +1140,7 @@ export function Panes() {
if (!hands.delete(Number(col.dataset.col))) return; if (!hands.delete(Number(col.dataset.col))) return;
cancelAnimationFrame(snapping); cancelAnimationFrame(snapping);
easing = null; easing = null;
latest.current(true); relayout();
measure();
schedule();
}; };
const onHoldStart = (e: TouchEvent) => { const onHoldStart = (e: TouchEvent) => {
if (!store.pages) return; if (!store.pages) return;
@@ -1160,14 +1151,10 @@ export function Panes() {
return void (hold || drag?.touch ? end(false) : undefined); return void (hold || drag?.touch ? end(false) : undefined);
} }
press = null; press = null;
const t = e.target as HTMLElement; const h = handleAt(e.target);
if (t.closest("[data-close], [data-pin], [data-more]")) return; if (!h) return;
const handle = t.closest<HTMLElement>("[data-grip], .tabline"); const { pane, col } = h;
const pane = handle?.closest<HTMLElement>(".pane");
const col = pane?.parentElement as HTMLElement | undefined;
if (!handle || !pane || !col) return;
const ps = [...col.querySelectorAll<HTMLElement>(":scope > .pane")]; const ps = [...col.querySelectorAll<HTMLElement>(":scope > .pane")];
if (ps.length < 2) return;
const p = e.changedTouches[0]; const p = e.changedTouches[0];
cancelHold(); cancelHold();
press = { x: p.clientX, y: p.clientY, id: p.identifier, pane, col, i: ps.indexOf(pane), lock: null, start: [], ps: [], now: [], dy: 0 }; press = { x: p.clientX, y: p.clientY, id: p.identifier, pane, col, i: ps.indexOf(pane), lock: null, start: [], ps: [], now: [], dy: 0 };
@@ -1252,57 +1239,33 @@ export function Panes() {
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
}; };
el.addEventListener("touchstart", onHoldStart, { passive: true }); el.addEventListener("touchstart", onHoldStart, { passive: true, signal });
el.addEventListener("touchmove", onHoldMove, { passive: true }); el.addEventListener("touchmove", onHoldMove, { passive: true, signal });
el.addEventListener("touchend", onHoldEnd); el.addEventListener("touchend", onHoldEnd, { signal });
el.addEventListener("touchcancel", onHoldEnd); el.addEventListener("touchcancel", onHoldEnd, { signal });
window.addEventListener("contextmenu", onLongPress, true); window.addEventListener("contextmenu", onLongPress, { capture: true, signal });
// A press elsewhere puts a peeking pane back; on it, the click goes through to it (and makes it the active pane), and then it goes back. // A press elsewhere puts a peeking pane back; on it, the click goes through to it (and makes it the active pane), and then it goes back.
const onPress = (e: PointerEvent) => !peeked.some((p) => p.contains(e.target as Node)) && unpeek(); const onPress = (e: PointerEvent) => !peeked.some((p) => p.contains(e.target as Node)) && unpeek();
const afterClick = () => peeked.length && requestAnimationFrame(unpeek); const afterClick = () => peeked.length && requestAnimationFrame(unpeek);
el.addEventListener("pointerdown", onDown); el.addEventListener("pointerdown", onDown, { signal });
el.addEventListener("pointerdown", onPress); el.addEventListener("pointerdown", onPress, { signal });
el.addEventListener("click", afterClick); el.addEventListener("click", afterClick, { signal });
el.addEventListener("pointermove", onDrag); el.addEventListener("pointermove", onDrag, { signal });
el.addEventListener("pointerup", onUp); el.addEventListener("pointerup", onUp, { signal });
el.addEventListener("pointercancel", onCancel); el.addEventListener("pointercancel", onCancel, { signal });
window.addEventListener("keydown", onKey, true); window.addEventListener("keydown", onKey, { capture: true, signal });
window.addEventListener("click", onClick, true); window.addEventListener("click", onClick, { capture: true, signal });
return () => { return () => {
stopGlide(el); stopGlide(el);
cancelAnimationFrame(frame.current); cancelAnimationFrame(frame.current);
clearTimeout(later.current); clearTimeout(later.current);
clearTimeout(timer); clearTimeout(timer);
clearTimeout(rest); clearTimeout(rest);
el.removeEventListener("touchstart", onTouch); ac.abort();
window.removeEventListener("touchend", onTouch, { capture: true });
window.removeEventListener("touchcancel", onTouch, { capture: true });
if (ends) el.removeEventListener("scrollend", settle);
wrap.removeEventListener("scroll", onScroll, { capture: true });
window.removeEventListener(GEOMETRY, schedule);
wrap.removeEventListener("transitionrun", onRun);
wrap.removeEventListener("transitionend", onEnd);
wrap.removeEventListener("transitioncancel", onEnd);
bodies.current?.disconnect(); bodies.current?.disconnect();
sizes.disconnect(); sizes.disconnect();
el.removeEventListener("pointermove", onMove);
el.removeEventListener("pointerleave", unpeek);
window.removeEventListener("keydown", unpeek, true);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointerdown", onPress);
el.removeEventListener("click", afterClick);
el.removeEventListener("pointermove", onDrag);
el.removeEventListener("pointerup", onUp);
el.removeEventListener("pointercancel", onCancel);
window.removeEventListener("keydown", onKey, true);
window.removeEventListener("click", onClick, true);
end(false); end(false);
handleMove = null; handleMove = null;
el.removeEventListener("touchstart", onHoldStart);
el.removeEventListener("touchmove", onHoldMove);
el.removeEventListener("touchend", onHoldEnd);
el.removeEventListener("touchcancel", onHoldEnd);
window.removeEventListener("contextmenu", onLongPress, true);
}; };
}, []); }, []);
@@ -1412,15 +1375,8 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
if (!el || !svg) return; if (!el || !svg) return;
if (store.pages) return pageMarks(el, svg); if (store.pages) return pageMarks(el, svg);
if (tinted.size) untint(); if (tinted.size) untint();
if (!store.settings.curves) { if (!store.settings.curves) return uncurve(paneEls(el), svg);
for (const p of svg.querySelectorAll("path")) p.remove();
for (const s of underlined) s.removeAttribute("data-curved");
underlined = new Set();
markRuled(paneEls(el), new Map());
return;
}
// The curves' layer covers the window from its corner (style.css), so its pixels are the device's and a hairline set on device pixels lands on them; it shows only over the strip. // The curves' layer covers the window from its corner (style.css), so its pixels are the device's and a hairline set on device pixels lands on them; it shows only over the strip.
const box = { left: 0, top: 0 };
// (Clipped inside the drawing: a CSS clip on the layer would have it resampled, softening every hairline.) // (Clipped inside the drawing: a CSS clip on the layer would have it resampled, softening every hairline.)
const area = (svg.parentElement as HTMLElement).getBoundingClientRect(); const area = (svg.parentElement as HTMLElement).getBoundingClientRect();
const dpr = window.devicePixelRatio || 1; const dpr = window.devicePixelRatio || 1;
@@ -1462,7 +1418,6 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
// What of the child shows: up to the next column where it covers it, down to the pane after it in a crowded column. // What of the child shows: up to the next column where it covers it, down to the pane after it in a crowded column.
const nextCol = colEls[colEls.indexOf(ccol) + 1]?.getBoundingClientRect().left ?? Infinity; const nextCol = colEls[colEls.indexOf(ccol) + 1]?.getBoundingClientRect().left ?? Infinity;
const shownRight = Math.min(cbox.right, nextCol); const shownRight = Math.min(cbox.right, nextCol);
// A pane folded down a crowded column shows its tab, and may still show its title under it.
// A pane showing its tab (folded down a crowded column, or scrolled past its title): the curve lands in the tab's foot; else in the rule under its title, where that shows (the same test as the tab's, ruleShows, so the two hand over at once). // A pane showing its tab (folded down a crowded column, or scrolled past its title): the curve lands in the tab's foot; else in the rule under its title, where that shows (the same test as the tab's, ruleShows, so the two hand over at once).
const below = ccol.classList.contains("crowded") ? ((ce.nextElementSibling as HTMLElement | null)?.getBoundingClientRect().top ?? Infinity) : Infinity; const below = ccol.classList.contains("crowded") ? ((ce.nextElementSibling as HTMLElement | null)?.getBoundingClientRect().top ?? Infinity) : Infinity;
let folded = ce.hasAttribute("data-tab") || ce.hasAttribute("data-scrolled") || ce.hasAttribute("data-buried") || (ce.hasAttribute("data-covered") && !ruleShows(ce, ccolBox, below)); let folded = ce.hasAttribute("data-tab") || ce.hasAttribute("data-scrolled") || ce.hasAttribute("data-buried") || (ce.hasAttribute("data-covered") && !ruleShows(ce, ccolBox, below));
@@ -1473,9 +1428,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
const tr = t?.getBoundingClientRect(); const tr = t?.getBoundingClientRect();
ey = tr && tr.bottom > scroll.top + 4 ? Math.max(scroll.top + 6, tr.top + Math.min(tr.height, 32) / 2) : scroll.top + 14; ey = tr && tr.bottom > scroll.top + 4 ? Math.max(scroll.top + 6, tr.top + Math.min(tr.height, 32) / 2) : scroll.top + 14;
// The rule: under the pane's own head (a section's, a page's title, an article's), not an article's set under a node; the focused head's too (the heavy rule on top marks the active pane). // The rule: under the pane's own head (a section's, a page's title, an article's), not an article's set under a node; the focused head's too (the heavy rule on top marks the active pane).
const head = ruled ? ce.querySelector<HTMLElement>(HEADS) : null; const rr = ruled ? ruleOf(ce)?.getBoundingClientRect() : undefined;
const ruleEl = head?.matches(".top") ? head.querySelector<HTMLElement>("h1") : head;
const rr = ruleEl?.getBoundingClientRect();
// Scrolled past its title (its tab is on its way): its tab's foot. // Scrolled past its title (its tab is on its way): its tab's foot.
if (rr && rr.bottom <= Math.max(cbox.top, scroll.top) + TAB) { if (rr && rr.bottom <= Math.max(cbox.top, scroll.top) + TAB) {
folded = true; folded = true;
@@ -1496,7 +1449,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
rules.set(x.node.id, "tab"); rules.set(x.node.id, "tab");
tabbed.add(x.node.id); tabbed.add(x.node.id);
} }
// Below the column's foot (every pane leaves at least its tab there now, so this is only a pane still being laid out). // Below the column's foot (every pane leaves at least its tab there, so this is only a pane still being laid out).
if (ey > ccolBox.bottom) { if (ey > ccolBox.bottom) {
ey = ccolBox.bottom - 4; ey = ccolBox.bottom - 4;
lost = true; lost = true;
@@ -1531,7 +1484,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
sx = footRight; sx = footRight;
// A few pixels straight on before it turns, so the foot runs on visibly. // A few pixels straight on before it turns, so the foot runs on visibly.
textRight = footRight + 6; textRight = footRight + 6;
if (ruled) feet.set(parent.id, { x0: pbox.left - box.left, x1: footRight - box.left, y: sy - box.top, hue: parent.hue, on: branch.has(parent.id) }); if (ruled) feet.set(parent.id, { x0: pbox.left, x1: footRight, y: sy, hue: parent.hue, on: branch.has(parent.id) });
} else { } else {
src ??= cands[0]; src ??= cands[0];
const head = pe.querySelector<HTMLElement>(".pane-head h2, .top h1, .wiki-head h2"); const head = pe.querySelector<HTMLElement>(".pane-head h2, .top h1, .wiki-head h2");
@@ -1585,7 +1538,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
tabbed.delete(x.node.id); tabbed.delete(x.node.id);
} }
const gutter = colEls.indexOf(ccol); const gutter = colEls.indexOf(ccol);
edges.push({ from: parent.id, to: x.node.id, gutter, left: left - box.left, sx: sx - box.left, sy: sy - box.top, under: under && { x: under.x - box.left, y: under.y - box.top }, hint: hint && { x: hint.x - box.left, y: hint.y - box.top }, lines: lines?.map((q) => ({ x0: q.x0 - box.left, x1: q.x1 - box.left, y: q.y - box.top })), textRight: textRight - box.left, ex: ex - box.left, ey: ey - box.top, on: branch.has(x.node.id) && branch.has(parent.id), lost, hue: x.node.hue, rule: rule && { x0: rule.x0 - box.left, x1: rule.x1 - box.left } }); edges.push({ from: parent.id, to: x.node.id, gutter, left, sx, sy, under, hint, lines, textRight, ex, ey, on: branch.has(x.node.id) && branch.has(parent.id), lost, hue: x.node.hue, rule });
} }
// Lanes, gutter by gutter. // Lanes, gutter by gutter.
const lane = new Map<Edge, number>(); const lane = new Map<Edge, number>();
@@ -1619,7 +1572,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
const x1 = Math.round(right * dpr) / dpr - h; const x1 = Math.round(right * dpr) / dpr - h;
const yb = Math.round(bottom * dpr) / dpr - h; const yb = Math.round(bottom * dpr) / dpr - h;
if (bottom > top) { if (bottom > top) {
const d = right < r.right - 1 ? `M${fx(x0 - box.left)} ${fx(top - box.top)}V${fx(yb - box.top)}H${fx(right - box.left)}` : `M${fx(x0 - box.left)} ${fx(top - box.top)}V${fx(yb - box.top)}H${fx(x1 - box.left)}V${fx(top - box.top)}`; const d = right < r.right - 1 ? `M${fx(x0)} ${fx(top)}V${fx(yb)}H${fx(right)}` : `M${fx(x0)} ${fx(top)}V${fx(yb)}H${fx(x1)}V${fx(top)}`;
out.push({ key: "frame", from: Number(act.dataset.tid), to: -1, lane: -1, cls: "frame", d, hue: "" }); out.push({ key: "frame", from: Number(act.dataset.tid), to: -1, lane: -1, cls: "frame", d, hue: "" });
} }
} }
@@ -1659,7 +1612,7 @@ function curves(el: HTMLElement | null, svg: SVGSVGElement | null) {
} }
// What peeks out, and the selection bar, leave their places clear of the curves (holes in a mask), but for the curves that belong to what peeks. // What peeks out, and the selection bar, leave their places clear of the curves (holes in a mask), but for the curves that belong to what peeks.
const peeked = [...el.querySelectorAll<HTMLElement>("[data-peek]")]; const peeked = [...el.querySelectorAll<HTMLElement>("[data-peek]")];
const local = (r: DOMRect) => ({ x: r.left - box.left, y: r.top - box.top, w: r.width, h: r.height }); const local = (r: DOMRect) => ({ x: r.left, y: r.top, w: r.width, h: r.height });
const holes = peeked.map((p) => local(p.getBoundingClientRect())); const holes = peeked.map((p) => local(p.getBoundingClientRect()));
const bar = el.querySelector<HTMLElement>(".pane > .selbar"); const bar = el.querySelector<HTMLElement>(".pane > .selbar");
const barHole = bar && bar.style.visibility !== "hidden" ? [local(bar.getBoundingClientRect())] : []; const barHole = bar && bar.style.visibility !== "hidden" ? [local(bar.getBoundingClientRect())] : [];
@@ -1770,13 +1723,9 @@ let tinted = new Set<HTMLElement>();
* under its title, of its tab and of its place in the trail (style.css, data-src-hue). Drawn when * under its title, of its tab and of its place in the trail (style.css, data-src-hue). Drawn when
* the panes change, not as anything scrolls. * the panes change, not as anything scrolls.
*/ */
function pageMarks(el: HTMLElement | null, svg: SVGSVGElement | null) { function pageMarks(el: HTMLElement, svg: SVGSVGElement) {
if (!el) return;
if (svg) for (const p of svg.querySelectorAll("path")) p.remove();
for (const s of underlined) s.removeAttribute("data-curved");
underlined = new Set();
const els = paneEls(el); const els = paneEls(el);
markRuled(els, new Map()); uncurve(els, svg);
const branch = new Set(store.branchNodes.map((n) => n.id)); const branch = new Set(store.branchNodes.map((n) => n.id));
const now = new Set<HTMLElement>(); const now = new Set<HTMLElement>();
for (const x of store.panesPlaced) { for (const x of store.panesPlaced) {
@@ -1792,6 +1741,14 @@ function pageMarks(el: HTMLElement | null, svg: SVGSVGElement | null) {
untint(now); untint(now);
} }
/** No curves drawn: every link's underline and pane's rule its own. */
function uncurve(els: Map<number, HTMLElement>, svg: SVGSVGElement) {
for (const p of svg.querySelectorAll("path")) p.remove();
for (const s of underlined) s.removeAttribute("data-curved");
underlined = new Set();
markRuled(els, new Map());
}
/** Take the colour off what no longer opens a pane (all of it, when the panes are side by side again). */ /** Take the colour off what no longer opens a pane (all of it, when the panes are side by side again). */
function untint(keep = new Set<HTMLElement>()) { function untint(keep = new Set<HTMLElement>()) {
for (const s of tinted) for (const s of tinted)
@@ -1804,6 +1761,11 @@ function untint(keep = new Set<HTMLElement>()) {
/** A pane's own head, whose rule a curve into it lands in: a section's, a page's title, an article's (not an article set under a node). */ /** A pane's own head, whose rule a curve into it lands in: a section's, a page's title, an article's (not an article set under a node). */
const HEADS = ":scope > .pane-scroll > .pane-body > .pane-head, :scope > .pane-scroll > .pane-body > .top, :scope > .pane-scroll > .pane-body > .wiki:not(.embedded) > .wiki-head"; const HEADS = ":scope > .pane-scroll > .pane-body > .pane-head, :scope > .pane-scroll > .pane-body > .top, :scope > .pane-scroll > .pane-body > .wiki:not(.embedded) > .wiki-head";
/** The element under which a pane's own head draws its rule (a page's title is its h1). */
function ruleOf(p: HTMLElement): HTMLElement | null {
const head = p.querySelector<HTMLElement>(HEADS);
return head?.matches(".top") ? head.querySelector<HTMLElement>("h1") : head;
}
/** Which panes' rules a curve draws (head or tab), so that their own are left out. */ /** Which panes' rules a curve draws (head or tab), so that their own are left out. */
function markRuled(els: Map<number, HTMLElement>, rules: Map<number, string>) { function markRuled(els: Map<number, HTMLElement>, rules: Map<number, string>) {
+10 -9
View File
@@ -50,13 +50,13 @@ export interface Forest<R, S = unknown> {
hues?: number; hues?: number;
} }
export type Same<R> = (a: R, b: R) => boolean; type Same<R> = (a: R, b: R) => boolean;
let ids = 0; let ids = 0;
export const leaf = <R, S>(ref: R): Tree<R, S> => ({ ref, kids: [], pick: 0, id: ++ids }); const leaf = <R, S>(ref: R): Tree<R, S> => ({ ref, kids: [], pick: 0, id: ++ids });
/** A plain trail as a tree. */ /** A plain trail as a tree. */
export function chain<R, S>(refs: R[]): Tree<R, S> | null { function chain<R, S>(refs: R[]): Tree<R, S> | null {
let t: Tree<R, S> | null = null; let t: Tree<R, S> | null = null;
for (let i = refs.length - 1; i >= 0; i--) t = { ref: refs[i], kids: t ? [t] : [], pick: 0, id: ++ids }; for (let i = refs.length - 1; i >= 0; i--) t = { ref: refs[i], kids: t ? [t] : [], pick: 0, id: ++ids };
return t; return t;
@@ -89,7 +89,7 @@ function palette(f: Forest<unknown, unknown>) {
} }
/** The column a tree's root is in. */ /** The column a tree's root is in. */
export const colOf = (t: Tree<unknown, unknown>) => t.col ?? 0; const colOf = (t: Tree<unknown, unknown>) => t.col ?? 0;
/** The focused tree. */ /** The focused tree. */
export const focused = <R, S>(f: Forest<R, S>): Tree<R, S> | null => f.trees[f.at] ?? null; export const focused = <R, S>(f: Forest<R, S>): Tree<R, S> | null => f.trees[f.at] ?? null;
@@ -192,17 +192,18 @@ export function columns<R, S>(f: Forest<R, S>): Map<number, Placed<R, S>[]> {
export function reorder<R, S>(f: Forest<R, S>, id: number, before: number | null): Forest<R, S> { export function reorder<R, S>(f: Forest<R, S>, id: number, before: number | null): Forest<R, S> {
const me = all(f).find((x) => x.node.id === id); const me = all(f).find((x) => x.node.id === id);
if (!me || id === before) return f; if (!me || id === before) return f;
const col = columns(f).get(me.col)!.map((x) => x.node.id); const items = columns(f).get(me.col)!;
const col = items.map((x) => x.node.id);
const rest = col.filter((x) => x !== id); const rest = col.filter((x) => x !== id);
const at = before === null ? rest.length : rest.indexOf(before); const at = before === null ? rest.length : rest.indexOf(before);
if (at < 0) return f; if (at < 0) return f;
rest.splice(at, 0, id); rest.splice(at, 0, id);
if (rest.every((x, i) => x === col[i]) && col.every((x) => (all(f).find((y) => y.node.id === x)!.node.rank ?? -1) >= 0)) return f; if (rest.every((x, i) => x === col[i]) && items.every((x) => (x.node.rank ?? -1) >= 0)) return f;
return rest.reduce((g, x, i) => updateIn(g, x, (n) => (n.rank === i ? n : { ...n, rank: i })), f); return rest.reduce((g, x, i) => updateIn(g, x, (n) => (n.rank === i ? n : { ...n, rank: i })), f);
} }
/** Change the node with this id, copying the path to it. */ /** Change the node with this id, copying the path to it. */
export function update<R, S>(t: Tree<R, S>, id: number, f: (n: Tree<R, S>) => Tree<R, S>): Tree<R, S> { function update<R, S>(t: Tree<R, S>, id: number, f: (n: Tree<R, S>) => Tree<R, S>): Tree<R, S> {
if (t.id === id) return f(t); if (t.id === id) return f(t);
let changed = false; let changed = false;
const kids = t.kids.map((k) => { const kids = t.kids.map((k) => {
@@ -222,7 +223,7 @@ export function updateIn<R, S>(f: Forest<R, S>, id: number, fn: (n: Tree<R, S>)
} }
/** Make the node with this id lie on its tree's focused branch (its own picks below it kept). */ /** Make the node with this id lie on its tree's focused branch (its own picks below it kept). */
export function select<R, S>(t: Tree<R, S>, id: number): Tree<R, S> | null { function select<R, S>(t: Tree<R, S>, id: number): Tree<R, S> | null {
if (t.id === id) return t; if (t.id === id) return t;
for (let k = 0; k < t.kids.length; k++) { for (let k = 0; k < t.kids.length; k++) {
const s = select(t.kids[k], id); const s = select(t.kids[k], id);
@@ -422,7 +423,7 @@ export function withBranch<R, S>(f: Forest<R, S>, refs: R[], same: Same<R>): For
} }
/** As stored: refs (made storable by the caller), children, picks, pins, an orphan's column, places and colours; no ids, nothing remembered. */ /** As stored: refs (made storable by the caller), children, picks, pins, an orphan's column, places and colours; no ids, nothing remembered. */
export interface Saved<R> { interface Saved<R> {
ref: R; ref: R;
kids?: Saved<R>[]; kids?: Saved<R>[];
pick?: number; pick?: number;
+1 -5
View File
@@ -37,11 +37,7 @@ export function crossings(order: { sy: number; ey: number }[]): number {
* scroll or an open elsewhere does not reshuffle the bundle. * scroll or an open elsewhere does not reshuffle the bundle.
*/ */
export function laneOrder<T extends { key: string; sy: number; ey: number }>(edges: T[], last: string[] = []): T[] { export function laneOrder<T extends { key: string; sy: number; ey: number }>(edges: T[], last: string[] = []): T[] {
const rule = [...edges].sort((a, b) => { const rule = [...edges].sort((a, b) => Math.abs(a.ey - a.sy) - Math.abs(b.ey - b.sy));
const da = a.ey >= a.sy ? a.ey - a.sy : a.sy - a.ey;
const db = b.ey >= b.sy ? b.ey - b.sy : b.sy - b.ey;
return da - db;
});
const byKey = new Map(edges.map((e) => [e.key, e])); const byKey = new Map(edges.map((e) => [e.key, e]));
const order = last.flatMap((k) => byKey.get(k) ?? []); const order = last.flatMap((k) => byKey.get(k) ?? []);
for (const e of rule) { for (const e of rule) {
+8 -10
View File
@@ -12,22 +12,19 @@
* height less a tab for each other pane) and applies what comes back. * height less a tab for each other pane) and applies what comes back.
*/ */
export interface Axis { interface Axis {
/** The sticky inset, and the start and end of a box along the axis. */ /** The sticky inset, where a box starts along the axis. */
start: "left" | "top"; start: "left" | "top";
end: "right" | "bottom";
size: "offsetWidth" | "offsetHeight"; size: "offsetWidth" | "offsetHeight";
client: "clientWidth" | "clientHeight"; client: "clientWidth" | "clientHeight";
scroll: "scrollLeft" | "scrollTop";
scrollSize: "scrollWidth" | "scrollHeight";
} }
/** Across: the columns of the strip. */ /** Across: the columns of the strip. */
export const ACROSS: Axis = { start: "left", end: "right", size: "offsetWidth", client: "clientWidth", scroll: "scrollLeft", scrollSize: "scrollWidth" }; export const ACROSS: Axis = { start: "left", size: "offsetWidth", client: "clientWidth" };
/** Down: the panes of a crowded column. */ /** Down: the panes of a crowded column. */
export const DOWN: Axis = { start: "top", end: "bottom", size: "offsetHeight", client: "clientHeight", scroll: "scrollTop", scrollSize: "scrollHeight" }; export const DOWN: Axis = { start: "top", size: "offsetHeight", client: "clientHeight" };
/** An item covered to less than this share of its size shows only its strip (spine or tab). */ /** An item covered to less than this share of its size shows only its strip (spine or tab). */
export const COVERED = 0.4; const COVERED = 0.4;
/** /**
* Each item's sticky offset: every item before it leaves its strip, a pinned one its whole size; * Each item's sticky offset: every item before it leaves its strip, a pinned one its whole size;
@@ -77,7 +74,7 @@ export const starts = (sizes: number[]) => sizes.map((_, i) => sizes.slice(0, i)
const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0); const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0);
/** Sizes from edges (each item's start, then the end of the last), each edge rounded to a whole pixel: an item at least `min` before stays so after. */ /** Sizes from edges (each item's start, then the end of the last), each edge rounded to a whole pixel. */
const fromEdges = (e: number[]) => e.slice(1).map((x, k) => Math.round(x) - Math.round(e[k])); const fromEdges = (e: number[]) => e.slice(1).map((x, k) => Math.round(x) - Math.round(e[k]));
/** /**
@@ -160,7 +157,8 @@ export function reveal(scroll: number, view: number, start: number, size: number
/** Whether an item is shown whole at this scroll. */ /** Whether an item is shown whole at this scroll. */
export const whole = (scroll: number, view: number, start: number, size: number, stuck: number) => scroll >= start + size - view - 1 && scroll <= start - stuck + 1; export const whole = (scroll: number, view: number, start: number, size: number, stuck: number) => scroll >= start + size - view - 1 && scroll <= start - stuck + 1;
const setAttr = (el: Element | undefined, name: string, on: boolean) => { /** Set or remove a boolean attribute, touching the DOM only when it changes. */
export const setAttr = (el: Element | undefined, name: string, on: boolean) => {
if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name); if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name);
}; };