mdbake 0.1.1__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.
- mdbake/__init__.py +3 -0
- mdbake/builder.py +216 -0
- mdbake/builtin/__init__.py +1 -0
- mdbake/builtin/draft.py +29 -0
- mdbake/builtin/frontmatter_defaults.py +38 -0
- mdbake/cli.py +51 -0
- mdbake/config.py +130 -0
- mdbake/files.py +110 -0
- mdbake/frontmatter.py +34 -0
- mdbake/links.py +104 -0
- mdbake/markdown.py +111 -0
- mdbake/middleware.py +131 -0
- mdbake/nav.py +215 -0
- mdbake/page.py +79 -0
- mdbake/theme/base.html +46 -0
- mdbake/theme/nav.html +21 -0
- mdbake/theme/style.css +174 -0
- mdbake/theme/toc.html +8 -0
- mdbake/toc.py +33 -0
- mdbake-0.1.1.dist-info/METADATA +185 -0
- mdbake-0.1.1.dist-info/RECORD +23 -0
- mdbake-0.1.1.dist-info/WHEEL +4 -0
- mdbake-0.1.1.dist-info/entry_points.txt +2 -0
mdbake/links.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Rewrite relative links between docs (``.md`` -> page URL) and record anchors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import posixpath
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
from urllib.parse import quote, unquote, urlsplit
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from markdown_it.rules_core import StateCore
|
|
13
|
+
from markdown_it.token import Token
|
|
14
|
+
|
|
15
|
+
from .files import File, Files
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class LinkRef:
|
|
20
|
+
"""A link found in a page. ``target`` is None when it could not be resolved."""
|
|
21
|
+
|
|
22
|
+
source: File
|
|
23
|
+
url: str # original URL as written
|
|
24
|
+
target: File | None
|
|
25
|
+
fragment: str | None
|
|
26
|
+
broken: bool = False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_external(url: str) -> bool:
|
|
30
|
+
"""True for anything that is not a relative path (scheme, host, or site-absolute)."""
|
|
31
|
+
parts = urlsplit(url)
|
|
32
|
+
return bool(parts.scheme or parts.netloc or url.startswith("/"))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def relative_url(to_url: str, from_url: str) -> str:
|
|
36
|
+
"""Relative URL from page ``from_url`` to ``to_url`` (both site-root-relative)."""
|
|
37
|
+
start = posixpath.dirname(from_url) or "."
|
|
38
|
+
return posixpath.relpath(to_url, start)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def resolve_link(url: str, source: File, files: Files) -> tuple[str, LinkRef | None]:
|
|
42
|
+
"""Return ``(new_url, ref)``. External links are returned unchanged with ref None."""
|
|
43
|
+
if is_external(url):
|
|
44
|
+
return url, None
|
|
45
|
+
parts = urlsplit(url)
|
|
46
|
+
fragment = unquote(parts.fragment) or None
|
|
47
|
+
path = unquote(parts.path)
|
|
48
|
+
if not path: # "#anchor" (same page) or "?query"
|
|
49
|
+
return url, LinkRef(source, url, source, fragment)
|
|
50
|
+
|
|
51
|
+
base = posixpath.dirname(source.src_path)
|
|
52
|
+
target_path = posixpath.normpath(posixpath.join(base, path))
|
|
53
|
+
if target_path == ".":
|
|
54
|
+
target_path = ""
|
|
55
|
+
if target_path == ".." or target_path.startswith("../"):
|
|
56
|
+
return url, LinkRef(source, url, None, fragment, broken=True)
|
|
57
|
+
|
|
58
|
+
target = files.get(target_path) if target_path else None
|
|
59
|
+
if target is None: # maybe a directory link -> its index page
|
|
60
|
+
for index in ("index.md", "README.md", "index.markdown"):
|
|
61
|
+
candidate = files.get(posixpath.join(target_path, index) if target_path else index)
|
|
62
|
+
if candidate is not None and candidate.is_page:
|
|
63
|
+
target = candidate
|
|
64
|
+
break
|
|
65
|
+
if target is None:
|
|
66
|
+
return url, LinkRef(source, url, None, fragment, broken=True)
|
|
67
|
+
|
|
68
|
+
new_url = quote(relative_url(target.url, source.url), safe="/")
|
|
69
|
+
if parts.query:
|
|
70
|
+
new_url += "?" + parts.query
|
|
71
|
+
if parts.fragment:
|
|
72
|
+
new_url += "#" + parts.fragment
|
|
73
|
+
return new_url, LinkRef(source, url, target, fragment)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _walk(tokens: list[Token]) -> Iterator[Token]:
|
|
77
|
+
for tok in tokens:
|
|
78
|
+
yield tok
|
|
79
|
+
if tok.children:
|
|
80
|
+
yield from _walk(tok.children)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def rewrite_links_rule(state: StateCore) -> None:
|
|
84
|
+
"""markdown-it core rule: rewrite ``href``/``src`` of link and image tokens."""
|
|
85
|
+
page = state.env.get("page")
|
|
86
|
+
files = state.env.get("files")
|
|
87
|
+
if page is None or files is None:
|
|
88
|
+
return
|
|
89
|
+
refs: list[LinkRef] = state.env.setdefault("link_refs", [])
|
|
90
|
+
for tok in _walk(state.tokens):
|
|
91
|
+
if tok.type == "link_open":
|
|
92
|
+
attr = "href"
|
|
93
|
+
elif tok.type == "image":
|
|
94
|
+
attr = "src"
|
|
95
|
+
else:
|
|
96
|
+
continue
|
|
97
|
+
url = tok.attrGet(attr)
|
|
98
|
+
if not isinstance(url, str):
|
|
99
|
+
continue
|
|
100
|
+
new_url, ref = resolve_link(url, page.file, files)
|
|
101
|
+
if ref is not None:
|
|
102
|
+
refs.append(ref)
|
|
103
|
+
if new_url != url:
|
|
104
|
+
tok.attrSet(attr, new_url)
|
mdbake/markdown.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""markdown-it factory: GFM preset, plugins, heading ids, code highlighting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
import unicodedata
|
|
8
|
+
|
|
9
|
+
from markdown_it import MarkdownIt
|
|
10
|
+
from markdown_it.rules_core import StateCore
|
|
11
|
+
from markdown_it.token import Token
|
|
12
|
+
from mdit_py_plugins.deflist import deflist_plugin
|
|
13
|
+
from mdit_py_plugins.footnote import footnote_plugin
|
|
14
|
+
from mdit_py_plugins.tasklists import tasklists_plugin
|
|
15
|
+
|
|
16
|
+
from .links import rewrite_links_rule
|
|
17
|
+
|
|
18
|
+
try: # Pygments is optional
|
|
19
|
+
import pygments
|
|
20
|
+
from pygments.formatters import HtmlFormatter
|
|
21
|
+
from pygments.lexers import get_lexer_by_name
|
|
22
|
+
from pygments.util import ClassNotFound
|
|
23
|
+
|
|
24
|
+
_FORMATTER = HtmlFormatter(nowrap=True)
|
|
25
|
+
except ImportError: # pragma: no cover
|
|
26
|
+
pygments = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def slugify(text: str) -> str:
|
|
30
|
+
"""GitHub-style slug: lowercase, drop punctuation, spaces become dashes."""
|
|
31
|
+
text = unicodedata.normalize("NFKC", text).strip().lower()
|
|
32
|
+
text = re.sub(r"[^\w\- ]", "", text)
|
|
33
|
+
text = text.replace(" ", "-")
|
|
34
|
+
return text or "section"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def unique_id(candidate: str, used: set[str]) -> str:
|
|
38
|
+
result, n = candidate, 0
|
|
39
|
+
while result in used:
|
|
40
|
+
n += 1
|
|
41
|
+
result = f"{candidate}-{n}"
|
|
42
|
+
used.add(result)
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def inline_text(token: Token) -> str:
|
|
47
|
+
"""Plain text of an inline token (formatting and raw HTML stripped)."""
|
|
48
|
+
if not token.children:
|
|
49
|
+
return token.content.strip()
|
|
50
|
+
parts = []
|
|
51
|
+
for child in token.children:
|
|
52
|
+
if child.type in ("text", "code_inline"):
|
|
53
|
+
parts.append(child.content)
|
|
54
|
+
elif child.type in ("softbreak", "hardbreak"):
|
|
55
|
+
parts.append(" ")
|
|
56
|
+
elif child.type == "image":
|
|
57
|
+
parts.append(child.content)
|
|
58
|
+
return "".join(parts).strip()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def heading_ids_rule(state: StateCore) -> None:
|
|
62
|
+
"""Give every heading a unique ``id`` and record ``(level, title, id)`` in env."""
|
|
63
|
+
used: set[str] = state.env.setdefault("heading_ids", set())
|
|
64
|
+
headings: list = state.env.setdefault("headings", [])
|
|
65
|
+
tokens = state.tokens
|
|
66
|
+
for i, tok in enumerate(tokens):
|
|
67
|
+
if tok.type != "heading_open":
|
|
68
|
+
continue
|
|
69
|
+
title = inline_text(tokens[i + 1]) if i + 1 < len(tokens) else ""
|
|
70
|
+
anchor = unique_id(str(tok.attrGet("id") or slugify(title)), used)
|
|
71
|
+
tok.attrSet("id", anchor)
|
|
72
|
+
headings.append((int(tok.tag[1]), title, anchor))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def highlight_code(code: str, lang: str, attrs: str) -> str:
|
|
76
|
+
if pygments is None or not lang:
|
|
77
|
+
return ""
|
|
78
|
+
try:
|
|
79
|
+
lexer = get_lexer_by_name(lang)
|
|
80
|
+
except ClassNotFound:
|
|
81
|
+
return ""
|
|
82
|
+
body = pygments.highlight(code, lexer, _FORMATTER)
|
|
83
|
+
lang_attr = html.escape(lang, quote=True)
|
|
84
|
+
return f'<pre class="highlight"><code class="language-{lang_attr}">{body}</code></pre>'
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def pygments_css(light: str = "default", dark: str | None = "monokai") -> str:
|
|
88
|
+
if pygments is None: # pragma: no cover
|
|
89
|
+
return ""
|
|
90
|
+
css = HtmlFormatter(style=light).get_style_defs(".highlight")
|
|
91
|
+
if dark:
|
|
92
|
+
dark_css = HtmlFormatter(style=dark).get_style_defs(".highlight")
|
|
93
|
+
css += "\n@media (prefers-color-scheme: dark) {\n" + dark_css + "\n}\n"
|
|
94
|
+
return css
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def create_markdown(*, highlight: bool = True) -> MarkdownIt:
|
|
98
|
+
"""Create a GFM-like renderer with heading ids and relative link rewriting.
|
|
99
|
+
|
|
100
|
+
Per-render ``env`` keys used: ``page`` + ``files`` (enable link rewriting);
|
|
101
|
+
the render fills ``headings`` and ``link_refs``.
|
|
102
|
+
"""
|
|
103
|
+
md = MarkdownIt(
|
|
104
|
+
"gfm-like",
|
|
105
|
+
{"html": True, "linkify": True, "typographer": False,
|
|
106
|
+
"highlight": highlight_code if highlight else None},
|
|
107
|
+
)
|
|
108
|
+
md.use(tasklists_plugin).use(footnote_plugin).use(deflist_plugin)
|
|
109
|
+
md.core.ruler.push("mdbake_heading_ids", heading_ids_rule)
|
|
110
|
+
md.core.ruler.push("mdbake_links", rewrite_links_rule)
|
|
111
|
+
return md
|
mdbake/middleware.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Middleware loading and the hook pipeline.
|
|
2
|
+
|
|
3
|
+
A middleware is any object (module, class instance, ...) exposing some of the hook
|
|
4
|
+
methods below. Hooks that transform an item return the new value, or ``None`` to
|
|
5
|
+
keep the item unchanged. Middleware runs in config order.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
import inspect
|
|
12
|
+
import sys
|
|
13
|
+
from collections.abc import Iterable
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from markdown_it import MarkdownIt
|
|
19
|
+
|
|
20
|
+
from .config import Config
|
|
21
|
+
|
|
22
|
+
HOOKS = (
|
|
23
|
+
"on_config", # (config) -> config
|
|
24
|
+
"on_files", # (files, *, config) -> files
|
|
25
|
+
"on_page_source", # (page, *, site) -> page (meta + markdown available; set page.skip)
|
|
26
|
+
"on_page_markdown", # (markdown, *, page, site) -> str
|
|
27
|
+
"on_page_html", # (html, *, page, site) -> str
|
|
28
|
+
"on_nav", # (nav, *, site) -> nav
|
|
29
|
+
"on_page_context", # (ctx, *, page, site) -> dict
|
|
30
|
+
"on_post_build", # (*, site) -> None
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class MiddlewareError(Exception):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def import_object(path: str) -> Any:
|
|
39
|
+
"""Import ``pkg.mod``, ``pkg.mod:attr`` or ``pkg.mod.attr``."""
|
|
40
|
+
if ":" in path:
|
|
41
|
+
module_name, attr = path.split(":", 1)
|
|
42
|
+
else:
|
|
43
|
+
try:
|
|
44
|
+
return importlib.import_module(path)
|
|
45
|
+
except ModuleNotFoundError as exc:
|
|
46
|
+
if "." not in path or (exc.name and not path.startswith(exc.name)):
|
|
47
|
+
raise MiddlewareError(f"cannot import middleware '{path}': {exc}") from exc
|
|
48
|
+
module_name, attr = path.rsplit(".", 1)
|
|
49
|
+
try:
|
|
50
|
+
obj: Any = importlib.import_module(module_name)
|
|
51
|
+
except ImportError as exc:
|
|
52
|
+
raise MiddlewareError(f"cannot import middleware '{path}': {exc}") from exc
|
|
53
|
+
for part in attr.split("."):
|
|
54
|
+
try:
|
|
55
|
+
obj = getattr(obj, part)
|
|
56
|
+
except AttributeError as exc:
|
|
57
|
+
raise MiddlewareError(f"middleware '{path}': no attribute '{part}'") from exc
|
|
58
|
+
return obj
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_middleware(spec: str | dict) -> Any:
|
|
62
|
+
"""Load one middleware from ``"dotted.path[:Attr]"`` or ``{path, options}``.
|
|
63
|
+
|
|
64
|
+
Classes are instantiated with ``options`` as keyword arguments; anything else
|
|
65
|
+
(modules, objects) is used as-is.
|
|
66
|
+
"""
|
|
67
|
+
if isinstance(spec, str):
|
|
68
|
+
path, options = spec, {}
|
|
69
|
+
elif isinstance(spec, dict) and isinstance(spec.get("path"), str):
|
|
70
|
+
path, options = spec["path"], spec.get("options") or {}
|
|
71
|
+
if not isinstance(options, dict):
|
|
72
|
+
raise MiddlewareError(f"middleware '{path}': options must be a mapping")
|
|
73
|
+
else:
|
|
74
|
+
raise MiddlewareError(f"invalid middleware spec: {spec!r}")
|
|
75
|
+
|
|
76
|
+
target = import_object(path)
|
|
77
|
+
if inspect.isclass(target):
|
|
78
|
+
try:
|
|
79
|
+
return target(**options)
|
|
80
|
+
except TypeError as exc:
|
|
81
|
+
raise MiddlewareError(f"middleware '{path}': {exc}") from exc
|
|
82
|
+
if options:
|
|
83
|
+
raise MiddlewareError(f"middleware '{path}': options given but target is not a class")
|
|
84
|
+
return target
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _name(mw: Any) -> str:
|
|
88
|
+
if inspect.ismodule(mw):
|
|
89
|
+
return mw.__name__
|
|
90
|
+
return f"{type(mw).__module__}.{type(mw).__qualname__}"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Pipeline:
|
|
94
|
+
def __init__(self, middlewares: Iterable[Any] = ()):
|
|
95
|
+
self.middlewares = list(middlewares)
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def from_config(cls, config: Config) -> Pipeline:
|
|
99
|
+
# Allow local hook modules next to the config file.
|
|
100
|
+
if config.config_file is not None:
|
|
101
|
+
config_dir = str(Path(config.config_file).parent)
|
|
102
|
+
if config_dir not in sys.path:
|
|
103
|
+
sys.path.insert(0, config_dir)
|
|
104
|
+
return cls(load_middleware(spec) for spec in config.middleware)
|
|
105
|
+
|
|
106
|
+
def _call(self, mw: Any, hook: str, *args: Any, **kwargs: Any) -> Any:
|
|
107
|
+
fn = getattr(mw, hook, None)
|
|
108
|
+
if fn is None:
|
|
109
|
+
return None
|
|
110
|
+
try:
|
|
111
|
+
return fn(*args, **kwargs)
|
|
112
|
+
except MiddlewareError:
|
|
113
|
+
raise
|
|
114
|
+
except Exception as exc:
|
|
115
|
+
raise MiddlewareError(f"{_name(mw)}.{hook} failed: {exc!r}") from exc
|
|
116
|
+
|
|
117
|
+
def run(self, hook: str, item: Any, **ctx: Any) -> Any:
|
|
118
|
+
"""Pass ``item`` through every middleware's ``hook``; ``None`` keeps it."""
|
|
119
|
+
for mw in self.middlewares:
|
|
120
|
+
result = self._call(mw, hook, item, **ctx)
|
|
121
|
+
if result is not None:
|
|
122
|
+
item = result
|
|
123
|
+
return item
|
|
124
|
+
|
|
125
|
+
def notify(self, hook: str, **ctx: Any) -> None:
|
|
126
|
+
for mw in self.middlewares:
|
|
127
|
+
self._call(mw, hook, **ctx)
|
|
128
|
+
|
|
129
|
+
def md_setup(self, md: MarkdownIt) -> None:
|
|
130
|
+
for mw in self.middlewares:
|
|
131
|
+
self._call(mw, "md_setup", md)
|
mdbake/nav.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Site navigation: explicit (from config) or auto-discovered from the dir tree."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import posixpath
|
|
7
|
+
from collections.abc import Callable, Iterator
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Union
|
|
10
|
+
|
|
11
|
+
from .links import is_external
|
|
12
|
+
from .page import Page, pretty_title
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(eq=False)
|
|
16
|
+
class Section:
|
|
17
|
+
name: str
|
|
18
|
+
children: list[NavItem] = field(default_factory=list)
|
|
19
|
+
page: Page | None = None # optional index page the section title links to
|
|
20
|
+
parent: Section | None = None
|
|
21
|
+
explicit_title: str | None = None
|
|
22
|
+
|
|
23
|
+
is_page = False
|
|
24
|
+
is_section = True
|
|
25
|
+
is_link = False
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def title(self) -> str:
|
|
29
|
+
if self.explicit_title:
|
|
30
|
+
return self.explicit_title
|
|
31
|
+
if self.page is not None:
|
|
32
|
+
return self.page.title
|
|
33
|
+
return pretty_title(self.name)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def ancestors(self) -> list[Section]:
|
|
37
|
+
result, node = [], self.parent
|
|
38
|
+
while node is not None:
|
|
39
|
+
result.append(node)
|
|
40
|
+
node = node.parent
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
def __repr__(self) -> str:
|
|
44
|
+
return f"Section({self.title!r}, children={len(self.children)})"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(eq=False)
|
|
48
|
+
class Link:
|
|
49
|
+
title: str
|
|
50
|
+
url: str
|
|
51
|
+
parent: Section | None = None
|
|
52
|
+
|
|
53
|
+
is_page = False
|
|
54
|
+
is_section = False
|
|
55
|
+
is_link = True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
NavItem = Union[Page, Section, Link]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(eq=False)
|
|
62
|
+
class Navigation:
|
|
63
|
+
items: list[NavItem]
|
|
64
|
+
pages: list[Page] # pages in nav order (for prev/next)
|
|
65
|
+
|
|
66
|
+
def __iter__(self) -> Iterator[NavItem]:
|
|
67
|
+
return iter(self.items)
|
|
68
|
+
|
|
69
|
+
def __len__(self) -> int:
|
|
70
|
+
return len(self.items)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
Warn = Callable[[str], None]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _noop_warn(msg: str) -> None:
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def build_nav(config_nav: list | None, pages: list[Page], *, warn: Warn = _noop_warn) -> Navigation:
|
|
81
|
+
"""Build navigation, then wire ``previous_page``/``next_page``."""
|
|
82
|
+
for page in pages:
|
|
83
|
+
page.parent = None
|
|
84
|
+
page.previous_page = page.next_page = None
|
|
85
|
+
if config_nav:
|
|
86
|
+
by_src = {p.src_path: p for p in pages}
|
|
87
|
+
items = _parse_explicit(config_nav, by_src, None, warn, set())
|
|
88
|
+
else:
|
|
89
|
+
items = _auto_nav(pages)
|
|
90
|
+
nav = Navigation(items=items, pages=list(_iter_pages(items)))
|
|
91
|
+
link_pages(nav)
|
|
92
|
+
return nav
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def link_pages(nav: Navigation) -> None:
|
|
96
|
+
for prev, nxt in zip(nav.pages, nav.pages[1:]):
|
|
97
|
+
prev.next_page = nxt
|
|
98
|
+
nxt.previous_page = prev
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _iter_pages(items: list[NavItem]) -> Iterator[Page]:
|
|
102
|
+
seen: set[int] = set()
|
|
103
|
+
|
|
104
|
+
def walk(items: list[NavItem]) -> Iterator[Page]:
|
|
105
|
+
for item in items:
|
|
106
|
+
if isinstance(item, Section):
|
|
107
|
+
if item.page is not None and id(item.page) not in seen:
|
|
108
|
+
seen.add(id(item.page))
|
|
109
|
+
yield item.page
|
|
110
|
+
yield from walk(item.children)
|
|
111
|
+
elif isinstance(item, Page) and id(item) not in seen:
|
|
112
|
+
seen.add(id(item))
|
|
113
|
+
yield item
|
|
114
|
+
|
|
115
|
+
return walk(items)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _parse_explicit(
|
|
119
|
+
raw: list, pages: dict[str, Page], parent: Section | None, warn: Warn, placed: set[int]
|
|
120
|
+
) -> list[NavItem]:
|
|
121
|
+
items: list[NavItem] = []
|
|
122
|
+
for entry in raw:
|
|
123
|
+
title: Any
|
|
124
|
+
if isinstance(entry, str):
|
|
125
|
+
title, value = None, entry
|
|
126
|
+
elif isinstance(entry, dict) and len(entry) == 1:
|
|
127
|
+
title, value = next(iter(entry.items()))
|
|
128
|
+
else:
|
|
129
|
+
warn(f"nav: invalid entry {entry!r} (expected 'path', 'Title: path' or 'Title: [..]')")
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
if isinstance(value, list):
|
|
133
|
+
name = str(title) if title is not None else "Section"
|
|
134
|
+
section = Section(name=name, parent=parent, explicit_title=name)
|
|
135
|
+
section.children = _parse_explicit(value, pages, section, warn, placed)
|
|
136
|
+
items.append(section)
|
|
137
|
+
elif isinstance(value, str):
|
|
138
|
+
if is_external(value):
|
|
139
|
+
items.append(Link(title=str(title) if title is not None else value, url=value, parent=parent))
|
|
140
|
+
continue
|
|
141
|
+
page = pages.get(posixpath.normpath(value))
|
|
142
|
+
if page is None:
|
|
143
|
+
warn(f"nav: page '{value}' not found in docs_dir")
|
|
144
|
+
continue
|
|
145
|
+
if title is not None:
|
|
146
|
+
page.nav_title = str(title)
|
|
147
|
+
if id(page) not in placed:
|
|
148
|
+
placed.add(id(page))
|
|
149
|
+
page.parent = parent
|
|
150
|
+
items.append(page)
|
|
151
|
+
else:
|
|
152
|
+
warn(f"nav: invalid value for {title!r}: {value!r}")
|
|
153
|
+
return items
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _order(page: Page | None) -> float:
|
|
157
|
+
if page is None:
|
|
158
|
+
return math.inf
|
|
159
|
+
value = page.meta.get("nav_order")
|
|
160
|
+
try:
|
|
161
|
+
return float(value) if value is not None else math.inf
|
|
162
|
+
except (TypeError, ValueError):
|
|
163
|
+
return math.inf
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass
|
|
167
|
+
class _Dir:
|
|
168
|
+
index: Page | None = None
|
|
169
|
+
pages: list[Page] = field(default_factory=list)
|
|
170
|
+
dirs: dict[str, _Dir] = field(default_factory=dict)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _auto_nav(pages: list[Page]) -> list[NavItem]:
|
|
174
|
+
root = _Dir()
|
|
175
|
+
for page in pages:
|
|
176
|
+
node = root
|
|
177
|
+
for part in page.src_path.split("/")[:-1]:
|
|
178
|
+
node = node.dirs.setdefault(part, _Dir())
|
|
179
|
+
if page.is_index and node.index is None:
|
|
180
|
+
node.index = page
|
|
181
|
+
else:
|
|
182
|
+
node.pages.append(page)
|
|
183
|
+
|
|
184
|
+
def build(node: _Dir, parent: Section | None) -> list[NavItem]:
|
|
185
|
+
entries: list[tuple[tuple, Any]] = []
|
|
186
|
+
for page in node.pages:
|
|
187
|
+
name = posixpath.basename(page.src_path).lower()
|
|
188
|
+
entries.append(((_order(page), 0, name), page))
|
|
189
|
+
for dirname, sub in node.dirs.items():
|
|
190
|
+
entries.append(((_order(sub.index), 1, dirname.lower()), (dirname, sub)))
|
|
191
|
+
entries.sort(key=lambda e: e[0])
|
|
192
|
+
|
|
193
|
+
items: list[NavItem] = []
|
|
194
|
+
for _, value in entries:
|
|
195
|
+
if isinstance(value, Page):
|
|
196
|
+
value.parent = parent
|
|
197
|
+
items.append(value)
|
|
198
|
+
continue
|
|
199
|
+
dirname, sub = value
|
|
200
|
+
section = Section(name=dirname, parent=parent, page=sub.index)
|
|
201
|
+
section.children = build(sub, section)
|
|
202
|
+
if not section.children and sub.index is not None:
|
|
203
|
+
sub.index.parent = parent # lone index page: no need for a section
|
|
204
|
+
items.append(sub.index)
|
|
205
|
+
continue
|
|
206
|
+
if sub.index is not None:
|
|
207
|
+
sub.index.parent = section
|
|
208
|
+
items.append(section)
|
|
209
|
+
return items
|
|
210
|
+
|
|
211
|
+
items = build(root, None)
|
|
212
|
+
if root.index is not None:
|
|
213
|
+
root.index.parent = None
|
|
214
|
+
items.insert(0, root.index)
|
|
215
|
+
return items
|
mdbake/page.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""The :class:`Page` model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import posixpath
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from .files import File
|
|
10
|
+
from .toc import AnchorLink
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .nav import Section
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def pretty_title(name: str) -> str:
|
|
17
|
+
"""``getting-started`` -> ``Getting started``."""
|
|
18
|
+
text = name.replace("-", " ").replace("_", " ").strip()
|
|
19
|
+
return text[:1].upper() + text[1:] if text else name
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(eq=False)
|
|
23
|
+
class Page:
|
|
24
|
+
file: File
|
|
25
|
+
meta: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
markdown: str = ""
|
|
27
|
+
html: str = ""
|
|
28
|
+
toc: list[AnchorLink] = field(default_factory=list)
|
|
29
|
+
h1_title: str | None = None
|
|
30
|
+
nav_title: str | None = None
|
|
31
|
+
skip: bool = False
|
|
32
|
+
anchors: set[str] = field(default_factory=set)
|
|
33
|
+
parent: Section | None = None
|
|
34
|
+
previous_page: Page | None = None
|
|
35
|
+
next_page: Page | None = None
|
|
36
|
+
|
|
37
|
+
is_page = True
|
|
38
|
+
is_section = False
|
|
39
|
+
is_link = False
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def src_path(self) -> str:
|
|
43
|
+
return self.file.src_path
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def url(self) -> str:
|
|
47
|
+
return self.file.url
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def is_index(self) -> bool:
|
|
51
|
+
return self.file.is_index
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def is_homepage(self) -> bool:
|
|
55
|
+
return self.url == "index.html"
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def title(self) -> str:
|
|
59
|
+
"""Explicit nav title > frontmatter ``title`` > first H1 > file name."""
|
|
60
|
+
meta_title = self.meta.get("title")
|
|
61
|
+
return self.nav_title or (str(meta_title) if meta_title else None) or self.h1_title or self._fallback_title()
|
|
62
|
+
|
|
63
|
+
def _fallback_title(self) -> str:
|
|
64
|
+
directory, name = posixpath.split(self.src_path)
|
|
65
|
+
if self.is_index:
|
|
66
|
+
return pretty_title(posixpath.basename(directory)) if directory else "Home"
|
|
67
|
+
return pretty_title(name.rsplit(".", 1)[0])
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def ancestors(self) -> list[Section]:
|
|
71
|
+
result = []
|
|
72
|
+
node = self.parent
|
|
73
|
+
while node is not None:
|
|
74
|
+
result.append(node)
|
|
75
|
+
node = node.parent
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
def __repr__(self) -> str:
|
|
79
|
+
return f"Page({self.src_path!r})"
|
mdbake/theme/base.html
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="{{ extra.get('lang', 'en') }}">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>{% if page.is_homepage %}{{ site_name }}{% else %}{{ page.title }} · {{ site_name }}{% endif %}</title>
|
|
7
|
+
{% if page.meta.description %}
|
|
8
|
+
<meta name="description" content="{{ page.meta.description }}">
|
|
9
|
+
{% endif %}
|
|
10
|
+
<link rel="stylesheet" href="{{ assets_url }}/style.css">
|
|
11
|
+
<link rel="stylesheet" href="{{ assets_url }}/pygments.css">
|
|
12
|
+
{% block extrahead %}{% endblock %}
|
|
13
|
+
</head>
|
|
14
|
+
<body>
|
|
15
|
+
<input type="checkbox" id="nav-toggle" class="nav-toggle" aria-hidden="true">
|
|
16
|
+
<header class="topbar">
|
|
17
|
+
<label for="nav-toggle" class="nav-toggle-label" title="Toggle navigation">☰</label>
|
|
18
|
+
<a class="site-name" href="{{ home_url }}">{{ site_name }}</a>
|
|
19
|
+
</header>
|
|
20
|
+
<div class="layout">
|
|
21
|
+
<nav class="sidebar" aria-label="Site navigation">
|
|
22
|
+
{% include "nav.html" %}
|
|
23
|
+
</nav>
|
|
24
|
+
<main class="content">
|
|
25
|
+
{% block content %}
|
|
26
|
+
<article class="markdown-body">
|
|
27
|
+
{{ page.html | safe }}
|
|
28
|
+
</article>
|
|
29
|
+
{% endblock %}
|
|
30
|
+
{% if page.previous_page or page.next_page %}
|
|
31
|
+
<footer class="pager">
|
|
32
|
+
{% if page.previous_page %}
|
|
33
|
+
<a class="prev" href="{{ url(page.previous_page.url) }}" rel="prev"><span>Previous</span>{{ page.previous_page.title }}</a>
|
|
34
|
+
{% endif %}
|
|
35
|
+
{% if page.next_page %}
|
|
36
|
+
<a class="next" href="{{ url(page.next_page.url) }}" rel="next"><span>Next</span>{{ page.next_page.title }}</a>
|
|
37
|
+
{% endif %}
|
|
38
|
+
</footer>
|
|
39
|
+
{% endif %}
|
|
40
|
+
</main>
|
|
41
|
+
<aside class="toc" aria-label="On this page">
|
|
42
|
+
{% include "toc.html" %}
|
|
43
|
+
</aside>
|
|
44
|
+
</div>
|
|
45
|
+
</body>
|
|
46
|
+
</html>
|