diff --git a/README.md b/README.md index 1840d4e..10703b2 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,16 @@ remains at `#/pcp-reading-guide`. The algebraic proof is due to Amireddy, Behera, Srinivasan, Sudan and Willumsgaard; Lee wrote the Lean formalization. AI agents wrote the three explanations under Will Cook's direction. -On a desktop, the paper is on the left and the proof diagram is on the right. -As you scroll, the diagram highlights the step linked to the passage you are -reading. Click a statement or diagram card to see its Lean code. Use **Back** +On a desktop, each visit opens with the paper on the left and the proof pane on +the right: the graph above the Lean, or beside it on a very wide screen. Drag +the divider between the paper and the proof to give either side more room, and +the handle between the graph and the Lean to share the pane; both are +remembered. Closing the proof pane lasts for that visit. +As you scroll, the proof pane follows the linked passage you are reading: the +Lean shows its declaration, and the graph shows that declaration with what it +uses. Choosing another card or result holds the graph there until you choose +**Follow the paper again**. Click a statement or diagram +card to see its Lean code. Use **Back** to return to the diagram without losing your place, or the **Graph / Lean** toggle to choose what stays beside the paper. diff --git a/tests/journey.py b/tests/journey.py index 1272d5b..c7f28b0 100644 --- a/tests/journey.py +++ b/tests/journey.py @@ -106,8 +106,8 @@ def lean_open(page: Page) -> bool: GRAPH_FIRST = """ try { - if (!localStorage.getItem('proof-reader-pane-2')) - localStorage.setItem('proof-reader-pane-2', JSON.stringify({graph: true, lean: false, share: 0, sideShare: 0})); + if (!localStorage.getItem('proof-reader-pane-3')) + localStorage.setItem('proof-reader-pane-3', JSON.stringify({graph: true, lean: false, share: 0, sideShare: 0})); } catch { /* a frame with no storage, such as the PDF's: nothing to set there */ } """ @@ -146,6 +146,93 @@ def opening(page: Page, url: str) -> None: check(page.evaluate("location.hash") == hashes[0], "and stays in the address bar") +def reopen_proof(page: Page, url: str) -> None: + """A previously closed proof pane must not hide the split on later visits.""" + print("Reopening the proof pane") + page.goto(f"{url}#/{SLUG}", wait_until="load") + page.locator(".proof").wait_for() + page.evaluate("""localStorage.setItem('proof-reader-pane-3', JSON.stringify({ + graph: false, lean: false, share: 0.3, sideShare: 0.4 + }))""") + for slug in ("pcp-exposition", "pcp-specialist", "pcp-full-argument", "pcp-reading-guide", SLUG): + page.goto(f"{url}#/{slug}", wait_until="load") + page.locator(".proof").wait_for() + paper = page.locator(".left").bounding_box() + proof = page.locator(".proof").bounding_box() + check(paper is not None and proof is not None + and proof["x"] >= paper["x"] + paper["width"] - 1 + and abs(proof["y"] - paper["y"]) <= 1, + f"{slug} opens beside its proof despite a saved closed pane") + check(not lean_open(page), "the saved Graph mode is preserved") + page.locator(".proof").get_by_role("button", name="Close", exact=True).click() + page.locator(".proof").wait_for(state="hidden") + check(True, "Close still hides the proof for the current visit") + page.reload(wait_until="load") + page.locator(".proof").wait_for() + check(True, "reloading opens the proof pane again") + check(page.evaluate("""() => { + const layout = JSON.parse(localStorage.getItem('proof-reader-pane-3')); + return layout.share === 0.3 && layout.sideShare === 0.4 && layout.lean === false + && !Object.hasOwn(layout, 'graph'); + }"""), "mode and split sizes persist without a saved closed pane") + + +def graph_follows(page: Page, url: str, shots: Path | None) -> None: + """A paper with many results: the graph shows the statement being read, and the + divider between paper and proof moves, is remembered and can be put back.""" + print("The graph follows the reading") + page.goto(f"{url}#/pcp-exposition", wait_until="load") + page.locator(".nearmap__card.is-head").first.wait_for() + head = lambda: page.eval_on_selector_all(".nearmap__card.is-head .nearmap__title", "els => els.map(e => e.textContent)") + check(page.locator(".proof__graph").bounding_box()["height"] > 150 and lean_open(page), + "a fresh visit opens with the graph above the Lean") + check(page.locator(".claims--many select").count() == 1, "many results share one line with a menu") + seen = set() + for _ in range(8): + page.mouse.move(400, 500) + page.mouse.wheel(0, 2200) + page.wait_for_timeout(700) + heads = head() + seen.add(tuple(heads)) + if "Following" in caption(page) and heads: + check(any(title in caption(page) for title in heads), f"the graph shows the statement being read: {heads[0]}") + check(len(seen) >= 4, f"the graph changed {len(seen)} times as the paper scrolled") + page.get_by_role("button", name="Next result").click() + page.wait_for_timeout(300) + held = head() + check(page.locator(".graph__paused").count() == 1, "choosing a result holds the graph there") + page.mouse.move(400, 500) + page.mouse.wheel(0, -4000) + page.wait_for_timeout(900) + check(head() == held, "a held graph stays put while the paper scrolls") + page.get_by_role("button", name="Follow the paper again").click() + wait_until(page, lambda: head() != held and page.locator(".graph__paused").count() == 0, "following again returns to the statement being read") + shot(page, shots, "05-graph-follows") + width = lambda: page.locator(".left").bounding_box()["width"] + start = width() + grip = page.locator(".papersplit").bounding_box() + page.mouse.move(grip["x"] + 13, 400) + page.mouse.down() + page.mouse.move(grip["x"] - 107, 400, steps=6) + page.mouse.up() + page.wait_for_timeout(300) + moved = width() + check(abs((start - moved) - 120) < 4, f"dragging the divider narrows the paper by the drag ({start:.0f} to {moved:.0f})") + page.reload(wait_until="load") + page.locator(".papersplit").wait_for() + page.wait_for_timeout(600) + check(abs(width() - moved) < 2, "the divider's place survives a reload") + page.locator(".papersplit").dblclick() + page.wait_for_timeout(300) + check(abs(width() - start) < 2, "a double click puts the divider back") + page.locator(".papersplit").focus() + page.keyboard.press("ArrowRight") + page.wait_for_timeout(200) + check(width() > start + 20, "the arrow keys move the divider") + page.keyboard.press("Home") + check(page.evaluate("document.documentElement.scrollWidth <= innerWidth"), "no sideways scroll after resizing") + + def active(page: Page) -> str: return page.evaluate("document.querySelector('[data-paper-pane] .q.is-active')?.dataset.p ?? ''") @@ -931,7 +1018,9 @@ def rested(want: dict, how: str) -> None: reload(page) page.wait_for_selector(".sheet__text .q", state="attached") page.wait_for_timeout(400) - check(page.locator(".proof").count() == 0, "and stays closed") + check(page.locator(".proof__graph").is_visible(), "a reload restores the side-by-side view") + page.locator(".proof__close").click() + page.locator(".proof").wait_for(state="hidden") page.locator(".bar__open").click() wait_until(page, lambda: page.locator(".proof__graph").is_visible(), "and opens again") @@ -1149,7 +1238,7 @@ def monitors(page: Page, url: str, shots: Path | None, size: tuple[int, int]) -> page.wait_for_selector(".decl") page.wait_for_timeout(1400) check(page.evaluate("document.documentElement.scrollWidth <= innerWidth"), "no sideways scroll") - check(page.locator(".proof[data-side]").count() == (1 if w >= 1920 else 0), "stacked or side by side by the room on the right page") + check(page.locator(".proof[data-side]").count() == (1 if w >= 2560 else 0), "stacked or side by side by the room on the right page") box = page.locator(".proof").bounding_box() check(box["width"] >= 500, f"the right page is {box['width']:.0f}px wide") shot(page, shots, f"30-{w}") @@ -1379,6 +1468,12 @@ def main() -> int: context = browser.new_context(viewport={"width": 1440, "height": 790}) opening(context.new_page(), url) context.close() + context = browser.new_context(viewport={"width": 1440, "height": 790}) + reopen_proof(context.new_page(), url) + context.close() + context = browser.new_context(viewport={"width": 1440, "height": 790}) + graph_follows(context.new_page(), url, args.shots) + context.close() context = graph_first(browser.new_context(viewport={"width": 1440, "height": 790})) journey(context.new_page(), url, args.shots) context.close() diff --git a/tests/test_markdown.py b/tests/test_markdown.py index 0843adc..b603d8f 100644 --- a/tests/test_markdown.py +++ b/tests/test_markdown.py @@ -102,6 +102,42 @@ def test_markdown_formatting_is_rendered_without_rewording(self): self.assertNotIn("p", built["code"]) self.assertEqual(self.path.read_text(), source) + def test_quote_html_sets_formulas_as_the_reading_copy_does(self): + source = ("## Section\n\nThen $\\operatorname{Val}$ vanishes on $H^m$ for **every** `x`:\n" + "$$\\sum_i Z_H(X_i) = 0.$$\n") + quote = source.split("\n\n", 1)[1].rstrip("\n") + done, passages = self.resolve(source, quote) + built = reading.build_markdown(done, "test", passages, [], "https://example.org/guide.md") + markup = built["quote_html"]["p"] + self.assertIn('class="katex"', markup) + self.assertIn('class="katex-display"', markup) + self.assertIn("every", markup) + self.assertIn("", markup) + # Inline: no paragraph, no reading-copy display block, no placeholder left. + self.assertNotRegex(markup, r"<(?:p|div)\b") + self.assertNotIn('data-m="', markup) + # Each formula is exactly the one the reading copy shows. + for formula in done["math"]: + self.assertIn(formula, markup) + self.assertIn(formula, built["html"]) + # The plain text is unchanged: labels, search and the text checks read it. + self.assertTrue(built["display_quotes"]["p"].startswith("Then Val")) + self.assertNotIn("<", built["display_quotes"]["p"]) + + def test_quote_html_keeps_no_link_inside_it(self): + done, passages = self.resolve("## Section\n\nSee [the source](code.lean) for $x$.\n", "See [the source](code.lean) for $x$.") + built = reading.build_markdown(done, "test", passages, [], "https://example.org/guide.md") + self.assertNotRegex(built["quote_html"]["p"], r"x', ["x"]) + def test_rendered_collision_inside_one_block_fails(self): done, passages = self.resolve("## Section\n\nA **word** and a `word`.\n", "**word**") with self.assertRaisesRegex(reading.ReadingError, "rendered quote found 2 times"): @@ -132,6 +168,7 @@ def test_fenced_quote_stays_code_and_has_no_pdf_coordinates(self): self.assertEqual(passages[0]["rects"], []) self.assertEqual(built["pages"], 0) self.assertNotIn('class="pg"', built["html"]) + self.assertEqual(built["quote_html"]["p"], "def x_y : Nat := 0") def test_dotted_heading_links_use_reader_routes(self): source = "## 3. The definitions\n\n[Continue](#4-the-pcp-theorem).\n\n## 4. The PCP theorem\n\nIt holds.\n" @@ -240,6 +277,8 @@ def only_node(args, **kwargs): self.assertEqual(edition["paper"]["sizes"], []) self.assertEqual(edition["passages"][0]["quote"], "Here is Demo.statement.") self.assertEqual(edition["passages"][0]["source_quote"], "Here is `Demo.statement`.") + self.assertEqual(edition["passages"][0]["quote_html"], + 'Here is Demo.statement.') self.assertEqual(edition["shelf"]["example"]["page_label"], "") self.assertEqual(json.loads((paper.PUBLIC / "index.json").read_text())["papers"][0]["source_kind"], "markdown") diff --git a/tests/test_paper.py b/tests/test_paper.py index 4ee9555..9dee13b 100644 --- a/tests/test_paper.py +++ b/tests/test_paper.py @@ -490,6 +490,11 @@ def test_the_three_examples_in_order(self): roles = {p["id"]: p["role"] for p in links["passages"]} self.assertEqual([e["role"] for e in examples], [roles[e["id"]] for e in examples]) + def test_a_pdf_sourced_paper_has_no_set_quotes(self): + passages = self.built["passages"] + self.assertTrue(passages) + self.assertFalse([p["id"] for p in passages if "quote_html" in p or p.get("source_quote")]) + def test_each_example_is_its_paragraph(self): page = reading.parse(self.built["reading_html"]) for example in self.built["shelf"]["examples"]: diff --git a/tools/paper.py b/tools/paper.py index f9ca157..938cd4f 100644 --- a/tools/paper.py +++ b/tools/paper.py @@ -749,8 +749,11 @@ def split(names: list[str], statement: bool, kind_of) -> list[str]: setting = reading_copy.build_markdown(data["markdown_render"], slug, data["passages"], names, config["paper"].get("url", ""), links.get("name_sections"), config.get("reading", {}).get("companions")) display_quotes = setting.pop("display_quotes") + quote_html = setting.pop("quote_html") for passage in data["passages"]: passage["quote"] = display_quotes[passage["id"]] + # The same words set as the reading copy sets them; `quote` stays the plain text. + passage["quote_html"] = quote_html[passage["id"]] elif (data["folder"] / "paper.md").is_file(): setting = reading_copy.build(data["folder"], slug, data["passages"], names, data["words"], config.get("reading", {}), links) diff --git a/tools/reading.py b/tools/reading.py index 9a68d6b..e8b54ec 100644 --- a/tools/reading.py +++ b/tools/reading.py @@ -141,6 +141,33 @@ def locate_markdown(page: Page, done: dict, passages: list[dict]) -> tuple[dict, return spans, visible_quotes +MATH_SPAN = re.compile(r'.*?', re.S) +DISPLAY_WRAP = re.compile(r'
(.*?)
', re.S) +INLINE_ONLY = re.compile(r" str: + """A quoted passage as the reading copy sets it: the same inline Markdown and + the same KaTeX output, with no block around it and no link inside it, since + it is printed inside a blockquote or a link on the Lean page.""" + check_tags(raw) + raw = DISPLAY_WRAP.sub(r"\1", raw) + raw = re.sub(r"]*>", "", raw) + if INLINE_ONLY.search(raw): + raise ReadingError(f"passage {pid}: quoted words hold a block, which a quotation cannot show inline") + + def formula(match: re.Match) -> str: + index = int(match[1]) + if index >= len(math) or 'class="katex' not in math[index]: + raise ReadingError(f"passage {pid}: formula {index} in the quote was not typeset") + return math[index] + + out = MATH_SPAN.sub(formula, raw) + if re.search(r"[\ue000-\ue003]", out) or 'data-m="' in out: + raise ReadingError(f"passage {pid}: a formula in the quote was left unset") + return out + + def numbered_ranges(ranges: list[tuple[str, int]], outline: list[dict]) -> list[tuple[str, int]]: """An unnumbered subheading belongs to the numbered section above it, so that `name_sections` can name section 3 and cover its subheadings too.""" @@ -195,6 +222,7 @@ def link(match): "heading_aliases": done["heading_aliases"], "words": len(page.visible.split()), "formulas": len(done["math"]), "pages": 0, "order": sorted(spans, key=lambda pid: spans[pid][0]), "code": code, "display_quotes": quotes, + "quote_html": {p["id"]: quote_markup(p["id"], done["quote_html"][p["id"]], done["math"]) for p in passages}, "paragraphs": {pid: paragraph(page, start, stop, quotes[pid]) for pid, (start, stop) in spans.items()}} diff --git a/web/src/app/app.css b/web/src/app/app.css index 667840a..440d38c 100644 --- a/web/src/app/app.css +++ b/web/src/app/app.css @@ -99,7 +99,16 @@ button:disabled { cursor: default; } /* The open book */ .spread { --rail-width: 212px; position: relative; flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr); justify-content: center; background: var(--desk); } .spread.has-right { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } -.spread--reading.has-right { grid-template-columns: var(--rail-width) minmax(0, clamp(480px, calc(44vw - 26px), 1000px)) minmax(0, 1fr); column-gap: 0; } +.spread--reading { --paper-w: clamp(480px, calc(44vw - 26px), 1000px); } +.spread--reading.has-right { grid-template-columns: var(--rail-width) minmax(0, var(--paper-w)) minmax(0, 1fr); column-gap: 0; } +/* The divider stands in the gutter between the paper and the proof (after the Quartic Reader). */ +.papersplit { position: absolute; z-index: 13; top: 0; bottom: 0; left: calc(var(--rail-width) + var(--paper-w)); width: 26px; display: grid; place-items: center; cursor: col-resize; touch-action: none; } +.papersplit span { width: 3px; height: 44px; border-radius: 2px; background: var(--rule-strong); opacity: 0; transition: opacity var(--t-hover) var(--ease-out), background-color var(--t-hover) var(--ease-out); } +.spread:hover .papersplit span { opacity: 1; } +.papersplit:hover span, .papersplit:focus-visible span, .spread.is-resizing .papersplit span { opacity: 1; background: var(--thread); } +.papersplit:focus-visible { outline: 2px solid var(--thread); outline-offset: -4px; } +.spread.is-resizing { user-select: none; cursor: col-resize; } +.spread.is-resizing .threads { visibility: hidden; } .spread--reading.has-right .proof { margin-left: 26px; } .left { position: relative; min-width: 0; min-height: 0; display: flex; flex-direction: column; } .left > * { flex: 1; min-height: 0; } @@ -392,7 +401,7 @@ a.source__ref:hover { color: var(--lit); text-decoration: underline solid; } } @media (min-width: 2100px) { .spread { --rail-width: 260px; } - .spread--reading.has-right { grid-template-columns: var(--rail-width) minmax(0, 1000px) minmax(0, 1fr); } + .spread--reading { --paper-w: 1000px; } .lean-code { font-size: 0.875rem; } .rail { font-size: var(--fs-ui); } } @@ -457,3 +466,26 @@ a.source__ref:hover { color: var(--lit); text-decoration: underline solid; } .nearmap__key { margin: 0; padding: 6px 16px 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: var(--fs-sm); color: var(--ink-2); } .proof:has(.graph--near) .proof__key { display: none; } @media (prefers-reduced-motion: no-preference) { .nearmap__card, .nearmap__line { transition: opacity 120ms; } } + +/* Many results: one line names the result on show, with a menu and a step either way. */ +.claims--many { flex-wrap: nowrap; align-items: center; gap: 6px; padding: 5px 12px 5px 16px; border-bottom: 1px solid var(--rule); } +.claims__pick { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; } +.claims__count { flex: none; color: var(--ink-2); font-variant-numeric: tabular-nums; } +.claims__pick select { flex: 1; min-width: 0; min-height: 28px; padding: 0 28px 0 8px; font: inherit; font-weight: 600; color: var(--ink); text-overflow: ellipsis; background-color: var(--sheet); border: 1px solid var(--rule-control); border-radius: var(--radius-s); cursor: pointer; } +.claims__pick select:hover { border-color: var(--ink-3); } +.claims--many .claims__step { flex: none; min-width: 28px; padding: 0; font-size: var(--fs-base); line-height: 1; color: var(--ink); border: 1px solid var(--rule-control); } +.claims--many .claims__step:hover:not(:disabled) { border-color: var(--ink-3); } +.claims--many .claims__step:disabled { color: var(--ink-3); opacity: 0.5; cursor: default; } +.claims__pick select:focus-visible, .claims__step:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } +/* The drawing changes with the statement being read: a short dissolve says it is a new drawing. */ +@media (prefers-reduced-motion: no-preference) { + .nearmap__world { animation: nearmap-arrive 180ms cubic-bezier(0.16, 1, 0.3, 1) backwards; } + @keyframes nearmap-arrive { from { opacity: 0; } } +} +/* A Lean name stays on one line inside its card; the whole name is in its tooltip and in the Lean. */ +.nearmap__raw { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.nearmap__key { display: flex; flex-wrap: wrap; gap: 2px 18px; white-space: normal; } +.nearmap__shapes { color: var(--ink-3); } +.nearmap__shapes .key-shape { margin-left: 10px; } +.nearmap__shapes .key-shape:first-child { margin-left: 0; } +.nearmap__alone { max-width: 46ch; margin: 4px auto 0; padding: 0 16px; text-align: center; font-size: var(--fs-sm); line-height: 1.45; color: var(--ink-2); text-wrap: pretty; } diff --git a/web/src/app/edition.ts b/web/src/app/edition.ts index b29a321..52649a8 100644 --- a/web/src/app/edition.ts +++ b/web/src/app/edition.ts @@ -10,6 +10,8 @@ export interface Passage { /** It is a line of code in the paper, not a sentence. */ code?: boolean; quote: string; + /** The same words set as the reading copy sets them, formulas typeset. Markdown papers only. */ + quote_html?: string; lean: string[]; /** Null for Markdown; source_lines give its location. */ page: number | null; diff --git a/web/src/paper/PaperPage.tsx b/web/src/paper/PaperPage.tsx index caa35eb..959aaa2 100644 --- a/web/src/paper/PaperPage.tsx +++ b/web/src/paper/PaperPage.tsx @@ -24,6 +24,7 @@ import { ProofPage, readLayout, saveLayout, type Layout } from "../proof/ProofPa import { Contents } from "./Contents"; import { ReadingPane } from "./ReadingPane"; import { Threads } from "./Threads"; +import { PaperSplit } from "./PaperSplit"; import { DWELL_MS, type Follow, type PaperHandle, type Pointed, type Target, type Zone } from "./reading-line"; // The paper comes first. The PDF, the map and the Lean page each load when they are wanted. @@ -684,7 +685,8 @@ export function PaperPage({ edition }: { edition: Edition }) { if (shown.mode === "after") return <>{hereLabel ? `No statement in ${hereLabel} is linked to this Lean.` : "No statement here is linked to this Lean."} The linked statements are in {sectionLabel(firstTie)} to {sectionLabel(lastSection)}.; if (shown.mode === "between") return <>No statement at this line. The last was {name}.; if (shown.mode === "start") return <>Before the first statement, in {sectionLabel(firstTie)}. Showing the main claim.; - return <>Following the {noun(edition)}: {stepView.title}; + // The statement by its plain name and section; its exact place is under "In the paper". + return <>Following the {noun(edition)}: {name && stepView.passage ? `${name}, ${sectionLabel(stepView.passage.section)}` : stepView.title}; })(); const backButton = entry.back && ; @@ -908,6 +910,7 @@ export function PaperPage({ edition }: { edition: Edition }) { )} /> )} + {wide && showRight && edition.reading && } {wide && showRight && } diff --git a/web/src/paper/PaperSplit.tsx b/web/src/paper/PaperSplit.tsx new file mode 100644 index 0000000..3ad8f85 --- /dev/null +++ b/web/src/paper/PaperSplit.tsx @@ -0,0 +1,141 @@ +// The divider between the paper and the proof. Drag it, or use the arrow keys, to give +// either side more of the window; a double click puts it back. The choice is remembered. +// Adapted from the Quartic Reader's ReaderSplit (itself after ProofPage's handle here): +// pointer capture, one CSS property written while dragging, a persisted share. + +import { useLayoutEffect, useRef, useState } from "react"; + +const KEY = "proof-reader-paper-share-1"; +/** The narrowest either side may become, in pixels. */ +const MIN_PAPER = 420; +const MIN_PROOF = 420; +const GUTTER = 26; + +function stored(): number | null { + try { + const n = Number(localStorage.getItem(KEY)); + return n > 0.15 && n < 0.85 ? n : null; + } catch { + return null; + } +} + +export function PaperSplit() { + // The paper's share of the window; none until the reader chooses one. + const [share, setShare] = useState(stored); + const [now, setNow] = useState(44); + const handle = useRef(null); + // The open book this divider stands in. Read from the handle: a parent's ref is not yet + // set when this component's first layout effect runs. + const root = { get current() { return handle.current?.closest(".spread") ?? null; } }; + + const bounds = () => { + const el = root.current; + const width = el?.clientWidth || window.innerWidth; + const rail = el ? parseFloat(getComputedStyle(el).getPropertyValue("--rail-width")) || 0 : 0; + return { width, low: MIN_PAPER / width, high: Math.max(MIN_PAPER / width, (width - rail - GUTTER - MIN_PROOF) / width) }; + }; + const write = (value: number | null) => { + const el = root.current; + if (!el) return; + if (value === null) el.style.removeProperty("--paper-w"); + else el.style.setProperty("--paper-w", `${(value * 100).toFixed(2)}%`); + }; + const apply = (value: number | null, save = true) => { + const { low, high } = bounds(); + const next = value === null ? null : Math.min(high, Math.max(low, value)); + write(next); + setShare(next); + if (!save) return; + try { + if (next === null) localStorage.removeItem(KEY); + else localStorage.setItem(KEY, String(next)); + } catch { + /* storage unavailable: the choice lasts until the page closes */ + } + }; + /** Where the divider stands now, as a share of the window, whoever put it there. */ + const measured = () => { + const el = root.current; + const paper = el?.querySelector(".left"); + return el && paper ? paper.getBoundingClientRect().width / el.clientWidth : 0.44; + }; + + useLayoutEffect(() => { + const el = root.current; + if (!el) return; + apply(share, false); + const measure = () => setNow(Math.round(measured() * 100)); + measure(); + // A narrower window may no longer hold the stored share: clamp it again. + const observer = new ResizeObserver(() => { + const kept = stored(); + if (kept !== null) { + const { low, high } = bounds(); + write(Math.min(high, Math.max(low, kept))); + } + measure(); + }); + observer.observe(el); + return () => { + observer.disconnect(); + el.style.removeProperty("--paper-w"); + el.classList.remove("is-resizing"); + }; + // The stored share is applied once; dragging writes the same property. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return ( +
apply(null)} + onKeyDown={(event) => { + if (!["ArrowLeft", "ArrowRight", "Home", "Enter"].includes(event.key)) return; + event.preventDefault(); + event.stopPropagation(); + if (event.key === "Home" || event.key === "Enter") apply(null); + else apply((share ?? measured()) + (event.key === "ArrowRight" ? 0.025 : -0.025)); + }} + onPointerDown={(event) => { + const el = root.current; + if (event.button !== 0 || !el) return; + event.preventDefault(); + const grip = event.currentTarget; + grip.setPointerCapture(event.pointerId); + el.classList.add("is-resizing"); + const rail = parseFloat(getComputedStyle(el).getPropertyValue("--rail-width")) || 0; + // Keep the point that was pressed under the pointer. + const grab = event.clientX - grip.getBoundingClientRect().left; + const move = (e: PointerEvent) => { + const box = el.getBoundingClientRect(); + apply((e.clientX - grab - box.left - rail) / box.width, false); + }; + const end = () => { + grip.removeEventListener("pointermove", move); + grip.removeEventListener("pointerup", end); + grip.removeEventListener("pointercancel", end); + el.classList.remove("is-resizing"); + // Save where the drag ended, or nothing if the press never moved. + const at = el.style.getPropertyValue("--paper-w"); + if (at) apply(parseFloat(at) / 100); + }; + grip.addEventListener("pointermove", move); + grip.addEventListener("pointerup", end); + grip.addEventListener("pointercancel", end); + }} + > +
+ ); +} diff --git a/web/src/paper/Quote.tsx b/web/src/paper/Quote.tsx new file mode 100644 index 0000000..b1d1952 --- /dev/null +++ b/web/src/paper/Quote.tsx @@ -0,0 +1,11 @@ +import type { Passage } from "../app/edition"; + +/** + * A passage's words as the reading copy sets them. `quote_html` is written by + * tools/paper.py from the same Markdown and KaTeX as the reading copy, and is + * trusted the way that copy is; a PDF-based paper has only the plain `quote`. + */ +export function Quote({ passage }: { passage: Pick }) { + if (passage.quote_html) return ; + return <>{passage.quote}; +} diff --git a/web/src/paper/StatementSheet.tsx b/web/src/paper/StatementSheet.tsx index f97a5b5..696a6d1 100644 --- a/web/src/paper/StatementSheet.tsx +++ b/web/src/paper/StatementSheet.tsx @@ -12,6 +12,7 @@ import { LeanCode, useFileLines, type LeanActions } from "../lean/code"; import { sectionLabel } from "../model/fromEdition"; import { verdictWords } from "../proof/Fidelity"; import "./sheet.css"; +import { Quote } from "./Quote"; export function StatementSheet({ edition }: { edition: Edition }) { const [files, setFiles] = useState | null>(null); @@ -103,7 +104,7 @@ function Entry({ edition, entry, files, names, act, head = false }: { edition: E

In the {word}

{passages.map((p) => (
-

{p.quote}

+

{sectionLabel(p.section)}, {passageLocation(p)}
))} diff --git a/web/src/paper/reading.css b/web/src/paper/reading.css index 8cdfdd0..7a4d5f6 100644 --- a/web/src/paper/reading.css +++ b/web/src/paper/reading.css @@ -238,3 +238,7 @@ dialog.plot p { margin: 8px 0 0; font-family: var(--font-sans); font-size: var(- border-bottom: 1px solid var(--rule); } .sheet__text th { font-weight: 600; } + +/* A passage quoted on the Lean page or a statement sheet, set as the reading copy sets it. */ +.quote-set .katex { font-size: 1.02em; text-rendering: auto; } +.quote-set .katex-display { display: block; margin: 0.3em 0; overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; } diff --git a/web/src/proof/DeclBlock.tsx b/web/src/proof/DeclBlock.tsx index 9b0c08b..3e84ba3 100644 --- a/web/src/proof/DeclBlock.tsx +++ b/web/src/proof/DeclBlock.tsx @@ -8,6 +8,7 @@ import { DeclLink, LeanCode, useFileLines, type LeanActions } from "../lean/code import { isType, sectionLabel, shapeOf } from "../model/fromEdition"; import { routeHref } from "../app/router"; import { FidelityBlock } from "./Fidelity"; +import { Quote } from "../paper/Quote"; export const KIND_WORDS: Record = { theorem: "Theorem", @@ -176,7 +177,7 @@ export function DeclBlock({ edition, d, passage, exact, open, onToggle, onPassag onPassage(p.id); }} > - {sectionLabel(p.section)}, {passageLocation(p)} {p.quote} + {sectionLabel(p.section)}, {passageLocation(p)} ))} diff --git a/web/src/proof/LeanPage.tsx b/web/src/proof/LeanPage.tsx index d24e471..9fa2283 100644 --- a/web/src/proof/LeanPage.tsx +++ b/web/src/proof/LeanPage.tsx @@ -11,6 +11,7 @@ import { READING_LINE } from "../paper/reading-line"; import { DeclBlock, KIND_WORDS, list } from "./DeclBlock"; import { AllChecks, FidelityLines, HowMade } from "./Fidelity"; import { MadeLink } from "./MadeLink"; +import { Quote } from "../paper/Quote"; export interface Step { /** Names the view, so its scroll can be kept while something else is previewed. */ @@ -153,7 +154,7 @@ export const LeanPage = memo(function LeanPage({ ref, edition, step, open, start {step.passage && (
{step.title &&

{step.title}

} -
{step.passage.quote}
+
{step.decls.length > 1 && (