Textos: the words are data now, starting with the navigation

Renaming «Inicio» was six edits — base.html, home.py's section list,
config.yaml three times, an aria-label, and the breadcrumb schema — and
none of them reachable from Gestión. That is the thing Identidad exists
to end for the site's name, and it stopped before it reached the labels.

The mechanism, and the navigation through it. The rest of the ~560
strings follow in later commits; this one is the path proved end to end.

apps/board/strings/*.yaml is the catalogue, shipped in the image through
the Dockerfile's existing COPY. Only the differences are stored, which
is brand.FACTORY's rule and buys the same thing: a wording I improve
later improves for everyone who has not deliberately overridden it.

The `site.` prefix decides everything — one box or three, SQLite or a
commit of data/ui.yaml, this page load or the next pipeline run.

The fallback order is a judgement rather than an accident: an override
for the asked-for language, then the *shipped* word in that language,
then Spanish. Somebody who reworded only the Spanish has said nothing
about German, and showing a German reader Spanish would be reading an
intention into silence. Verified in a real build: with es overridden,
the Spanish menu says «Escritorio» and the German still says «Start».

The screen is generic — it iterates the catalogue, so extracting another
hundred strings costs nothing here. There is no field list in ui.py and
there must never be one.

Two guards are what make a 560-string extraction mechanical rather than
risky: every t("…") used must exist, and every key defined must be used.
A typo renders as nav.incio on a page; an orphan is a box in Gestión
that changes nothing. Both fail the suite instead. I proved all three
guards (including the one holding t.html to the catalogue) by
introducing the bug each describes and watching it go red.

Two things fixed on the way, both found by the extraction rather than
looked for: home.py and base.html held two copies of the same six words,
so a rename would have reached the members area and not the strip on the
public site; and memberbar.js hardcoded two more in a fingerprinted
script, the one surface no setting could ever reach.

No migration — `strings` is a new table, so CREATE TABLE IF NOT EXISTS
makes it, as activity and site arrived. The erase guard caught the new
members(id) reference by itself, which is the mechanism working.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
This commit is contained in:
Claude 2026-10-14 12:35:10 +00:00
parent f6236a3acf
commit 8936f296ea
No known key found for this signature in database
21 changed files with 1283 additions and 30 deletions

View File

@ -44,6 +44,8 @@ SENTENCES = {
"brand.saved": "cambió el aspecto del sitio", "brand.saved": "cambió el aspecto del sitio",
"brand.restored": "restauró el aspecto de fábrica", "brand.restored": "restauró el aspecto de fábrica",
"identity.saved": "cambió la identidad del sitio", "identity.saved": "cambió la identidad del sitio",
"ui.saved": "cambió los textos del sitio",
"ui.restored": "restauró los textos originales",
"media.deleted": "borró la imagen {object}", "media.deleted": "borró la imagen {object}",
} }

View File

@ -97,11 +97,12 @@ def create_app(overrides: dict | None = None) -> Flask:
from . import (activity, auth, board, brand, content, events, home, from . import (activity, auth, board, brand, content, events, home,
identity, media, members, messages, profiles, status, identity, media, members, messages, profiles, status,
submissions, uploads) strings, submissions, ui, uploads)
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX) app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
app.register_blueprint(home.bp, url_prefix=URL_PREFIX) app.register_blueprint(home.bp, url_prefix=URL_PREFIX)
app.register_blueprint(brand.bp, url_prefix=URL_PREFIX) app.register_blueprint(brand.bp, url_prefix=URL_PREFIX)
app.register_blueprint(identity.bp, url_prefix=URL_PREFIX) app.register_blueprint(identity.bp, url_prefix=URL_PREFIX)
app.register_blueprint(ui.bp, url_prefix=URL_PREFIX)
app.register_blueprint(status.bp, url_prefix=URL_PREFIX) app.register_blueprint(status.bp, url_prefix=URL_PREFIX)
app.register_blueprint(activity.bp, url_prefix=URL_PREFIX) app.register_blueprint(activity.bp, url_prefix=URL_PREFIX)
app.register_blueprint(media.bp, url_prefix=URL_PREFIX) app.register_blueprint(media.bp, url_prefix=URL_PREFIX)
@ -137,6 +138,12 @@ def create_app(overrides: dict | None = None) -> Flask:
# <template> that the editor adopts, so the browser never has to parse # <template> that the editor adopts, so the browser never has to parse
# markdown and cannot disagree with the server about what text means. # markdown and cannot disagree with the server about what text means.
app.jinja_env.globals["to_html"] = to_html app.jinja_env.globals["to_html"] = to_html
# Every word the chrome says. A global rather than a context processor
# because it is a function templates call with an argument, and eager
# rather than lazy because `base.html` asks for six of them on every page —
# the read behind it is one row, memoised on `g`, and falls back to the
# shipped wording rather than raising. See strings.overrides().
app.jinja_env.globals["t"] = strings.t
@app.context_processor @app.context_processor
def _year(): def _year():
@ -149,6 +156,13 @@ def create_app(overrides: dict | None = None) -> Flask:
# that would save the query by deferring it. # that would save the query by deferring it.
return {"brand": brand.state()} return {"brand": brand.state()}
@app.context_processor
def _ui_state():
# Only the Gestión card and the Textos screen draw it, so lazy like
# `identity` rather than eager like `brand`: a callable costs nothing on
# the pages that never ask.
return {"ui_state": strings.state}
@app.context_processor @app.context_processor
def _identity(): def _identity():
# Only Gestión draws it, so unlike `brand` this one is lazy: a function # Only Gestión draws it, so unlike `brand` this one is lazy: a function

View File

@ -15,7 +15,7 @@ from __future__ import annotations
from flask import Blueprint, g, jsonify, render_template, request, url_for from flask import Blueprint, g, jsonify, render_template, request, url_for
from . import submissions from . import strings, submissions
from .db import TOMBSTONE_LOGIN, get_db from .db import TOMBSTONE_LOGIN, get_db
from .render import excerpt, to_html from .render import excerpt, to_html
from .security import admin_required, csrf_token, is_at_least, login_required from .security import admin_required, csrf_token, is_at_least, login_required
@ -124,20 +124,30 @@ def session_state():
if g.member is None: if g.member is None:
return _no_store(jsonify({"signed_in": False})) return _no_store(jsonify({"signed_in": False}))
# The same six words base.html draws, through the same lookup. They were
# written out twice — here and in the template — until Gestión → Textos
# made them editable, at which point two copies would have meant the strip
# on the public site saying «Inicio» while the members area said
# «Escritorio».
sections = [ sections = [
{"label": "Inicio", "url": url_for("home.index")}, {"label": strings.t("nav.inicio"), "url": url_for("home.index")},
{"label": "Muro", "url": url_for("board.threads")}, {"label": strings.t("nav.muro"), "url": url_for("board.threads")},
{"label": "Miembros", "url": url_for("members.index")}, {"label": strings.t("nav.miembros"), "url": url_for("members.index")},
{"label": "Publicaciones", "url": url_for("submissions.index")}, {"label": strings.t("nav.publicaciones"), "url": url_for("submissions.index")},
{"label": "Calendario", "url": url_for("events.month")}, {"label": strings.t("nav.calendario"), "url": url_for("events.month")},
] ]
if is_at_least(g.member["role"], "admin"): if is_at_least(g.member["role"], "admin"):
sections.append({"label": "Gestión", "url": url_for("home.gestion")}) sections.append({"label": strings.t("nav.gestion"),
"url": url_for("home.gestion")})
return _no_store(jsonify({ return _no_store(jsonify({
"signed_in": True, "signed_in": True,
"name": g.member["display_name"] or g.member["gitea_login"], "name": g.member["display_name"] or g.member["gitea_login"],
"sections": sections, "sections": sections,
# The bar's own two words, which it used to hardcode in JavaScript —
# the one surface on the public site that no setting could reach.
"labels": {"bar": strings.t("chrome.miembros"),
"logout": strings.t("account.salir")},
"profile": url_for("profiles.edit"), "profile": url_for("profiles.edit"),
"logout": url_for("auth.logout"), "logout": url_for("auth.logout"),
# Signing out is a POST, so the bar needs the token to render a real # Signing out is a POST, so the bar needs the token to render a real

View File

@ -157,6 +157,9 @@ CLEARED_ON_ERASE = {
# reason for the site to go back to looking like a default install. # reason for the site to go back to looking like a default install.
("brand", "updated_by"), ("brand", "updated_by"),
("site", "updated_by"), ("site", "updated_by"),
# And the words. Whoever decided this association says «Socios» rather than
# «Miembros» leaving is not a reason for it to start saying «Miembros».
("strings", "updated_by"),
# That a role was changed is the association's record; whose name was on it # That a role was changed is the association's record; whose name was on it
# is the erased person's data. The row stays, the name goes — which is also # is the erased person's data. The row stays, the name goes — which is also
# why the log is not a cascade: an audit trail that deletes itself when the # why the log is not a cascade: an audit trail that deletes itself when the

View File

@ -440,3 +440,25 @@ CREATE TABLE IF NOT EXISTS site (
updated_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')),
published_at TEXT published_at TEXT
); );
-- Every word the software says that somebody has decided to say differently.
-- One row, pinned like `brand` and `site`.
--
-- Only the differences from apps/board/strings/*.yaml are stored, as JSON:
-- {"nav.inicio": {"es": "Escritorio"}}. A snapshot of all five hundred would
-- mean that a wording improved in a later version arrived frozen at whatever
-- this version thought it should be, for every install that had ever opened the
-- screen — the same rule, and the same reason, as `brand.tokens_json`.
--
-- `published_at` is NULL between a save and the commit that carries the `site.*`
-- half to the content repository. The members-area half needs no commit and is
-- true the moment the row is written.
CREATE TABLE IF NOT EXISTS strings (
id INTEGER PRIMARY KEY CHECK (id = 1),
strings_json TEXT NOT NULL DEFAULT '{}',
-- Cleared rather than reassigned when that member is erased: the words belong
-- to the association, like the colours and the events.
updated_by INTEGER REFERENCES members(id),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
published_at TEXT
);

View File

@ -1234,3 +1234,25 @@ input[type="file"] {
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.toggle__track, .toggle__track::after { transition: none; } .toggle__track, .toggle__track::after { transition: none; }
} }
/* --- Gestión → Textos ---------------------------------------------------- */
/* One block per string: the key and its note above, the boxes below. Drawn from
the catalogue rather than written out, so these rules have to hold for a
one-word label and for a four-line explanation alike. */
.stringrow {
padding: 0.9rem 0;
border-top: 1px solid var(--border-light);
}
.stringrow:first-of-type { border-top: 0; padding-top: 0; }
.stringrow__head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0.5rem;
}
.stringrow .muted { margin: 0.15rem 0 0.4rem; }
/* The shipped wording is the placeholder, so it has to read as "this is what it
says now" rather than as a half-typed value. */
.stringrow input::placeholder,
.stringrow textarea::placeholder { color: var(--subtle); opacity: 1; }

