Skip to content

Commit a11f5e1

Browse files
committed
docs: ref redirector
1 parent 2a89f75 commit a11f5e1

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

docs/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
# Add any Sphinx extension module names here, as strings. They can be
3636
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
3737
# ones.
38-
extensions = ["sphinx.ext.intersphinx"]
38+
extensions = ["sphinx.ext.intersphinx", "docs.source.html_builder"]
3939

4040
# Add any paths that contain templates here, relative to this directory.
4141
templates_path = ["_templates"]

docs/source/html_builder.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from __future__ import annotations
2+
3+
import json
4+
import textwrap
5+
from pathlib import Path
6+
from typing import Any
7+
8+
from sphinx.addnodes import document
9+
from sphinx.application import Sphinx
10+
from sphinx.builders.html import StandaloneHTMLBuilder
11+
12+
13+
class MypyHTMLBuilder(StandaloneHTMLBuilder):
14+
def __init__(self, app: Sphinx) -> None:
15+
super().__init__(app=app)
16+
self._ref_to_doc = {}
17+
18+
def write_doc(self, docname: str, doctree: document) -> None:
19+
super().write_doc(docname, doctree)
20+
self._ref_to_doc.update({ref: docname for ref in doctree.ids.keys()})
21+
22+
def _write_ref_redirector(self) -> None:
23+
p = Path(self.outdir) / "_refs.html"
24+
p.write_text(
25+
textwrap.dedent(
26+
f"""
27+
<html>
28+
<body>
29+
<script>
30+
const ref_to_doc = {json.dumps(self._ref_to_doc)};
31+
const hash = window.location.hash.substring(1);
32+
const doc = ref_to_doc[hash];
33+
if (doc) {{
34+
window.location.href = doc + '.html' + '#' + hash;
35+
}} else {{
36+
window.document.innerText = 'Unknown reference: ' + hash;
37+
}}
38+
</script>
39+
</body>
40+
</html>
41+
"""
42+
)
43+
)
44+
45+
def finish(self) -> None:
46+
super().finish()
47+
self._write_ref_redirector()
48+
49+
50+
def setup(app: Sphinx) -> dict[str, Any]:
51+
app.add_builder(MypyHTMLBuilder, override=True)
52+
53+
return {"version": "0.1", "parallel_read_safe": True, "parallel_write_safe": True}

0 commit comments

Comments
 (0)