diff --git a/.gitignore b/.gitignore index 7bbc71c..4ea7119 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 f4c8122..7b76574 100755 --- a/babel_runner.py +++ b/babel_runner.py @@ -4,10 +4,12 @@ import argparse import ast +import json import subprocess import tomllib from pathlib import Path +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 +109,49 @@ 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 JavaScript messages from the PO catalog.""" + jsfile = pofile.with_suffix(".js") + with pofile.open("rb") as f: + source = read_po(f) + if source.fuzzy: + jsfile.unlink(missing_ok=True) + return + messages = {} + for message in source: + 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 + 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" + f"Documentation.addTranslations({serialized});\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 ba70242..2225968 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/**/*.js", + "python_docs_theme/locale/**/*.mo", +] 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 1d51947..2ff17cf 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__,