198
apps/board/strings.py Normal file
View File

@ -0,0 +1,198 @@
"""Every word the software says, in one place and editable.
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. That is the
thing `identity.py` exists to end for the site's *name*, and it stopped before
it reached the *labels*.
### The catalogue is the default, not the value
`strings/*.yaml` ships with the code, inside the image, through the Dockerfile's
existing `COPY apps /srv/apps`. It holds what the software says when nobody has
said otherwise. Only the **differences** are stored, which is `brand.FACTORY`'s
rule and it buys the same thing: a wording I improve in a later version improves
for every install that has not deliberately overridden it, instead of arriving
frozen at whatever this version happened to think.
### Two namespaces, because there are two runtimes
`site.*` is the public site: three languages, written to `data/ui.yaml` and read
by Hugo on the next build. Everything else is the members area: one language
today, read from SQLite and true on the next page load. The prefix is what
decides, and it is load-bearing — it picks the store, the number of boxes on the
form, and whether a save needs the git server at all.
The entries are keyed by language even where only `es` is filled, so the members
area can gain a second language without a format change. `_note` is for whoever
is editing, and the underscore is the rule: every other key in an entry is a
language code.
### What this deliberately does not do
It is not an i18n framework. There is no plural machinery, no gender, no
context disambiguation and no `.po` files — this is a dict with a fallback, and
the moment it needs more than that it should become Babel rather than grow into
a worse Babel.
"""
from __future__ import annotations
import json
from pathlib import Path
import yaml
from flask import current_app, g
from .db import get_db
CATALOGUE_DIR = Path(__file__).resolve().parent / "strings"
# The site's languages, in the order the form draws them. Spanish first because
# it is the one the association writes in and the only one the members area has.
LANGS = ("es", "de", "pt-br")
LANG_LABELS = {"es": "Español", "de": "Deutsch", "pt-br": "Português (Brasil)"}
DEFAULT_LANG = "es"
# A key under this prefix is the public site's and goes to `data/ui.yaml`.
PUBLIC = "site."
VALUE_MAX = 2000
def _load() -> dict:
"""Every file in `strings/`, merged, keyed by the area it came from.
Returns {key: {"langs": {...}, "note": str, "area": str}}. Read once per
process at first use — the files are in the image and cannot change while
it runs, so re-reading them per request would be work for nothing.
"""
catalogue: dict[str, dict] = {}
for path in sorted(CATALOGUE_DIR.glob("*.yaml")):
area = path.stem
loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
for key, entry in loaded.items():
if not isinstance(entry, dict):
raise ValueError(f"{path.name}: «{key}» is not a mapping")
langs = {code: str(text) for code, text in entry.items()
if not code.startswith("_")}
unknown = set(langs) - set(LANGS)
if unknown:
raise ValueError(f"{path.name}: «{key}» has {sorted(unknown)}, "
f"which are not languages of this site")
if DEFAULT_LANG not in langs:
raise ValueError(f"{path.name}: «{key}» has no Spanish")
if key in catalogue:
raise ValueError(f"«{key}» is defined twice")
catalogue[key] = {"langs": langs, "note": entry.get("_note", ""),
"area": area}
return catalogue
_CATALOGUE: dict | None = None
def catalogue() -> dict:
global _CATALOGUE
if _CATALOGUE is None:
_CATALOGUE = _load()
return _CATALOGUE
def is_public(key: str) -> bool:
return key.startswith(PUBLIC)
def areas() -> list[str]:
"""The files, in the order the screen offers them."""
return sorted({entry["area"] for entry in catalogue().values()})
# --- what has been overridden ---------------------------------------------
def _row():
return get_db().execute("SELECT * FROM strings WHERE id = 1").fetchone()
def stored() -> dict:
"""{key: {lang: text}} — only what somebody actually changed."""
row = _row()
try:
value = json.loads(row["strings_json"]) if row else {}
except (TypeError, ValueError):
current_app.logger.warning("strings_json is not readable; using the catalogue")
return {}
return value if isinstance(value, dict) else {}
def overrides() -> dict:
"""`stored()`, once per request, and never raising.
`base.html` asks for a word on every page, the error pages included — and on
a 500 the thing that broke may well be the database. A page in the shipped
wording is still a page; a second traceback inside the error handler is not.
The same arrangement `brand.state()` has, for the same reason.
"""
if "string_overrides" not in g:
try:
g.string_overrides = stored()
except Exception: # pragma: no cover - defensive
current_app.logger.warning("strings unreadable, using the catalogue",
exc_info=True)
g.string_overrides = {}
return g.string_overrides
def state() -> dict:
"""What the screen and its Gestión card read."""
row = _row()
given = stored()
return {
"stored": given,
"updated_at": row["updated_at"] if row else None,
"published_at": row["published_at"] if row else None,
"customised": bool(given),
}
# --- the lookup -----------------------------------------------------------
def t(key: str, lang: str = DEFAULT_LANG, **values) -> str:
"""The word, overridden if somebody changed it, formatted if it takes a value.
An unknown key returns itself. That is the rule `t.html` already uses on the
public side and it is the right one: a typo renders as `nav.incio` on the
page, which somebody notices, rather than as nothing, which nobody does.
The order of the fallbacks matters on the public side. An override for the
asked-for language wins; then the **shipped** word in that language, before
the override in Spanish — somebody who reworded only the Spanish has said
nothing about German, and showing a German reader Spanish would be reading
an intention into silence.
"""
entry = catalogue().get(key)
if entry is None:
return (overrides().get(key) or {}).get(lang) or key
given = overrides().get(key) or {}
text = (given.get(lang) or entry["langs"].get(lang)
or given.get(DEFAULT_LANG) or entry["langs"][DEFAULT_LANG])
if not values:
return text
try:
return text.format(**values)
except (KeyError, IndexError) as exc:
# Loudly, in the log, and the unformatted text on the page. A label
# somebody edited into `{nombre}` must not take the page down, and must
# not render half a sentence either.
current_app.logger.warning("string %s wants %s: %s", key, sorted(values), exc)
return text
def public_langs(key: str) -> dict:
"""Every language of a public string, overrides applied — what gets written
into `data/ui.yaml`."""
entry = catalogue()[key]
given = overrides().get(key) or {}
return {lang: (given.get(lang) or "").strip() or entry["langs"].get(lang, "")
for lang in LANGS}

