skimproof 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
skimproof/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Skim the text. Keep the proof."""
2
+
3
+ from .api import Bundle, Quote, Result, Statement, Task, build, capture, finish, skim
4
+ from .bundle import SkimError
5
+ from .checks import Issue
6
+
7
+ __version__ = "0.8.0"
8
+ __all__ = ["Bundle", "Issue", "Quote", "Result", "SkimError", "Statement", "Task", "build", "capture", "finish", "skim"]
skimproof/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
skimproof/api.py ADDED
@@ -0,0 +1,258 @@
1
+ """skimproof from Python. It never calls a model: your code gives a function that does, or hands the tasks to its own agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ import re
8
+ from collections.abc import Callable, Iterable
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from urllib.parse import unquote, urlparse
13
+
14
+ from . import plan
15
+ from .bundle import SkimError, load
16
+ from .checks import Issue, brief_words, load_brief, run, todo
17
+ from .ingest import ingest
18
+ from .render import render
19
+ from .verify import write_sheets
20
+
21
+ # What a second reader found does not stop the page. The page shows it.
22
+ JUDGED = {"unverified", "unsupported", "scope", "verdict"}
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Task:
27
+ """One piece of work for a model. An agent with file tools follows `file`. Any other model answers `prompt`, and `save` writes the reply."""
28
+
29
+ bundle: Path
30
+ name: str # "01", "02", ... for a reader of one part, and "brief" for the task that writes the brief
31
+
32
+ @property
33
+ def file(self) -> Path:
34
+ return self.bundle / "task.md" if self.name == "brief" else self.bundle / "parts" / f"{self.name}.task.md"
35
+
36
+ @property
37
+ def output(self) -> Path:
38
+ return self.bundle / "brief.md" if self.name == "brief" else self.bundle / "parts" / f"{self.name}.brief.md"
39
+
40
+ @property
41
+ def prompt(self) -> str:
42
+ return plan.prompt(self.bundle, "" if self.name == "brief" else self.name)
43
+
44
+ def save(self, reply: str) -> Path:
45
+ text = reply.strip()
46
+ # A model can put the whole reply in a fence.
47
+ if m := re.fullmatch(r"```(?:markdown|md)?[ \t]*\n(\s*#.*?)\n```", text, re.DOTALL):
48
+ text = m[1].strip()
49
+ if not text:
50
+ raise SkimError(f"The model gave an empty reply for {self.output}.")
51
+ new = self.output.with_suffix(".new")
52
+ new.write_text(text + "\n", encoding="utf-8")
53
+ if self.name != "brief" and not plan.cites(new):
54
+ new.unlink()
55
+ raise SkimError(f"The reply for {self.output} cites no sentence: {text[:200]!r}")
56
+ new.replace(self.output)
57
+ return self.output
58
+
59
+ @property
60
+ def done(self) -> bool:
61
+ return self.output.exists() if self.name == "brief" else plan.cites(self.output)
62
+
63
+
64
+ class Bundle:
65
+ """A folder that `capture` wrote."""
66
+
67
+ def __init__(self, path: str | Path) -> None:
68
+ self.path = Path(path).expanduser()
69
+ if not (self.path / "source.json").exists():
70
+ raise SkimError(f"{self.path} is not a bundle, the folder that skimproof capture writes.")
71
+
72
+ def __repr__(self) -> str:
73
+ return f"Bundle({str(self.path)!r})"
74
+
75
+ @property
76
+ def source(self) -> dict:
77
+ """What was captured: `meta`, `sentences`, and `figures`."""
78
+ return load(self.path)
79
+
80
+ @property
81
+ def tasks(self) -> list[Task]:
82
+ """The work for models. All tasks but the last can run at the same time. The last one writes the brief."""
83
+ if not (self.path / "plan.json").exists():
84
+ raise SkimError(f"{self.path} has no plan. An earlier version of skimproof made it, so capture again.")
85
+ return [Task(self.path, n) for n in (*plan.readers(self.path), "brief")]
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Quote:
90
+ """A source sentence that a statement cites. `text` is word for word."""
91
+
92
+ number: int
93
+ text: str
94
+ document: str = ""
95
+ heading: str = ""
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class Statement:
100
+ text: str
101
+ kind: str # "claim", "caveat" (Keep in mind), "conflict", "code", and the kinds of a full proof
102
+ section: str
103
+ topic: str
104
+ line: int
105
+ quotes: tuple[Quote, ...]
106
+
107
+
108
+ @dataclass
109
+ class Result:
110
+ """What `build` found. `page` is None if an error stops the page."""
111
+
112
+ bundle: Bundle
113
+ page: Path | None = None
114
+ issues: list[Issue] = field(default_factory=list)
115
+ markdown: str = ""
116
+ statements: list[Statement] = field(default_factory=list)
117
+ left_out: list[Quote] = field(default_factory=list) # all source sentences that no statement cites, the riskiest first
118
+ source_words: int = 0
119
+ brief_words: int = 0
120
+
121
+ @property
122
+ def errors(self) -> list[Issue]:
123
+ return [i for i in self.issues if i.level == "error"]
124
+
125
+ @property
126
+ def warnings(self) -> list[Issue]:
127
+ return [i for i in self.issues if i.level != "error"]
128
+
129
+
130
+ def _quote(s: dict, names: dict, text: str = "") -> Quote:
131
+ return Quote(int(s["id"][1:]), text or s["text"], names.get(s.get("doc", ""), ""), s.get("under", ""))
132
+
133
+
134
+ def _statements(brief: list[dict], L: dict, by: dict, names: dict) -> list[Statement]:
135
+ units = {u["id"]: u for u in L["units"]}
136
+ out = []
137
+ for b in brief:
138
+ mine = [units[c] for c in b.get("cites", []) if c in units]
139
+ if b["kind"] not in ("sentence", "code") or b.get("draw"):
140
+ continue
141
+ quotes = {a["s"]: _quote(by[a["s"]], names, a["quote"]) for u in mine for a in u.get("anchors", []) if a.get("s") in by}
142
+ out.append(Statement(b["text"], "code" if b["kind"] == "code" else mine[0].get("type", "claim") if mine else "claim", b.get("section", ""), b.get("topic", ""), b["line"], tuple(quotes.values())))
143
+ return out
144
+
145
+
146
+ def bundle_name(target: str) -> Path:
147
+ u = urlparse(target)
148
+ last = unquote(u.path if u.scheme in ("http", "https") else target).rstrip("/").rsplit("/", 1)[-1] or u.netloc
149
+ stem = re.sub(r"\.(?:html?|md|markdown|txt|pdf)$", "", last, flags=re.IGNORECASE)
150
+ return Path((re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-") or "brief") + ".skim")
151
+
152
+
153
+ def capture(source: str | Path | Iterable[str | Path], out: str | Path | None = None, *, purpose: str = "", words: int = 0, storage_state: str | Path | None = None, ocr: str = "fast", force: bool = False) -> Bundle:
154
+ """Save links, files, or folders into a new folder, with a number for each sentence, and write the tasks. No model runs."""
155
+ targets = [str(x) for x in ([source] if isinstance(source, str | Path) else source)]
156
+ if not targets:
157
+ raise SkimError("There is nothing to capture.")
158
+ if ocr not in ("fast", "both", "none"):
159
+ raise ValueError('ocr is "fast", "both", or "none"')
160
+ d = Path(out).expanduser() if out else bundle_name(targets[0])
161
+ state = str(Path(storage_state).expanduser()) if storage_state else None
162
+ _outside_loop(lambda: ingest(targets, d, run_ocr=ocr, storage_state=state, force=force))
163
+ plan.make(d, words=words, purpose=purpose)
164
+ return Bundle(d)
165
+
166
+
167
+ def _outside_loop(work: Callable[[], object]) -> None:
168
+ """The browser cannot start in a thread with a running event loop, for example in a notebook."""
169
+ try:
170
+ asyncio.get_running_loop()
171
+ except RuntimeError:
172
+ work()
173
+ return
174
+ with ThreadPoolExecutor(1) as pool:
175
+ pool.submit(work).result()
176
+
177
+
178
+ def build(bundle: Bundle | str | Path) -> Result:
179
+ """Check the brief against its quotes, and write brief.html. No model runs."""
180
+ b = bundle if isinstance(bundle, Bundle) else Bundle(bundle)
181
+ src = b.source
182
+ r = Result(b, issues=check(b.path), source_words=src["meta"]["words"])
183
+ page = b.path / "brief.html"
184
+ if (b.path / "brief.md").exists() and not any(i.code == "json" for i in r.issues):
185
+ by, names = {s["id"]: s for s in src["sentences"]}, {x["id"]: x["name"] for x in src["meta"].get("docs", [])}
186
+ brief, L = load_brief(b.path, src)
187
+ r.markdown = (b.path / "brief.md").read_text(encoding="utf-8")
188
+ r.brief_words = brief_words(brief)
189
+ r.statements = _statements(brief, L, by, names)
190
+ r.left_out = [_quote(by[sid], names) for _, sid, _, _ in todo(b.path)]
191
+ if any(i.code not in JUDGED for i in r.errors):
192
+ # An old page and old second-reader tasks would not be those of this brief.
193
+ for old in (page, *(b.path / "verify.d").glob("*.md")):
194
+ old.unlink(missing_ok=True)
195
+ return r
196
+ write_sheets(b.path)
197
+ r.page = render(b.path)
198
+ return r
199
+
200
+
201
+ def check(d: Path, part: str = "") -> list[Issue]:
202
+ issues = run(d, part)
203
+ left = [] if any(i.code == "json" for i in issues) else todo(d, part)
204
+ # Readers of parts run at the same time, so each one has its own file.
205
+ name = f"checks-{re.sub(r'[^A-Za-z0-9_.-]', '-', part)}.md" if part else "checks.md"
206
+ (d / name).write_text("\n".join(["# Checks", *(f"- {i}" for i in issues), "", "# Source sentences that nothing uses, the riskiest first", *(f"- {score:.1f} {sid} [{why or 'plain'}] {text}" for score, sid, why, text in left)]) + "\n", encoding="utf-8")
207
+ return issues
208
+
209
+
210
+ def repair_prompt(result: Result) -> str:
211
+ """The prompt that asks a model to repair the errors of a brief that it wrote."""
212
+ lines = result.markdown.splitlines()
213
+
214
+ def said(i: Issue) -> str:
215
+ m = re.fullmatch(r"line (\d+)", i.where)
216
+ n = int(m[1]) if m else 0
217
+ return f"- {i.where}, {i.code}: {i.text}" + (f"\n > {lines[n - 1]}" if 0 < n <= len(lines) else "")
218
+
219
+ return plan.REPAIR.format(prompt=result.bundle.tasks[-1].prompt, brief=result.markdown.strip(), errors="\n".join(said(i) for i in result.errors))
220
+
221
+
222
+ def skim(source: str | Path | Iterable[str | Path], out: str | Path | None = None, *, llm: Callable[[str], str], repairs: int = 1, readers: int = 8, **options) -> Result:
223
+ """Capture, let `llm` read and write, and build. `llm` gets a prompt and returns the reply of a model. Readers of a large source call it from several threads."""
224
+ return finish(capture(source, out, **options), llm=llm, repairs=repairs, readers=readers)
225
+
226
+
227
+ def finish(bundle: Bundle | str | Path, *, llm: Callable[[str], str], repairs: int = 1, readers: int = 8) -> Result:
228
+ """The rest of a skim: the tasks that have no reply yet, the build, and the repairs. Use it again after a model call failed."""
229
+ b = bundle if isinstance(bundle, Bundle) else Bundle(bundle)
230
+ *parts, last = b.tasks
231
+ todo_now = [t for t in parts if not t.done]
232
+ if todo_now:
233
+ with ThreadPoolExecutor(max(1, min(readers, len(todo_now)))) as pool:
234
+ list(pool.map(lambda t: t.save(_ask(llm, t.prompt)), todo_now))
235
+ if not last.done:
236
+ last.save(_ask(llm, last.prompt))
237
+ r = build(b)
238
+ for _ in range(repairs):
239
+ bad = {i.where for i in r.errors}
240
+ if not bad:
241
+ break
242
+ last.save(_ask(llm, repair_prompt(r)))
243
+ new = build(b)
244
+ # A reply with only the repaired lines would remove the rest of the brief, and what is left would have no errors.
245
+ if len(new.statements) < len(r.statements) - len(bad):
246
+ last.save(r.markdown)
247
+ return build(b)
248
+ r = new
249
+ return r
250
+
251
+
252
+ def _ask(llm: Callable[[str], str], prompt: str) -> str:
253
+ reply = llm(prompt)
254
+ if inspect.iscoroutine(reply):
255
+ reply.close()
256
+ if not isinstance(reply, str):
257
+ raise TypeError(f"llm must return the reply as a str, not {type(reply).__name__}. For an async client, pass a function that waits for the reply.")
258
+ return reply
@@ -0,0 +1,56 @@
1
+ :root{--bg:#fbfaf7;--ink:#1c1b19;--soft:#625e56;--line:#e2ddd3;--card:#fffefb;--keep:#0b6474;--keep2:#e3f0f2;--off:#dcd7cb;--code:#f0ece3;--sans:ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;--mono:ui-monospace,SFMono-Regular,Menlo,monospace}
2
+ @media (prefers-color-scheme:dark){:root{--bg:#161513;--ink:#ebe8e1;--soft:#a9a399;--line:#35322d;--card:#1f1d1a;--keep:#62c4d2;--keep2:#17333a;--off:#3d3933;--code:#2a2723}}
3
+ *{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:1rem}
4
+ body{margin:0;background:var(--bg);color:var(--ink);font:18px/1.58 "Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif}
5
+ main{max-width:45rem;margin:0 auto;padding:3rem 1.2rem 5rem}
6
+ h2,h3,.meta,figcaption,.src,.map,.cut,.tag,.n,.gos,footer,table,.toc,dialog,.copy{font-family:var(--sans)}
7
+ h1{font-size:2rem;line-height:1.18;margin:0 0 .6rem;font-weight:600;text-wrap:balance}
8
+ h2{font-size:1.16rem;line-height:1.3;font-weight:680;margin:2.8rem 0 .7rem;padding-top:1.1rem;border-top:1px solid var(--line);text-wrap:balance}
9
+ h3{font-size:.96rem;line-height:1.35;font-weight:660;margin:1.7rem 0 .35rem}h2+h3{margin-top:.9rem}
10
+ a{color:var(--keep);text-underline-offset:.18em}.meta{color:var(--soft);font-size:.86rem;line-height:1.5}.meta p{margin:.15rem 0}
11
+ :focus-visible{outline:2px solid var(--keep);outline-offset:2px;border-radius:4px}
12
+ strong{font-weight:680}code{font:.84em/1 var(--mono);background:var(--code);border-radius:4px;padding:.08em .3em;overflow-wrap:anywhere;-webkit-box-decoration-break:clone;box-decoration-break:clone}pre code{background:none;padding:0;font-size:1em;line-height:inherit;overflow-wrap:normal}
13
+ code.k{white-space:nowrap}.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}
14
+
15
+ /* statements */
16
+ details.s{margin:.42rem 0}details.s>summary{list-style:none;cursor:pointer;padding:.12rem .5rem .12rem .7rem;margin-left:-.7rem;border-radius:6px}
17
+ details.s>summary::-webkit-details-marker{display:none}details.s>summary:hover,details.s[open]>summary,.hit>summary,tr.s:hover td,tr.s.open td,tr.hit td{background:var(--keep2)}
18
+ .answer h2{border-top:0;padding-top:0;margin-top:2rem}.answer details.s>summary{font-size:1.1rem;line-height:1.48}
19
+ .n{white-space:nowrap;overflow-wrap:normal;word-break:keep-all;padding:.16em .5em;border:0;border-radius:9px;background:var(--code);color:var(--soft);font-size:.66rem;font-weight:600;line-height:1.15;text-align:center;vertical-align:.18em;font-variant-numeric:tabular-nums;cursor:pointer}
20
+ summary:hover .n,details[open]>summary .n,tr.s:hover .n,tr.s.open .n{background:var(--keep);color:var(--bg)}
21
+ .tag{display:inline-block;font-size:.69rem;font-weight:620;line-height:1;color:var(--soft);border:1px solid var(--soft);border-radius:4px;padding:.2em .42em;vertical-align:.14em;margin-right:.2em;white-space:nowrap}
22
+ .run{margin:.8rem 0;padding-left:.95rem;border-left:2px solid var(--off)}.run .rl{margin:0 0 .1rem;line-height:1.2}
23
+ ul.b{margin:.5rem 0;padding-left:1.15rem}ul.b li::marker{color:var(--soft)}ul.b details.s{margin:.2rem 0}ul.b details.s>summary{margin-left:-.45rem;padding-left:.45rem}
24
+ .src{font-size:.84rem;line-height:1.5;color:var(--soft);margin:.35rem 0 .9rem;padding:.1rem 0 .1rem .85rem;border-left:2px solid var(--keep)}.src,.readout,h2,h3,summary{overflow-wrap:anywhere}td{overflow-wrap:break-word}td code{overflow-wrap:normal}.src p{margin:.4rem 0}.src q{color:var(--ink)}.src pre.qc{max-height:13rem;overflow:auto;margin:.4rem 0 .2rem;font-size:.78rem}
25
+ .gos{margin:-.1rem 0 .5rem;font-size:.82rem;display:flex;flex-wrap:wrap;gap:.1rem .9rem}
26
+
27
+ /* tables, code, figures */
28
+ .tw{position:relative;overflow-x:auto;margin:1rem 0;border:1px solid var(--line);border-radius:10px;background:linear-gradient(to right,var(--card) 30%,transparent) 0 0/36px 100% local,linear-gradient(to left,var(--card) 30%,transparent) 100% 0/36px 100% local,linear-gradient(to right,#0003,transparent) 0 0/12px 100% scroll,linear-gradient(to left,#0003,transparent) 100% 0/12px 100% scroll,var(--card);background-repeat:no-repeat}
29
+ table{border-collapse:collapse;width:100%;font-size:.83rem;line-height:1.42}th{text-align:left;font-weight:620;color:var(--soft);padding:.5rem .7rem;border-bottom:1px solid var(--line);vertical-align:bottom}td{padding:.5rem .7rem;vertical-align:top;border-bottom:1px solid var(--line)}tr.s{cursor:pointer}tbody tr:last-child td,tr.s:nth-last-child(2) td{border-bottom:0}.nc{width:1%;min-width:2.6rem;text-align:right;padding-left:0;white-space:nowrap}tr.sr td{padding-top:0;background:var(--card)}td .src{margin:.2rem 0 .4rem}td code{font-size:.92em}
30
+ pre{font:.8rem/1.5 var(--mono);background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.8rem 1rem;overflow-x:auto;margin:1rem 0}
31
+ .cb{position:relative}.copy{position:absolute;top:.45rem;right:.45rem;font-size:.72rem;color:var(--soft);background:var(--card);border:1px solid var(--line);border-radius:5px;padding:.2rem .5rem;cursor:pointer;opacity:0;transition:opacity .12s}.cb:hover .copy,.copy:focus-visible{opacity:1}@media (hover:none){.copy{opacity:1}}
32
+ figure{margin:1.4rem 0;background:var(--card);border:1px solid var(--line);border-radius:10px;overflow:hidden}figure .zoom{display:block;width:100%;padding:0;border:0;background:#fff;cursor:zoom-in}figure img{display:block;width:100%;height:auto;max-height:34rem;object-fit:contain}
33
+ figure.drawn .zoom{background:none}figure.drawn img{max-height:none}figure.drawn details.s{margin:0}figcaption{font-size:.84rem;line-height:1.45;padding:.65rem .9rem;color:var(--soft)}figcaption b{color:var(--ink);font-weight:600}figure.hit{outline:3px solid var(--keep)}
34
+ dialog{width:min(96vw,110rem);max-height:94vh;border:1px solid var(--line);border-radius:12px;padding:.6rem;background:var(--card);color:var(--ink)}dialog::backdrop{background:#000a}dialog form{text-align:right;margin:0 0 .4rem}dialog button{font:inherit;font-size:.85rem;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--ink);padding:.25rem .8rem;cursor:pointer}dialog div{overflow:auto;max-height:84vh;background:#fff}dialog img{display:block;max-width:none;margin:0 auto}dialog img.fit{max-width:100%}
35
+
36
+ /* the map of the originals */
37
+ .map{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:.9rem 1rem .8rem;margin:1.8rem 0 0;font-size:.84rem}.mh{display:flex;flex-wrap:wrap;gap:.2rem 1.2rem;align-items:baseline;color:var(--soft)}.mh b{color:var(--ink);font-weight:620;margin-right:auto}
38
+ .key i{display:inline-block;width:.75em;height:.75em;border-radius:2px;background:var(--off);margin-right:.4em}.key i.k{background:var(--keep)}
39
+ .strip{position:relative;height:34px;margin:.5rem 0 .4rem;cursor:pointer;touch-action:pan-y;background-position:0 50%;background-size:100% 18px;background-repeat:no-repeat;border-radius:3px;transition:opacity .12s}
40
+ .strip i{position:absolute;top:0;bottom:0;background:var(--ink);min-width:2px;border-radius:1px;box-shadow:0 0 0 1px var(--card)}
41
+ .rows{display:grid;grid-template-columns:fit-content(15rem) minmax(0,1fr);gap:.1rem .8rem;align-items:center;margin:.5rem 0 .4rem}.rows .strip{margin:0;height:24px;background-size:100% 12px}.dn{color:var(--soft);font-size:.92em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dn a{color:inherit;text-decoration-color:var(--line)}.dn a:hover{color:var(--keep)}
42
+ .grp{border-top:1px solid var(--line);padding:.35rem 0}.grp:first-of-type{margin-top:.6rem}.grp summary{cursor:pointer;display:grid;grid-template-columns:1fr auto;gap:0 1rem;list-style-position:inside}.grp summary b{font-weight:600}.grp summary b::before{content:"\25B8";display:inline-block;width:1em;color:var(--soft);font-weight:400;transition:transform .12s}.grp[open] summary b::before{transform:rotate(90deg) translate(.1em,.2em)}.grp summary span{color:var(--soft);font-variant-numeric:tabular-nums}.grp summary i{grid-column:1/-1;height:6px;border-radius:3px;margin-top:.3rem;background:linear-gradient(to right,var(--keep) var(--p),var(--off) var(--p))}.grp.on>summary b{color:var(--keep)}
43
+ .readout{margin:.5rem 0 0;min-height:3em;color:var(--soft);line-height:1.5}.readout b{color:var(--ink);font-weight:620}.readout q{color:var(--ink)}
44
+
45
+ /* what was left out */
46
+ .cut{font-size:.86rem;line-height:1.5;color:var(--soft)}.cut>p{margin:.45rem 0}.cut summary{cursor:pointer;color:var(--ink);padding:.22rem 0}.cut summary span{color:var(--soft);font-variant-numeric:tabular-nums;margin-left:.3em}.cut details p{margin:.3rem 0 .3rem 1.1rem;overflow-wrap:anywhere}.cut details p b{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums;margin-right:.35em}.cut .note{color:var(--ink);font-weight:600;margin-top:.8rem!important}.cut .gh{color:var(--ink);font-weight:620;margin-top:1rem}.cut pre{margin:.3rem 0 .5rem 1.1rem;max-height:10rem;font-size:.75rem}
47
+ .q{margin:.45rem 0}.q summary{cursor:pointer}.q p{margin:.2rem 0 .6rem 1.2rem;color:var(--soft)}
48
+ details.bg>summary{cursor:pointer}details.bg>summary h2{display:inline;border:0}
49
+ footer{margin-top:3rem;font-size:.78rem;color:var(--soft)}
50
+
51
+ /* contents */
52
+ .toc{font-size:.84rem;line-height:1.4;max-width:45rem;margin:0 auto;padding:1rem 1.2rem 0}.toc summary{cursor:pointer;color:var(--soft);font-weight:600}.toc ol{list-style:none;margin:.5rem 0 0;padding:0}.toc ol ol{margin:.1rem 0 .3rem .8rem}.toc li{margin:.28rem 0}.toc ol ol li{margin:.16rem 0}.toc a{color:var(--soft);text-decoration:none}.toc a:hover{color:var(--ink);text-decoration:underline}.toc span{color:var(--soft);opacity:.75;font-size:.9em;margin-left:.2em;white-space:nowrap}.toc a.now{color:var(--keep);font-weight:620}
53
+ @media (min-width:76rem){body{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,45rem) minmax(0,1fr)}main{grid-column:2;grid-row:1;margin:0;width:100%}.toc{grid-column:1;grid-row:1;justify-self:end;position:sticky;top:0;align-self:start;max-height:100vh;overflow-y:auto;width:15.5rem;margin:0;padding:3.2rem 1.2rem 2rem 1rem}.toc ol ol{display:none}.toc li.here>ol{display:block}.toc summary{list-style:none;pointer-events:none}.toc summary::-webkit-details-marker{display:none}}
54
+ @media (max-width:34rem){body{font-size:17px}main{padding-top:1.6rem}h1{font-size:1.65rem}.rows{grid-template-columns:minmax(0,1fr);gap:0}.dn{margin-top:.35rem}.grp summary{grid-template-columns:1fr}td,th{padding:.42rem .5rem}}
55
+ @media print{.map,.toc,details.s>.src,.n,.copy,#left-out{display:none}details.s>summary{padding:0}}
56
+ @media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}*{transition:none!important}}
@@ -0,0 +1,98 @@
1
+ (() => {
2
+ const $ = (s, r = document) => r.querySelector(s), $$ = (s, r = document) => [...r.querySelectorAll(s)];
3
+ const data = JSON.parse($('#data').textContent), many = data.length > 1 || !!data[0].k;
4
+ const at = new Map(), docs = new Map(data.map((d) => [d.k, d]));
5
+ for (const d of data) d.s.forEach((x, i) => at.set(x[0], [d, i]));
6
+ const strips = new Map($$('.strip').map((e) => [e.dataset.k, e])), out = $('.readout'), rest = out.textContent;
7
+ const units = (e) => new Set((e.dataset.u || '').split(' ').filter(Boolean));
8
+ const statements = $$('.s'), figures = $$('figure[data-u]');
9
+ const shares = (a, b) => [...a].some((x) => b.has(x));
10
+ const list = (n) => n.length < 2 ? String(n[0]) : n.slice(0, -1).join(', ') + ' and ' + n[n.length - 1];
11
+ const el = (tag, text, cls) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; if (cls) n.className = cls; return n; };
12
+ const say = (...parts) => out.replaceChildren(...parts);
13
+ const short = (t) => t.length > 260 ? t.slice(0, 250).replace(/\s\S*$/, '') + '…' : t;
14
+ const ids = (s) => (s.dataset.s || '').split(' ').filter((i) => at.has(i));
15
+ let pinned = null;
16
+
17
+ function light(sel) {
18
+ for (const s of strips.values()) s.replaceChildren();
19
+ for (const g of $$('.grp.on')) g.classList.remove('on');
20
+ for (const id of sel) {
21
+ const [d, i] = at.get(id), strip = strips.get(d.k), mark = el('i');
22
+ mark.style.left = 100 * i / d.s.length + '%'; mark.style.width = 100 / d.s.length + '%';
23
+ strip.append(mark); strip.closest('.grp')?.classList.add('on');
24
+ }
25
+ }
26
+ function from(s) {
27
+ const sel = ids(s); light(sel);
28
+ if (!sel.length) say('This rests on a figure, not on a sentence.');
29
+ else {
30
+ const by = new Map(); for (const id of sel) { const [d, i] = at.get(id); by.set(d, [...(by.get(d) || []), i + 1]); }
31
+ const parts = ['This comes from ']; let k = 0;
32
+ for (const [d, n] of by) {
33
+ if (k) parts.push(k === by.size - 1 ? ' and ' : ', '); k++;
34
+ parts.push(el('b', `${n.length > 1 ? 'sentences' : 'sentence'} ${list(n)}`), many ? ` of ${d.name}` : ` of ${d.s.length} in the original`);
35
+ }
36
+ say(...parts, '.');
37
+ }
38
+ const mine = units(s); for (const f of figures) f.classList.toggle('hit', shares(units(f), mine));
39
+ }
40
+ function read(id) {
41
+ const [d, i] = at.get(id), [, text, why] = d.s[i], strip = strips.get(d.k);
42
+ light([id]); strip.setAttribute('aria-valuenow', i + 1); strip.setAttribute('aria-valuetext', text);
43
+ say(el('b', `${many ? d.name + ', sentence' : 'Sentence'} ${i + 1} of ${d.s.length}`), why.startsWith('Not used') ? ', not used: ' : why ? `, left out (${why[0].toLowerCase() + why.slice(1)}): ` : ', used here: ', el('q', short(text)));
44
+ }
45
+ function clear() {
46
+ for (const f of figures) f.classList.remove('hit'); for (const s of statements) s.classList.remove('hit');
47
+ if (pinned) return pinned();
48
+ light([]); out.textContent = rest;
49
+ }
50
+ function opened(s, on) { pinned = on ? () => from(s) : null; if (on) from(s); else clear(); }
51
+ for (const s of statements) {
52
+ s.addEventListener('mouseenter', () => from(s)); s.addEventListener('mouseleave', clear); s.addEventListener('focusin', () => from(s));
53
+ if (s.tagName === 'DETAILS') s.addEventListener('toggle', () => opened(s, s.open));
54
+ else s.addEventListener('click', (e) => {
55
+ if (e.target.closest('a') || String(getSelection())) return;
56
+ const row = s.nextElementSibling, on = row.hidden; row.hidden = !on; s.classList.toggle('open', on); $('button', s).setAttribute('aria-expanded', on); opened(s, on);
57
+ });
58
+ }
59
+ for (const f of figures) {
60
+ const mine = units(f), big = $('#zoom');
61
+ f.addEventListener('mouseenter', () => { const sel = []; for (const s of statements) { const y = shares(units(s), mine); s.classList.toggle('hit', y); if (y) sel.push(...ids(s)); } light(sel); say('This figure supports the highlighted statements.'); });
62
+ f.addEventListener('mouseleave', clear);
63
+ $('.zoom', f)?.addEventListener('click', () => { const i = $('img', big), o = $('img', f); i.src = o.src; i.alt = o.alt; i.classList.add('fit'); big.showModal(); });
64
+ }
65
+ const zoom = $('#zoom'); zoom?.addEventListener('click', (e) => { if (e.target === zoom) zoom.close(); else if (e.target.tagName === 'IMG') e.target.classList.toggle('fit'); });
66
+ for (const [k, strip] of strips) {
67
+ const d = docs.get(k), total = d.s.length;
68
+ const id = (x) => { const r = strip.getBoundingClientRect(); return d.s[Math.max(0, Math.min(total - 1, Math.floor((x - r.left) / r.width * total)))][0]; };
69
+ strip.addEventListener('pointermove', (e) => { if (e.pointerType === 'mouse') read(id(e.clientX)); });
70
+ strip.addEventListener('pointerleave', clear);
71
+ strip.addEventListener('click', (e) => { const i = id(e.clientX), s = statements.find((x) => ids(x).includes(i)); pinned = () => read(i); read(i); if (s) { s.classList.add('hit'); s.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } });
72
+ strip.addEventListener('keydown', (e) => {
73
+ const step = { ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1 }[e.key]; if (!step) return;
74
+ e.preventDefault(); const i = d.s[Math.max(0, Math.min(total - 1, +strip.getAttribute('aria-valuenow') - 1 + step))][0]; pinned = () => read(i); read(i);
75
+ });
76
+ }
77
+ // What was left out can be thousands of sentences, so build each list when it opens.
78
+ for (const box of $$('.lo')) box.addEventListener('toggle', () => {
79
+ if (!box.open || box.dataset.done) return;
80
+ box.dataset.done = '1'; let last = null;
81
+ docs.get(box.dataset.k).s.forEach(([, text, why], i) => {
82
+ const kind = why.split(':')[0]; if (!why || (box.dataset.kind && kind !== box.dataset.kind)) return;
83
+ const note = box.dataset.kind ? why.slice(kind.length + 1).trim() : why.replace(/^Not used: /, '');
84
+ if (note !== last && note) box.append(el('p', note[0].toUpperCase() + note.slice(1), 'note'));
85
+ last = note;
86
+ const p = el('p'), many = text.includes('\n'); p.append(el('b', String(i + 1)), many ? '' : text); box.append(p); if (many) box.append(el('pre', text));
87
+ });
88
+ });
89
+ for (const b of $$('.copy')) b.addEventListener('click', () => navigator.clipboard?.writeText($('pre', b.parentElement).textContent).then(() => { b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy'; }, 1500); }));
90
+ const toc = $('.toc details');
91
+ if (toc) {
92
+ const wide = matchMedia('(min-width:76rem)'), set = () => { toc.open = wide.matches; }; set(); wide.addEventListener('change', set);
93
+ const links = new Map($$('.toc a').map((a) => [a.getAttribute('href').slice(1), a])), spots = [...links.keys()].map((i) => document.getElementById(i)).filter(Boolean);
94
+ const mark = () => { let now = spots[0]; for (const x of spots) if (x.getBoundingClientRect().top < 140) now = x; for (const [i, a] of links) { a.classList.toggle('now', i === now?.id); a.parentElement.classList.remove('here'); } let li = links.get(now?.id)?.parentElement; while (li) { li.classList.add('here'); li = li.parentElement.closest('li'); } };
95
+ addEventListener('scroll', mark, { passive: true }); mark();
96
+ for (const a of links.values()) a.addEventListener('click', () => { if (!wide.matches) toc.open = false; });
97
+ }
98
+ })();