diff --git a/scripts/test-website.py b/scripts/test-website.py index 55342c80dcb..6b749686e7b 100644 --- a/scripts/test-website.py +++ b/scripts/test-website.py @@ -21,7 +21,7 @@ from urllib.request import build_opener, ProxyHandler, urlopen import xml.etree.ElementTree as ET import polib -from website_i18n import FALLBACK_NOTICE, Document, build_translations, checked_catalog, extract_catalogs, languages, prose_units, reading_pages, read_runtime +from website_i18n import FALLBACK_NOTICE, SUGGESTION_DISMISS, SUGGESTION_OFFER, Document, language_markup, required_messages, build_translations, checked_catalog, extract_catalogs, languages, prose_units, reading_pages, read_runtime ROOT = Path(__file__).resolve().parent.parent @@ -763,6 +763,22 @@ class WebsiteTranslationChecks(unittest.TestCase): base = "https://example.com" + prefix self.assertEqual(urljoin(base + encoded, picker.attrs["href"]), base + "zh-CN/" + encoded) + def test_language_offer_labels_decorate_only_complete_editions(self): + # A missing offer label must never turn a translated page into a fallback. + site = ROOT / "website/public" + template = extract_catalogs(ROOT, check=True) + offer_keys = {("runtime", SUGGESTION_OFFER), ("runtime", SUGGESTION_DISMISS)} + for path in reading_pages(site): + with self.subTest(page=path.relative_to(site).as_posix()): + self.assertFalse(offer_keys & required_messages(ROOT, path, template)) + suggestions = {"en": (SUGGESTION_OFFER, SUGGESTION_DISMISS), "pt-BR": ('Ver "esta" página', "Fechar"), "bg": ("Вижте", "Затвори")} + selector, _ = language_markup(ROOT, "index.html", "en", {"en", "pt-BR"}, suggestions) + links = {node.attrs["data-language"]: node.attrs for node in Document(selector).nodes if "data-language" in node.attrs} + self.assertEqual(links["pt-BR"]["data-offer"], 'Ver "esta" página') + self.assertEqual(links["pt-BR"]["data-dismiss"], "Fechar") + self.assertNotIn("data-offer", links["bg"]) # English fallback edition + self.assertNotIn("data-offer", links["de"]) # no label supplied + def test_language_inventory_preserves_script_identity(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/scripts/website_i18n.py b/scripts/website_i18n.py index 96533aadc0b..9c7558a1aa9 100644 --- a/scripts/website_i18n.py +++ b/scripts/website_i18n.py @@ -25,6 +25,14 @@ ATTRIBUTES = {"alt", "aria-label", "aria-description", "title", "placeholder"} PLACEHOLDER = re.compile(r"\{([a-zA-Z][a-zA-Z0-9_]*)\}") LITERALS = {"REA", "Reverse Engineer Anything", "REA · Reverse Engineer Anything", "GitHub", "Discord", "FAQ", "MCP", "CLI", "CSV", "JSON", "HTML", "CSS", "JavaScript", "Electron", "Hopper", "Ghidra", "IDA", "Windows", "Linux", "macOS", "Notion", "DX-Ball", "TH04", "TH08", "TH095", "Aegis", "SHA-1", "HMAC", "Node.js", "Windows PowerShell", "macOS · Homebrew", "npm", "npx", "DOS", "PC-98"} FALLBACK_NOTICE = "Translation is being updated. Read this page in English for now." +# The browser-language suggestion speaks the offered language, so each catalog +# names itself. These labels decorate the selector and never gate a page. +SUGGESTION_OFFER = "View this page in English" +SUGGESTION_DISMISS = "Dismiss" +SUGGESTION_NOTES = { + SUGGESTION_OFFER: "Offer this page in your own language and name it, for example Ver esta página em português.", + SUGGESTION_DISMISS: "Accessible name of the button that hides the language offer.", +} LANGUAGE_CODE = re.compile(r"[a-z]{2}(?:-[A-Z][a-z]{3})?(?:-[A-Z]{2})?") @@ -91,8 +99,12 @@ def localized_path(relative, code): return Path(relative) if code == "en" else Path(code) / relative -def language_markup(root, relative, code="en", available=None): - """Render a keyboard-accessible same-page selector and reciprocal hreflang links.""" +def language_markup(root, relative, code="en", available=None, suggestions=None): + """Render a keyboard-accessible same-page selector and reciprocal hreflang links. + + Suggestions map a language code to its own offer and dismiss labels; the + browser-language offer reads them from the selector's translated choices. + """ from website import SITE_ORIGIN, page_route inventory = languages(root) available = set(available) if available is not None else {item["code"] for item in inventory} @@ -106,7 +118,9 @@ def language_markup(root, relative, code="en", available=None): href = base + target active = ' aria-current="true"' if item["code"] == code else "" fallback = " · English" if item["code"] not in available else "" - choices.append(f'{escape(item["name"])}{fallback}') + labels = (suggestions or {}).get(item["code"]) if item["code"] in available else None + offer = f' data-offer="{escape(labels[0], quote=True)}" data-dismiss="{escape(labels[1], quote=True)}"' if labels else "" + choices.append(f'{escape(item["name"])}{fallback}') if item["code"] in available: alternates.append(f'\n') alternates.append(f'\n') @@ -291,6 +305,8 @@ def attribute_units(source, path): def runtime_units(root): """Extract the constrained t("literal", namedValues) authoring form directly.""" yield "fallback", FALLBACK_NOTICE, "scripts/website_i18n.py", "" + for text in SUGGESTION_NOTES: + yield "suggestion", text, "scripts/website_i18n.py", "" site = root / "website/public" for path in sorted((site / "assets").glob("*.js")): if path.name == "i18n.js": # Owns t itself, rather than reader-facing calls. @@ -346,6 +362,8 @@ def source_catalog(root): add(context, text, slots, "website/public/" + relative, node.line) for _, text, reference, line in runtime_units(root): add("runtime", text, {}, reference, line) + for text, note in SUGGESTION_NOTES.items(): + entries[("runtime", text)].comment = note for path in sorted((site / "assets/figures").glob("*.svg")): source = path.read_text(encoding="utf-8") for node in Document(source).nodes: @@ -496,9 +514,9 @@ def relative_reference(reference, source_path, output_path, site, available, cod return urlunsplit(("", "", quote(destination, safe="/"), parsed.query, parsed.fragment)) -def replace_language_markup(source, root, relative, code, available): +def replace_language_markup(source, root, relative, code, available, suggestions=None): """Derive selectors and alternates from the same page-level completeness decision.""" - selector, alternates = language_markup(root, relative, code, available) + selector, alternates = language_markup(root, relative, code, available, suggestions) document = Document(source) picker = next(node for node in document.nodes if node.tag == "details" and node.attrs.get("class") == "language-picker") source = apply_edits(source, [(picker.start, picker.end, selector)]) @@ -550,7 +568,7 @@ def rewrite_edition_tags(root, source_path, source, language, *, metadata=None, return apply_edits(source, replacements) -def render_page(root, source_path, language, messages, available, figures, page_languages): +def render_page(root, source_path, language, messages, available, figures, page_languages, suggestions=None): """Create one complete translation, preserving routes, code, IDs and reference data.""" from website import PageMetadata site = root / "website/public" @@ -567,7 +585,7 @@ def render_page(root, source_path, language, messages, available, figures, page_ source = apply_edits(source, [(node.start, node.open_end, replacements[node.start]) for node in Document(source).nodes if node.start in replacements]) metadata.feed(source) source = rewrite_edition_tags(root, source_path, source, language, metadata=metadata, available=available, figures=figures) - source = replace_language_markup(source, root, relative, code, page_languages) + source = replace_language_markup(source, root, relative, code, page_languages, suggestions) runtime = {text: messages[("runtime", text)] for text in read_runtime(root, source_path)} payload = json.dumps(runtime, ensure_ascii=False).replace("<", "\\u003c").replace("&", "\\u0026") # Only Korean editions request the font stylesheet; English fallbacks keep @@ -600,14 +618,14 @@ def required_messages(root, path, template): return required -def render_fallback(root, path, language, page_languages, messages): +def render_fallback(root, path, language, page_languages, messages, suggestions=None): """Expose a clear English fallback instead of a stale or partially translated article.""" relative = path.relative_to(root / "website/public").as_posix() code = language["code"] source = path.read_text(encoding="utf-8") source = rewrite_edition_tags(root, path, source, language) source = source.replace("", '\n ') - source = replace_language_markup(source, root, relative, code, page_languages) + source = replace_language_markup(source, root, relative, code, page_languages, suggestions) notice = messages.get(("runtime", FALLBACK_NOTICE), FALLBACK_NOTICE) translated = ("runtime", FALLBACK_NOTICE) in messages # An untranslated notice is English text and keeps English direction. @@ -628,6 +646,11 @@ def build_translations(root, destination, finalize=None): catalogs = {language["code"]: checked_catalog(root, language, template)[0] for language in inventory[1:]} required = {path.relative_to(site).as_posix(): required_messages(root, path, template) for path in pages} page_languages = {relative: {"en"} | {code for code, messages in catalogs.items() if keys <= messages.keys()} for relative, keys in required.items()} + suggestions = {"en": (SUGGESTION_OFFER, SUGGESTION_DISMISS)} + for code, messages in catalogs.items(): + offer, dismiss = (messages.get(("runtime", text)) for text in (SUGGESTION_OFFER, SUGGESTION_DISMISS)) + if offer and dismiss: + suggestions[code] = offer, dismiss # Finish rendering before replacing the previous preview/publish artifact. with TemporaryDirectory(prefix=".i18n-", dir=root / "website") as directory: staging = Path(directory) / "site" @@ -635,7 +658,7 @@ def build_translations(root, destination, finalize=None): for path in pages: relative = path.relative_to(site).as_posix() output = staging / relative - output.write_text(replace_language_markup(path.read_text(encoding="utf-8"), root, relative, "en", page_languages[relative]), encoding="utf-8") + output.write_text(replace_language_markup(path.read_text(encoding="utf-8"), root, relative, "en", page_languages[relative], suggestions), encoding="utf-8") for language in inventory[1:]: messages = catalogs[language["code"]] available = {relative for relative, codes in page_languages.items() if language["code"] in codes} @@ -658,7 +681,7 @@ def build_translations(root, destination, finalize=None): relative = path.relative_to(site).as_posix() output = staging / localized_path(relative, language["code"]) output.parent.mkdir(parents=True, exist_ok=True) - rendered = render_page(root, path, language, messages, available, figures, page_languages[relative]) if relative in available else render_fallback(root, path, language, page_languages[relative], messages) + rendered = render_page(root, path, language, messages, available, figures, page_languages[relative], suggestions) if relative in available else render_fallback(root, path, language, page_languages[relative], messages, suggestions) output.write_text(rendered, encoding="utf-8") fallback_count = len(pages) - len(available) if fallback_count: diff --git a/website/README.md b/website/README.md index 8a12e89c686..84b60724f6f 100644 --- a/website/README.md +++ b/website/README.md @@ -12,7 +12,12 @@ scripts for copying code, following code comparisons and playing the dinosaur speed reconstruction. Small Python commands maintain shared HTML, prepare downloads and check the site. The site uses ordinary static files without a frontend framework or bundler. A build generates all editions in -`website/_site/`. Language switching needs no JavaScript. +`website/_site/`. Language switching needs no JavaScript. When the browser's +languages prefer another complete edition of the page, a small floating offer +links to it in that language until the reader picks a language or dismisses it. +Each catalog's `View this page in English` and `Dismiss` messages supply the offer +in its own language; without them the offer shows the language name, and the +page's translation status is unaffected. Korean editions load the variable Noto Sans KR webfont through Google Fonts (`fonts.googleapis.com` and `fonts.gstatic.com`) so the preferred Korean font diff --git a/website/locales/ar/messages.po b/website/locales/ar/messages.po index 8a45a4474aa..c44aa202d7c 100644 --- a/website/locales/ar/messages.po +++ b/website/locales/ar/messages.po @@ -15682,6 +15682,19 @@ msgstr "" " تشغيله. يستخدم هذا المثال 6.10.1. يتتبع السكربت الموجود في الفرع الافتراضي " "main، ولا يرتبط بإصدار محدد ثابت." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "اعرض هذه الصفحة بالعربية" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "إغلاق" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/bg/messages.po b/website/locales/bg/messages.po index e9515858e32..016ebcc3ade 100644 --- a/website/locales/bg/messages.po +++ b/website/locales/bg/messages.po @@ -14132,6 +14132,19 @@ msgstr "" "Скриптът от клона по подразбиране следва main и не е фиксиран към конкретна " "издадена версия." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Вижте тази страница на български" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Затвори" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/de/messages.po b/website/locales/de/messages.po index 128d999957e..50debc715b5 100644 --- a/website/locales/de/messages.po +++ b/website/locales/de/messages.po @@ -16309,6 +16309,19 @@ msgstr "" "Beispiel verwendet 6.10.1. Das Skript des Standardbranches folgt main und " "ist nicht auf ein bestimmtes Release festgelegt." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Diese Seite auf Deutsch ansehen" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Schließen" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/el/messages.po b/website/locales/el/messages.po index 3485df6122a..f30a1f34b49 100644 --- a/website/locales/el/messages.po +++ b/website/locales/el/messages.po @@ -16270,6 +16270,19 @@ msgstr "" "χρησιμοποιεί την έκδοση 6.10.1. Το σενάριο του προεπιλεγμένου κλάδου " "ακολουθεί το main και δεν είναι συνδεδεμένο με μια συγκεκριμένη έκδοση." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Δείτε αυτή τη σελίδα στα ελληνικά" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Κλείσιμο" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/es/messages.po b/website/locales/es/messages.po index b4036ccba1b..06345129b88 100644 --- a/website/locales/es/messages.po +++ b/website/locales/es/messages.po @@ -16313,6 +16313,19 @@ msgstr "" "de la rama predeterminada sigue main y no está fijado a una versión " "concreta." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Ver esta página en español" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Cerrar" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/fa/messages.po b/website/locales/fa/messages.po index 62658eb86b9..eb5b902cf4b 100644 --- a/website/locales/fa/messages.po +++ b/website/locales/fa/messages.po @@ -15844,6 +15844,19 @@ msgstr "" "استفاده می‌کند. اسکریپت شاخهٔ پیش‌فرض تغییرات main را دنبال می‌کند و روی " "انتشار مشخصی ثابت نشده است." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "این صفحه را به فارسی ببینید" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "بستن" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/fr/messages.po b/website/locales/fr/messages.po index fe6e3b19a34..05d1f602228 100644 --- a/website/locales/fr/messages.po +++ b/website/locales/fr/messages.po @@ -16243,6 +16243,19 @@ msgstr "" "exemple utilise 6.10.1. Le script de la branche par défaut suit main et " "n’est pas figé sur une version précise." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Voir cette page en français" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Fermer" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/id/messages.po b/website/locales/id/messages.po index d6282fa1f36..12fea652c42 100644 --- a/website/locales/id/messages.po +++ b/website/locales/id/messages.po @@ -16069,6 +16069,19 @@ msgstr "" " tag rilis sebelum menjalankannya. Contoh ini menggunakan 6.10.1. Skrip dari" " cabang default mengikuti main dan tidak dipatok ke rilis tertentu." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Lihat halaman ini dalam Bahasa Indonesia" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Tutup" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/it/messages.po b/website/locales/it/messages.po index 42c9e50521c..734d6226955 100644 --- a/website/locales/it/messages.po +++ b/website/locales/it/messages.po @@ -16143,6 +16143,19 @@ msgstr "" "esempio usa 6.10.1. Lo script del ramo predefinito segue main e non è " "vincolato a un rilascio specifico." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Visualizza questa pagina in italiano" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Chiudi" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/ja/messages.po b/website/locales/ja/messages.po index 944a6464a48..ef7b9a1dcfd 100644 --- a/website/locales/ja/messages.po +++ b/website/locales/ja/messages.po @@ -14964,6 +14964,19 @@ msgstr "" "を準備してください。実行する前に、リリースタグから取得したインストーラーの内容を確認してください。この例では 6.10.1 " "を使用します。デフォルトブランチのスクリプトは main の更新に追従し、特定のリリースに固定されていません。" +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "このページを日本語で表示" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "閉じる" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/ko/messages.po b/website/locales/ko/messages.po index 0073bc5f338..914c5e84faa 100644 --- a/website/locales/ko/messages.po +++ b/website/locales/ko/messages.po @@ -15032,6 +15032,19 @@ msgstr "" "검토하세요. 이 예제에서는 6.10.1을 사용합니다. 기본 브랜치의 스크립트는 main의 변경 사항을 따라가며 특정 릴리스에 고정되어 " "있지 않습니다." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "이 페이지를 한국어로 보기" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "닫기" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/messages.pot b/website/locales/messages.pot index 77a4cc5a7ea..249d96fc343 100644 --- a/website/locales/messages.pot +++ b/website/locales/messages.pot @@ -13274,6 +13274,19 @@ msgctxt "runtime" msgid "Translation is being updated. Read this page in English for now." msgstr "" +#. Offer this page in your own language and name it, for example Ver esta página em +#. português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "" + #: website/public/assets/aegis-demo.js:22 #, python-brace-format msgctxt "runtime" diff --git a/website/locales/ml/messages.po b/website/locales/ml/messages.po index 77b8d6da1e9..3b434598504 100644 --- a/website/locales/ml/messages.po +++ b/website/locales/ml/messages.po @@ -14155,6 +14155,19 @@ msgstr "" "main-ലെ മാറ്റങ്ങൾ പിന്തുടരുന്നു. അത് ഒരു പ്രത്യേക റിലീസിൽ " "സ്ഥിരപ്പെടുത്തിയതല്ല." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "ഈ പേജ് മലയാളത്തിൽ കാണുക" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "അടയ്ക്കുക" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/pl/messages.po b/website/locales/pl/messages.po index 61dc31977b1..62982fa90bc 100644 --- a/website/locales/pl/messages.po +++ b/website/locales/pl/messages.po @@ -16030,6 +16030,19 @@ msgstr "" "Skrypt z domyślnej gałęzi śledzi main i nie jest przypięty do konkretnego " "wydania." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Zobacz tę stronę po polsku" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Zamknij" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/pt-BR/messages.po b/website/locales/pt-BR/messages.po index 89274b28122..2ee7cd29990 100644 --- a/website/locales/pt-BR/messages.po +++ b/website/locales/pt-BR/messages.po @@ -16108,6 +16108,19 @@ msgstr "" "tag de versão antes de executá-lo. Este exemplo usa 6.10.1. O script da " "branch padrão acompanha main e não está fixado em uma versão específica." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Ver esta página em português" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Fechar" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/ro/messages.po b/website/locales/ro/messages.po index 42bff33f6b3..db4b9af54d3 100644 --- a/website/locales/ro/messages.po +++ b/website/locales/ro/messages.po @@ -14155,6 +14155,19 @@ msgstr "" "folosește 6.10.1. Scriptul din ramura implicită urmărește main și nu este " "fixat la o anumită versiune publicată." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Vezi această pagină în română" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Închide" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/ru/messages.po b/website/locales/ru/messages.po index d0b9c3e0103..40c4b459336 100644 --- a/website/locales/ru/messages.po +++ b/website/locales/ru/messages.po @@ -16142,6 +16142,19 @@ msgstr "" "Скрипт из ветки по умолчанию обновляется вместе с main и не закреплён за " "конкретным выпуском." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Открыть эту страницу на русском" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Закрыть" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/th/messages.po b/website/locales/th/messages.po index 32a216e8d49..8aa86d7aae0 100644 --- a/website/locales/th/messages.po +++ b/website/locales/th/messages.po @@ -15737,6 +15737,19 @@ msgstr "" "สคริปต์ในสาขาเริ่มต้นจะเปลี่ยนตาม main " "และไม่ได้ตรึงไว้กับรุ่นที่เผยแพร่รุ่นใดรุ่นหนึ่ง" +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "ดูหน้านี้เป็นภาษาไทย" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "ปิด" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/tr/messages.po b/website/locales/tr/messages.po index f59b0f926a5..515e0ba476e 100644 --- a/website/locales/tr/messages.po +++ b/website/locales/tr/messages.po @@ -16005,6 +16005,19 @@ msgstr "" "kullanılır. Varsayılan dalın betiği main dalını takip eder ve belirli bir " "sürüme sabitlenmemiştir." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Bu sayfayı Türkçe görüntüleyin" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Kapat" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/uk/messages.po b/website/locales/uk/messages.po index f63cb2d476f..84f9e638c3d 100644 --- a/website/locales/uk/messages.po +++ b/website/locales/uk/messages.po @@ -16089,6 +16089,19 @@ msgstr "" "6.10.1. Скрипт із типової гілки відстежує main і не зафіксований на " "конкретному релізі." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Відкрити цю сторінку українською" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Закрити" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/ur-Latn/messages.po b/website/locales/ur-Latn/messages.po index 72df6f38fb2..87dab2cce0e 100644 --- a/website/locales/ur-Latn/messages.po +++ b/website/locales/ur-Latn/messages.po @@ -14148,6 +14148,19 @@ msgstr "" "istemal kiya gaya hai. Default branch ka script main ki tabdeeliyon ke saath" " badalta hai aur kisi muayyan release par muqarrar nahin hai." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Yeh safha Roman Urdu mein dekhein" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Band karein" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/vi/messages.po b/website/locales/vi/messages.po index ed883febfe1..7e9734b519b 100644 --- a/website/locales/vi/messages.po +++ b/website/locales/vi/messages.po @@ -16095,6 +16095,19 @@ msgstr "" "trên nhánh mặc định thay đổi theo main và không được cố định ở một bản phát " "hành cụ thể." +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "Xem trang này bằng tiếng Việt" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "Đóng" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/zh-CN/messages.po b/website/locales/zh-CN/messages.po index d7fc15746f3..9c656bb7635 100644 --- a/website/locales/zh-CN/messages.po +++ b/website/locales/zh-CN/messages.po @@ -14689,6 +14689,19 @@ msgstr "" "在 macOS 或 Linux 上,请先准备好 Node.js。运行安装脚本前,请先审阅发布标签中的脚本。本示例使用 6.10.1。默认分支的脚本随 " "main 更新,并未固定到某个发布版本。" +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "以简体中文查看此页面" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "关闭" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/locales/zh-TW/messages.po b/website/locales/zh-TW/messages.po index ce451433ba8..3d855503c2e 100644 --- a/website/locales/zh-TW/messages.po +++ b/website/locales/zh-TW/messages.po @@ -14660,6 +14660,19 @@ msgstr "" "在 macOS 或 Linux 上,請先準備好 Node.js。執行安裝腳本前,請先檢閱發行標籤中的腳本。本範例使用 6.10.1。預設分支的腳本會隨 " "main 更新,並未固定至特定發行版本。" +#. Offer this page in your own language and name it, for example Ver esta +#. página em português. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "View this page in English" +msgstr "以繁體中文檢視此頁面" + +#. Accessible name of the button that hides the language offer. +#: scripts/website_i18n.py +msgctxt "runtime" +msgid "Dismiss" +msgstr "關閉" + #~ msgctxt "page:get-started/index.html" #~ msgid "" #~ "On macOS or Linux, you can also use the curl installer after preparing " diff --git a/website/public/assets/i18n.js b/website/public/assets/i18n.js index 9af94bb63d5..3fc627b4c56 100644 --- a/website/public/assets/i18n.js +++ b/website/public/assets/i18n.js @@ -9,13 +9,34 @@ export function t(message, values = {}) { ); } -document.querySelectorAll("[data-language]").forEach((link) => { - link.addEventListener("click", () => { +// A language chosen in the selector, accepted from the offer or declined by +// dismissing it is the reader's choice; the offer never appears again. +const LANGUAGE_CHOICE = "rea-language"; + +function rememberLanguage(code) { + document.querySelector(".language-suggestion")?.remove(); + try { + localStorage.setItem(LANGUAGE_CHOICE, code); + } catch { + // Without storage the choice lasts for this page only. + } +} + +function followLanguage(link) { + const choose = () => { const target = new URL(link.href); target.hash = window.location.hash; link.href = target.href; + rememberLanguage(link.dataset.language); + }; + link.addEventListener("click", choose); + // A middle click opens the edition in a new tab without a click event. + link.addEventListener("auxclick", (event) => { + if (event.button === 1) choose(); }); -}); +} + +document.querySelectorAll("[data-language]").forEach(followLanguage); const picker = document.querySelector(".language-picker"); if (picker !== null) { @@ -29,3 +50,78 @@ if (picker !== null) { } }); } + +// Match one browser preference to an edition: the exact tag first, then the +// same base language. Chinese chooses its script from the preference and +// never offers the other script. +function matchLanguage(preference, codes) { + const tag = preference.toLowerCase(); + const exact = codes.find((code) => code.toLowerCase() === tag); + if (exact !== undefined) return exact; + const base = tag.split("-")[0]; + const sameBase = codes.filter( + (code) => code.toLowerCase().split("-")[0] === base, + ); + if (base === "zh") { + const preferred = /^zh-(hant|tw|hk|mo)\b/.test(tag) ? "zh-TW" : "zh-CN"; + return sameBase.find((code) => code === preferred); + } + return sameBase[0]; +} + +function offerLanguage(link, current) { + const notice = document.createElement("aside"); + notice.className = "language-suggestion"; + notice.lang = link.lang; + notice.dir = link.dir; + const offer = document.createElement("a"); + offer.href = link.href; + offer.dataset.language = link.dataset.language; + offer.textContent = link.dataset.offer ?? link.textContent; + followLanguage(offer); + const dismiss = document.createElement("button"); + dismiss.type = "button"; + dismiss.textContent = "×"; + dismiss.setAttribute("aria-label", link.dataset.dismiss ?? "Dismiss"); + if (link.dataset.dismiss === undefined) dismiss.lang = "en"; + dismiss.addEventListener("click", () => { + rememberLanguage(current); + notice.remove(); + }); + notice.append(offer, dismiss); + document.body.append(notice); +} + +// Offer the edition that matches the browser's languages when it differs from +// this page. Only editions with a complete translation of this page qualify. +function suggestLanguage() { + if (picker === null) return; + try { + if (localStorage.getItem(LANGUAGE_CHOICE) !== null) return; + } catch { + return; // A choice that cannot be remembered would be offered on every page. + } + const links = [...picker.querySelectorAll("a[data-language]")]; + const current = links.find( + (link) => link.getAttribute("aria-current") === "true", + ); + if (current === undefined) return; + const translated = new Set( + [...document.querySelectorAll('link[rel="alternate"][hreflang]')].map( + (link) => link.hreflang, + ), + ); + const editions = links.filter( + (link) => link === current || translated.has(link.dataset.language), + ); + const codes = editions.map((link) => link.dataset.language); + for (const preference of navigator.languages ?? [navigator.language]) { + const code = matchLanguage(preference, codes); + if (code === undefined) continue; + if (code !== current.dataset.language) + offerLanguage(editions[codes.indexOf(code)], current.dataset.language); + return; + } +} + +suggestLanguage(); diff --git a/website/public/assets/styles.css b/website/public/assets/styles.css index d3ef5a434f1..f4cac82b20c 100644 --- a/website/public/assets/styles.css +++ b/website/public/assets/styles.css @@ -2839,3 +2839,53 @@ html[dir="rtl"] .brand-name { --font-sans: var(--font-latin), sans-serif; --font-mono: var(--font-code), monospace; } +/* The language offer floats above the page so content never shifts. */ +/* It shares the bottom edge with the back-to-top button, which returns once + the offer is accepted or dismissed. */ +body:has(.language-suggestion) .back-to-top { + display: none; +} +.language-suggestion { + position: fixed; + inset-inline: 1rem; + inset-block-end: 1rem; + z-index: 20; + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + max-inline-size: 30rem; + margin-inline: auto; + padding-block: 0.35rem; + padding-inline: 1.1rem 0.35rem; + border: 1px solid var(--line); + border-inline-start: 2px solid var(--accent); + border-radius: 6px; + background: var(--page); + box-shadow: 0 5px 20px rgb(32 37 43 / 8%); + font-size: 0.9rem; +} +.language-suggestion a { + color: var(--accent); + font-weight: 600; +} +.language-suggestion button { + flex-shrink: 0; + min-inline-size: 44px; + min-block-size: 44px; + border: 0; + border-radius: 5px; + background: transparent; + color: var(--muted); + font-size: 1.25rem; + cursor: pointer; +} +.language-suggestion button:hover { + background: var(--soft); + color: var(--ink); +} +@media print { + .language-suggestion { + display: none; + } +}