View File

@ -0,0 +1,68 @@
# The members area's own chrome: the sections, the corner menu, the footer.
#
# Every key here is a word somebody can change in Gestión → Textos. What is in
# this file is the default — what the software says when nobody has said
# otherwise — and only the differences are stored, so a wording improved in a
# later version improves for everybody who has not deliberately overridden it.
#
# `_note` is for whoever is editing: it says where the word appears, because
# «nav.gestion» is not a question an admin can answer from the key alone.
# Every other key in an entry is a language code.
nav.inicio:
es: "Inicio"
_note: "La primera sección: el resumen de lo que ha pasado desde la última visita."
nav.muro:
es: "Muro"
_note: "El tablón interno donde los miembros escriben entre ellos."
nav.miembros:
es: "Miembros"
_note: "El directorio de personas. Lleva el aviso de mensajes sin leer."
nav.publicaciones:
es: "Publicaciones"
_note: "Proponer algo para el sitio público, y la cola de revisión."
nav.calendario:
es: "Calendario"
_note: "Los eventos, internos y públicos."
nav.gestion:
es: "Gestión"
_note: "Sólo la ve la administración."
nav.secciones:
es: "Secciones"
_note: "No se ve: es el nombre de la barra de navegación para un lector de pantalla."
account.perfil:
es: "Mi perfil"
_note: "En el menú de tu nombre, arriba a la derecha."
account.datos:
es: "Descargar mis datos"
_note: "En el menú de tu nombre. Es un derecho, no una función: cámbialo con cuidado."
account.salir:
es: "Salir"
_note: "En el menú de tu nombre, y también en la barra del sitio público."
chrome.titulo:
es: "Comunidad"
_note: "El título de la pestaña del navegador cuando una página no pone el suyo."
chrome.publico:
es: "Ir al sitio público"
_note: "El enlace del pie que lleva de vuelta a vienalatina.com."
chrome.privada:
es: "Área privada"
_note: "La línea del pie, después del nombre y el año."
chrome.miembros:
es: "Área de miembros"
_note: >-
No se ve: nombra la franja que aparece en el sitio público cuando has
iniciado sesión, para un lector de pantalla.

