feat(focus): selection toolbar

This commit is contained in:
kert
2026-11-14 11:12:38 -05:00
parent 13c6d2ad23
commit 56188acd87
7 changed files with 933 additions and 1 deletions

View File

@@ -118,6 +118,9 @@ def search_page() -> str:
_VENDOR = {"pdf.min.mjs", "pdf.worker.min.mjs", "jszip.min.js", "docx-preview.min.js"}
# Pane scripts. Not the vendored libraries: those are immutable blobs,
# these are our modules and must not be cached across a deploy.
_FOCUS_UI = {"focus.js", "focus_anchor.mjs"}
@app.get("/ui/vendor/{name}")
@@ -135,6 +138,19 @@ def vendor(name: str) -> Response:
)
@app.get("/ui/{asset}")
def focus_ui(asset: str) -> Response:
"""The deep-focus pane modules. A fixed allow-list, same as /ui/vendor."""
if asset not in _FOCUS_UI:
raise HTTPException(404)
body = resources.files("llm").joinpath(f"web/{asset}").read_bytes()
return Response(
body,
media_type="text/javascript",
headers={"Cache-Control": "no-cache"},
)
@app.get("/ui/pdf/{key}", response_class=HTMLResponse)
def pdf_page(key: str) -> str:
"""The PDF viewer; the page reads its item key, file, page and search

387
src/llm/web/focus.js Normal file
View File

@@ -0,0 +1,387 @@
// Deep-focus pane on the library viewer. Protocol picker, selection
// toolbar, annotation list, and link mode. No localStorage: the URL
// carries protocol and ann. Label text is always visible; color is extra.
import { reanchor, selectionSelectors } from "./focus_anchor.mjs";
const KEY_RE = /^[A-Za-z0-9]{6,12}$/;
export async function mountFocus(host) {
const picker = document.getElementById("protocol");
const bar = document.getElementById("focusbar");
const panel = document.getElementById("focuspanel");
if (!picker || !bar || !panel) return;
const params = new URLSearchParams(location.search);
let protocolName = params.get("protocol") || "";
let currentId = params.get("ann") || "";
let protocols = [];
let annotations = [];
let canonical = "";
let pending = null;
try {
const r = await fetch("/api/focus/protocols");
if (r.ok) protocols = await r.json();
} catch (e) {
console.warn("focus protocols:", e);
}
if (!protocols.length) return;
if (!protocols.some((p) => p.name === protocolName)) protocolName = protocols[0].name;
picker.replaceChildren();
for (const proto of protocols) {
const opt = document.createElement("option");
opt.value = proto.name;
opt.textContent = proto.title || proto.name;
picker.appendChild(opt);
}
picker.value = protocolName;
picker.addEventListener("change", () => {
protocolName = picker.value;
currentId = "";
writeUrl();
buildToolbar();
refresh();
});
bar.addEventListener("mousedown", (e) => e.preventDefault());
document.addEventListener("mouseup", () => queueSelect());
document.addEventListener("keyup", (e) => {
if (e.key === "Shift" || e.key.startsWith("Arrow")) queueSelect();
});
document.addEventListener("keydown", onKey, true);
host.viewer.addEventListener("focus-page", () => paint());
buildToolbar();
writeUrl();
await refresh();
function proto() {
return protocols.find((p) => p.name === protocolName) || protocols[0];
}
function labelOf(id) {
return proto().labels.find((l) => l.id === id) || null;
}
function labelText(id) {
const found = labelOf(id);
return found ? found.text : id;
}
function writeUrl() {
const next = new URLSearchParams(location.search);
next.set("protocol", protocolName);
if (currentId) next.set("ann", currentId);
else next.delete("ann");
history.replaceState(null, "", location.pathname + "?" + next.toString() + location.hash);
}
function buildToolbar() {
bar.replaceChildren();
for (const label of proto().labels) {
const button = document.createElement("button");
button.type = "button";
button.dataset.label = label.id;
const key = document.createElement("kbd");
key.textContent = label.key;
button.appendChild(key);
button.appendChild(document.createTextNode(label.text));
button.addEventListener("click", () => apply(label));
bar.appendChild(button);
}
}
function queueSelect() {
setTimeout(showSelection, 0);
}
function showSelection() {
const sel = window.getSelection();
if (!sel || sel.isCollapsed || !sel.rangeCount) {
hideBar();
return;
}
const range = sel.getRangeAt(0);
if (!host.viewer.contains(range.commonAncestorContainer)) {
hideBar();
return;
}
const raw = sel.toString();
if (!raw.trim()) {
hideBar();
return;
}
const rect = range.getBoundingClientRect();
if (!rect.width && !rect.height) {
hideBar();
return;
}
pending = { range: range.cloneRange(), raw };
bar.hidden = false;
const left = Math.min(Math.max(8, rect.left), window.innerWidth - 360);
const top = rect.bottom + 8 + 40 > window.innerHeight ? rect.top - 44 : rect.bottom + 8;
bar.style.left = left + "px";
bar.style.top = Math.max(8, top) + "px";
}
function hideBar() {
bar.hidden = true;
pending = null;
}
function onKey(e) {
if (e.target.closest("input, textarea, select")) return;
if (!bar.hidden && e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
hideBar();
window.getSelection()?.removeAllRanges();
return;
}
if (bar.hidden || !pending) return;
const label = proto().labels.find((l) => l.key === e.key);
if (!label) return;
e.preventDefault();
e.stopPropagation();
apply(label);
}
async function apply(label) {
if (!pending) return;
const { range, raw } = pending;
const local = contextOf(range, raw);
const quote = (local.quote || raw).trim();
if (!quote) return;
const placed = canonical
? reanchor(canonical, {
quote,
prefix: local.prefix,
suffix: local.suffix,
start_char: null,
end_char: null,
})
: { orphaned: true };
const body = {
attachment: host.file,
protocol: protocolName,
label: label.id,
quote,
prefix: local.prefix,
suffix: local.suffix,
start_char: placed.orphaned ? null : placed.start,
end_char: placed.orphaned ? null : placed.end,
page: pageNumber(range),
rects: rectsOf(range),
note: "",
};
hideBar();
window.getSelection()?.removeAllRanges();
const r = await fetch("/api/focus/" + encodeURIComponent(host.key) + "/annotations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!r.ok) {
setStatus("Could not save the highlight (" + r.status + ").");
return;
}
const saved = await r.json();
currentId = saved.id;
writeUrl();
await refresh();
}
function contextOf(range, raw) {
const root = range.commonAncestorContainer.nodeType === 1
? range.commonAncestorContainer
: range.commonAncestorContainer.parentElement;
const box = root && host.viewer.contains(root) ? root : host.viewer;
const built = textOffsets(box, range);
if (built && built.start != null && built.end != null && built.end > built.start) {
try {
return selectionSelectors(built.text, built.start, built.end);
} catch (e) {
/* fall through to the raw selection */
}
}
return { quote: raw.trim(), prefix: "", suffix: "" };
}
function textOffsets(root, range) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
let text = "";
let start = null;
let end = null;
while (walker.nextNode()) {
const node = walker.currentNode;
if (node === range.startContainer) start = text.length + range.startOffset;
if (node === range.endContainer) end = text.length + range.endOffset;
text += node.nodeValue;
}
return { text, start, end };
}
function pageNumber(range) {
const page = pageEl(range);
if (page && page.dataset.page) return parseInt(page.dataset.page, 10);
if (host.kind === "docx") {
const node = range.startContainer.nodeType === 1
? range.startContainer
: range.startContainer.parentElement;
const section = node && node.closest("section.docx");
if (section) {
const all = [...host.viewer.querySelectorAll("section.docx")];
const i = all.indexOf(section);
if (i >= 0) return i + 1;
}
}
return 1;
}
function pageEl(range) {
const node = range.startContainer.nodeType === 1
? range.startContainer
: range.startContainer.parentElement;
return node ? node.closest(".page") : null;
}
function rectsOf(range) {
if (host.kind !== "pdf") return null;
const page = pageEl(range);
if (!page) return null;
const pw = parseFloat(page.dataset.pw);
const ph = parseFloat(page.dataset.ph);
const box = page.getBoundingClientRect();
if (!pw || !ph || !box.width || !box.height) return null;
const out = [];
for (const r of range.getClientRects()) {
if (!r.width || !r.height) continue;
out.push({
x: ((r.left - box.left) / box.width) * pw,
y: ((r.top - box.top) / box.height) * ph,
w: (r.width / box.width) * pw,
h: (r.height / box.height) * ph,
});
}
return out.length ? out : null;
}
async function refresh() {
canonical = "";
try {
const textUrl = "/api/focus/" + encodeURIComponent(host.key) + "/text?attachment="
+ encodeURIComponent(host.file);
const tr = await fetch(textUrl);
if (tr.ok) canonical = (await tr.json()).text || "";
} catch (e) {
canonical = "";
}
try {
const url = "/api/focus/" + encodeURIComponent(host.key) + "/annotations?protocol="
+ encodeURIComponent(protocolName);
const r = await fetch(url);
annotations = r.ok ? await r.json() : [];
} catch (e) {
annotations = [];
}
paint();
renderPanel();
if (currentId) reveal(currentId, false);
}
function paint() {
clearMarks();
for (const ann of annotations) {
const placed = canonical
? reanchor(canonical, ann)
: { start: null, end: null, orphaned: true, how: "orphaned" };
const drawn = draw(ann, placed);
ann._orphaned = placed.orphaned && !drawn;
}
}
function clearMarks() {
host.viewer.querySelectorAll(".hl").forEach((el) => el.remove());
host.viewer.querySelectorAll("mark.focus-hl").forEach((mark) => {
mark.replaceWith(document.createTextNode(mark.textContent));
});
}
function draw(ann, placed) {
if (placed.orphaned) return false;
if (host.kind === "pdf" && ann.rects && ann.rects.length && ann.page) {
const page = host.viewer.querySelector('.page[data-page="' + ann.page + '"]');
if (!page || !page.dataset.pw || !page.dataset.ph) return false;
const pw = parseFloat(page.dataset.pw);
const ph = parseFloat(page.dataset.ph);
for (const r of ann.rects) {
const d = document.createElement("div");
d.className = "hl lab-" + cssId(ann.label);
d.dataset.ann = ann.id;
d.style.left = (r.x / pw) * 100 + "%";
d.style.top = (r.y / ph) * 100 + "%";
d.style.width = (r.w / pw) * 100 + "%";
d.style.height = (r.h / ph) * 100 + "%";
d.title = labelText(ann.label);
page.appendChild(d);
}
return true;
}
return wrapQuote(ann);
}
function wrapQuote(ann) {
const root = host.kind === "text"
? host.viewer.querySelector("#textdoc")
: host.kind === "docx"
? host.viewer.querySelector("#docxwrap")
: host.viewer;
if (!root || !ann.quote) return false;
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
for (const node of nodes) {
if (node.parentElement && node.parentElement.closest("mark.focus-hl")) continue;
const i = node.nodeValue.indexOf(ann.quote);
if (i === -1) continue;
const frag = document.createDocumentFragment();
frag.appendChild(document.createTextNode(node.nodeValue.slice(0, i)));
const mark = document.createElement("mark");
mark.className = "focus-hl lab-" + cssId(ann.label);
mark.dataset.ann = ann.id;
mark.textContent = ann.quote;
mark.title = labelText(ann.label);
frag.appendChild(mark);
frag.appendChild(document.createTextNode(node.nodeValue.slice(i + ann.quote.length)));
node.parentNode.replaceChild(frag, node);
return true;
}
return false;
}
function renderPanel() {
panel.replaceChildren();
const heading = document.createElement("h2");
heading.textContent = "Annotations";
panel.appendChild(heading);
const line = document.createElement("p");
line.id = "focus-status";
line.className = "focus-empty";
const n = annotations.length;
line.textContent = n
? n + " highlight" + (n === 1 ? "" : "s") + " on this protocol."
: "No highlights for this protocol.";
panel.appendChild(line);
}
function setStatus(text) {
const el = document.getElementById("focus-status");
if (el) el.textContent = text;
}
}
function cssId(id) {
return String(id || "").replace(/[^a-z0-9-]+/gi, "-");
}

View File

@@ -0,0 +1,235 @@
// Pure highlight anchoring. Offsets are into the canonical item text
// (the same string /api/focus/{key}/text returns). Prefix and suffix
// are at most CONTEXT_CHARS on each side, in the style of a W3C
// TextQuoteSelector. Re-anchoring tries the stored offsets, then an
// exact quote (whitespace-insensitive, prefix/suffix break ties),
// then a small edit-distance window. Nothing matched is orphaned.
export const CONTEXT_CHARS = 32;
export function selectionSelectors(text, start, end) {
if (
!Number.isInteger(start) ||
!Number.isInteger(end) ||
start < 0 ||
end > text.length ||
end < start
) {
throw new Error("bad range");
}
return {
quote: text.slice(start, end),
prefix: text.slice(Math.max(0, start - CONTEXT_CHARS), start),
suffix: text.slice(end, Math.min(text.length, end + CONTEXT_CHARS)),
start_char: start,
end_char: end,
};
}
/**
* @param {string} text
* @param {{quote?: string, prefix?: string, suffix?: string,
* start_char?: number|null, end_char?: number|null}} ann
* @returns {{start: number|null, end: number|null, orphaned: boolean,
* how: "position"|"quote"|"fuzzy"|"orphaned"}}
*/
export function reanchor(text, ann) {
const quote = ann.quote || "";
if (!quote) return { start: null, end: null, orphaned: true, how: "orphaned" };
const prefix = ann.prefix || "";
const suffix = ann.suffix || "";
const start = ann.start_char;
const end = ann.end_char;
if (
Number.isInteger(start) &&
Number.isInteger(end) &&
start >= 0 &&
end <= text.length &&
end > start &&
text.slice(start, end) === quote
) {
return { start, end, orphaned: false, how: "position" };
}
const exact = locateExact(text, quote, prefix, suffix);
if (exact) return { start: exact.start, end: exact.end, orphaned: false, how: "quote" };
const fuzzy = locateFuzzy(text, quote, prefix, suffix);
if (fuzzy) return { start: fuzzy.start, end: fuzzy.end, orphaned: false, how: "fuzzy" };
return { start: null, end: null, orphaned: true, how: "orphaned" };
}
function locateExact(text, quote, prefix, suffix) {
const direct = pick(occurrences(text, quote).map((start) => ({
start,
end: start + quote.length,
})), text, prefix, suffix);
if (direct) return direct;
return pick(collapsedSpans(text, quote), text, prefix, suffix);
}
function locateFuzzy(text, quote, prefix, suffix) {
const maxDist = Math.max(2, Math.floor(quote.length * 0.2));
let best = null;
for (const plan of seedPlan(quote)) {
const hits = occurrences(text, plan.needle);
if (!hits.length) continue;
if (hits.length > 40 && plan.needle.length < 8) continue;
for (const at of hits) {
const base = at - plan.pos;
for (let shift = -plan.slack - 1; shift <= plan.slack + 1; shift++) {
const start = base + shift;
if (start < 0) continue;
for (let len = quote.length - maxDist; len <= quote.length + maxDist; len++) {
if (len <= 0 || start + len > text.length) continue;
const window = text.slice(start, start + len);
if (window === quote) continue;
const dist = levenshtein(window, quote, maxDist);
if (dist === null || dist === 0) continue;
const score = contextScore(text, start, start + len, prefix, suffix) - dist * 2;
if (!best || score > best.score || (score === best.score && dist < best.dist)) {
best = { start, end: start + len, score, dist };
}
}
}
}
}
return best ? { start: best.start, end: best.end } : null;
}
function seedPlan(quote) {
const plans = [];
const seen = new Set();
const add = (needle, pos, slack) => {
if (!needle || pos < 0) return;
const key = needle + "@" + pos;
if (seen.has(key)) return;
seen.add(key);
plans.push({ needle, pos, slack });
};
for (const word of quote.split(/\s+/)) {
if (word.length < 4) continue;
const pos = quote.indexOf(word);
add(word, pos, 0);
if (word.length <= 16) {
for (let i = 0; i < word.length; i++) {
add(word.slice(0, i) + word.slice(i + 1), pos, 1);
}
}
}
if (quote.length >= 8) {
add(quote.slice(0, 8), 0, 0);
add(quote.slice(-8), quote.length - 8, 0);
}
return plans;
}
function pick(spans, text, prefix, suffix) {
if (!spans.length) return null;
if (spans.length === 1) return spans[0];
let best = null;
let bestScore = -1;
for (const span of spans) {
const score = contextScore(text, span.start, span.end, prefix, suffix);
if (score > bestScore) {
bestScore = score;
best = span;
}
}
return best;
}
function occurrences(text, needle) {
if (!needle) return [];
const out = [];
let at = 0;
while (at < text.length) {
const i = text.indexOf(needle, at);
if (i === -1) break;
out.push(i);
at = i + Math.max(1, needle.length);
}
return out;
}
function collapsedSpans(text, quote) {
const wanted = quote.replace(/\s+/g, " ").trim();
if (!wanted) return [];
const { out, map } = collapseWithMap(text);
const spans = [];
let from = 0;
while (from < out.length) {
const i = out.indexOf(wanted, from);
if (i === -1) break;
const last = i + wanted.length - 1;
spans.push({ start: map[i], end: map[last] + 1 });
from = i + 1;
}
return spans;
}
function collapseWithMap(text) {
let out = "";
const map = [];
let pending = false;
for (let i = 0; i < text.length; i++) {
if (/\s/.test(text[i])) {
pending = out.length > 0;
continue;
}
if (pending) {
out += " ";
map.push(i);
pending = false;
}
out += text[i];
map.push(i);
}
return { out, map };
}
function contextScore(text, start, end, prefix, suffix) {
let score = 0;
if (prefix) {
const got = text.slice(Math.max(0, start - prefix.length), start);
score += sharedSuffix(got, prefix);
}
if (suffix) {
const got = text.slice(end, end + suffix.length);
score += sharedPrefix(got, suffix);
}
return score;
}
function sharedPrefix(a, b) {
const n = Math.min(a.length, b.length);
let i = 0;
while (i < n && a[i] === b[i]) i++;
return i;
}
function sharedSuffix(a, b) {
const n = Math.min(a.length, b.length);
let i = 0;
while (i < n && a[a.length - 1 - i] === b[b.length - 1 - i]) i++;
return i;
}
// Banded Levenshtein. Returns null when the distance exceeds max.
function levenshtein(a, b, max) {
if (Math.abs(a.length - b.length) > max) return null;
let prev = new Array(b.length + 1);
for (let j = 0; j <= b.length; j++) prev[j] = j;
for (let i = 1; i <= a.length; i++) {
const cur = new Array(b.length + 1);
cur[0] = i;
let rowMin = cur[0];
const ai = a[i - 1];
for (let j = 1; j <= b.length; j++) {
const cost = ai === b[j - 1] ? 0 : 1;
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
if (cur[j] < rowMin) rowMin = cur[j];
}
if (rowMin > max) return null;
prev = cur;
}
return prev[b.length] <= max ? prev[b.length] : null;
}

View File

@@ -112,6 +112,74 @@
}
.notice.err { color: var(--destructive); border-color: var(--destructive); font-style: normal; }
.notice a { color: var(--accent); }
header label.proto {
font-family: var(--font-mono); font-size: 11px; text-transform: uppercase;
letter-spacing: .06em; display: flex; align-items: center; gap: 6px;
}
header select#protocol {
font-family: var(--font-mono); font-size: 12px; height: 26px; max-width: 200px;
background: var(--card); color: var(--foreground); border: 1px solid var(--border); border-radius: 3px;
}
#stage { flex: 1 1 auto; display: flex; min-height: 0; min-width: 0; }
#focuspanel {
flex: 0 0 300px; overflow: auto; border-left: 1px solid var(--border);
background: var(--card); padding: 12px 12px 24px; font-size: 13.5px;
}
#focuspanel h2 {
font-family: var(--font-display); font-size: 16px; margin: 0 0 8px;
}
#focuspanel .focus-empty, #focuspanel .focus-status { color: var(--muted-fg); margin: 0 0 8px; }
#focuspanel .focus-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
#focuspanel li { border-top: 1px solid var(--border); padding-top: 8px; }
#focuspanel li.current { background: var(--secondary); margin: 0 -8px; padding: 8px; }
#focuspanel button, #focuspanel textarea, #focuspanel input {
font-family: var(--font-body); font-size: 13px; color: var(--foreground);
}
#focuspanel button.jump {
display: block; width: 100%; text-align: left; background: none; border: 0; padding: 0;
cursor: pointer; font-family: var(--font-body);
}
#focuspanel button.jump:hover { text-decoration: underline; }
#focuspanel textarea, #focuspanel input {
width: 100%; margin-top: 6px; border: 1px solid var(--border); border-radius: 3px;
background: var(--background); padding: 4px 6px; font-family: var(--font-body);
}
#focuspanel .focus-actions { display: flex; gap: 6px; margin-top: 6px; }
#focuspanel .focus-actions button, #focuspanel .focus-link-form button {
font-family: var(--font-mono); font-size: 11px; height: 26px; padding: 0 8px; cursor: pointer;
border: 1px solid var(--border); border-radius: 3px; background: var(--secondary);
}
#focuspanel .badge {
display: inline-block; margin-left: 6px; font-family: var(--font-mono); font-size: 10px;
text-transform: uppercase; letter-spacing: .06em; border: 1px solid var(--destructive);
color: var(--destructive); border-radius: 3px; padding: 0 4px;
}
#focusbar {
position: fixed; z-index: 20; display: flex; flex-wrap: wrap; gap: 4px; max-width: min(440px, 92vw);
background: var(--card); border: 1px solid var(--foreground); border-radius: 3px; padding: 6px;
box-shadow: 0 2px 8px rgba(0, 0, 0, .18);
}
#focusbar[hidden] { display: none; }
#focusbar button {
font-family: var(--font-body); font-size: 13px; padding: 4px 8px; cursor: pointer;
border: 1px solid var(--border); border-radius: 3px; background: var(--secondary); color: var(--foreground);
}
#focusbar button:hover { background: #E2DFD8; }
#focusbar kbd {
font-family: var(--font-mono); font-size: 10px; margin-right: 6px; padding: 0 4px;
border: 1px solid var(--border); border-radius: 2px; background: var(--card);
}
.hl {
position: absolute; pointer-events: none; border-radius: 2px; z-index: 2;
background: rgba(46, 61, 143, .28);
}
mark.focus-hl { background: rgba(46, 61, 143, .28); color: inherit; border-radius: 2px; }
.hl.lab-support, mark.focus-hl.lab-support { background: rgba(30, 122, 58, .32); }
.hl.lab-support-with-modifications, mark.focus-hl.lab-support-with-modifications { background: rgba(180, 120, 20, .34); }
.hl.lab-do-not-support, mark.focus-hl.lab-do-not-support { background: rgba(192, 57, 43, .32); }
.hl.lab-finalized-as-proposed, mark.focus-hl.lab-finalized-as-proposed { background: rgba(30, 122, 58, .32); }
.hl.lab-finalized-with-modifications, mark.focus-hl.lab-finalized-with-modifications { background: rgba(180, 120, 20, .34); }
.hl.lab-other, mark.focus-hl.lab-other { background: rgba(107, 107, 104, .35); }
@media (max-width: 640px) {
header { padding: 8px 10px; gap: 8px; }
header .title { flex-basis: 100%; }
@@ -119,12 +187,17 @@
.toolbar input#find { width: 130px; }
.toolbar select#file { max-width: 160px; }
#viewer { padding: 10px 6px 30px; gap: 10px; }
#stage { flex-direction: column; }
#focuspanel { flex: 0 0 38%; border-left: 0; border-top: 1px solid var(--border); }
}
</style>
</head>
<body>
<header>
<h1>Library Document</h1>
<label class="proto" for="protocol">Protocol
<select id="protocol" title="Review protocol"></select>
</label>
<span class="title" id="title"></span>
<a class="nav" href="/">Chat</a>
<a class="nav" href="/ui/search">Search</a>
@@ -153,7 +226,11 @@
<a class="dl" id="download" href="#" download>download</a>
</div>
<div id="progress"><div id="bar"></div></div>
<div id="viewer" tabindex="0"></div>
<div id="stage">
<div id="viewer" tabindex="0"></div>
<aside id="focuspanel" aria-label="Annotations"></aside>
</div>
<div id="focusbar" role="toolbar" aria-label="Apply a highlight label" hidden></div>
<script type="module">
// Everything below reads only this page's own URL and the JSON from
@@ -283,6 +360,15 @@
return { run, step };
}
async function mountFocusPane(goToPage) {
try {
const { mountFocus } = await import('/ui/focus.js');
await mountFocus({ key, file: current.name, kind: renderer, viewer, goToPage });
} catch (e) {
console.warn('focus:', e && e.message || e);
}
}
function seedFind(find) {
if (!wantQuery) return;
const probe = wantQuery.split(/\s+/).slice(0, 6).join(' ');
@@ -350,6 +436,7 @@
const find = domFind(pre);
nav.goTo(1, false);
seedFind(find);
await mountFocusPane(n => nav.goTo(n, false));
return;
}
@@ -413,6 +500,7 @@
const hashPage = parseInt((location.hash.match(/page=(\d+)/) || [])[1] || '0', 10);
nav.goTo(hashPage || wantPage, false);
seedFind(find);
await mountFocusPane(n => nav.goTo(n, false));
return;
}
@@ -503,6 +591,9 @@
}
async function paintText(p, vp) {
const unit = p.page.getViewport({ scale: 1 });
p.el.dataset.pw = String(unit.width);
p.el.dataset.ph = String(unit.height);
if (p.textLayer) p.textLayer.remove();
const layer = document.createElement('div');
layer.className = 'textLayer';
@@ -517,6 +608,7 @@
// no text layer (scanned page) — the canvas alone is fine
}
if (findState.term) highlight(p);
p.el.dispatchEvent(new CustomEvent('focus-page', { bubbles: true }));
}
// Lazy rendering: pages within ~1.5 screens of the viewport render,
@@ -665,6 +757,7 @@
$('find').value = probe;
runFind(probe);
}
await mountFocusPane(n => goTo(n, false));
}
show().catch(e => console.warn('viewer:', e && e.message || e));
</script>

130
tests/focus/anchor.test.mjs Normal file
View File

@@ -0,0 +1,130 @@
import { test } from "node:test";
import { equal as eq } from "node:assert/strict";
import { CONTEXT_CHARS, reanchor, selectionSelectors } from "../../src/llm/web/focus_anchor.mjs";
test("a unique quote round-trips through its offsets", () => {
const text = "alpha we support the proposal beta";
const start = text.indexOf("we support the proposal");
const sel = selectionSelectors(text, start, start + "we support the proposal".length);
eq(sel.quote, "we support the proposal");
eq(sel.prefix, "alpha ");
eq(sel.suffix, " beta");
eq(sel.start_char, start);
const hit = reanchor(text, sel);
eq(hit.orphaned, false);
eq(hit.how, "position");
eq(hit.start, start);
eq(text.slice(hit.start, hit.end), sel.quote);
});
test("prefix and suffix stay within 32 characters", () => {
const text = "0123456789".repeat(6) + "QUOTE" + "abcdefghij".repeat(6);
const start = text.indexOf("QUOTE");
const sel = selectionSelectors(text, start, start + "QUOTE".length);
eq(CONTEXT_CHARS, 32);
eq(sel.prefix.length, 32);
eq(sel.suffix.length, 32);
eq(sel.prefix, text.slice(start - 32, start));
eq(sel.suffix, text.slice(start + 5, start + 5 + 32));
});
test("a repeated quote is disambiguated by prefix and suffix", () => {
const text = "before LEFT QUOTE after middle RIGHT QUOTE end";
const start = text.lastIndexOf("QUOTE");
const sel = selectionSelectors(text, start, start + "QUOTE".length);
const hit = reanchor(text, {
quote: "QUOTE",
prefix: sel.prefix,
suffix: sel.suffix,
start_char: null,
end_char: null,
});
eq(hit.orphaned, false);
eq(hit.how, "quote");
eq(hit.start, start);
eq(text.slice(hit.start, hit.end), "QUOTE");
});
test("stale offsets fall through to the quote", () => {
const text = "xxxx hello yyyy";
const hit = reanchor(text, {
quote: "hello",
prefix: "xxxx ",
suffix: " yyyy",
start_char: 0,
end_char: 5,
});
eq(hit.how, "quote");
eq(hit.start, text.indexOf("hello"));
});
test("whitespace differences still count as the quote", () => {
const text = "we\nsupport the proposal today";
const hit = reanchor(text, {
quote: "we support the proposal",
prefix: "",
suffix: " today",
start_char: null,
end_char: null,
});
eq(hit.orphaned, false);
eq(hit.how, "quote");
eq(text.slice(hit.start, hit.end).replace(/\s+/g, " "), "we support the proposal");
});
test("a slight text change is a fuzzy match", () => {
const text = "we suport the proposal today";
const hit = reanchor(text, {
quote: "we support the proposal",
prefix: "",
suffix: " today",
start_char: null,
end_char: null,
});
eq(hit.orphaned, false);
eq(hit.how, "fuzzy");
eq(text.slice(hit.start, hit.end), "we suport the proposal");
});
test("an absent quote is orphaned", () => {
const hit = reanchor("nothing here", {
quote: "missing sentence",
prefix: "no ",
suffix: " where",
start_char: 0,
end_char: 4,
});
eq(hit.orphaned, true);
eq(hit.how, "orphaned");
eq(hit.start, null);
eq(hit.end, null);
});
test("unicode quotes round-trip", () => {
const text = "The naïve café — 提案 stands.";
const quote = "naïve café — 提案";
const start = text.indexOf(quote);
const sel = selectionSelectors(text, start, start + quote.length);
eq(sel.quote, quote);
const hit = reanchor(text, {
quote,
prefix: sel.prefix,
suffix: sel.suffix,
start_char: null,
end_char: null,
});
eq(hit.orphaned, false);
eq(text.slice(hit.start, hit.end), quote);
});
test("a bad range is rejected", () => {
let threw = false;
try {
selectionSelectors("abc", 2, 1);
} catch (e) {
threw = true;
eq(e.message, "bad range");
}
eq(threw, true);
});

67
tests/focus/test_js.py Normal file
View File

@@ -0,0 +1,67 @@
"""The focus JS unit tests (``tests/focus/*.test.mjs``) under pytest.
The anchor module is an ES module. Node runs that from 22.7 on. This
test skips when the host has no such node; the gate is the docker run
docker run --rm -v /home/kert/stack:/w:ro -w /w node:22-slim \\
sh -c 'node --test tests/focus/*.test.mjs'
which must print ``# fail 0``.
"""
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
MIN_NODE = (22, 7)
SKIP_REASON = "node ≥ 22.7 not on PATH; run NODE"
def node_version(text: str) -> tuple[int, int] | None:
"""``(major, minor)`` from ``node --version`` output such as ``v22.7.0``."""
m = re.match(r"\s*v(\d+)\.(\d+)", text or "")
return (int(m.group(1)), int(m.group(2))) if m else None
def node_ok(text: str) -> bool:
v = node_version(text)
return v is not None and v >= MIN_NODE
def test_node_gate() -> None:
assert node_version("v22.7.0\n") == (22, 7)
assert node_ok("v22.7.0") and node_ok("v24.1.3") and node_ok("v23.0.0")
assert not node_ok("v22.6.9") and not node_ok("v20.18.0")
assert not node_ok("") and not node_ok("node: not found")
def test_focus_js_unit_tests() -> None:
node = shutil.which("node")
if node is None:
pytest.skip(SKIP_REASON)
probe = subprocess.run(
[node, "--version"], capture_output=True, text=True, check=False
)
if not node_ok(probe.stdout):
pytest.skip(SKIP_REASON)
files = sorted(
str(p.relative_to(ROOT)) for p in (ROOT / "tests/focus").glob("*.test.mjs")
)
assert files, "no tests/focus/*.test.mjs"
r = subprocess.run(
[node, "--test", *files],
cwd=ROOT,
capture_output=True,
text=True,
timeout=300,
check=False,
)
assert r.returncode == 0 and "# fail 0" in r.stdout, (
r.stdout[-6000:] + r.stderr[-2000:]
)

View File

@@ -479,6 +479,10 @@ class TestPdfViewer:
)
assert client.get("/ui/vendor/../api.py").status_code in (404, 400)
assert client.get("/ui/vendor/evil.mjs").status_code == 404
assert "import('/ui/focus.js')" in html
assert client.get("/ui/focus.js").status_code == 200
assert client.get("/ui/focus_anchor.mjs").status_code == 200
assert client.get("/ui/evil.js").status_code == 404
def test_list_and_serve(self, tmp_path, monkeypatch):
import llm.api as api