doxtr-epub-theme-core 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Doxtr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: doxtr-epub-theme-core
3
+ Version: 0.1.0
4
+ Summary: Core accessible Sphinx EPUB3 theme powered by doxtr-theme-core with WCAG contrast and light/dark mode support.
5
+ Author: Jens Frey
6
+ Project-URL: Homepage, https://github.com/doxtr/doxtr-epub-theme-core
7
+ Project-URL: Repository, https://github.com/doxtr/doxtr-epub-theme-core
8
+ Project-URL: Issues, https://github.com/doxtr/doxtr-epub-theme-core/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Framework :: Sphinx :: Extension
14
+ Classifier: Framework :: Sphinx :: Theme
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Documentation :: Sphinx
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: doxtr-theme-core>=0.2.0
22
+ Requires-Dist: Sphinx>=7.0
23
+ Requires-Dist: Pillow>=10.0
24
+ Dynamic: license-file
25
+
26
+ # doxtr-epub-theme-core
27
+
28
+ Core accessible Sphinx EPUB3 theme powered by `doxtr-theme-core`.
29
+
30
+ ## Features
31
+
32
+ - Consumes brand specs (`ColorPalette`, `FontSpec`, `BrandConfig`) from `doxtr-theme-core`
33
+ - Emits EPUB3-compatible hex CSS variables (`light`, `dark`, and `auto` modes via `prefers-color-scheme` and reader dark-mode selectors)
34
+ - Enforces WCAG contrast across semantic palette tokens, Pygments syntax CSS, and SVG covers
35
+ - Automatically pairs user `-dark` / `_dark` assets or adapts bright raster/SVG diagrams while preserving strict XHTML validity
36
+ - Generates an accessible SVG EPUB cover with shared `doxtr-theme-core` icon fallback
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install doxtr-epub-theme-core
42
+ ```
43
+
44
+ ## Usage
45
+
46
+ ```python
47
+ extensions = ["doxtr_epub_theme_core"]
48
+ epub_theme = "doxtr_epub_core"
49
+ ```
@@ -0,0 +1,24 @@
1
+ # doxtr-epub-theme-core
2
+
3
+ Core accessible Sphinx EPUB3 theme powered by `doxtr-theme-core`.
4
+
5
+ ## Features
6
+
7
+ - Consumes brand specs (`ColorPalette`, `FontSpec`, `BrandConfig`) from `doxtr-theme-core`
8
+ - Emits EPUB3-compatible hex CSS variables (`light`, `dark`, and `auto` modes via `prefers-color-scheme` and reader dark-mode selectors)
9
+ - Enforces WCAG contrast across semantic palette tokens, Pygments syntax CSS, and SVG covers
10
+ - Automatically pairs user `-dark` / `_dark` assets or adapts bright raster/SVG diagrams while preserving strict XHTML validity
11
+ - Generates an accessible SVG EPUB cover with shared `doxtr-theme-core` icon fallback
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install doxtr-epub-theme-core
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```python
22
+ extensions = ["doxtr_epub_theme_core"]
23
+ epub_theme = "doxtr_epub_core"
24
+ ```
@@ -0,0 +1,229 @@
1
+ """Core accessible Sphinx EPUB3 theme powered by ``doxtr-theme-core``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from sphinx.util import logging
10
+
11
+ from doxtr_theme_core import (
12
+ DEFAULT_CORE_THEME_SPEC,
13
+ add_config_value_if_missing,
14
+ fonts as _tc_fonts,
15
+ generate_css_font_faces,
16
+ get_active_theme,
17
+ get_default_icon_path,
18
+ get_registered_fonts,
19
+ process_user_font_config,
20
+ register_renderer,
21
+ )
22
+ from doxtr_theme_core.fonts import collect_font_files
23
+
24
+ from .cover import build_cover_svg_from_config
25
+ from .images import collect_epub_image_opt_outs, process_epub_theme_images
26
+ from .tokens import generate_epub_tokens_css, resolve_epub_palettes, rewrite_epub_pygments_css
27
+
28
+ __version__ = "0.1.0"
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ THEME_DIR = Path(__file__).resolve().parent
33
+ EPUB_FONT_EXTENSIONS = frozenset({".ttf", ".otf", ".woff"})
34
+
35
+ register_renderer("epub", "core", "doxtr_epub_theme_core", html_theme_name="doxtr_epub_core")
36
+
37
+
38
+ def _is_epub_builder(app: Any) -> bool:
39
+ builder = getattr(app, "builder", None)
40
+ if builder is None:
41
+ return False
42
+ return str(getattr(builder, "name", "") or "").lower().startswith("epub")
43
+
44
+
45
+ def _write_cover_svg(app: Any, light_palette: dict[str, str], dark_palette: dict[str, str], scheme: str, wcag_level: float) -> None:
46
+ if not getattr(app.config, "doxtr_epub_auto_cover", True):
47
+ return
48
+ if not getattr(app, "_doxtr_epub_owns_cover", False):
49
+ return
50
+ outdir = Path(app.outdir)
51
+ static_dir = outdir / "_static"
52
+ static_dir.mkdir(parents=True, exist_ok=True)
53
+ try:
54
+ default_icon = get_default_icon_path()
55
+ except FileNotFoundError:
56
+ default_icon = None
57
+ svg_text = build_cover_svg_from_config(
58
+ app.config,
59
+ light_palette,
60
+ dark_palette,
61
+ scheme=scheme,
62
+ icon_path=default_icon,
63
+ wcag_level=wcag_level,
64
+ )
65
+ (static_dir / "doxtr-epub-cover.svg").write_text(svg_text, encoding="utf-8")
66
+
67
+
68
+ def _finalize_epub_assets(app: Any) -> None:
69
+ """Write EPUB CSS tokens, WCAG Pygments CSS, cover SVG, fonts, and dark images before zip."""
70
+ if not _is_epub_builder(app):
71
+ return
72
+ outdir = Path(app.outdir)
73
+ static_dir = outdir / "_static"
74
+ static_dir.mkdir(parents=True, exist_ok=True)
75
+
76
+ spec, light_pal, dark_pal, wcag_level, wcag_debug, scheme = resolve_epub_palettes(app.config)
77
+
78
+ font_faces_css = ""
79
+ if getattr(app.config, "doxtr_epub_embed_fonts", False):
80
+ if getattr(app.config, "doxtr_fonts", None):
81
+ process_user_font_config(app.config.doxtr_fonts, str(app.confdir))
82
+ registered = list(get_registered_fonts())
83
+ seen_names = {entry.get("name") for entry in registered}
84
+ for api_entry in getattr(_tc_fonts, "_api_font_registrations", ()):
85
+ if api_entry.get("name") not in seen_names:
86
+ registered.append(api_entry)
87
+ font_files = [
88
+ Path(f)
89
+ for f in collect_font_files(registered)
90
+ if Path(f).suffix.lower() in EPUB_FONT_EXTENSIONS and Path(f).is_file()
91
+ ]
92
+ if font_files:
93
+ fonts_out = static_dir / "fonts"
94
+ fonts_out.mkdir(parents=True, exist_ok=True)
95
+ for src_path in font_files:
96
+ shutil.copy2(src_path, fonts_out / src_path.name)
97
+ font_faces_css = generate_css_font_faces(registered, url_prefix="fonts/")
98
+
99
+ fonts = spec.fonts
100
+ tokens_css = generate_epub_tokens_css(
101
+ light_pal,
102
+ dark_pal,
103
+ scheme=scheme,
104
+ css_body_stack=fonts.css_body_stack,
105
+ css_heading_stack=fonts.css_heading_stack,
106
+ css_mono_stack=fonts.css_mono_stack,
107
+ font_faces_css=font_faces_css,
108
+ )
109
+ (static_dir / "doxtr-epub-tokens.css").write_text(tokens_css, encoding="utf-8")
110
+
111
+ pyg_wcag = float(getattr(app.config, "doxtr_pygments_wcag_level", None) or wcag_level)
112
+ pyg_light_path = static_dir / "pygments.css"
113
+ pyg_dark_path = static_dir / "pygments_dark.css"
114
+ if scheme == "dark" and pyg_dark_path.is_file():
115
+ dark_raw = pyg_dark_path.read_text(encoding="utf-8", errors="ignore")
116
+ fixed_dark = rewrite_epub_pygments_css(
117
+ dark_raw,
118
+ dark_pal["code_bg"],
119
+ dark_pal["code_fg"],
120
+ wcag_level=pyg_wcag,
121
+ color_debug=wcag_debug,
122
+ )
123
+ pyg_dark_path.write_text(fixed_dark, encoding="utf-8")
124
+ # Also populate pygments.css with dark tokens so readers ignoring media queries render cleanly
125
+ pyg_light_path.write_text(fixed_dark, encoding="utf-8")
126
+ else:
127
+ if pyg_light_path.is_file():
128
+ raw_l = pyg_light_path.read_text(encoding="utf-8", errors="ignore")
129
+ pyg_light_path.write_text(
130
+ rewrite_epub_pygments_css(
131
+ raw_l,
132
+ light_pal["code_bg"],
133
+ light_pal["code_fg"],
134
+ wcag_level=pyg_wcag,
135
+ color_debug=wcag_debug,
136
+ ),
137
+ encoding="utf-8",
138
+ )
139
+ if pyg_dark_path.is_file():
140
+ raw_d = pyg_dark_path.read_text(encoding="utf-8", errors="ignore")
141
+ pyg_dark_path.write_text(
142
+ rewrite_epub_pygments_css(
143
+ raw_d,
144
+ dark_pal["code_bg"],
145
+ dark_pal["code_fg"],
146
+ wcag_level=pyg_wcag,
147
+ color_debug=wcag_debug,
148
+ ),
149
+ encoding="utf-8",
150
+ )
151
+
152
+ process_epub_theme_images(app, dark_pal, scheme=scheme)
153
+ _write_cover_svg(app, light_pal, dark_pal, scheme, wcag_level)
154
+
155
+
156
+ def _on_builder_inited(app: Any) -> None:
157
+ if not _is_epub_builder(app):
158
+ return
159
+ app.add_css_file("doxtr-epub-tokens.css", priority=150)
160
+ app.add_css_file("doxtr-epub-core.css", priority=175)
161
+
162
+ # Wire auto-cover before gen_additional_pages if user didn't configure epub_cover
163
+ app._doxtr_epub_owns_cover = False
164
+ if getattr(app.config, "doxtr_epub_auto_cover", True) and not getattr(app.config, "epub_cover", None):
165
+ app._doxtr_epub_owns_cover = True
166
+ app.config.epub_cover = ("_static/doxtr-epub-cover.svg", "epub-cover.html")
167
+ _, light_pal, dark_pal, wcag_level, _, scheme = resolve_epub_palettes(app.config)
168
+ _write_cover_svg(app, light_pal, dark_pal, scheme, wcag_level)
169
+
170
+ builder = app.builder
171
+ if not getattr(builder, "_doxtr_epub_wrapped_finish", False):
172
+ orig_handle_finish = builder.handle_finish
173
+
174
+ def _wrapped_handle_finish() -> Any:
175
+ try:
176
+ _finalize_epub_assets(app)
177
+ except Exception as exc: # pragma: no cover - defensive build guard
178
+ logger.warning("[Doxtr EPUB Core] Failed finalizing EPUB assets: %s", exc)
179
+ return orig_handle_finish()
180
+
181
+ builder.handle_finish = _wrapped_handle_finish
182
+ builder._doxtr_epub_wrapped_finish = True
183
+
184
+
185
+ def _on_doctree_resolved(app: Any, doctree: Any, docname: str) -> None:
186
+ if _is_epub_builder(app):
187
+ collect_epub_image_opt_outs(app, doctree)
188
+
189
+
190
+ def _inject_epub_page_context(
191
+ app: Any,
192
+ pagename: str,
193
+ templatename: str,
194
+ context: dict[str, Any],
195
+ doctree: Any,
196
+ ) -> None:
197
+ if not _is_epub_builder(app):
198
+ return
199
+ spec = get_active_theme(app.config) or DEFAULT_CORE_THEME_SPEC
200
+ _, _, _, _, _, scheme = resolve_epub_palettes(app.config)
201
+
202
+ context["doxtr_color_scheme"] = scheme
203
+ context["doxtr_active_brand"] = spec.name
204
+ context["doxtr_brand"] = spec.branding
205
+ context["doxtr_epub_body_class"] = f"doxtr-scheme-{scheme}"
206
+ context["doxtr_epub_meta_color_scheme"] = (
207
+ "light dark" if scheme == "auto" else scheme
208
+ )
209
+
210
+
211
+ def setup(app: Any) -> dict[str, Any]:
212
+ """Sphinx extension entry point for ``doxtr_epub_theme_core``."""
213
+ app.setup_extension("doxtr_theme_core")
214
+ add_config_value_if_missing(app, "doxtr_epub_dark_images", True, "env")
215
+ add_config_value_if_missing(app, "doxtr_epub_dark_image_brightness_threshold", 0.65, "env")
216
+ add_config_value_if_missing(app, "doxtr_epub_embed_fonts", False, "env")
217
+ add_config_value_if_missing(app, "doxtr_epub_auto_cover", True, "env")
218
+ add_config_value_if_missing(app, "doxtr_epub_cover_style", {}, "env")
219
+
220
+ app.add_html_theme("doxtr_epub_core", str(THEME_DIR))
221
+ app.connect("builder-inited", _on_builder_inited)
222
+ app.connect("doctree-resolved", _on_doctree_resolved)
223
+ app.connect("html-page-context", _inject_epub_page_context, priority=600)
224
+
225
+ return {
226
+ "version": __version__,
227
+ "parallel_read_safe": True,
228
+ "parallel_write_safe": True,
229
+ }
@@ -0,0 +1,174 @@
1
+ """SVG EPUB cover generation with WCAG-verified contrast and brand icon support."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import html
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from doxtr_theme_core import get_default_icon_path, get_highest_contrast_color
11
+
12
+ _SVG_WIDTH = 600
13
+ _SVG_HEIGHT = 900
14
+
15
+
16
+ def _wrap_text(text: str, max_chars: int = 22, max_lines: int = 4) -> list[str]:
17
+ words = text.strip().split()
18
+ if not words:
19
+ return ["Documentation"]
20
+ lines: list[str] = []
21
+ cur = ""
22
+ for word in words:
23
+ cand = f"{cur} {word}".strip() if cur else word
24
+ if len(cand) <= max_chars or not cur:
25
+ cur = cand
26
+ else:
27
+ lines.append(cur)
28
+ cur = word
29
+ if len(lines) >= max_lines - 1:
30
+ break
31
+ if len(lines) < max_lines and cur:
32
+ lines.append(cur)
33
+ return lines[:max_lines]
34
+
35
+
36
+ def _encode_png_data_uri(icon_path: Path | None) -> str:
37
+ if icon_path is None or not icon_path.is_file():
38
+ return ""
39
+ suffix = icon_path.suffix.lower()
40
+ mime = "image/png" if suffix == ".png" else "image/jpeg" if suffix in {".jpg", ".jpeg"} else ""
41
+ if not mime:
42
+ return ""
43
+ payload = base64.b64encode(icon_path.read_bytes()).decode("ascii")
44
+ return f"data:{mime};base64,{payload}"
45
+
46
+
47
+ def generate_epub_cover_svg(
48
+ *,
49
+ title: str,
50
+ subtitle: str = "",
51
+ author: str = "",
52
+ version: str = "",
53
+ background_color: str = "#183060",
54
+ surface_color: str = "#243B6B",
55
+ accent_color: str = "#78D8F0",
56
+ title_color: str = "#FFFFFF",
57
+ muted_color: str = "#CBD5E1",
58
+ icon_path: Path | None = None,
59
+ wcag_level: float = 4.5,
60
+ ) -> str:
61
+ """Render a valid 600x900 SVG EPUB cover with WCAG AA verified text colors."""
62
+ safe_title_color = (
63
+ get_highest_contrast_color(title_color, background_color, target="foreground", wcag_level=wcag_level)
64
+ or "#FFFFFF"
65
+ )
66
+ safe_sub_color = (
67
+ get_highest_contrast_color(accent_color, background_color, target="foreground", wcag_level=wcag_level)
68
+ or safe_title_color
69
+ )
70
+ safe_muted_color = (
71
+ get_highest_contrast_color(muted_color, background_color, target="foreground", wcag_level=wcag_level)
72
+ or safe_title_color
73
+ )
74
+
75
+ resolved_icon = icon_path
76
+ if resolved_icon is None:
77
+ try:
78
+ resolved_icon = get_default_icon_path()
79
+ except FileNotFoundError:
80
+ resolved_icon = None
81
+ icon_uri = _encode_png_data_uri(resolved_icon)
82
+
83
+ title_lines = _wrap_text(title or "Documentation", max_chars=22, max_lines=4)
84
+ title_start_y = 320
85
+ line_step = 54
86
+ title_tspans = "\n".join(
87
+ f' <text x="56" y="{title_start_y + idx * line_step}" '
88
+ f'font-family="sans-serif" font-size="42" font-weight="700" '
89
+ f'fill="{safe_title_color}">{html.escape(line, quote=True)}</text>'
90
+ for idx, line in enumerate(title_lines)
91
+ )
92
+
93
+ sub_y = title_start_y + len(title_lines) * line_step + 24
94
+ sub_el = (
95
+ f' <text x="56" y="{sub_y}" font-family="sans-serif" font-size="22" font-weight="500" '
96
+ f'fill="{safe_sub_color}">{html.escape(subtitle, quote=True)}</text>'
97
+ if subtitle.strip()
98
+ else ""
99
+ )
100
+ icon_el = (
101
+ f' <image x="56" y="72" width="84" height="84" '
102
+ f'href="{icon_uri}" xlink:href="{icon_uri}" preserveAspectRatio="xMidYMid meet" />'
103
+ if icon_uri
104
+ else ""
105
+ )
106
+ author_el = (
107
+ f' <text x="56" y="796" font-family="sans-serif" font-size="20" font-weight="600" '
108
+ f'fill="{safe_title_color}">{html.escape(author, quote=True)}</text>'
109
+ if author.strip()
110
+ else ""
111
+ )
112
+ ver_el = (
113
+ f' <text x="56" y="832" font-family="monospace" font-size="16" '
114
+ f'fill="{safe_muted_color}">{html.escape(version, quote=True)}</text>'
115
+ if version.strip()
116
+ else ""
117
+ )
118
+
119
+ return f"""<?xml version="1.0" encoding="UTF-8"?>
120
+ <svg xmlns="http://www.w3.org/2000/svg"
121
+ xmlns:xlink="http://www.w3.org/1999/xlink"
122
+ width="{_SVG_WIDTH}" height="{_SVG_HEIGHT}" viewBox="0 0 {_SVG_WIDTH} {_SVG_HEIGHT}">
123
+ <rect x="0" y="0" width="{_SVG_WIDTH}" height="{_SVG_HEIGHT}" fill="{background_color}" />
124
+ <rect x="0" y="0" width="18" height="{_SVG_HEIGHT}" fill="{accent_color}" />
125
+ <rect x="40" y="44" width="520" height="812" rx="14" fill="{surface_color}" opacity="0.32" />
126
+ <rect x="56" y="218" width="120" height="6" rx="3" fill="{accent_color}" />
127
+ {icon_el}
128
+ {title_tspans}
129
+ {sub_el}
130
+ {author_el}
131
+ {ver_el}
132
+ </svg>
133
+ """
134
+
135
+
136
+ def build_cover_svg_from_config(
137
+ config: Any,
138
+ light_palette: dict[str, str],
139
+ dark_palette: dict[str, str],
140
+ *,
141
+ scheme: str = "auto",
142
+ icon_path: Path | None = None,
143
+ wcag_level: float = 4.5,
144
+ ) -> str:
145
+ """Create SVG cover markup from Sphinx config + resolved brand palettes."""
146
+ custom_style = dict(getattr(config, "doxtr_epub_cover_style", None) or {})
147
+ use_dark = scheme == "dark"
148
+ base = dark_palette if use_dark else light_palette
149
+
150
+ bg = str(custom_style.get("background_color") or ("#141A29" if not use_dark else base.get("page", "#1A1721")))
151
+ surface = str(custom_style.get("surface_color") or base.get("surface", "#24304A"))
152
+ accent = str(custom_style.get("accent_color") or base.get("accent") or base.get("primary") or "#78D8F0")
153
+ title_col = str(custom_style.get("title_color") or "#FFFFFF")
154
+ muted_col = str(custom_style.get("muted_color") or base.get("text_muted") or "#CBD5E1")
155
+
156
+ project = str(getattr(config, "project", "") or "Documentation")
157
+ author = str(getattr(config, "author", "") or "")
158
+ rel = str(getattr(config, "release", "") or getattr(config, "version", "") or "")
159
+ version_label = f"Release {rel}" if rel else ""
160
+ subtitle = str(custom_style.get("subtitle") or "")
161
+
162
+ return generate_epub_cover_svg(
163
+ title=project,
164
+ subtitle=subtitle,
165
+ author=author,
166
+ version=version_label,
167
+ background_color=bg,
168
+ surface_color=surface,
169
+ accent_color=accent,
170
+ title_color=title_col,
171
+ muted_color=muted_col,
172
+ icon_path=icon_path,
173
+ wcag_level=wcag_level,
174
+ )