Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions .github/site-scaffolding.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,16 @@
{
"path": "anchor-landing.html",
"source_path": "anchor-landing.html",
"commit": "dd7c5708d219552e40d15c762e8ca7f5228e005a",
"sha256": "ee631187883546beb90d1290771a7920a2cf123ba573ef515bf84d93a4203e07",
"source_url": "https://github.com/Morrison-Lab/qwt/blob/dd7c5708d219552e40d15c762e8ca7f5228e005a/anchor-landing.html"
"commit": "4520162927a78dca41527432ab9559afb75bf2e8",
"sha256": "feea770a4864ff3bf477eb88200a0c95b318e841a817e6c9f94f3b944318a443",
"source_url": "https://github.com/Morrison-Lab/qwt/blob/4520162927a78dca41527432ab9559afb75bf2e8/anchor-landing.html"
},
{
"path": "anchor-index.py",
"source_path": "anchor-index.py",
"commit": "8ec9168519369b0d53f10178c873291d68602666",
"sha256": "e90142cbbe3c62171c1cf756bd8626cc2624e2230a26f433e8b34e094a52cb91",
"source_url": "https://github.com/Morrison-Lab/qwt/blob/8ec9168519369b0d53f10178c873291d68602666/anchor-index.py"
},
{
"path": "revealjs-html-links.lua",
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/sync-site-scaffolding.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
offwhite.scss=offwhite.scss
theme-picker.html=theme-picker.html
anchor-landing.html=anchor-landing.html
anchor-index.py=anchor-index.py
revealjs-html-links.lua=revealjs-html-links.lua
qwt-reveal-toggle.html=qwt-reveal-toggle.html
manifest-path: .github/site-scaffolding.json
Expand Down
3 changes: 3 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ Authoritative style guide: [UCD-SERG Lab Manual](https://ucd-serg.github.io/lab-
(saved under `lds-theme`, falling back to `mln-theme`, shared with the slides and the other sites on this origin);
`language-picker.html` --- the navbar dropdown that sets which R/Python tab is open in every `group="language"` tabset
(copied from lds)
- `anchor-landing.html`, `anchor-index.py` --- vendored from [`Morrison-Lab/qwt`](https://github.com/Morrison-Lab/qwt) by `.github/workflows/sync-site-scaffolding.yml`; do not edit them here.
`anchor-landing.html` keeps the reader's place while equations load, and sends a link to an id that moved to another page on to that page,
using `_site/anchor-index.json`, which the `anchor-index.py` `post-render` step writes
- `styles.css` --- website styling; `styles-reveal.scss`, `qwt-reveal-toggle.html` (the same dropdown for slides), and the `revealjs-*.lua` filters drive the reveal.js slide output
- `assets/`, `images/` --- static image and asset files (site pages, docs, CI/PR screenshots)
- `.github/workflows/` --- CI workflow definitions
Expand Down
5 changes: 5 additions & 0 deletions _quarto-website.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ project:
# Runs last: on a pull request's build it removes the pdf format from the working copy
# unless the PR carries the `preview:pdf` label.
- python3 tools/skip-pdf-in-previews.py
# Writes _site/anchor-index.json, which page holds each id, so that
# anchor-landing.html sends a link to an id that moved to another page on to
# the page that holds it now (course sites such as lds link to sds anchors).
post-render:
- anchor-index.py
resources:
- dependency-graph.js
- dependency-graph.json
Expand Down
110 changes: 110 additions & 0 deletions anchor-index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Write anchor-index.json: which page of the rendered site holds each id.

anchor-landing.html reads it when a reader arrives at a page whose `#id` the page
no longer holds, because the content moved to another page, and sends them to the
page that holds the id now. So a link from another site, a bookmark or a search
result keeps working after a definition moves, without the link being rewritten.

Runs as a `post-render` step: it scans every website page in the output directory
(`QUARTO_PROJECT_OUTPUT_DIR`, else `_site`) and writes

{"version": 1, "ids": {"def-intercept": "algebra-polynomials.html", ...}}

with each page given relative to the site root. It leaves out

- reveal.js decks, which repeat their page's ids (the reader wants the page);
- ids held by more than one page, such as Quarto's own page chrome,
since a redirect to one of them would be a guess;
- ids that only number a position on the page, such as code lines (`cb3-12`),
footnotes (`fn2`), callouts and unnumbered sections (`callout-4`, `section-1.2`),
and random widget ids: the same id on another page is unrelated content;
- ids inside HTML comments and scripts.

Shared site scaffolding: the canonical copy is in Morrison-Lab/qwt. The sites
built on it vendor it, with anchor-landing.html, through their
.github/workflows/sync-site-scaffolding.yml (for example Morrison-Lab/mds).
Do not edit a site's copy.

anchor-index.py [--site DIR] [--out FILE]
"""
import argparse
import json
import os
import re
import sys
from html.parser import HTMLParser
from pathlib import Path

POSITIONAL = re.compile(
r"^(?:cb\d+(?:-\d+)?|fn(?:ref)?\d+(?:-\d+)?|callout-\d+|tabset-\d+(?:-\d+)*"
r"|(?:toc-)?section-\d+(?:[.-]\d+)*|htmlwidget-.*|ojs-.*"
r"|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}.*)$",
re.I,
)
OUT_NAME = "anchor-index.json"


class Ids(HTMLParser):
"""The ids on one page, read with an HTML parser.

The parser unescapes attribute values and does not read tags inside a
<script> or <style>, or inside a comment, so those yield no ids.
"""

def __init__(self):
super().__init__(convert_charrefs=True)
self.ids = set()
self.deck = False

def handle_starttag(self, tag, attrs):
for name, value in attrs:
if name == "id" and value:
self.ids.add(value)
elif name == "class" and tag == "div" and value and "reveal" in value.split():
self.deck = True

handle_startendtag = handle_starttag


def site_pages(site):
"""The website pages in `site`, as (path relative to the site root, its ids)."""
for path in sorted(site.rglob("*.html")):
rel = path.relative_to(site).as_posix()
# site_libs holds Quarto's assets; a notebook preview repeats its page's ids.
if rel.startswith("site_libs/") or "/site_libs/" in rel or rel.endswith(".ipynb.html"):
continue
parser = Ids()
parser.feed(path.read_text(encoding="utf-8", errors="replace"))
parser.close()
if not parser.deck:
yield rel, parser.ids


def build(site):
holders = {}
for rel, ids in site_pages(site):
for name in ids:
if not POSITIONAL.match(name):
holders.setdefault(name, set()).add(rel)
ids = {i: next(iter(p)) for i, p in sorted(holders.items()) if len(p) == 1}
return {"version": 1, "ids": ids}


def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--site", default=os.environ.get("QUARTO_PROJECT_OUTPUT_DIR", "_site"),
help="the rendered site (default: $QUARTO_PROJECT_OUTPUT_DIR or _site)")
ap.add_argument("--out", help=f"where to write the index (default: SITE/{OUT_NAME})")
args = ap.parse_args(argv)
site = Path(args.site)
if not site.is_dir():
sys.exit(f"anchor-index.py: no rendered site at {site}")
index = build(site)
out = Path(args.out) if args.out else site / OUT_NAME
out.write_text(json.dumps(index, separators=(",", ":"), sort_keys=True) + "\n", encoding="utf-8")
print(f"anchor-index.py: {len(index['ids'])} ids -> {out}")


if __name__ == "__main__":
main()
40 changes: 40 additions & 0 deletions anchor-landing.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,44 @@
<script>
// A link to an id that has moved to another page of this site: when the page
// holds no element with the link's #id, look the id up in anchor-index.json,
// which the site's anchor-index.py post-render step writes at the site root,
// and go to the page that holds it now, keeping the rest of the hash (a text
// fragment). A site without the index, an id it does not list, or an id that
// maps back to this page leaves the reader where they are. It runs on load
// and again when an in-page link changes the hash.
(function () {
if (!window.fetch) return;
var meta = document.querySelector('meta[name="quarto:offset"]');
var root = new URL(meta ? meta.getAttribute("content") : "./", location.href);
var index = null;
function follow() {
var id = "";
try { id = decodeURIComponent(location.hash.slice(1).replace(/:~:.*$/, "")); } catch (e) { return; }
if (!id || document.getElementById(id)) return;
index = index || fetch(new URL("anchor-index.json", root)).then(function (r) {
return r.ok ? r.json() : null;
}).catch(function () { return null; });
index.then(function (data) {
var ids = data && data.ids;
var page = ids && Object.prototype.hasOwnProperty.call(ids, id) ? ids[id] : null;
if (typeof page !== "string" || document.getElementById(id)) return;
var dest = new URL(page, root);
var here = location.pathname.replace(/\/$/, "/index.html");
if (dest.pathname === here) return;
// location.hash leaves out a text fragment; the navigation entry keeps it.
var hash = location.hash;
try {
var nav = performance.getEntriesByType("navigation")[0];
var m = nav && /#(.*)$/.exec(nav.name);
if (m && m[1].indexOf(hash.slice(1)) === 0) hash = "#" + m[1];
} catch (e) {}
location.replace(dest.href.replace(/#.*$/, "") + hash);
});
}
follow();
window.addEventListener("hashchange", follow);
})();

// Typesetting equations and loading images change the height of everything
// above the reader and push the text they were reading out of view. Keep the
// reader's place: until they scroll, that is the link target (#id or a text
Expand Down
Loading