View File

@ -0,0 +1,142 @@
# The words the public site says for itself — everything that is not an article
# somebody wrote. Three languages each, because vienalatina.com is built in
# three and a label left in Spanish on the German pages is the one kind of
# mistake nobody reports.
#
# These are the `site.*` namespace, and the prefix is load-bearing: it is what
# tells the screen to draw three boxes instead of one, and what sends the value
# to `data/ui.yaml` and the pipeline rather than only to SQLite.
#
# The theme keeps its own copy of these defaults in
# themes/vienalatina/layouts/partials/t.html, because Hugo reads the repository
# and the members area reads its own image — neither can read the other's file.
# A test holds the two together, the way the two `:root` blocks are held to
# brand.py's FACTORY.
#
# A language left empty is filled by the pipeline's translation engine on the
# next build. That is a fallback and not the plan: a one-word label is the worst
# case for machine translation, and the three boxes are there to be used.
site.home:
es: "Inicio"
de: "Start"
pt-br: "Início"
_note: >-
La primera entrada del menú público, y también el nombre del enlace del
logotipo para un lector de pantalla.
site.community:
es: "Comunidad"
de: "Community"
pt-br: "Comunidade"
_note: "El botón de la barra que lleva al área de miembros."
site.menu:
es: "Menú"
de: "Menü"
pt-br: "Menu"
_note: "No se ve: nombra el botón ☰ en el móvil."
site.back:
es: "← Volver al inicio"
de: "← Zurück zur Startseite"
pt-br: "← Voltar ao início"
_note: "Al final de cada artículo."
site.by:
es: "por"
de: "von"
pt-br: "por"
_note: "Antes del nombre de quien escribió el artículo. «por Salvador Dalí»."
site.faq:
es: "Preguntas frecuentes"
de: "Häufige Fragen"
pt-br: "Perguntas frequentes"
_note: "El título de la sección de preguntas, cuando el artículo tiene."
site.agenda:
es: "Agenda"
de: "Termine"
pt-br: "Agenda"
_note: "No se ve: nombra la barra de meses de la agenda."
site.previous:
es: "Mes anterior"
de: "Voriger Monat"
pt-br: "Mês anterior"
_note: "No se ve: el botón ← de la agenda."
site.next:
es: "Mes siguiente"
de: "Nächster Monat"
pt-br: "Próximo mês"
_note: "No se ve: el botón → de la agenda."
site.noevents:
es: "No hay nada en este mes."
de: "In diesem Monat ist nichts geplant."
pt-br: "Nada marcado neste mês."
_note: "Cuando un mes de la agenda está vacío."
site.time:
es: "Hora"
de: "Uhrzeit"
pt-br: "Hora"
_note: "En la ficha de un evento."
site.place:
es: "Lugar"
de: "Ort"
pt-br: "Local"
_note: "En la ficha de un evento."
site.add:
es: "Añadir a mi calendario"
de: "Zum Kalender hinzufügen"
pt-br: "Adicionar ao meu calendário"
_note: "El botón que descarga el evento al móvil."
site.ai:
es: "Generado con IA"
de: "Mit KI erstellt"
pt-br: "Gerado com IA"
_note: "La etiqueta en un artículo marcado como escrito por una máquina."
site.aifull:
es: "Quien lo publicó marcó este texto como generado con inteligencia artificial."
de: >-
Wer diesen Beitrag veröffentlicht hat, hat ihn als mit künstlicher
Intelligenz erstellt gekennzeichnet.
pt-br: "Quem publicou marcou este texto como gerado com inteligência artificial."
_note: "La explicación que sale al posar el ratón sobre esa etiqueta."
site.pinned:
es: "Fijado"
de: "Angeheftet"
pt-br: "Fixado"
_note: "La etiqueta de un artículo puesto arriba a propósito."
site.share:
es: "Compartir"
de: "Teilen"
pt-br: "Compartilhar"
_note: "El título de la fila de botones para compartir."
site.copylink:
es: "Copiar enlace"
de: "Link kopieren"
pt-br: "Copiar link"
_note: "El último botón de esa fila."
site.copied:
es: "Enlace copiado"
de: "Link kopiert"
pt-br: "Link copiado"
_note: "Lo que dice después de copiarlo."
site.askmasto:
es: "¿En qué servidor de Mastodon tienes tu cuenta? Por ejemplo: mastodon.social"
de: "Auf welchem Mastodon-Server hast du dein Konto? Zum Beispiel: mastodon.social"
pt-br: "Em qual servidor do Mastodon está a sua conta? Por exemplo: mastodon.social"
_note: "La pregunta antes de compartir en Mastodon."

