From 8936f296eae8ff5336dda953ce326616d869837e Mon Sep 17 00:00:00 2001
From: Claude {{ g.member.display_name }}
Hay cambios guardados que no han llegado al sitio público.
+ {% endif %} ++ Cómo se llaman las secciones y qué dicen los botones y los avisos, en las + dos mitades del sitio. Si aquí dentro preferís «Escritorio» a «Inicio», o + «Socios» a «Miembros», se cambia desde aquí. +
++ Las palabras que dice el programa: los nombres de las secciones, los botones + y los avisos. Deja una casilla vacía para que siga diciendo lo de siempre — + sólo se guarda lo que cambias, así que una mejora de la próxima versión te + llega sola si no la has tocado. +
+ +{% if state.updated_at and not state.published_at %} ++ Guardado aquí, pero las palabras del sitio público no han salido: no se + pudo contactar con el servidor de git la última vez. Las del área privada + ya están puestas. +
+ ++ Lo marcado sitio público va a + vienalatina.com y tarda un par de minutos en salir. Un idioma que dejes vacío + lo rellena la traducción automática en la siguiente publicación — que para + una palabra suelta acierta poco, así que merece la pena escribirlo. +
+{% endif %} + +{% if state.customised %} + +{% endif %} +{% endblock %} diff --git a/apps/board/tests/test_strings.py b/apps/board/tests/test_strings.py new file mode 100644 index 0000000..9bfb6c9 --- /dev/null +++ b/apps/board/tests/test_strings.py @@ -0,0 +1,313 @@ +"""The words the software says, and the screen that changes them. + +The first test in this file is the one that matters most, and it is the reason +extracting five hundred strings is mechanical rather than risky: every `t("…")` +used anywhere must exist in the catalogue, and every key in the catalogue must +be used somewhere. A typo and an orphan are the only two failure modes of a +change this shape — one renders `nav.incio` on a page, the other grows a field +in Gestión that changes nothing — and both are a red test here instead. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +import pytest + +from apps.board import strings + +ROOT = Path(__file__).resolve().parents[3] +BOARD = Path(__file__).resolve().parents[1] +THEME = ROOT / "themes" / "vienalatina" + +# `t('nav.inicio')` and `strings.t("nav.inicio", ...)`, in templates and Python. +USED = re.compile(r"""\bt\(\s*['"]([a-z][\w.]*)['"]""") + + +def _keys_used() -> dict[str, set[str]]: + """Every key referenced, and the files that reference it.""" + where: dict[str, set[str]] = {} + for path in [*BOARD.glob("*.py"), *(BOARD / "templates").glob("*.html")]: + if path.name.startswith("test_"): + continue + for key in USED.findall(path.read_text(encoding="utf-8")): + where.setdefault(key, set()).add(path.name) + return where + + +def test_every_key_used_exists_in_the_catalogue(): + """A typo in a key renders as the key itself, which is the right failure on + a page and a silent one in a review.""" + unknown = {key: sorted(files) for key, files in _keys_used().items() + if key not in strings.catalogue()} + assert not unknown, f"used but not defined: {unknown}" + + +def test_every_key_in_the_catalogue_is_used(): + """The other direction, and the one that keeps the screen honest: an + orphaned key is a box in Gestión that somebody fills in and that changes + nothing on any page.""" + used = set(_keys_used()) + # The public half is used by the theme, in Go templates, not by the app. + for path in THEME.rglob("*.html"): + for key in re.findall(r'"key"\s+"([\w.]+)"', path.read_text(encoding="utf-8")): + used.add(strings.PUBLIC + key) + orphans = sorted(set(strings.catalogue()) - used) + assert not orphans, f"defined but never shown: {orphans}" + + +def test_the_theme_and_the_catalogue_agree_on_the_public_defaults(): + """Two copies, deliberately — Hugo reads the repository and the members area + reads its own image, and neither can read the other's file. The same trade + `brand.FACTORY` makes with the two `:root` blocks, held together the same + way: by a test that fails rather than by a comment that asks nicely. + """ + source = (THEME / "layouts" / "partials" / "t.html").read_text(encoding="utf-8") + block = source.split("$words := dict", 1)[1].split("\n-}}", 1)[0] + theme = {} + for key, body in re.findall(r'"([\w-]+)"\s+\(dict((?:\s*"[\w-]+"\s*"[^"]*")+)\s*\)', + block): + theme[key] = dict(re.findall(r'"([\w-]+)"\s*"([^"]*)"', body)) + + assert len(theme) > 15, f"only parsed {len(theme)} keys out of t.html — did it move?" + for key, entry in sorted(strings.catalogue().items()): + if not strings.is_public(key): + continue + bare = key[len(strings.PUBLIC):] + assert bare in theme, f"{key} is in the catalogue and not in t.html" + for lang, text in entry["langs"].items(): + assert theme[bare].get(lang) == text, ( + f"{key} [{lang}]: t.html says {theme[bare].get(lang)!r} and the " + f"catalogue says {text!r}. One of the two is wrong.") + extra = sorted(set(theme) - {k[len(strings.PUBLIC):] for k in strings.catalogue()}) + assert not extra, f"t.html has keys the screen cannot reach: {extra}" + + +# --- the lookup ----------------------------------------------------------- + +def test_the_catalogue_is_what_the_software_says(app): + with app.test_request_context(): + assert strings.t("nav.inicio") == "Inicio" + assert strings.t("site.share", "de") == "Teilen" + + +def test_an_unknown_key_renders_as_itself(app): + """`t.html` has done this since it was written, and for the same reason: a + typo on the page is a typo somebody reports.""" + with app.test_request_context(): + assert strings.t("nav.incio") == "nav.incio" + + +def test_an_override_wins_and_a_blank_one_falls_back(app, db, superadmin_id): + db.execute("INSERT INTO strings (id, strings_json) VALUES (1, ?)", + (json.dumps({"nav.inicio": {"es": "Escritorio"}}),)) + with app.test_request_context(): + assert strings.t("nav.inicio") == "Escritorio" + assert strings.t("nav.muro") == "Muro" + + +def test_rewording_spanish_says_nothing_about_german(app, db): + """The fallback order, and it is a judgement rather than an accident: an + override for the asked-for language wins, then the *shipped* word in that + language, before the Spanish override. Somebody who reworded only the + Spanish has said nothing about German, and showing a German reader Spanish + would be reading an intention into silence.""" + db.execute("INSERT INTO strings (id, strings_json) VALUES (1, ?)", + (json.dumps({"site.share": {"es": "Pasar a alguien"}}),)) + with app.test_request_context(): + assert strings.t("site.share") == "Pasar a alguien" + assert strings.t("site.share", "de") == "Teilen" + + +def test_a_string_that_takes_a_value_formats_it(app): + with app.test_request_context(): + assert strings.t("nav.inicio", nombre="x") == "Inicio" + + +def test_a_string_edited_into_a_placeholder_does_not_take_the_page_down(app, db): + """Somebody types «{nombre}» into a box. The page must still render, and it + must not render half a sentence either.""" + db.execute("INSERT INTO strings (id, strings_json) VALUES (1, ?)", + (json.dumps({"nav.inicio": {"es": "Hola {quien}"}}),)) + with app.test_request_context(): + assert strings.t("nav.inicio", nombre="Pablo") == "Hola {quien}" + + +def test_the_catalogue_refuses_a_language_this_site_does_not_have(tmp_path, monkeypatch): + """Caught at load, which is start-up, rather than as a missing word months + later.""" + (tmp_path / "x.yaml").write_text('a.b:\n es: "Hola"\n fr: "Bonjour"\n', + encoding="utf-8") + monkeypatch.setattr(strings, "CATALOGUE_DIR", tmp_path) + monkeypatch.setattr(strings, "_CATALOGUE", None) + with pytest.raises(ValueError, match="not languages"): + strings.catalogue() + + +def test_the_catalogue_refuses_an_entry_with_no_spanish(tmp_path, monkeypatch): + (tmp_path / "x.yaml").write_text('a.b:\n de: "Hallo"\n', encoding="utf-8") + monkeypatch.setattr(strings, "CATALOGUE_DIR", tmp_path) + monkeypatch.setattr(strings, "_CATALOGUE", None) + with pytest.raises(ValueError, match="no Spanish"): + strings.catalogue() + + +# --- the screen ----------------------------------------------------------- + +@pytest.fixture +def boss(superadmin_id, sign_in): + sign_in(superadmin_id) + return superadmin_id + + +def test_a_renamed_section_shows_up_everywhere_at_once(client, post, boss, repo): + """The navigation, and the strip the public site draws from `sesion.json`. + Those were two copies of six words until this phase; a rename that reached + one and not the other is the failure this is shaped around.""" + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio"}) + + assert "Escritorio" in client.get("/comunidad/").get_data(as_text=True) + session = client.get("/comunidad/sesion.json").get_json() + assert session["sections"][0]["label"] == "Escritorio" + + +def test_only_what_was_typed_is_stored(client, db, post, boss, repo): + """The form posts every box it drew, almost all of them empty. Saving the + shipped wording back into the row would freeze it — a later version's better + sentence would never arrive.""" + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio", + "nav.muro:es": ""}) + + stored = json.loads(db.execute("SELECT strings_json FROM strings").fetchone()[0]) + assert stored == {"nav.inicio": {"es": "Escritorio"}} + + +def test_typing_the_default_back_in_stores_nothing(client, db, post, boss, repo): + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Inicio"}) + + stored = json.loads(db.execute("SELECT strings_json FROM strings").fetchone()[0]) + assert stored == {} + + +def test_clearing_a_box_goes_back_to_the_shipped_word(client, db, post, boss, repo): + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio"}) + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": ""}) + + stored = json.loads(db.execute("SELECT strings_json FROM strings").fetchone()[0]) + assert stored == {} + assert "Inicio" in client.get("/comunidad/").get_data(as_text=True) + + +def test_saving_one_area_does_not_blank_another(client, db, post, boss, repo): + """The screen is one page per area, so a save sees a fraction of the keys. + What it did not draw it must leave alone.""" + post("/comunidad/gestion/textos?area=sitio", {"site.share:es": "Pasar"}) + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio"}) + + stored = json.loads(db.execute("SELECT strings_json FROM strings").fetchone()[0]) + assert stored == {"site.share": {"es": "Pasar"}, + "nav.inicio": {"es": "Escritorio"}} + + +def test_a_label_is_flattened_to_one_line(client, db, post, boss, repo): + """A newline in a menu entry is a menu that renders raggedly and nobody can + see why. Long explanations keep theirs — see `row.long`.""" + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escri\n\ntorio"}) + + stored = json.loads(db.execute("SELECT strings_json FROM strings").fetchone()[0]) + assert stored["nav.inicio"]["es"] == "Escri torio" + + +def test_the_public_half_is_written_for_hugo(client, post, boss, repo): + post("/comunidad/gestion/textos?area=sitio", + {"site.home:es": "Escritorio", "site.home:de": "Schreibtisch", + "site.share:es": "Pasar a alguien"}) + + written = repo.files["data/ui.yaml"].decode("utf-8") + assert 'home:\n es: "Escritorio"\n de: "Schreibtisch"' in written + assert ' pt-br:' not in written, "an empty language must be left for the pipeline" + assert 'share:\n es: "Pasar a alguien"' in written + + +def test_the_members_area_half_is_not_written_for_hugo(client, post, boss, repo): + """`nav.*` is this software's own chrome. Committing it would put words the + public site never says into the repository it builds from.""" + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio"}) + + written = repo.files["data/ui.yaml"].decode("utf-8") + assert "inicio" not in written and "Escritorio" not in written + + +def test_a_quote_in_a_word_cannot_break_the_file(client, post, boss, repo): + post("/comunidad/gestion/textos?area=sitio", + {"site.home:es": 'El "Escritorio"\\'}) + + written = repo.files["data/ui.yaml"].decode("utf-8") + assert r'es: "El \"Escritorio\"\\"' in written + + +def test_a_save_survives_the_git_server_being_down(client, db, post, boss): + """SQLite first, so the members area's own words are never blocked by git — + and the screen says the public site is a step behind rather than pretending + it is not. No `repo` fixture here, so the git layer refuses.""" + response = post("/comunidad/gestion/textos?area=nav", + {"nav.inicio:es": "Escritorio"}, follow_redirects=True) + + row = db.execute("SELECT strings_json, published_at FROM strings").fetchone() + assert json.loads(row["strings_json"]) == {"nav.inicio": {"es": "Escritorio"}} + assert row["published_at"] is None + assert "Pendiente de publicar" in response.get_data(as_text=True) + assert "Escritorio" in client.get("/comunidad/").get_data(as_text=True) + + +def test_the_retry_publishes_what_was_already_saved(db, post, boss, monkeypatch, repo): + """What the *Reintentar publicar* button is for: the words are in SQLite + and the commit never happened.""" + from apps.board import gitea, ui + + def boom(*args, **kwargs): + raise gitea.GiteaError("caído") + + # Only the write, and put it back by hand rather than with + # `monkeypatch.undo()` — which would also undo the `repo` fixture's own + # patches and leave the retry talking to the real git server. + working = ui.gitea.write_file + monkeypatch.setattr(ui.gitea, "write_file", boom) + post("/comunidad/gestion/textos?area=sitio", {"site.home:es": "Escritorio"}) + assert db.execute("SELECT published_at FROM strings").fetchone()["published_at"] is None + + monkeypatch.setattr(ui.gitea, "write_file", working) + post("/comunidad/gestion/textos/publicar") + + assert 'es: "Escritorio"' in repo.files["data/ui.yaml"].decode("utf-8") + assert db.execute("SELECT published_at FROM strings").fetchone()["published_at"] + + +def test_restoring_puts_every_word_back(client, db, post, boss, repo): + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio"}) + post("/comunidad/gestion/textos/restaurar") + + assert db.execute("SELECT COUNT(*) AS n FROM strings").fetchone()["n"] == 0 + assert "Inicio" in client.get("/comunidad/").get_data(as_text=True) + + +def test_the_search_finds_a_word_across_areas(client, boss, repo): + page = client.get("/comunidad/gestion/textos?area=todo&q=compartir").get_data(as_text=True) + assert "site.share" in page + assert "nav.inicio" not in page + + +def test_erasing_whoever_chose_the_words_leaves_them_standing(client, db, post, boss, + make_member, repo): + """The words belong to the association, like the colours and the calendar.""" + former = make_member("anterior", role="admin") + post("/comunidad/gestion/textos?area=nav", {"nav.inicio:es": "Escritorio"}) + db.execute("UPDATE strings SET updated_by = ? WHERE id = 1", (former,)) + + post(f"/comunidad/miembros/{former}/eliminar") + + row = db.execute("SELECT strings_json, updated_by FROM strings").fetchone() + assert json.loads(row["strings_json"]) == {"nav.inicio": {"es": "Escritorio"}} + assert row["updated_by"] is None diff --git a/apps/board/tests/test_tools.py b/apps/board/tests/test_tools.py index 190bfae..f0f91ae 100644 --- a/apps/board/tests/test_tools.py +++ b/apps/board/tests/test_tools.py @@ -14,6 +14,7 @@ from apps.board import activity, identity SCREENS = { "/comunidad/gestion/identidad": "superadmin", + "/comunidad/gestion/textos": "superadmin", "/comunidad/gestion/estado": "superadmin", "/comunidad/gestion/registro": "superadmin", "/comunidad/gestion/medios": "admin", diff --git a/apps/board/ui.py b/apps/board/ui.py new file mode 100644 index 0000000..416136f --- /dev/null +++ b/apps/board/ui.py @@ -0,0 +1,211 @@ +"""Gestión → Textos: changing what the software says. + +The screen is **generic**, and that is the whole economy of it: it iterates +`strings.catalogue()` and draws a box per entry, so extracting another hundred +strings later costs nothing here at all. There is no field list in this module +and there must never be one. + +The same two destinations as `brand.py` and `identity.py`, written in the same +order and for the same reason: SQLite first, so a change to the members area's +own words is never blocked by the git server, then the commit of `data/ui.yaml` +that carries the public half to the next build. +""" + +from __future__ import annotations + +import json + +from flask import (Blueprint, current_app, flash, g, redirect, render_template, + request, url_for) + +from . import activity, gitea, strings +from .db import get_db +from .security import superadmin_required + +bp = Blueprint("ui", __name__) + +DATA_FILE = "data/ui.yaml" + +# Above this, the form draws a textarea instead of a line. Measured rather than +# guessed: the longest label is 32 characters and the shortest explanation is +# well past eighty, so the break falls in the gap between the two kinds. +LONG = 80 + + +def _matches(key: str, entry: dict, needle: str) -> bool: + if not needle: + return True + haystack = " ".join([key, entry["note"], *entry["langs"].values()]).lower() + return needle in haystack + + +def _rows(area: str, needle: str) -> list[dict]: + """What the form draws: one entry per string, with what is stored on it.""" + given = strings.stored() + out = [] + for key, entry in sorted(strings.catalogue().items()): + if entry["area"] != area and area != "todo": + continue + if not _matches(key, entry, needle): + continue + public = strings.is_public(key) + out.append({ + "key": key, + "note": entry["note"], + "public": public, + "long": any(len(text) > LONG for text in entry["langs"].values()), + # The shipped word is the placeholder and what was typed is the + # value — the split `identity.py` uses, and for the same reason: a + # field prefilled with the default saves the default the first time + # anybody presses the button, and freezes it from then on. + "langs": [{ + "code": code, + "label": strings.LANG_LABELS[code], + "default": entry["langs"].get(code, ""), + "stored": (given.get(key) or {}).get(code, ""), + } for code in (strings.LANGS if public else (strings.DEFAULT_LANG,))], + }) + return out + + +@bp.route("/gestion/textos", methods=["GET", "POST"]) +@superadmin_required +def edit(): + area = request.args.get("area", "nav") + needle = request.args.get("q", "").strip().lower()[:80] + if area not in strings.areas() and area != "todo": + area = strings.areas()[0] + + if request.method == "GET": + return render_template("ui_form.html", state=strings.state(), + areas=strings.areas(), area=area, q=needle, + rows=_rows(area, needle)) + + # Only this page's fields are read, so saving one area cannot blank another: + # the form posts what it drew, and what it did not draw is left alone. + given = dict(strings.stored()) + touched = 0 + for row in _rows(area, needle): + key = row["key"] + entry = strings.catalogue()[key] + values = {} + for lang in row["langs"]: + code = lang["code"] + text = (request.form.get(f"{key}:{code}") or "").strip()[:strings.VALUE_MAX] + # One line for a label, because a newline in a menu entry is a menu + # that renders raggedly and nobody can see why. + text = " ".join(text.split()) if not row["long"] else text.strip() + if text and text != entry["langs"].get(code): + values[code] = text + if values: + if given.get(key) != values: + touched += 1 + given[key] = values + elif key in given: + given.pop(key) + touched += 1 + + get_db().execute( + """INSERT INTO strings (id, strings_json, updated_by, updated_at, published_at) + VALUES (1, ?, ?, datetime('now'), NULL) + ON CONFLICT(id) DO UPDATE SET + strings_json = excluded.strings_json, + updated_by = excluded.updated_by, + updated_at = excluded.updated_at, + published_at = NULL""", + (json.dumps(given, sort_keys=True, ensure_ascii=False), g.member["id"]), + ) + # The override read is memoised per request; this one has just changed it. + g.pop("string_overrides", None) + activity.log("ui.saved", detail=f"{touched} en {area}") + + if _publish(): + flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok") + return redirect(url_for("ui.edit", area=area, q=needle or None)) + + +@bp.route("/gestion/textos/publicar", methods=["POST"]) +@superadmin_required +def publish(): + """Try the commit again after the git server was unreachable.""" + if _publish(): + flash("Publicado. El sitio público se reconstruye en un par de minutos.", "ok") + return redirect(url_for("ui.edit")) + + +@bp.route("/gestion/textos/restaurar", methods=["POST"]) +@superadmin_required +def restore(): + """Back to the words the software shipped with.""" + get_db().execute("DELETE FROM strings WHERE id = 1") + g.pop("string_overrides", None) + activity.log("ui.restored") + flash("Restaurados los textos originales.", "ok") + _publish() + return redirect(url_for("ui.edit")) + + +# --- the public half ------------------------------------------------------ + +def _quote(value: str) -> str: + """A double-quoted YAML scalar. Backslashes and quotes are the only two + characters that can end one, and both are escapable inside it.""" + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def yaml_for(given: dict) -> str: + """`data/ui.yaml`, written rather than dumped — the same trade `brand.py` + and `identity.py` make, and the values here are even better known: short + strings, one per line, no structure below two levels. + + **Only what was actually overridden is written**, and only the languages + that were. A file repeating the theme's own words back at it would make the + fallback in `t.html` meaningless and freeze today's wording for good — and a + language written out as an empty string would stop the pipeline filling it. + """ + lines = ["# Generado desde Gestión → Textos en vienalatina.com/comunidad.", + "# No editar a mano: el próximo guardado lo sobrescribe."] + for key in sorted(given): + if not strings.is_public(key): + continue + values = {code: text for code, text in given[key].items() if text} + if not values: + continue + # Without the `site.` prefix: inside this file the namespace is implied, + # and `t.html` looks the bare key up. + lines.append(f"{key[len(strings.PUBLIC):]}:") + for code in strings.LANGS: + if values.get(code): + lines.append(f" {code}: {_quote(values[code])}") + return "\n".join(lines) + "\n" + + +def _publish() -> bool: + """Commit the public half. True if it got there. + + Returns False and says why rather than raising, exactly as the other two + screens do: the words are already saved here, and a superadministrator whose + change took effect in the members area needs to know the public site is a + step behind, not to meet a traceback. + """ + try: + token = gitea.content_token() + except gitea.GiteaError as exc: + flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error") + return False + + try: + _, sha = gitea.read_file(DATA_FILE, token) + except gitea.GiteaError: + sha = None + + try: + gitea.write_file(DATA_FILE, yaml_for(strings.stored()).encode("utf-8"), + "textos: palabras del sitio", token, sha=sha) + except (gitea.GiteaError, OSError) as exc: + current_app.logger.warning("ui publish failed: %s", exc) + flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error") + return False + + get_db().execute("UPDATE strings SET published_at = datetime('now') WHERE id = 1") + return True diff --git a/config.yaml b/config.yaml index 33ac3a0..303ed53 100644 --- a/config.yaml +++ b/config.yaml @@ -48,6 +48,10 @@ languages: main: - name: "Inicio" url: "/" + # Named so partials/header.html can look its label up in + # the table: the entry and its weight stay here, the word + # is editable in Gestión → Textos. + identifier: "home" weight: 1 de: languageCode: "de" @@ -59,6 +63,10 @@ languages: main: - name: "Start" url: "/de/" + # Named so partials/header.html can look its label up in + # the table: the entry and its weight stay here, the word + # is editable in Gestión → Textos. + identifier: "home" weight: 1 pt-br: languageCode: "pt-BR" @@ -70,6 +78,10 @@ languages: main: - name: "Início" url: "/pt-br/" + # Named so partials/header.html can look its label up in + # the table: the entry and its weight stay here, the word + # is editable in Gestión → Textos. + identifier: "home" weight: 1 params: diff --git a/docs/server-setup.md b/docs/server-setup.md index 2c9ddd7..5690617 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -1552,6 +1552,73 @@ The theme's coarse block sits at the **end** of `main.css` on purpose: media query changes nothing about specificity, and a coarse rule written before it loses silently. +### 11.19b Textos: every word the software says + +Nothing this software said could be changed without a commit. «Inicio» was a +word in `base.html`, again in `home.py`'s section list, again three times in +`config.yaml`, again in an `aria-label` and again in the breadcrumb schema — six +edits to rename one section, none of them reachable from Gestión. §11.18b exists +to end exactly that for the site's *name*; it stopped before it reached the +*labels*. + +**`apps/board/strings/*.yaml` is the catalogue**, one file per area, shipped in +the image through the Dockerfile's existing `COPY apps /srv/apps`. It holds what +the software says when nobody has said otherwise, and **only the differences are +stored** — `brand.FACTORY`'s rule, buying the same thing: a wording improved in +a later version improves for every install that has not deliberately overridden +it, instead of arriving frozen. + +`_note` in an entry is for whoever is editing; every other key is a language +code. + +**The `site.` prefix is load-bearing.** It decides the store, the number of +boxes on the form, and whether a save needs the git server at all: + +| | Store | Reaches the reader | +|---|---|---| +| `site.*` | `data/ui.yaml`, committed | next pipeline run, three languages | +| everything else | `strings.strings_json`, one pinned row | next page load, Spanish | + +**No migration.** `strings` is a new table, so `CREATE TABLE IF NOT EXISTS` in +`schema.sql` creates it on start-up, as `activity` and `site` arrived. + +**`t()` is a Jinja global and a Python function**, `{{ t('nav.inicio') }}` and +`strings.t("nav.inicio")`. An unknown key renders as itself — the rule `t.html` +has used since it was written, and the right one: a typo renders as `nav.incio` +on the page, which somebody notices, rather than as nothing, which nobody does. +The read behind it is one row memoised on `g`, and it falls back to the +catalogue rather than raising, because `base.html` asks for six words on every +page including the error page. + +**The fallback order is a judgement, not an accident.** An override for the +asked-for language wins, then the **shipped** word in that language, before the +Spanish override — somebody who reworded only the Spanish has said nothing about +German, and showing a German reader Spanish would be reading an intention into +silence. + +**The screen is generic.** It iterates the catalogue, so extracting another +hundred strings costs no UI work; there is no field list in `ui.py` and there +must never be one. One page per area, a `?q=` search across all of them (server +side — a filter that needs a script is a filter that silently does nothing under +this CSP), and the shipped word as the placeholder with what was typed as the +value, never the other way round. + +**The public defaults are written twice**, in `t.html` for Hugo and in +`strings/sitio.yaml` so the screen can show them. That is deliberate and +unavoidable — Hugo reads the repository and the members area reads its own +image — and it is held together the way `brand.FACTORY` is held to the two +`:root` blocks: by a test that fails on divergence. + +**Two guards make extracting five hundred strings mechanical rather than +risky**, in `apps/board/tests/test_strings.py`: every `t("…")` used must exist in +the catalogue, and every key in the catalogue must be used somewhere. A typo and +an orphan are the only two failure modes of a change this shape. + +The public menu keeps its entry in `config.yaml` — a data file cannot override +`.Site.Menus.main`, which is why `site-name.html` exists — but the entry now +carries `identifier: home`, and `header.html` looks its *label* up in the table. +The entry and its weight stay in config; the word is editable. + ### 11.20 The three admin tools **Estado del sistema** (superadministrator). The backups panel reads diff --git a/themes/vienalatina/assets/js/memberbar.js b/themes/vienalatina/assets/js/memberbar.js index 4043caa..534f634 100644 --- a/themes/vienalatina/assets/js/memberbar.js +++ b/themes/vienalatina/assets/js/memberbar.js @@ -34,7 +34,11 @@ function draw(state) { var bar = el("div", "member-bar"); bar.setAttribute("role", "navigation"); - bar.setAttribute("aria-label", "Área de miembros"); + // From the endpoint, not from here: these were the one part of the + // signed-in strip that no setting could reach, because a word in a + // fingerprinted script is a word only a deploy can change. + var labels = state.labels || {}; + bar.setAttribute("aria-label", labels.bar || "Área de miembros"); var inner = el("div", "member-bar__inner"); var links = el("ul", "member-bar__links"); @@ -62,7 +66,7 @@ token.name = "csrf_token"; token.value = state.csrf; form.appendChild(token); - var out = el("button", "member-bar__out", "Salir"); + var out = el("button", "member-bar__out", labels.logout || "Salir"); out.type = "submit"; form.appendChild(out); account.appendChild(form); diff --git a/themes/vienalatina/layouts/_default/single.html b/themes/vienalatina/layouts/_default/single.html index b2d1fb2..551b0f3 100644 --- a/themes/vienalatina/layouts/_default/single.html +++ b/themes/vienalatina/layouts/_default/single.html @@ -19,7 +19,7 @@ nothing. */}} {{ with .Params.author }} - por + {{ partial "t.html" (dict "key" "by" "lang" .Site.Language.Lang) }} {{ with $.Params.author_url }} {{ $.Params.author }} {{ else }} @@ -96,7 +96,7 @@ cannot see is exactly what search engines penalise. */}} {{ with .Params.faq }}