sphinx-fonts 0.0.1a0__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,225 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ # Generated by sphinx_fonts extension (downloaded at build time)
210
+ docs/_static/fonts/
211
+ docs/_static/css/fonts.css
212
+
213
+ # Claude Code
214
+ **/CLAUDE.local.md
215
+ **/CLAUDE.*.md
216
+ **/.claude/settings.local.json
217
+
218
+ # Playwright MCP
219
+ .playwright-mcp/
220
+
221
+ # Misc
222
+ .vim/
223
+ *.lprof
224
+ pip-wheel-metadata/
225
+ monkeytype.sqlite3
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: sphinx-fonts
3
+ Version: 0.0.1a0
4
+ Summary: Sphinx extension for self-hosted fonts via Fontsource CDN
5
+ Project-URL: Repository, https://github.com/git-pull/gp-sphinx
6
+ Author-email: Tony Narlock <tony@git-pull.com>
7
+ License: MIT
8
+ Keywords: fonts,fontsource,self-hosted,sphinx
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: Sphinx
11
+ Classifier: Framework :: Sphinx :: Extension
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Documentation
21
+ Classifier: Topic :: Documentation :: Sphinx
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: <4.0,>=3.10
24
+ Requires-Dist: sphinx
25
+ Description-Content-Type: text/markdown
26
+
27
+ # sphinx-fonts
28
+
29
+ Sphinx extension for self-hosted fonts via [Fontsource](https://fontsource.org/) CDN.
30
+
31
+ Downloads font files at build time, caches them locally (`~/.cache/sphinx-fonts`), and
32
+ injects `@font-face` declarations via Jinja2 template context.
33
+
34
+ ## Install
35
+
36
+ ```console
37
+ $ pip install sphinx-fonts
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ In your `docs/conf.py`:
43
+
44
+ ```python
45
+ extensions = ["sphinx_fonts"]
46
+
47
+ sphinx_fonts = [
48
+ {
49
+ "family": "IBM Plex Sans",
50
+ "package": "@fontsource/ibm-plex-sans",
51
+ "version": "5.2.8",
52
+ "weights": [400, 500, 600, 700],
53
+ "styles": ["normal", "italic"],
54
+ "subset": "latin",
55
+ },
56
+ ]
57
+
58
+ sphinx_font_css_variables = {
59
+ "--font-stack": '"IBM Plex Sans", sans-serif',
60
+ }
61
+ ```
62
+
63
+ Requires a `page.html` template override that reads the `font_faces` and
64
+ `font_preload_hrefs` context variables. See the
65
+ [gp-sphinx docs](https://gp-sphinx.git-pull.com) for a complete template example.
@@ -0,0 +1,39 @@
1
+ # sphinx-fonts
2
+
3
+ Sphinx extension for self-hosted fonts via [Fontsource](https://fontsource.org/) CDN.
4
+
5
+ Downloads font files at build time, caches them locally (`~/.cache/sphinx-fonts`), and
6
+ injects `@font-face` declarations via Jinja2 template context.
7
+
8
+ ## Install
9
+
10
+ ```console
11
+ $ pip install sphinx-fonts
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ In your `docs/conf.py`:
17
+
18
+ ```python
19
+ extensions = ["sphinx_fonts"]
20
+
21
+ sphinx_fonts = [
22
+ {
23
+ "family": "IBM Plex Sans",
24
+ "package": "@fontsource/ibm-plex-sans",
25
+ "version": "5.2.8",
26
+ "weights": [400, 500, 600, 700],
27
+ "styles": ["normal", "italic"],
28
+ "subset": "latin",
29
+ },
30
+ ]
31
+
32
+ sphinx_font_css_variables = {
33
+ "--font-stack": '"IBM Plex Sans", sans-serif',
34
+ }
35
+ ```
36
+
37
+ Requires a `page.html` template override that reads the `font_faces` and
38
+ `font_preload_hrefs` context variables. See the
39
+ [gp-sphinx docs](https://gp-sphinx.git-pull.com) for a complete template example.
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "sphinx-fonts"
3
+ version = "0.0.1a0"
4
+ description = "Sphinx extension for self-hosted fonts via Fontsource CDN"
5
+ requires-python = ">=3.10,<4.0"
6
+ authors = [
7
+ {name = "Tony Narlock", email = "tony@git-pull.com"}
8
+ ]
9
+ license = { text = "MIT" }
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Framework :: Sphinx",
14
+ "Framework :: Sphinx :: Extension",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Topic :: Documentation",
23
+ "Topic :: Documentation :: Sphinx",
24
+ "Typing :: Typed",
25
+ ]
26
+ readme = "README.md"
27
+ keywords = ["sphinx", "fonts", "fontsource", "self-hosted"]
28
+ dependencies = [
29
+ "sphinx",
30
+ ]
31
+
32
+ [project.urls]
33
+ Repository = "https://github.com/git-pull/gp-sphinx"
34
+
35
+ [build-system]
36
+ requires = ["hatchling"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/sphinx_fonts"]
@@ -0,0 +1,270 @@
1
+ """Sphinx extension for self-hosted fonts via Fontsource CDN.
2
+
3
+ Downloads font files at build time, caches them locally, and passes
4
+ structured font data to the template context for inline @font-face CSS.
5
+
6
+ Examples
7
+ --------
8
+ >>> from sphinx_fonts import _cache_dir
9
+
10
+ >>> _cache_dir().name
11
+ 'sphinx-fonts'
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import pathlib
18
+ import shutil
19
+ import typing as t
20
+ import urllib.error
21
+ import urllib.request
22
+
23
+ if t.TYPE_CHECKING:
24
+ from sphinx.application import Sphinx
25
+
26
+ logger = logging.getLogger(__name__)
27
+ logger.addHandler(logging.NullHandler())
28
+ __version__ = "0.0.1a0"
29
+
30
+ CDN_TEMPLATE = (
31
+ "https://cdn.jsdelivr.net/npm/{package}@{version}"
32
+ "/files/{font_id}-{subset}-{weight}-{style}.woff2"
33
+ )
34
+
35
+
36
+ class SetupDict(t.TypedDict):
37
+ """Return type for Sphinx extension setup()."""
38
+
39
+ version: str
40
+ parallel_read_safe: bool
41
+ parallel_write_safe: bool
42
+
43
+
44
+ class _FontConfigRequired(t.TypedDict):
45
+ family: str
46
+ package: str
47
+ version: str
48
+ weights: list[int]
49
+ styles: list[str]
50
+
51
+
52
+ class FontConfig(_FontConfigRequired, total=False):
53
+ """A single font family configuration entry.
54
+
55
+ Required keys: ``family``, ``package``, ``version``, ``weights``, ``styles``.
56
+ Optional key: ``subset`` (defaults to ``"latin"`` when omitted).
57
+ """
58
+
59
+ subset: str
60
+
61
+
62
+ def _cache_dir() -> pathlib.Path:
63
+ """Return the local font cache directory.
64
+
65
+ Returns
66
+ -------
67
+ pathlib.Path
68
+ Path to ``~/.cache/sphinx-fonts``.
69
+
70
+ Examples
71
+ --------
72
+ >>> _cache_dir().name
73
+ 'sphinx-fonts'
74
+ """
75
+ return pathlib.Path.home() / ".cache" / "sphinx-fonts"
76
+
77
+
78
+ def _cdn_url(
79
+ package: str,
80
+ version: str,
81
+ font_id: str,
82
+ subset: str,
83
+ weight: int,
84
+ style: str,
85
+ ) -> str:
86
+ """Build a Fontsource CDN URL for a specific font variant.
87
+
88
+ Parameters
89
+ ----------
90
+ package : str
91
+ Fontsource npm package name (e.g., ``@fontsource/ibm-plex-sans``).
92
+ version : str
93
+ Package version.
94
+ font_id : str
95
+ Font identifier (last segment of package name).
96
+ subset : str
97
+ Unicode subset (e.g., ``latin``).
98
+ weight : int
99
+ Font weight (e.g., 400, 700).
100
+ style : str
101
+ Font style (e.g., ``normal``, ``italic``).
102
+
103
+ Returns
104
+ -------
105
+ str
106
+ Full CDN URL.
107
+
108
+ Examples
109
+ --------
110
+ >>> url = _cdn_url(
111
+ ... "@fontsource/ibm-plex-sans", "5.2.8",
112
+ ... "ibm-plex-sans", "latin", 400, "normal",
113
+ ... )
114
+ >>> "ibm-plex-sans-latin-400-normal.woff2" in url
115
+ True
116
+ """
117
+ return CDN_TEMPLATE.format(
118
+ package=package,
119
+ version=version,
120
+ font_id=font_id,
121
+ subset=subset,
122
+ weight=weight,
123
+ style=style,
124
+ )
125
+
126
+
127
+ def _download_font(url: str, dest: pathlib.Path) -> bool:
128
+ """Download a font file from the CDN, using local cache.
129
+
130
+ Parameters
131
+ ----------
132
+ url : str
133
+ URL to download from.
134
+ dest : pathlib.Path
135
+ Local path to write the file to.
136
+
137
+ Returns
138
+ -------
139
+ bool
140
+ True if the file is available (downloaded or cached).
141
+ """
142
+ if dest.exists():
143
+ logger.debug("font cached: %s", dest.name)
144
+ return True
145
+ dest.parent.mkdir(parents=True, exist_ok=True)
146
+ try:
147
+ urllib.request.urlretrieve(url, dest)
148
+ logger.info("downloaded font: %s", dest.name)
149
+ except (urllib.error.URLError, OSError):
150
+ if dest.exists():
151
+ dest.unlink()
152
+ logger.warning("failed to download font: %s", url)
153
+ return False
154
+ return True
155
+
156
+
157
+ def _on_builder_inited(app: Sphinx) -> None:
158
+ """Download fonts and prepare template context data on builder init."""
159
+ if app.builder.format != "html":
160
+ return
161
+
162
+ fonts: list[FontConfig] = app.config.sphinx_fonts
163
+ variables: dict[str, str] = app.config.sphinx_font_css_variables
164
+ if not fonts:
165
+ return
166
+
167
+ cache = _cache_dir()
168
+ static_dir = pathlib.Path(app.outdir) / "_static"
169
+ fonts_dir = static_dir / "fonts"
170
+ fonts_dir.mkdir(parents=True, exist_ok=True)
171
+
172
+ font_faces: list[dict[str, str]] = []
173
+ for font in fonts:
174
+ font_id = font["package"].split("/")[-1]
175
+ version = font["version"]
176
+ package = font["package"]
177
+ subset = font.get("subset", "latin")
178
+ for weight in font["weights"]:
179
+ for style in font["styles"]:
180
+ filename = f"{font_id}-{subset}-{weight}-{style}.woff2"
181
+ cached = cache / filename
182
+ url = _cdn_url(package, version, font_id, subset, weight, style)
183
+ if _download_font(url, cached):
184
+ shutil.copy2(cached, fonts_dir / filename)
185
+ font_faces.append(
186
+ {
187
+ "family": font["family"],
188
+ "style": style,
189
+ "weight": str(weight),
190
+ "filename": filename,
191
+ }
192
+ )
193
+
194
+ preload_hrefs: list[str] = []
195
+ preload_specs: list[tuple[str, int, str]] = app.config.sphinx_font_preload
196
+ for family_name, weight, style in preload_specs:
197
+ for font in fonts:
198
+ if font["family"] == family_name:
199
+ font_id = font["package"].split("/")[-1]
200
+ subset = font.get("subset", "latin")
201
+ filename = f"{font_id}-{subset}-{weight}-{style}.woff2"
202
+ preload_hrefs.append(filename)
203
+ break
204
+
205
+ fallbacks: list[dict[str, str]] = app.config.sphinx_font_fallbacks
206
+
207
+ app._font_preload_hrefs = preload_hrefs # type: ignore[attr-defined]
208
+ app._font_faces = font_faces # type: ignore[attr-defined]
209
+ app._font_fallbacks = fallbacks # type: ignore[attr-defined]
210
+ app._font_css_variables = variables # type: ignore[attr-defined]
211
+
212
+
213
+ def _on_html_page_context(
214
+ app: Sphinx,
215
+ pagename: str,
216
+ templatename: str,
217
+ context: dict[str, t.Any],
218
+ doctree: t.Any,
219
+ ) -> None:
220
+ """Inject font data into Jinja2 template context."""
221
+ context["font_preload_hrefs"] = getattr(app, "_font_preload_hrefs", [])
222
+ context["font_faces"] = getattr(app, "_font_faces", [])
223
+ context["font_fallbacks"] = getattr(app, "_font_fallbacks", [])
224
+ context["font_css_variables"] = getattr(app, "_font_css_variables", {})
225
+
226
+
227
+ def setup(app: Sphinx) -> SetupDict:
228
+ """Register config values, events, and return extension metadata.
229
+
230
+ Parameters
231
+ ----------
232
+ app : Sphinx
233
+ The Sphinx application object.
234
+
235
+ Returns
236
+ -------
237
+ SetupDict
238
+ Extension metadata.
239
+ """
240
+ app.add_config_value(
241
+ "sphinx_fonts",
242
+ [],
243
+ "html",
244
+ description="Font family dicts (family, package, version, weights, styles).",
245
+ )
246
+ app.add_config_value(
247
+ "sphinx_font_fallbacks",
248
+ [],
249
+ "html",
250
+ description="Fallback @font-face declarations with metric overrides for CLS.",
251
+ )
252
+ app.add_config_value(
253
+ "sphinx_font_css_variables",
254
+ {},
255
+ "html",
256
+ description="CSS custom properties for Furo font stacks (e.g. --font-stack)",
257
+ )
258
+ app.add_config_value(
259
+ "sphinx_font_preload",
260
+ [],
261
+ "html",
262
+ description="Critical font variants to preload (family, weight, style).",
263
+ )
264
+ app.connect("builder-inited", _on_builder_inited)
265
+ app.connect("html-page-context", _on_html_page_context)
266
+ return {
267
+ "version": __version__,
268
+ "parallel_read_safe": True,
269
+ "parallel_write_safe": True,
270
+ }
File without changes