From 243f079fa7684a09452d526e58243d47ae5c55f4 Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Sat, 21 Nov 2026 23:09:10 +0100 Subject: [PATCH 1/4] Generate and load JavaScript translation catalogs --- .gitignore | 1 + babel_runner.py | 40 +++++++++++++++++++++++++++++++++++ pyproject.toml | 5 ++++- python_docs_theme/__init__.py | 26 +++++++++++++++++++++++ 4 files changed, 71 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 7bbc71c0..4ea71192 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,7 @@ coverage.xml # Translations *.mo +/python_docs_theme/locale/**/*.js *.pot # Django stuff: diff --git a/babel_runner.py b/babel_runner.py index f4c81228..62cb9932 100755 --- a/babel_runner.py +++ b/babel_runner.py @@ -4,10 +4,13 @@ import argparse import ast +import json import subprocess import tomllib from pathlib import Path +from babel.messages.mofile import read_mo +from babel.messages.pofile import read_po from hatchling.builders.hooks.plugin.interface import BuildHookInterface # Global variables used by pybabel below (paths relative to PROJECT_DIR) @@ -107,6 +110,43 @@ def compile_catalogs(locale: str) -> None: cmd.extend(["-l", locale]) subprocess.run(cmd, cwd=PROJECT_DIR, check=True) + locale_dirs = PROJECT_DIR / LOCALES_DIR + catalogs = ( + [locale_dirs / locale / "LC_MESSAGES" / f"{DOMAIN}.po"] + if locale + else sorted(locale_dirs.glob(f"*/LC_MESSAGES/{DOMAIN}.po")) + ) + for pofile in catalogs: + compile_js_catalog(pofile) + + +def compile_js_catalog(pofile: Path) -> None: + """Export translated singular JavaScript messages from the compiled catalog.""" + mofile = pofile.with_suffix(".mo") + jsfile = pofile.with_suffix(".js") + if not mofile.exists(): + jsfile.unlink(missing_ok=True) + return + with pofile.open("rb") as f: + source = read_po(f) + with mofile.open("rb") as f: + compiled = read_mo(f) + messages = {} + for message in source: + if not isinstance(message.id, str): + continue + if not any(filename.endswith(".js") for filename, _ in message.locations): + continue + translation = compiled.get(message.id) + if translation is not None and translation.string: + messages[message.id] = translation.string + jsfile.write_text( + "Object.assign(Documentation.TRANSLATIONS, " + + json.dumps(messages, ensure_ascii=True, sort_keys=True) + + ");\n", + encoding="utf-8", + ) + class CustomBuildHook(BuildHookInterface): def initialize(self, version: str, build_data: dict[str, object]) -> None: diff --git a/pyproject.toml b/pyproject.toml index ba702421..3d3ff2c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,10 @@ entry-points."sphinx.html_themes".python_docs_theme = "python_docs_theme" [tool.hatch] version.path = "python_docs_theme/__init__.py" -build.artifacts = [ "python_docs_theme/locale/**/*.mo" ] +build.artifacts = [ + "python_docs_theme/locale/**/*.mo", + "python_docs_theme/locale/**/*.js", +] build.hooks.custom.path = "babel_runner.py" build.targets.wheel.packages = [ "python_docs_theme" ] build.targets.wheel.exclude = [ diff --git a/python_docs_theme/__init__.py b/python_docs_theme/__init__.py index 1d51947d..2ff17cf7 100644 --- a/python_docs_theme/__init__.py +++ b/python_docs_theme/__init__.py @@ -1,6 +1,8 @@ from __future__ import annotations +from gettext import find from pathlib import Path +from shutil import copyfile from sphinx.locale import get_translation @@ -37,12 +39,36 @@ def combined(message: str) -> str: context["_"] = context["gettext"] = context["ngettext"] = combined +def get_js_catalog(app: Sphinx) -> Path | None: + catalog = find( + MESSAGE_CATALOG_NAME, + localedir=LOCALE_DIR, + languages=[app.config.language or "en"], + ) + if catalog is not None: + js_catalog = Path(catalog).with_suffix(".js") + if js_catalog.is_file(): + return js_catalog + return None + + +def add_js_translations(app: Sphinx) -> None: + if app.builder.format != "html": + return + if catalog := get_js_catalog(app): + static_dir = Path(app.outdir) / "_static" + static_dir.mkdir(parents=True, exist_ok=True) + copyfile(catalog, static_dir / "python-docs-theme-translations.js") + app.add_js_file("python-docs-theme-translations.js") + + def setup(app: Sphinx) -> ExtensionMetadata: app.require_sphinx("7.3") app.add_html_theme("python_docs_theme", str(THEME_PATH)) app.add_message_catalog(MESSAGE_CATALOG_NAME, LOCALE_DIR) app.connect("html-page-context", add_translation_to_context) + app.connect("builder-inited", add_js_translations) return { "version": __version__, From bd78daa70fcba20d393abf273a4a516a37c1c339 Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Sun, 22 Nov 2026 11:18:04 +0100 Subject: [PATCH 2/4] Add header comment to JS translation catalogs for uniqueness, order artifact paths alphabetically in pyproject.toml --- babel_runner.py | 1 + pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/babel_runner.py b/babel_runner.py index 62cb9932..af53e921 100755 --- a/babel_runner.py +++ b/babel_runner.py @@ -141,6 +141,7 @@ def compile_js_catalog(pofile: Path) -> None: if translation is not None and translation.string: messages[message.id] = translation.string jsfile.write_text( + f"// {DOMAIN} translations for {pofile.parents[1].name}\n" "Object.assign(Documentation.TRANSLATIONS, " + json.dumps(messages, ensure_ascii=True, sort_keys=True) + ");\n", diff --git a/pyproject.toml b/pyproject.toml index 3d3ff2c4..2225968c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,8 +41,8 @@ entry-points."sphinx.html_themes".python_docs_theme = "python_docs_theme" [tool.hatch] version.path = "python_docs_theme/__init__.py" build.artifacts = [ - "python_docs_theme/locale/**/*.mo", "python_docs_theme/locale/**/*.js", + "python_docs_theme/locale/**/*.mo", ] build.hooks.custom.path = "babel_runner.py" build.targets.wheel.packages = [ "python_docs_theme" ] From 6b10012324de94b1c0361173d865a5d8c24cd29f Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Mon, 23 Nov 2026 23:42:01 +0100 Subject: [PATCH 3/4] Generate JavaScript translations directly from PO catalogs Affirm-Session: 01a20a8a-1869-7c52-8e68-246dde4499c5 --- babel_runner.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/babel_runner.py b/babel_runner.py index af53e921..234be548 100755 --- a/babel_runner.py +++ b/babel_runner.py @@ -9,7 +9,6 @@ import tomllib from pathlib import Path -from babel.messages.mofile import read_mo from babel.messages.pofile import read_po from hatchling.builders.hooks.plugin.interface import BuildHookInterface @@ -121,25 +120,22 @@ def compile_catalogs(locale: str) -> None: def compile_js_catalog(pofile: Path) -> None: - """Export translated singular JavaScript messages from the compiled catalog.""" - mofile = pofile.with_suffix(".mo") + """Export translated singular JavaScript messages from the PO catalog.""" jsfile = pofile.with_suffix(".js") - if not mofile.exists(): - jsfile.unlink(missing_ok=True) - return with pofile.open("rb") as f: source = read_po(f) - with mofile.open("rb") as f: - compiled = read_mo(f) + if source.fuzzy: + jsfile.unlink(missing_ok=True) + return messages = {} for message in source: if not isinstance(message.id, str): continue if not any(filename.endswith(".js") for filename, _ in message.locations): continue - translation = compiled.get(message.id) - if translation is not None and translation.string: - messages[message.id] = translation.string + if message.context is not None or message.fuzzy or not message.string: + continue + messages[message.id] = message.string jsfile.write_text( f"// {DOMAIN} translations for {pofile.parents[1].name}\n" "Object.assign(Documentation.TRANSLATIONS, " From fb80b8204ac381ff5d9e8b10d396c71db434ab03 Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Tue, 24 Nov 2026 00:09:01 +0100 Subject: [PATCH 4/4] Support plural JavaScript translations with Sphinx addTranslations Affirm-Session: 01a20a8a-1869-7c52-8e68-246dde4499c5 --- babel_runner.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/babel_runner.py b/babel_runner.py index 234be548..7b765740 100755 --- a/babel_runner.py +++ b/babel_runner.py @@ -120,7 +120,7 @@ def compile_catalogs(locale: str) -> None: def compile_js_catalog(pofile: Path) -> None: - """Export translated singular JavaScript messages from the PO catalog.""" + """Export translated JavaScript messages from the PO catalog.""" jsfile = pofile.with_suffix(".js") with pofile.open("rb") as f: source = read_po(f) @@ -129,18 +129,26 @@ def compile_js_catalog(pofile: Path) -> None: return messages = {} for message in source: - if not isinstance(message.id, str): - continue if not any(filename.endswith(".js") for filename, _ in message.locations): continue if message.context is not None or message.fuzzy or not message.string: continue - messages[message.id] = message.string + if message.pluralizable and not all(message.string): + continue + msgid = message.id[0] if message.pluralizable else message.id + messages[msgid] = message.string + serialized = json.dumps( + { + "locale": str(source.locale), + "messages": messages, + "plural_expr": f"Number({source.plural_expr})", + }, + ensure_ascii=True, + sort_keys=True, + ) jsfile.write_text( f"// {DOMAIN} translations for {pofile.parents[1].name}\n" - "Object.assign(Documentation.TRANSLATIONS, " - + json.dumps(messages, ensure_ascii=True, sort_keys=True) - + ");\n", + f"Documentation.addTranslations({serialized});\n", encoding="utf-8", )