Skip to content

Commit 243f079

Browse files
committed
Generate and load JavaScript translation catalogs
1 parent db635c1 commit 243f079

4 files changed

Lines changed: 71 additions & 1 deletion

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ coverage.xml
4848

4949
# Translations
5050
*.mo
51+
/python_docs_theme/locale/**/*.js
5152
*.pot
5253

5354
# Django stuff:

‎babel_runner.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
import argparse
66
import ast
7+
import json
78
import subprocess
89
import tomllib
910
from pathlib import Path
1011

12+
from babel.messages.mofile import read_mo
13+
from babel.messages.pofile import read_po
1114
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
1215

1316
# Global variables used by pybabel below (paths relative to PROJECT_DIR)
@@ -107,6 +110,43 @@ def compile_catalogs(locale: str) -> None:
107110
cmd.extend(["-l", locale])
108111
subprocess.run(cmd, cwd=PROJECT_DIR, check=True)
109112

113+
locale_dirs = PROJECT_DIR / LOCALES_DIR
114+
catalogs = (
115+
[locale_dirs / locale / "LC_MESSAGES" / f"{DOMAIN}.po"]
116+
if locale
117+
else sorted(locale_dirs.glob(f"*/LC_MESSAGES/{DOMAIN}.po"))
118+
)
119+
for pofile in catalogs:
120+
compile_js_catalog(pofile)
121+
122+
123+
def compile_js_catalog(pofile: Path) -> None:
124+
"""Export translated singular JavaScript messages from the compiled catalog."""
125+
mofile = pofile.with_suffix(".mo")
126+
jsfile = pofile.with_suffix(".js")
127+
if not mofile.exists():
128+
jsfile.unlink(missing_ok=True)
129+
return
130+
with pofile.open("rb") as f:
131+
source = read_po(f)
132+
with mofile.open("rb") as f:
133+
compiled = read_mo(f)
134+
messages = {}
135+
for message in source:
136+
if not isinstance(message.id, str):
137+
continue
138+
if not any(filename.endswith(".js") for filename, _ in message.locations):
139+
continue
140+
translation = compiled.get(message.id)
141+
if translation is not None and translation.string:
142+
messages[message.id] = translation.string
143+
jsfile.write_text(
144+
"Object.assign(Documentation.TRANSLATIONS, "
145+
+ json.dumps(messages, ensure_ascii=True, sort_keys=True)
146+
+ ");\n",
147+
encoding="utf-8",
148+
)
149+
110150

111151
class CustomBuildHook(BuildHookInterface):
112152
def initialize(self, version: str, build_data: dict[str, object]) -> None:

‎pyproject.toml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ entry-points."sphinx.html_themes".python_docs_theme = "python_docs_theme"
4040

4141
[tool.hatch]
4242
version.path = "python_docs_theme/__init__.py"
43-
build.artifacts = [ "python_docs_theme/locale/**/*.mo" ]
43+
build.artifacts = [
44+
"python_docs_theme/locale/**/*.mo",
45+
"python_docs_theme/locale/**/*.js",
46+
]
4447
build.hooks.custom.path = "babel_runner.py"
4548
build.targets.wheel.packages = [ "python_docs_theme" ]
4649
build.targets.wheel.exclude = [

‎python_docs_theme/__init__.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from __future__ import annotations
22

3+
from gettext import find
34
from pathlib import Path
5+
from shutil import copyfile
46

57
from sphinx.locale import get_translation
68

@@ -37,12 +39,36 @@ def combined(message: str) -> str:
3739
context["_"] = context["gettext"] = context["ngettext"] = combined
3840

3941

42+
def get_js_catalog(app: Sphinx) -> Path | None:
43+
catalog = find(
44+
MESSAGE_CATALOG_NAME,
45+
localedir=LOCALE_DIR,
46+
languages=[app.config.language or "en"],
47+
)
48+
if catalog is not None:
49+
js_catalog = Path(catalog).with_suffix(".js")
50+
if js_catalog.is_file():
51+
return js_catalog
52+
return None
53+
54+
55+
def add_js_translations(app: Sphinx) -> None:
56+
if app.builder.format != "html":
57+
return
58+
if catalog := get_js_catalog(app):
59+
static_dir = Path(app.outdir) / "_static"
60+
static_dir.mkdir(parents=True, exist_ok=True)
61+
copyfile(catalog, static_dir / "python-docs-theme-translations.js")
62+
app.add_js_file("python-docs-theme-translations.js")
63+
64+
4065
def setup(app: Sphinx) -> ExtensionMetadata:
4166
app.require_sphinx("7.3")
4267

4368
app.add_html_theme("python_docs_theme", str(THEME_PATH))
4469
app.add_message_catalog(MESSAGE_CATALOG_NAME, LOCALE_DIR)
4570
app.connect("html-page-context", add_translation_to_context)
71+
app.connect("builder-inited", add_js_translations)
4672

4773
return {
4874
"version": __version__,

0 commit comments

Comments
 (0)