View File

@ -6,7 +6,7 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow"> <meta name="robots" content="noindex, nofollow">
<title>{% block title %}Comunidad{% endblock %} — Viena Latina</title> <title>{% block title %}{{ t('chrome.titulo') }}{% endblock %} — Viena Latina</title>
<link rel="stylesheet" href="{{ url_for('static', filename='board.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='board.css') }}">
{% block brand_css %} {% block brand_css %}
{# After board.css, so the admin's colours win, and cache-busted by when {# After board.css, so the admin's colours win, and cache-busted by when
@ -43,11 +43,11 @@
<details class="account"> <details class="account">
<summary class="account__name">{{ g.member.display_name }}</summary> <summary class="account__name">{{ g.member.display_name }}</summary>
<div class="account__menu"> <div class="account__menu">
<a href="{{ url_for('profiles.edit') }}">Mi perfil</a> <a href="{{ url_for('profiles.edit') }}">{{ t('account.perfil') }}</a>
<a href="{{ url_for('members.export') }}">Descargar mis datos</a> <a href="{{ url_for('members.export') }}">{{ t('account.datos') }}</a>
<form method="post" action="{{ url_for('auth.logout') }}"> <form method="post" action="{{ url_for('auth.logout') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Salir</button> <button class="linkish" type="submit">{{ t('account.salir') }}</button>
</form> </form>
</div> </div>
</details> </details>
@ -55,7 +55,7 @@
</div> </div>
{% if g.member %} {% if g.member %}
<nav class="site-bar__pages" aria-label="Secciones"> <nav class="site-bar__pages" aria-label="{{ t('nav.secciones') }}">
{# Six entries, and five of them are the same for everybody. The role {# Six entries, and five of them are the same for everybody. The role
only decides whether Gestión is there — it used to decide three of only decides whether Gestión is there — it used to decide three of
them, which is how an ordinary member ended up signing in to a wall them, which is how an ordinary member ended up signing in to a wall
@ -69,19 +69,19 @@
left that tells a member somebody wrote to them, which is why it is left that tells a member somebody wrote to them, which is why it is
also repeated on the card of whoever wrote. #} also repeated on the card of whoever wrote. #}
<ul class="page-nav"> <ul class="page-nav">
<li><a href="{{ url_for('home.index') }}">Inicio</a></li> <li><a href="{{ url_for('home.index') }}">{{ t('nav.inicio') }}</a></li>
<li><a href="{{ url_for('board.threads') }}">Muro</a></li> <li><a href="{{ url_for('board.threads') }}">{{ t('nav.muro') }}</a></li>
<li> <li>
<a href="{{ url_for('members.index') }}">Miembros{% set unread = unread_private() %}{% if unread %} <span class="tag">{{ unread }}</span>{% endif %}</a> <a href="{{ url_for('members.index') }}">{{ t('nav.miembros') }}{% set unread = unread_private() %}{% if unread %} <span class="tag">{{ unread }}</span>{% endif %}</a>
</li> </li>
<li> <li>
{# The badge counts what is waiting for a moderator, so for {# The badge counts what is waiting for a moderator, so for
anybody else the function returns 0 and nothing is drawn. #} anybody else the function returns 0 and nothing is drawn. #}
<a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a> <a href="{{ url_for('submissions.index') }}">{{ t('nav.publicaciones') }}{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a>
</li> </li>
<li><a href="{{ url_for('events.month') }}">Calendario</a></li> <li><a href="{{ url_for('events.month') }}">{{ t('nav.calendario') }}</a></li>
{% if is_at_least(g.member.role, 'admin') %} {% if is_at_least(g.member.role, 'admin') %}
<li><a href="{{ url_for('home.gestion') }}">Gestión</a></li> <li><a href="{{ url_for('home.gestion') }}">{{ t('nav.gestion') }}</a></li>
{% endif %} {% endif %}
</ul> </ul>
</nav> </nav>
@ -100,8 +100,8 @@
</main> </main>
<footer class="site-foot"> <footer class="site-foot">
<a href="/">Ir al sitio público</a> <a href="/">{{ t('chrome.publico') }}</a>
<div class="site-foot__legal">Viena Latina © {{ current_year }} · Área privada</div> <div class="site-foot__legal">Viena Latina © {{ current_year }} · {{ t('chrome.privada') }}</div>
</footer> </footer>
</div> </div>

View File

@ -94,6 +94,21 @@
</p> </p>
</section> </section>
<section class="panel">
<div class="panel__head">
<h2>Textos</h2>
<a class="linkish" href="{{ url_for('ui.edit') }}">Abrir</a>
</div>
{% set words = ui_state() %}{% if words.updated_at and not words.published_at %}
<p class="panel__row">Hay cambios guardados que no han llegado al sitio público.</p>
{% endif %}
<p class="muted small">
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í.
</p>
</section>
<section class="panel"> <section class="panel">
<div class="panel__head"> <div class="panel__head">
<h2>Estado del sistema</h2> <h2>Estado del sistema</h2>

View File

@ -0,0 +1,124 @@
{# Gestión → Textos: what the software says, and how to say it differently.
The form is drawn from the catalogue rather than written out, so a string
extracted later appears here by itself. That is the point of the screen and
the reason there is no field list anywhere in it.
Each box shows the shipped word as its placeholder and what was typed as its
value — never the other way round. A field prefilled with the default saves
the default the first time anybody presses the button, and the default is
frozen from then on, which is the trap `identity_form.html` carries the same
warning about. #}
{% extends "base.html" %}
{% block title %}{{ t('nav.gestion') }} · Textos{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Textos</h1>
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a {{ t('nav.gestion') }}</a>
</div>
<p class="muted">
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.
</p>
{% if state.updated_at and not state.published_at %}
<section class="panel panel--attention">
<div class="panel__head"><h2>Pendiente de publicar</h2></div>
<p class="panel__row">
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.
</p>
<form method="post" action="{{ url_for('ui.publish') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn" type="submit">Reintentar publicar</button>
</form>
</section>
{% endif %}
{# Areas as tabs and a search box beside them. Server-side, because the CSP has
no 'unsafe-inline' and a filter that needs a script is a filter that silently
does nothing. #}
<nav class="tabs" aria-label="Apartados">
{% for name in areas %}
<a class="tab {{ 'tab--on' if area == name }}"
href="{{ url_for('ui.edit', area=name, q=q or None) }}">{{ name }}</a>
{% endfor %}
<a class="tab {{ 'tab--on' if area == 'todo' }}"
href="{{ url_for('ui.edit', area='todo', q=q or None) }}">todo</a>
</nav>
<form class="card" method="get" action="{{ url_for('ui.edit') }}">
<input type="hidden" name="area" value="todo">
<label for="q">Buscar en todos los apartados</label>
<input id="q" name="q" type="search" maxlength="80" value="{{ q }}"
placeholder="una palabra que salga en pantalla">
<p class="muted small">
Busca en la clave, en la nota y en el texto mismo. Si no sabes dónde está
una palabra, escríbela aquí.
</p>
<button class="btn btn--quiet" type="submit">Buscar</button>
</form>
<form class="card" method="post"
action="{{ url_for('ui.edit', area=area, q=q or None) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
{% if not rows %}
<p class="muted">No hay nada aquí con «{{ q }}».</p>
{% else %}
{% for row in rows %}
<div class="stringrow">
<div class="stringrow__head">
<span class="mono small">{{ row.key }}</span>
{% if row.public %}<span class="tag tag--quiet">sitio público</span>{% endif %}
</div>
{% if row.note %}<p class="muted small">{{ row.note }}</p>{% endif %}
{% for lang in row.langs %}
{% if row.public %}<label for="{{ row.key }}:{{ lang.code }}">{{ lang.label }}</label>{% endif %}
{% if row.long %}
<textarea id="{{ row.key }}:{{ lang.code }}" name="{{ row.key }}:{{ lang.code }}"
rows="3" maxlength="2000"
placeholder="{{ lang.default }}">{{ lang.stored }}</textarea>
{% else %}
<input id="{{ row.key }}:{{ lang.code }}" name="{{ row.key }}:{{ lang.code }}"
type="text" maxlength="2000"
value="{{ lang.stored }}" placeholder="{{ lang.default }}">
{% endif %}
{% endfor %}
</div>
{% endfor %}
<div class="actions">
<button class="btn" type="submit">Guardar</button>
</div>
{% endif %}
</form>
{% if rows and rows[0].public %}
<p class="muted small">
Lo marcado <span class="tag tag--quiet">sitio público</span> 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.
</p>
{% endif %}
{% if state.customised %}
<form class="card" method="post" action="{{ url_for('ui.restore') }}"
data-confirm="Se vuelve a los textos originales en todos los apartados. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<h2 class="section-title">Restaurar los textos originales</h2>
<p class="muted small">
Deja todas las palabras como venían. No toca nada más: ni los colores, ni
la identidad, ni lo que haya escrito la gente.
</p>
<button class="btn btn--danger" type="submit">Restaurar los textos originales</button>
</form>
{% endif %}
{% endblock %}

View File

@ -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

View File

@ -14,6 +14,7 @@ from apps.board import activity, identity
SCREENS = { SCREENS = {
"/comunidad/gestion/identidad": "superadmin", "/comunidad/gestion/identidad": "superadmin",
"/comunidad/gestion/textos": "superadmin",
"/comunidad/gestion/estado": "superadmin", "/comunidad/gestion/estado": "superadmin",
"/comunidad/gestion/registro": "superadmin", "/comunidad/gestion/registro": "superadmin",
"/comunidad/gestion/medios": "admin", "/comunidad/gestion/medios": "admin",

211
apps/board/ui.py Normal file
View File

@ -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

View File

@ -48,6 +48,10 @@ languages:
main: main:
- name: "Inicio" - name: "Inicio"
url: "/" 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 weight: 1
de: de:
languageCode: "de" languageCode: "de"
@ -59,6 +63,10 @@ languages:
main: main:
- name: "Start" - name: "Start"
url: "/de/" 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 weight: 1
pt-br: pt-br:
languageCode: "pt-BR" languageCode: "pt-BR"
@ -70,6 +78,10 @@ languages:
main: main:
- name: "Início" - name: "Início"
url: "/pt-br/" 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 weight: 1
params: params:

View File

@ -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 media query changes nothing about specificity, and a coarse rule written before
it loses silently. 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 ### 11.20 The three admin tools
**Estado del sistema** (superadministrator). The backups panel reads **Estado del sistema** (superadministrator). The backups panel reads

View File

@ -34,7 +34,11 @@
function draw(state) { function draw(state) {
var bar = el("div", "member-bar"); var bar = el("div", "member-bar");
bar.setAttribute("role", "navigation"); 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 inner = el("div", "member-bar__inner");
var links = el("ul", "member-bar__links"); var links = el("ul", "member-bar__links");
@ -62,7 +66,7 @@
token.name = "csrf_token"; token.name = "csrf_token";
token.value = state.csrf; token.value = state.csrf;
form.appendChild(token); form.appendChild(token);
var out = el("button", "member-bar__out", "Salir"); var out = el("button", "member-bar__out", labels.logout || "Salir");
out.type = "submit"; out.type = "submit";
form.appendChild(out); form.appendChild(out);
account.appendChild(form); account.appendChild(form);

View File

@ -19,7 +19,7 @@
nothing. */}} nothing. */}}
{{ with .Params.author }} {{ with .Params.author }}
<span class="article-card__by"> <span class="article-card__by">
por {{ partial "t.html" (dict "key" "by" "lang" .Site.Language.Lang) }}
{{ with $.Params.author_url }} {{ with $.Params.author_url }}
<a href="{{ . | relURL }}">{{ $.Params.author }}</a> <a href="{{ . | relURL }}">{{ $.Params.author }}</a>
{{ else }} {{ else }}
@ -96,7 +96,7 @@
cannot see is exactly what search engines penalise. */}} cannot see is exactly what search engines penalise. */}}
{{ with .Params.faq }} {{ with .Params.faq }}
<section class="faq"> <section class="faq">
<h2>Preguntas frecuentes</h2> <h2>{{ partial "t.html" (dict "key" "faq" "lang" .Site.Language.Lang) }}</h2>
<dl> <dl>
{{ range . }} {{ range . }}
{{ $parts := split . "|" }} {{ $parts := split . "|" }}
@ -112,7 +112,7 @@
{{ partial "share.html" . }} {{ partial "share.html" . }}
<a class="back-link" href="{{ .Site.Home.Permalink }}"> <a class="back-link" href="{{ .Site.Home.Permalink }}">
← Volver al inicio {{ partial "t.html" (dict "key" "back" "lang" .Site.Language.Lang) }}
</a> </a>
{{/* Only on this template: the home page and the lists carry no share {{/* Only on this template: the home page and the lists carry no share

View File

@ -3,7 +3,7 @@
sans-serif, keeping the site free of third-party requests (GDPR). */}} sans-serif, keeping the site free of third-party requests (GDPR). */}}
<header class="site-bar"> <header class="site-bar">
<div class="site-bar__inner"> <div class="site-bar__inner">
<a class="site-bar__brand" href="{{ .Site.Home.Permalink }}" aria-label="Inicio"> <a class="site-bar__brand" href="{{ .Site.Home.Permalink }}" aria-label="{{ partial "t.html" (dict "key" "home" "lang" .Site.Language.Lang) }}">
{{/* The logo uploaded in Gestión → Marca, and the site's name in {{/* The logo uploaded in Gestión → Marca, and the site's name in
letters when there is none. The alt text is the name either way, letters when there is none. The alt text is the name either way,
so a reader who does not see the picture reads the same thing. so a reader who does not see the picture reads the same thing.
@ -99,9 +99,17 @@
<nav class="site-bar__pages" id="site-bar-pages" aria-label="Secciones"> <nav class="site-bar__pages" id="site-bar-pages" aria-label="Secciones">
<ul class="page-nav"> <ul class="page-nav">
{{/* config.yaml still says the entry exists and where it sits —
`weight` decides the side, and a data file cannot override a
menu (see site-name.html). What it is *called* comes through
the table, so «Inicio» can become «Escritorio» without a
commit. Only the home entry has a key; anything else somebody
adds to the menu keeps its own name. */}}
{{ range where .Site.Menus.main "Weight" "<" 5 }} {{ range where .Site.Menus.main "Weight" "<" 5 }}
{{ $label := .Name }}
{{ if eq .Identifier "home" }}{{ $label = partial "t.html" (dict "key" "home" "lang" $.Site.Language.Lang) }}{{ end }}
<li{{ if $current.IsMenuCurrent "main" . }} class="current-menu-item"{{ end }}> <li{{ if $current.IsMenuCurrent "main" . }} class="current-menu-item"{{ end }}>
<a href="{{ .URL }}">{{ .Name }}</a> <a href="{{ .URL }}">{{ $label }}</a>
</li> </li>
{{ end }} {{ end }}

View File

@ -13,11 +13,9 @@
"place" (dict "es" "Lugar" "de" "Ort" "pt-br" "Local") "place" (dict "es" "Lugar" "de" "Ort" "pt-br" "Local")
"add" (dict "es" "Añadir a mi calendario" "de" "Zum Kalender hinzufügen" "pt-br" "Adicionar ao meu calendário") "add" (dict "es" "Añadir a mi calendario" "de" "Zum Kalender hinzufügen" "pt-br" "Adicionar ao meu calendário")
"agenda" (dict "es" "Agenda" "de" "Termine" "pt-br" "Agenda") "agenda" (dict "es" "Agenda" "de" "Termine" "pt-br" "Agenda")
"today" (dict "es" "Hoy" "de" "Heute" "pt-br" "Hoje")
"previous" (dict "es" "Mes anterior" "de" "Voriger Monat" "pt-br" "Mês anterior") "previous" (dict "es" "Mes anterior" "de" "Voriger Monat" "pt-br" "Mês anterior")
"next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês") "next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês")
"noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.") "noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.")
"allevents" (dict "es" "Todos los eventos" "de" "Alle Termine" "pt-br" "Todos os eventos")
"ai" (dict "es" "Generado con IA" "de" "Mit KI erstellt" "pt-br" "Gerado com IA") "ai" (dict "es" "Generado con IA" "de" "Mit KI erstellt" "pt-br" "Gerado com IA")
"pinned" (dict "es" "Fijado" "de" "Angeheftet" "pt-br" "Fixado") "pinned" (dict "es" "Fijado" "de" "Angeheftet" "pt-br" "Fixado")
"share" (dict "es" "Compartir" "de" "Teilen" "pt-br" "Compartilhar") "share" (dict "es" "Compartir" "de" "Teilen" "pt-br" "Compartilhar")
@ -31,10 +29,29 @@
"pt-br" "Quem publicou marcou este texto como gerado com inteligência artificial.") "pt-br" "Quem publicou marcou este texto como gerado com inteligência artificial.")
"community" (dict "es" "Comunidad" "de" "Community" "pt-br" "Comunidade") "community" (dict "es" "Comunidad" "de" "Community" "pt-br" "Comunidade")
"menu" (dict "es" "Menú" "de" "Menü" "pt-br" "Menu") "menu" (dict "es" "Menú" "de" "Menü" "pt-br" "Menu")
"home" (dict "es" "Inicio" "de" "Start" "pt-br" "Início")
"back" (dict "es" "← Volver al inicio" "de" "← Zurück zur Startseite" "pt-br" "← Voltar ao início")
"by" (dict "es" "por" "de" "von" "pt-br" "por")
"faq" (dict "es" "Preguntas frecuentes" "de" "Häufige Fragen" "pt-br" "Perguntas frequentes")
-}} -}}
{{- /* What Gestión → Textos has said instead, if anything. Read through
nested `with` rather than as site.Data.ui.<key>.<lang>, because on a site
with no data file that dotted chain is a field lookup on nil and fails the
build — which is the state every install starts in. Same shape, and the
same trap, as site-name.html. */ -}}
{{- $said := "" -}}
{{- with site.Data.ui -}}
{{- with index . $.key -}}
{{- with index . $.lang }}{{ $said = . }}{{ end -}}
{{- end -}}
{{- end -}}
{{- if $said -}}
{{- $said -}}
{{- else -}}
{{- $entry := index $words .key -}} {{- $entry := index $words .key -}}
{{- if $entry -}} {{- if $entry -}}
{{- index $entry .lang | default (index $entry "es") -}} {{- index $entry .lang | default (index $entry "es") -}}
{{- else -}} {{- else -}}
{{- .key -}} {{- .key -}}
{{- end -}} {{- end -}}
{{- end -}}