The bar, the share card, the writing box and subpages

**A signed-in member sees the members area from anywhere.** A slim bar above the
public header, with the same five sections /comunidad/ has. Those pages are
files on disk and get cached, so it is drawn in the browser: memberbar.js asks
/comunidad/sesion.json who is reading, and that endpoint is the only thing that
decides — a visitor is told `{"signed_in": false}` and the answer is never
cached. Sign-in also sets vl_sesion=1, a cookie holding one digit that scripts
can read, and without it the script makes no request at all: a stranger reading
one article costs the app nothing. It is a hint, never a credential — the
session cookie stays HttpOnly and signed, and a forged hint earns a reply saying
you are not signed in. Comunidad is now in the public menu in all three
languages, signed in or not.

**The public menu is built from the pages.** It was three names per language in
config.yaml, so a page published through Contenido never appeared on the site at
all and the German and Portuguese menus had to be kept in step by hand. Pages
carry `parent` (another page's basename — the one translate.py already uses to
pair siblings, so it holds in all three languages) and `weight`, both chosen in
the editor, and header.html builds two levels from them. URLs do not change: a
subpage is still /page/<slug>/, only the menu nests, so nothing in the Caddyfile
or the pipeline learns about folders. The dropdown is the theme's own, ported
from WordPress — hover, focus-within, inline on a phone, no script. A parent that
has been deleted is kept and labelled rather than silently dropped on the next
save.

**Sharing and the rest of SEO/GEO.** The groundwork was already here — hreflang,
Open Graph, Twitter card, BlogPosting, llms.txt, robots.txt naming the AI
crawlers — so this closes the gaps. Static pages had *none* of it and shared as
bare links; they now carry WebPage schema and the full set of tags. Both branches
gain og:image with an alt and a twitter:image, falling back to params.defaultImage
(empty until there is a logo, which is the one line to fill in then). The home
page gains Organization with areaServed Wien and a sameAs list; posts and pages
gain BreadcrumbList, and an article's structured data now carries the author's
profile URL. An optional FAQ — `pregunta|respuesta` per line — renders at the
foot of the page and as FAQPage schema, because current guidance for generative
engines puts exactly that shape at the top of what gets quoted, and schema
describing something invisible is what search engines penalise. translate.py
carries both new fields: image_alt joins the translated keys, and faq is
translated half by half so the separator survives.

**The writing boxes.** A markdown toolbar and a Vista previa on every box where
somebody writes prose, opted in with data-markdown. The preview POSTs to
/comunidad/previsualizar and renders with render.to_html — the same function the
board and the site use, so it cannot promise something publishing will not
deliver; a markdown parser in the browser would be a second opinion about what
somebody's text means. Choosing a picture now shows a thumbnail with its name and
size before anything is uploaded, which is the only reason `blob:` joins img-src:
a handle to bytes already in the page, reaching no network.

All of it ours, no dependency added, under a policy that loads scripts from this
origin only. Verified by building the site with Hugo 0.135, the version the
pipeline runs: the nested menu, the page's share tags, the FAQ schema matching
the rendered section, and llms.txt listing the pages.

463 tests pass.

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-02 15:21:35 +00:00
parent e52c1e4d49
commit c84a996eef
No known key found for this signature in database
29 changed files with 1254 additions and 40 deletions

View File

@ -148,8 +148,13 @@ def create_app(overrides: dict | None = None) -> Flask:
# pointing at another site will not load — which for a private board is
# the right answer anyway, since an external image is a request that
# tells someone else who read the thread and when.
#
# `blob:` is in img-src for one thing only: the thumbnail of a picture
# somebody has just chosen and not yet uploaded. A blob URL is a handle
# to bytes already in this page; it reaches no network and cannot be
# pointed at another site.
response.headers["Content-Security-Policy"] = (
"default-src 'self'; img-src 'self' data:; frame-ancestors 'none'"
"default-src 'self'; img-src 'self' data: blob:; frame-ancestors 'none'"
)
return response

View File

@ -121,7 +121,40 @@ def login():
passwords.prune_attempts()
get_db().execute("UPDATE members SET last_seen_at = datetime('now') WHERE id = ?",
(member["id"],))
return redirect(safe_next(target))
return remember_session(redirect(safe_next(target)))
# --- the hint the public site reads --------------------------------------
#
# The static pages on vienalatina.com are files on disk; nothing there knows who
# is looking. The members' bar is therefore drawn by a script that asks this app
# — and asking on every page view, for every stranger who ever lands on the
# site, to be told they are nobody, is a request per page for nothing.
#
# So sign-in also sets this: a second cookie holding the digit 1, readable by
# that script, saying only "somebody signed in on this browser once". Without it
# the script makes no request at all. It is a hint and never a credential: the
# real session cookie stays HttpOnly and signed, and `sesion.json` decides
# everything. Somebody who sets this by hand gets a bar that says they are not
# signed in.
SESSION_HINT = "vl_sesion"
def remember_session(response):
response.set_cookie(
SESSION_HINT, "1",
max_age=60 * 60 * 24 * 30,
secure=current_app.config["SESSION_COOKIE_SECURE"],
httponly=False, # the whole point: a script has to read it
samesite="Lax",
path="/", # including the static site, which is why it exists
)
return response
def forget_session(response):
response.delete_cookie(SESSION_HINT, path="/")
return response
def invite_url(token: str) -> str:
@ -207,4 +240,4 @@ def logout():
"""
session.clear()
flash("Has cerrado sesión.", "ok")
return redirect(url_for("auth.login"))
return forget_session(redirect(url_for("auth.login")))

View File

@ -76,6 +76,10 @@ SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*\.es\.md$")
# link somewhere else.
AUTHOR_URL = re.compile(r"^/[A-Za-z0-9][A-Za-z0-9._-]{0,38}$")
# A page's basename, as it appears in acerca.es.md — which is what another page
# names when it hangs under it.
PAGE_BASENAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$")
# --- the contract with translate.py --------------------------------------
@ -114,6 +118,17 @@ def frontmatter_for(collection: str, form: dict) -> dict:
fields["date"] = form["date"]
fields["lang"] = "es"
fields["manual_translation"] = form["manual_translation"]
if collection == "page":
# Only written when set, so a page that sits at the top of the menu has
# no `parent: ""` line for somebody to wonder about later.
if form.get("parent"):
fields["parent"] = form["parent"]
if form.get("weight"):
fields["weight"] = form["weight"]
if form.get("faq"):
fields["faq"] = form["faq"]
if form.get("image_alt"):
fields["image_alt"] = form["image_alt"]
if collection == "post":
if form["categories"]:
fields["categories"] = form["categories"]
@ -237,6 +252,26 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
# editing it, so saving a correction must not re-sign the post. Checked on
# the way back in because a hidden field is only a convention — the URL has
# to be a path on this site and nothing else.
# A page's place in the menu. `parent` is another page's basename — the one
# translate.py uses to pair siblings, so a parent chosen once holds in all
# three languages — and the menu is built from these, not from a list in
# config.yaml that nobody remembers to edit.
parent = request.form.get("parent", "").strip()
if parent and not PAGE_BASENAME.match(parent):
parent = ""
try:
weight = max(0, min(999, int(request.form.get("weight", "") or 50)))
except ValueError:
weight = 50
# Questions and answers, one `pregunta|respuesta` per line — the same shape
# the profile links field uses, and parsed the same way: a line without a
# separator is dropped rather than published half-formed. They are rendered
# on the page and as FAQPage structured data, which is the shape an answer
# engine quotes most readily.
faq = clean_faq(request.form.get("faq", ""))
image_alt = request.form.get("image_alt", "").strip()[:200]
author = request.form.get("author", "").strip()[:80]
author_url = request.form.get("author_url", "").strip()
if author_url and not AUTHOR_URL.match(author_url):
@ -257,6 +292,8 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
"image": image,
"manual_translation": request.form.get("manual_translation") == "on",
"author": author, "author_url": author_url,
"parent": parent, "weight": weight,
"faq": faq, "image_alt": image_alt,
}
return fields, body, errors
@ -295,6 +332,27 @@ def commit_picture(data: bytes, filename: str, author=None) -> str:
return f"/uploads/{name}"
def clean_faq(raw: str) -> list[str]:
"""`pregunta|respuesta` per line, kept only when both halves are there.
Stored as the lines themselves rather than as a list of dicts: the template
and the schema both split on the first separator, and a YAML list of strings
survives translate.py's `dict(fm)` copy unchanged, which a nested structure
would too but less legibly in a diff.
"""
entries = []
for line in raw.splitlines():
question, separator, answer = line.strip().partition("|")
if not separator:
continue
question, answer = question.strip(), answer.strip()
if question and answer:
entries.append(f"{question[:200]}|{answer[:600]}")
if len(entries) >= 10:
break
return entries
def _upload_image() -> str:
upload = request.files.get("picture")
if not upload or not upload.filename:
@ -378,7 +436,8 @@ def new(collection: str):
if request.method == "GET":
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item=None, fields=None,
body="", today=date_type.today().isoformat())
body="", today=date_type.today().isoformat(),
parents=possible_parents(collection))
fields, body, errors = _read_form(collection)
if errors:
@ -429,11 +488,16 @@ def edit(collection: str, name: str):
# people's words, applied to the byline.
"author": fm.get("author", ""),
"author_url": fm.get("author_url", ""),
"parent": fm.get("parent", ""),
"weight": fm.get("weight", ""),
"faq": "\n".join(fm.get("faq") or []),
"image_alt": fm.get("image_alt", ""),
}
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item={"name": name, "sha": sha},
fields=fields, body=body,
today=date_type.today().isoformat())
today=date_type.today().isoformat(),
parents=possible_parents(collection, name))
fields, body, errors = _read_form(collection)
sha = request.form.get("sha", "")
@ -493,12 +557,33 @@ def preview(collection: str):
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item=item, fields=fields, body=body,
today=date_type.today().isoformat(),
parents=possible_parents(collection,
item["name"] if item else ""),
preview_html=to_html(body))
def possible_parents(collection: str, exclude: str = "") -> list[dict]:
"""The pages a page may hang under, for the select in the form.
Only pages have a parent, and a page cannot be its own. A failure to reach
the git server returns an empty list rather than an error: not being able to
offer the choice is no reason to refuse to open the form.
"""
if collection != "page":
return []
try:
items = listing("page")
except gitea.GiteaError:
return []
return [{"base": item["name"].removesuffix(".es.md"), "title": item["title"]}
for item in items if item["name"] != exclude]
def _back_to_form(collection, meta, fields, body, errors, item):
for message in errors:
flash(message, "error")
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item=item, fields=fields, body=body,
today=date_type.today().isoformat()), 400
today=date_type.today().isoformat(),
parents=possible_parents(collection,
item["name"] if item else "")), 400

View File

@ -13,17 +13,22 @@ page is the only way to reach anything.
from __future__ import annotations
from flask import Blueprint, g, render_template
from flask import Blueprint, g, jsonify, render_template, request, url_for
from . import submissions
from .db import TOMBSTONE_LOGIN, get_db
from .render import excerpt
from .security import admin_required, login_required
from .render import excerpt, to_html
from .security import admin_required, csrf_token, login_required
bp = Blueprint("home", __name__)
RECENT = 5
# The longest text the preview will render. The forms themselves cap what can be
# saved; this is only here so a crafted request cannot ask for a megabyte of
# markdown to be parsed on every keystroke.
BODY_MAX = 100_000
@bp.route("/")
@login_required
@ -92,6 +97,73 @@ def index():
state_labels=submissions.STATE_LABELS)
@bp.route("/sesion.json")
def session_state():
"""Who is signed in, for the bar the public site draws.
vienalatina.com is files on disk; it cannot know who is reading it, and
baking the answer into those files would mean caching one member's name for
the next visitor. So the browser asks here instead, and this is the only
place that decides — including which sections to offer, read from the same
rule the navigation uses, so the two cannot drift.
Three properties worth stating, because each is a way this leaks:
* **A visitor gets `{"signed_in": false}` and nothing else.** No names, no
counts, no hint about who else exists.
* **`no-store`.** A cached answer is somebody else's name on a shared
machine, or a bar that stays after signing out.
* **No badge counts.** They would need queries on every public page view,
for a number nobody can act on until they are inside anyway.
"""
if g.member is None:
return _no_store(jsonify({"signed_in": False}))
sections = [
{"label": "Inicio", "url": url_for("home.index")},
{"label": "Muro", "url": url_for("board.threads")},
{"label": "Privados", "url": url_for("messages.inbox")},
{"label": "Publicaciones", "url": url_for("submissions.index")},
]
if g.member["role"] in ("owner", "admin"):
sections.append({"label": "Gestión", "url": url_for("home.gestion")})
return _no_store(jsonify({
"signed_in": True,
"name": g.member["display_name"] or g.member["gitea_login"],
"sections": sections,
"profile": url_for("profiles.edit"),
"logout": url_for("auth.logout"),
# Signing out is a POST, so the bar needs the token to render a real
# form. Handing it to a script on our own pages gives nothing away: a
# page on another origin cannot read this response — no CORS header
# allows it — and the session cookie is SameSite=Lax, so it is not sent
# with a cross-site POST in the first place.
"csrf": csrf_token(),
}))
def _no_store(response):
response.headers["Cache-Control"] = "no-store"
return response
@bp.route("/previsualizar", methods=["POST"])
@login_required
def preview():
"""Render markdown the way the site will, for the Vista previa button.
A round trip rather than a markdown parser in the browser, deliberately. The
preview has to agree with what gets published, and the only way to guarantee
that is to render it with the same function — `render.to_html`, with raw HTML
disabled, which is the whole of the XSS defence here. A second parser in
JavaScript would be a second opinion about what somebody's text means, and
the two would disagree the first time anybody wrote something unusual.
"""
body = request.form.get("body", "")[:BODY_MAX]
return _no_store(jsonify({"html": to_html(body)}))
@bp.route("/gestion")
@admin_required
def gestion():

View File

@ -540,3 +540,60 @@ input[type="file"] {
}
.person-card__actions form { margin: 0; }
.person-card__actions p { margin: 0; }
/* --- the writing boxes ------------------------------------------------- */
.md-bar {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
margin-bottom: 0.35rem;
}
.md-bar__button {
min-width: 2rem;
padding: 0.25rem 0.5rem;
border: 1px solid var(--border-light);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--muted);
font-size: 0.85rem;
cursor: pointer;
line-height: 1.4;
}
.md-bar__button:hover { border-color: var(--brand); color: var(--brand-dark); }
.md-bar__button--wide { margin-left: auto; }
.md-preview {
margin: 0.5rem 0 1rem;
padding: 0.85rem 1rem;
border: 1px dashed var(--border);
border-radius: var(--radius-md);
background: var(--surface-soft);
line-height: 1.6;
}
.md-preview :first-child { margin-top: 0; }
.md-preview :last-child { margin-bottom: 0; }
.md-preview img { max-width: 100%; border-radius: var(--radius-sm); }
/* What you just chose, before it is uploaded. */
.file-strip {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin: 0.5rem 0 0;
}
.file-strip__item { margin: 0; width: 120px; }
.file-strip__item img {
display: block;
width: 120px;
height: 90px;
object-fit: cover;
border-radius: var(--radius-sm);
border: 1px solid var(--border-light);
}
.file-strip__item figcaption {
margin-top: 0.2rem;
font-size: 0.72rem;
color: var(--subtle);
overflow-wrap: anywhere;
}

View File

@ -13,3 +13,152 @@ document.addEventListener("submit", function (event) {
event.preventDefault();
}
});
// --- the writing boxes ----------------------------------------------------
//
// A toolbar, a preview and thumbnails, all of it ours. Not because a library
// would be wrong, but because the Content-Security-Policy here loads scripts
// from this origin only, and vendoring an editor means owning its updates
// forever — for buttons that wrap a selection in asterisks.
//
// Everything below attaches on load and leaves anything it does not recognise
// alone, so a form that has not opted in behaves exactly as it did.
(function () {
"use strict";
// What each button does to the selected text. `wrap` goes on both sides,
// `prefix` goes at the start of every selected line.
var TOOLS = [
{ label: "N", title: "Negrita", wrap: "**" },
{ label: "I", title: "Cursiva", wrap: "_" },
{ label: "H", title: "Título", prefix: "## " },
{ label: "“”", title: "Cita", prefix: "> " },
{ label: "•", title: "Lista", prefix: "- " },
{ label: "🔗", title: "Enlace", link: true }
];
function apply(box, tool) {
var start = box.selectionStart;
var end = box.selectionEnd;
var selected = box.value.slice(start, end);
var replacement;
if (tool.link) {
var url = window.prompt("Dirección del enlace", "https://");
if (!url) return;
replacement = "[" + (selected || "texto") + "](" + url + ")";
} else if (tool.prefix) {
// Line by line, so marking three lines as a list marks three lines.
replacement = (selected || "").split("\n").map(function (line) {
return line.indexOf(tool.prefix) === 0 ? line : tool.prefix + line;
}).join("\n");
} else {
replacement = tool.wrap + (selected || "texto") + tool.wrap;
}
box.setRangeText(replacement, start, end, "end");
box.focus();
// Fires the input event frameworks and our own counters would expect; the
// browser does not fire one for a programmatic change.
box.dispatchEvent(new Event("input", { bubbles: true }));
}
function toolbarFor(box) {
var bar = document.createElement("div");
bar.className = "md-bar";
TOOLS.forEach(function (tool) {
var button = document.createElement("button");
button.type = "button"; // never a submit inside a form
button.className = "md-bar__button";
button.title = tool.title;
button.textContent = tool.label;
button.addEventListener("click", function () { apply(box, tool); });
bar.appendChild(button);
});
var preview = document.createElement("button");
preview.type = "button";
preview.className = "md-bar__button md-bar__button--wide";
preview.textContent = "Vista previa";
var panel = document.createElement("div");
panel.className = "md-preview";
panel.hidden = true;
preview.addEventListener("click", function () {
if (!panel.hidden) {
panel.hidden = true;
return;
}
var token = box.form && box.form.querySelector("input[name=csrf_token]");
var data = new FormData();
data.append("body", box.value);
data.append("csrf_token", token ? token.value : "");
panel.textContent = "Un momento…";
panel.hidden = false;
fetch("/comunidad/previsualizar", {
method: "POST", body: data, credentials: "same-origin"
}).then(function (response) {
return response.ok ? response.json() : null;
}).then(function (result) {
// The server rendered this with the same markdown the site uses, with
// raw HTML disabled, so what comes back is already safe to insert —
// and inserting it as text would show the tags instead of the writing.
panel.innerHTML = result ? result.html : "";
if (!result) panel.textContent = "No se pudo generar la vista previa.";
}).catch(function () {
panel.textContent = "No se pudo generar la vista previa.";
});
});
bar.appendChild(preview);
box.parentNode.insertBefore(bar, box);
box.parentNode.insertBefore(panel, box.nextSibling);
}
// --- thumbnails of what was just chosen ---------------------------------
//
// So that attaching the wrong photograph is noticed before posting rather
// than after. createObjectURL gives a handle to bytes already in this page —
// nothing is uploaded until the form is submitted — which is what `blob:` in
// the image policy is there for.
function previewFiles(input) {
var strip = input.nextElementSibling;
if (!strip || !strip.classList.contains("file-strip")) {
strip = document.createElement("div");
strip.className = "file-strip";
input.parentNode.insertBefore(strip, input.nextSibling);
}
Array.prototype.forEach.call(strip.querySelectorAll("img"), function (img) {
URL.revokeObjectURL(img.src); // or every re-pick leaks one
});
strip.textContent = "";
Array.prototype.forEach.call(input.files, function (file) {
if (file.type.indexOf("image/") !== 0) return;
var figure = document.createElement("figure");
figure.className = "file-strip__item";
var img = document.createElement("img");
img.src = URL.createObjectURL(file);
img.alt = "";
var caption = document.createElement("figcaption");
caption.textContent = file.name + " · " + Math.round(file.size / 1024) + " KB";
figure.appendChild(img);
figure.appendChild(caption);
strip.appendChild(figure);
});
}
document.addEventListener("DOMContentLoaded", function () {
Array.prototype.forEach.call(
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
document.addEventListener("change", function (event) {
var input = event.target;
if (input.tagName === "INPUT" && input.type === "file" &&
(input.accept || "").indexOf("image") !== -1) {
previewFiles(input);
}
});
});
})();

View File

@ -7,7 +7,7 @@
<h1>Editar respuesta</h1>
<label for="body">Mensaje</label>
<textarea id="body" name="body" rows="10" required>{{ comment.body_md }}</textarea>
<textarea id="body" data-markdown name="body" rows="10" required>{{ comment.body_md }}</textarea>
<div class="actions">
<button class="btn" type="submit">Guardar</button>

View File

@ -37,6 +37,34 @@
<input id="date" name="date" type="date" required value="{{ f.date or today }}">
{% endif %}
{% if collection == 'page' %}
{# Where this page sits in the public menu. The menu is built from the pages
themselves, so a page published here appears on the site by itself —
choosing a parent puts it in the submenu under that page instead of on the
top row. The choice is made once and holds in the three languages. #}
<label for="parent">En el menú</label>
{% set names = parents | map(attribute='base') | list %}
<select id="parent" name="parent">
<option value="">En la barra principal</option>
{% if f.parent and f.parent not in names %}
{# The page it hung under has been deleted, or the git server could not be
reached to list them. Either way the relationship is kept and said out
loud, rather than dropped silently by the next save. #}
<option value="{{ f.parent }}" selected>Dentro de «{{ f.parent }}» (no encontrada)</option>
{% endif %}
{% for other in parents %}
<option value="{{ other.base }}" {{ 'selected' if f.parent == other.base }}>
Dentro de «{{ other.title }}»
</option>
{% endfor %}
</select>
<label for="weight">Orden</label>
<input id="weight" name="weight" type="number" min="0" max="999"
value="{{ f.weight or 50 }}">
<p class="muted small">Menor número, más a la izquierda. 50 si da igual.</p>
{% endif %}
{% if collection == 'post' %}
<fieldset class="fieldset">
<legend>Categorías</legend>
@ -51,6 +79,11 @@
<label for="description">Resumen</label>
<textarea id="description" name="description" rows="2">{{ f.description or '' }}</textarea>
<p class="muted small">
Una o dos frases que se entiendan solas: es lo que aparece en los
listados, en WhatsApp al compartir el enlace y lo que citan los
buscadores. Mejor concreta («El sábado 12 en Ottakring») que general.
</p>
<label for="picture">Imagen destacada</label>
{% if f.image %}
@ -58,12 +91,28 @@
<input type="hidden" name="image" value="{{ f.image }}">
{% endif %}
<input id="picture" name="picture" type="file" accept="image/*">
<label for="image_alt">Texto alternativo de la imagen</label>
<input id="image_alt" name="image_alt" maxlength="200" value="{{ f.image_alt or '' }}">
<p class="muted small">
Qué se ve en la foto, en una frase. Lo lee quien no puede ver la imagen y
lo leen también los buscadores.
</p>
{% endif %}
<label for="body">Cuerpo</label>
<textarea id="body" name="body" rows="18" required
<textarea id="body" data-markdown name="body" rows="18" required
placeholder="Markdown: **negrita**, ## títulos, listas, [enlaces](https://…).">{{ body }}</textarea>
<label for="faq">Preguntas frecuentes <span class="muted small">(opcional)</span></label>
<textarea id="faq" name="faq" rows="5"
placeholder="¿Dónde es?|En la plaza de Ottakring, junto al mercado.">{{ f.faq or '' }}</textarea>
<p class="muted small">
Una por línea, con el formato <span class="mono">pregunta|respuesta</span>.
Se muestran al final de la página y son lo que mejor citan los buscadores
y los asistentes de IA: pregunta concreta, respuesta corta y verificable.
</p>
<label class="check">
<input type="checkbox" name="manual_translation" {{ 'checked' if f.manual_translation }}>
Traducción manual — no generar alemán ni portugués para esto

View File

@ -42,7 +42,7 @@
action="{{ url_for('messages.talk', member_id=other.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="body">Mensaje</label>
<textarea id="body" name="body" rows="4" autofocus
<textarea id="body" data-markdown name="body" rows="4" autofocus
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>

View File

@ -19,7 +19,7 @@
{% endif %}
<label for="bio">Sobre ti</label>
<textarea id="bio" name="bio" rows="8"
<textarea id="bio" data-markdown name="bio" rows="8"
placeholder="Se puede usar Markdown.">{{ g.member.bio or '' }}</textarea>
<label for="links">Enlaces</label>

View File

@ -36,7 +36,7 @@
</fieldset>
<label for="body">Texto</label>
<textarea id="body" name="body" rows="16" required
<textarea id="body" data-markdown name="body" rows="16" required
placeholder="Se puede usar Markdown: **negrita**, ## títulos, listas, enlaces.">{{ fields.body if fields else '' }}</textarea>
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>

View File

@ -81,7 +81,7 @@
action="{{ url_for('board.comment', thread_id=thread.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="body">Responder</label>
<textarea id="body" name="body" rows="5" required
<textarea id="body" data-markdown name="body" rows="5" required
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>

View File

@ -12,7 +12,7 @@
value="{{ thread.title if thread else '' }}">
<label for="body">Mensaje</label>
<textarea id="body" name="body" rows="14" required
<textarea id="body" data-markdown name="body" rows="14" required
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces.">{{ thread.body_md if thread else '' }}</textarea>
{# Only when writing, not when editing: the edit route does not read files,

View File

@ -108,3 +108,40 @@ def test_the_cooldown_stops_a_double_submit(app, client, post, make_member, sign
post("/comunidad/nuevo", {"title": "Segundo", "body": "Dos"})
count = db.execute("SELECT COUNT(*) AS n FROM threads").fetchone()["n"]
assert count == 1
# --- the preview behind the Vista previa button ---------------------------
#
# A round trip rather than a markdown parser in the browser: the preview has to
# agree with what gets published, and the only way to guarantee that is to
# render it with the same function the board and the site use.
def test_the_preview_renders_the_same_markdown_the_board_does(post, make_member, sign_in):
sign_in(make_member("maria"))
response = post("/comunidad/previsualizar", {"body": "**hola** y _adiós_"})
assert response.status_code == 200
assert response.get_json()["html"] == "<p><strong>hola</strong> y <em>adiós</em></p>\n"
def test_the_preview_drops_html_exactly_as_the_board_does(post, make_member, sign_in):
"""`html=False` in render.py is the whole XSS defence. A preview that
rendered raw HTML would be a hole in the members area and a lie about what
posting is going to do."""
sign_in(make_member("maria"))
html = post("/comunidad/previsualizar",
{"body": "<script>alert(1)</script>"}).get_json()["html"]
assert "<script>" not in html
def test_the_preview_needs_a_session(client):
assert client.post("/comunidad/previsualizar", data={"body": "hola"}).status_code in (302, 400)
def test_the_preview_is_never_cached(post, make_member, sign_in):
sign_in(make_member("maria"))
response = post("/comunidad/previsualizar", {"body": "hola"})
assert response.headers["Cache-Control"] == "no-store"

View File

@ -516,3 +516,86 @@ def test_a_page_carries_no_byline(repo, editor, post):
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert "author" not in front
# --- where a page sits in the public menu --------------------------------
#
# The menu used to be three names in config.yaml, so a page published here never
# appeared on the site and the three languages had to be kept in step by hand.
# It is built from the pages now, which makes these two fields the whole of the
# navigation: `parent` nests a page under another, `weight` orders them.
def test_a_page_records_where_it_goes_in_the_menu(repo, editor, post):
import yaml
post("/comunidad/contenido/page/nuevo",
{"title": "Estatutos", "body": "Texto.", "parent": "acerca", "weight": "10"})
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert front["parent"] == "acerca"
assert front["weight"] == 10
def test_a_top_level_page_carries_no_parent_line(repo, editor, post):
"""Rather than `parent: ""`, which is a line somebody has to decide whether
to worry about."""
import yaml
post("/comunidad/contenido/page/nuevo", {"title": "Contacto", "body": "Texto."})
path, = repo.files
assert "parent" not in yaml.safe_load(repo.files[path].decode().split("---")[1])
def test_a_parent_that_is_not_a_basename_is_dropped(repo, editor, post):
"""It arrives from a select, so anything else is somebody crafting a
request — and a parent with a slash in it would be a path, not a page."""
import yaml
post("/comunidad/contenido/page/nuevo",
{"title": "Estatutos", "body": "Texto.", "parent": "../../etc/passwd"})
path, = repo.files
assert "parent" not in yaml.safe_load(repo.files[path].decode().split("---")[1])
def test_a_page_keeps_its_place_when_edited(repo, editor, post, client):
repo.files["content/page/acerca.es.md"] = (
"---\ntitle: Acerca\nlang: es\n---\n\nTexto.\n").encode("utf-8")
repo.files["content/page/estatutos.es.md"] = (
"---\ntitle: Estatutos\nlang: es\nparent: acerca\nweight: 10\n---\n\nTexto.\n"
).encode("utf-8")
body = client.get("/comunidad/contenido/page/editar/estatutos.es.md").get_data(as_text=True)
assert 'value="acerca" selected' in body or 'value="acerca" selected' in body
assert 'value="10"' in body
def test_the_parent_select_never_offers_the_page_itself(repo, editor, client):
repo.files["content/page/acerca.es.md"] = (
"---\ntitle: Acerca\nlang: es\n---\n\nTexto.\n").encode("utf-8")
repo.files["content/page/contacto.es.md"] = (
"---\ntitle: Contacto\nlang: es\n---\n\nTexto.\n").encode("utf-8")
body = client.get("/comunidad/contenido/page/editar/acerca.es.md").get_data(as_text=True)
assert 'value="contacto"' in body
assert 'value="acerca"' not in body
def test_a_post_has_no_menu_fields(repo, editor, client):
"""Articles are dated and listed, never in the menu."""
body = client.get("/comunidad/contenido/post/nuevo").get_data(as_text=True)
assert 'name="parent"' not in body
assert 'name="weight"' not in body
def test_a_parent_that_has_been_deleted_is_kept_and_named(repo, editor, client):
"""Otherwise the next save would quietly promote the page to the top of the
menu, and nobody would connect that to having deleted another page."""
repo.files["content/page/estatutos.es.md"] = (
"---\ntitle: Estatutos\nlang: es\nparent: borrada\n---\n\nTexto.\n"
).encode("utf-8")
body = client.get("/comunidad/contenido/page/editar/estatutos.es.md").get_data(as_text=True)
assert 'value="borrada" selected' in body
assert "no encontrada" in body

View File

@ -151,3 +151,68 @@ def test_a_plain_member_is_offered_neither(client, make_member, sign_in):
assert "/comunidad/contenido" not in body
assert "Ya publicado" not in body
# --- the strip the public site draws --------------------------------------
#
# vienalatina.com is files on disk, so the bar is drawn by a script that asks
# this app who is reading. That makes this endpoint the whole privacy surface:
# it is the only thing on the public side that knows anything about anybody.
def test_a_visitor_is_told_nothing(client):
response = client.get("/comunidad/sesion.json")
assert response.status_code == 200
assert response.get_json() == {"signed_in": False}
assert response.headers["Cache-Control"] == "no-store"
def test_a_member_gets_their_name_and_their_sections(client, make_member, sign_in):
sign_in(make_member("maria"))
state = client.get("/comunidad/sesion.json").get_json()
assert state["signed_in"] is True
assert state["name"] == "Maria"
assert [s["label"] for s in state["sections"]] == [
"Inicio", "Muro", "Privados", "Publicaciones"]
assert state["csrf"] # the bar renders a real logout form
def test_the_sections_follow_the_same_rule_as_the_navigation(
client, make_member, sign_in):
"""Two places listing the sections would drift the first time one changed;
the navigation and this endpoint have to agree about Gestión."""
sign_in(make_member("admina", role="admin"))
labels = [s["label"] for s in client.get("/comunidad/sesion.json").get_json()["sections"]]
assert "Gestión" in labels
sign_in(make_member("luisa", role="moderator"))
labels = [s["label"] for s in client.get("/comunidad/sesion.json").get_json()["sections"]]
assert "Gestión" not in labels
def test_the_answer_is_never_cached(client, make_member, sign_in):
"""A cached answer is somebody else's name on a shared machine, or a bar
that stays up after signing out."""
sign_in(make_member("maria"))
assert client.get("/comunidad/sesion.json").headers["Cache-Control"] == "no-store"
def test_signing_in_sets_the_hint_and_signing_out_clears_it(client, db, post, make_member):
"""The hint is what keeps a stranger reading one article from costing a
request to this app on every page view."""
from apps.board import passwords
member_id = make_member("maria")
db.execute("UPDATE members SET password_hash = ? WHERE id = ?",
(passwords.hash_password("una-contraseña-larga"), member_id))
signed_in = post("/comunidad/login",
{"identifier": "maria", "password": "una-contraseña-larga"})
cookie = signed_in.headers.get_all("Set-Cookie")
assert any("vl_sesion=1" in header for header in cookie)
assert any("HttpOnly" not in header for header in cookie if "vl_sesion" in header)
signed_out = post("/comunidad/logout")
assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header
for header in signed_out.headers.get_all("Set-Cookie"))

View File

@ -140,3 +140,37 @@ def test_no_message_in_the_code_shows_it_either():
and "Gitea" in node.value and node.value not in docstrings
]
assert not offenders, "\n".join(offenders)
# --- the writing boxes opt in ---------------------------------------------
PROSE_BOXES = {
"thread_form.html": "body",
"comment_form.html": "body",
"thread.html": "body",
"conversation.html": "body",
"submission_form.html": "body",
"content_form.html": "body",
"profile_edit.html": "bio",
}
@pytest.mark.parametrize("name,box", sorted(PROSE_BOXES.items()))
def test_every_prose_box_has_the_markdown_toolbar(name, box):
"""`data-markdown` is what board.js attaches the toolbar and the preview to.
A box that forgets it loses both silently — the page still works, it is just
the plain textarea it always was, which nobody files as a bug."""
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
assert opening, f"{name} has no textarea #{box}"
assert "data-markdown" in opening.group(0), (
f"{name}: #{box} is prose and should carry data-markdown")
def test_the_fields_that_are_not_prose_stay_plain():
"""The links and FAQ boxes are parsed line by line, not rendered. A bold
button there would put asterisks into a value, not into writing."""
for name, box in (("profile_edit.html", "links"), ("content_form.html", "faq")):
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
assert opening and "data-markdown" not in opening.group(0), name

View File

@ -32,17 +32,22 @@ languages:
weight: 1
params:
description: "Comunidad latinoamericana en Viena — turismo, cultura, gastronomía, comunidad y comercio."
# Only the two ends of the menu live here. Everything between them is built
# from the pages themselves by partials/header.html — so a page published
# from the members area appears on the site, with its own translated title,
# instead of needing three edits in this file. Weight decides the side:
# under 5 goes before the pages, 5 or more after them.
menus:
main:
- name: "Inicio"
url: "/"
weight: 1
- name: "Acerca"
url: "/page/acerca/"
weight: 2
- name: "Contacto"
url: "/page/contacto/"
weight: 3
# The way into the members area, in the menu for everybody: somebody who
# has an account needs to find the door, and somebody who does not should
# at least see that there is one.
- name: "Comunidad"
url: "/comunidad/"
weight: 9
de:
languageCode: "de"
languageName: "Deutsch"
@ -54,12 +59,9 @@ languages:
- name: "Start"
url: "/de/"
weight: 1
- name: "Über uns"
url: "/de/page/acerca/"
weight: 2
- name: "Kontakt"
url: "/de/page/contacto/"
weight: 3
- name: "Community"
url: "/comunidad/"
weight: 9
pt-br:
languageCode: "pt-BR"
languageName: "Português (Brasil)"
@ -71,14 +73,23 @@ languages:
- name: "Início"
url: "/pt-br/"
weight: 1
- name: "Sobre"
url: "/pt-br/page/acerca/"
weight: 2
- name: "Contato"
url: "/pt-br/page/contacto/"
weight: 3
- name: "Comunidade"
url: "/comunidad/"
weight: 9
params:
# The picture a share card falls back on when a post or page has none, and the
# organisation's logo in the structured data. One path — /uploads/algo.png —
# and WhatsApp, Signal, Mastodon and Bluesky all start showing an image. Left
# empty until there is a logo to put here; a link then shares as title and
# description, which is what happens today.
defaultImage: ""
# The organisation's profiles elsewhere, for `sameAs` in the Organization
# schema: it is how a search or answer engine knows the Instagram account and
# this site are the same body. One URL per line when they exist.
sameAs: []
# og:locale values per language slug (ported from theme/inc/seo.php).
localeMap:
es: "es_ES"

View File

@ -668,6 +668,24 @@ the conversation would lose its shape; a two-party exchange has no such
remainder. This does destroy the other person's copy — the uncomfortable half
of the choice, and deliberate.
### 11.10b The members' bar on the public site
A signed-in member sees a slim bar above the public header on vienalatina.com,
with the same five sections the members area has. The public pages are files on
disk and get cached, so the bar is drawn in the browser:
`themes/vienalatina/assets/js/memberbar.js` asks `/comunidad/sesion.json` who is
reading, and that endpoint is the only thing that decides anything — a visitor
gets `{"signed_in": false}` and the answer is `Cache-Control: no-store`.
**The hint cookie is why this is not a request per page view.** Signing in also
sets `vl_sesion=1`, readable by scripts, holding nothing but the digit 1; without
it the script makes no request at all, so a stranger reading one article costs
the app nothing. It is never trusted: the session cookie stays `HttpOnly` and
signed, and forging the hint earns a reply saying you are not signed in.
*Comunidad* is in the public menu in all three languages, signed in or not,
because somebody who has an account needs to find the door.
### 11.11 Schema changes: `PRAGMA user_version`
`schema.sql` is all `CREATE TABLE IF NOT EXISTS`, which handles exactly one
@ -839,6 +857,68 @@ member's photo shows here even when their public page is unpublished, because
this side is behind the login; `profiles.member_photo` serves it and the profile
form says so in plain words.
### 11.15 The public menu is built from the pages
It used to be three names per language in `config.yaml`, which meant a page
published through *Contenido* never appeared on the site, and that the German and
Portuguese menus had to be edited by hand to match. `partials/header.html` now
builds it from the pages themselves, so a page shows up when it is published,
with its own translated title.
Two fields in the editor decide where it goes:
- **`parent`** — another page's basename (`acerca` for `acerca.es.md`), which puts
this page in the submenu under that one. The basename is what `translate.py`
uses to pair siblings, so a parent chosen once holds in all three languages.
- **`weight`** — the order, lower first, 50 by default.
**URLs do not change.** A subpage is still `/page/<slug>/`; only the menu nests,
so nothing in the Caddyfile, the pipeline or the editor's filename rules has to
learn about folders. The dropdown is the one the theme already had, ported from
WordPress: hover and `:focus-within`, inline on a phone, no script.
Only *Inicio* and *Comunidad* remain in `config.yaml`. Weight under 5 puts a menu
entry before the pages, 5 or more after them.
### 11.16 Sharing, SEO and answer engines
`partials/seo-head.html` was already emitting hreflang, Open Graph, a Twitter
card and `BlogPosting` for articles. What it now also does:
- **Static pages get all of it** — they had none, so *Acerca de* shared as a bare
link. `WebPage` schema, Open Graph, the card
- **`og:image` with an alt**, from the post's own picture or `params.defaultImage`
as a fallback. That param is empty: fill it in when there is a logo, and every
link shared on WhatsApp, Signal, Mastodon or Bluesky starts carrying a picture
- **`Organization`** on the home, with `areaServed: Wien` and a `sameAs` list
ready for social profiles — this is how a search or answer engine knows the
Instagram account and this site are one body
- **`BreadcrumbList`** on every post and page, and the author's profile URL in the
article's structured data
- **Optional `FAQPage`**: `pregunta|respuesta` per line in the editor, rendered at
the foot of the page *and* described in the schema. Current guidance for
generative engines puts a short factual answer to a concrete question at the
top of what gets quoted, and this is the cheapest way to write one
- `llms.txt` lists the static pages as well as the articles
The translation pipeline carries all of it: `image_alt` joins the translated
keys, and `faq` is translated line by line with each half handled separately so
the `|` survives.
### 11.17 Writing boxes
Every box where somebody writes prose — the wall, a comment, a private message, a
proposal, the editor, a profile bio — carries a markdown toolbar and a *Vista
previa*, opted in with `data-markdown` and attached by `static/board.js`. The
preview POSTs to `/comunidad/previsualizar`, which renders with `render.to_html`:
the same function the board and the site use, so the preview cannot promise
something publishing will not deliver. A markdown parser in the browser would be
a second opinion about what somebody's text means.
Choosing a picture shows a thumbnail with its name and size before anything is
uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to
bytes already in the page, which reaches no network.
## 12. Make Gitea look like the site
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its

View File

@ -60,7 +60,14 @@ CONTENT_DIR = REPO_ROOT / "content"
# Frontmatter strings translated alongside the body. Note `categories` is
# deliberately absent: the taxonomy terms stay Spanish in every language, or
# Hugo would fork the taxonomy per language.
TRANSLATED_KEYS = ("title", "description")
TRANSLATED_KEYS = ("title", "description", "image_alt")
# `faq` is a list of "question|answer" lines, so it cannot go through the loop
# above: str() on a list would translate the brackets. Each half is translated
# separately and rejoined, because the separator has to survive — a translator
# handed "¿Dónde es?|En la plaza" is free to move or drop that bar, and a line
# without it is dropped on the way out.
FAQ_KEY = "faq"
BOT_NAME = "vienalatina-translations"
BOT_EMAIL = "translations@vienalatina.com"
@ -220,6 +227,20 @@ def orphaned_siblings() -> list[Path]:
return orphans
def translate_faq(entries, src_lang: str, tgt: str, provider) -> list[str]:
"""Translate each half of each `question|answer` line, keeping the bar."""
out = []
for entry in entries or []:
question, separator, answer = str(entry).partition("|")
if not separator:
continue
out.append("{}|{}".format(
translate_text(question.strip(), src_lang, tgt, provider),
translate_text(answer.strip(), src_lang, tgt, provider),
))
return out
def translate_file(source: Path, basename: str, src_lang: str, provider) -> list[Path]:
fm, body = split_frontmatter(source.read_text(encoding="utf-8"))
written: list[Path] = []
@ -237,6 +258,8 @@ def translate_file(source: Path, basename: str, src_lang: str, provider) -> list
for key in TRANSLATED_KEYS:
if fm.get(key):
new_fm[key] = translate_text(str(fm[key]), src_lang, tgt, provider)
if fm.get(FAQ_KEY):
new_fm[FAQ_KEY] = translate_faq(fm[FAQ_KEY], src_lang, tgt, provider)
new_fm["lang"] = tgt
new_fm["translated_from"] = src_lang
new_fm["manual_translation"] = False

View File

@ -3715,3 +3715,104 @@ a.notif-card__message:hover {
.site-bar__inner { padding: 8px 12px; }
.site-bar__btn { padding: 7px 12px; font-size: 0.82rem; }
}
/* --- preguntas frecuentes ---------------------------------------------- */
/*
* Rendered from the `faq` frontmatter, and described by FAQPage structured data
* — which is why it has to be visible: schema for something a reader cannot see
* is what search engines penalise.
*/
.faq {
margin: 40px 0 0;
padding-top: 24px;
border-top: 1px solid var(--border-light, #e0cec8);
}
.faq h2 {
font-size: 1.15rem;
margin: 0 0 16px;
}
.faq dl {
margin: 0;
}
.faq dt {
font-weight: 700;
margin-top: 16px;
}
.faq dd {
margin: 4px 0 0;
color: var(--muted, #5c3d37);
line-height: 1.55;
}
/* --- the members' bar -------------------------------------------------- */
/*
* Drawn by assets/js/memberbar.js when somebody is signed in, above everything
* else. Deliberately in the brand colour and deliberately not subtle: its whole
* job is to answer "am I signed in, and where is the rest of it" from any page
* on the public site.
*/
.member-bar {
background: var(--brand, #c0391c);
color: #fff;
font-size: 0.86rem;
}
.member-bar__inner {
max-width: 1000px;
margin: 0 auto;
padding: 6px 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.member-bar__links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.member-bar a,
.member-bar__out {
color: #fff;
text-decoration: none;
opacity: 0.92;
}
.member-bar a:hover,
.member-bar__out:hover {
opacity: 1;
text-decoration: underline;
}
.member-bar__account {
display: flex;
align-items: center;
gap: 12px;
}
.member-bar__name {
font-weight: 700;
}
.member-bar form {
margin: 0;
}
/* A button that reads as part of the bar rather than as a form control. */
.member-bar__out {
background: none;
border: 0;
padding: 0;
font: inherit;
cursor: pointer;
}

View File

@ -0,0 +1,87 @@
// The signed-in strip on the public site.
//
// vienalatina.com is files on disk. They are the same files for everyone and
// they get cached, so the one thing they cannot contain is who is reading them.
// This asks the members area instead, and draws a bar above the header when the
// answer is somebody.
//
// Three decisions worth knowing before changing anything here:
//
// * **It does nothing without the hint cookie.** `vl_sesion` is set at sign-in
// and cleared at sign-out, holds the digit 1, and exists so that a stranger
// reading one article costs zero requests to the app. It is not trusted for
// anything: the server decides, and a forged hint earns a request that says
// "not signed in".
// * **Every value goes in as text, never as HTML.** A display name is whatever
// somebody typed into a form. textContent makes that a name; innerHTML would
// make it a script.
// * **No frameworks, no build step.** Hugo fingerprints this file and serves it
// from our own domain, which is the only place the site loads anything from.
(function () {
"use strict";
if (document.cookie.indexOf("vl_sesion=1") === -1) {
return;
}
function el(tag, className, text) {
var node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function draw(state) {
var bar = el("div", "member-bar");
bar.setAttribute("role", "navigation");
bar.setAttribute("aria-label", "Área de miembros");
var inner = el("div", "member-bar__inner");
var links = el("ul", "member-bar__links");
state.sections.forEach(function (section) {
var item = document.createElement("li");
var link = el("a", null, section.label);
link.href = section.url;
item.appendChild(link);
links.appendChild(item);
});
inner.appendChild(links);
var account = el("div", "member-bar__account");
var me = el("a", "member-bar__name", state.name);
me.href = state.profile;
account.appendChild(me);
// A real form, because signing out changes something and a link that
// changes something is a link a prefetching browser will follow by itself.
var form = document.createElement("form");
form.method = "post";
form.action = state.logout;
var token = document.createElement("input");
token.type = "hidden";
token.name = "csrf_token";
token.value = state.csrf;
form.appendChild(token);
var out = el("button", "member-bar__out", "Salir");
out.type = "submit";
form.appendChild(out);
account.appendChild(form);
inner.appendChild(account);
bar.appendChild(inner);
document.body.insertBefore(bar, document.body.firstChild);
document.body.classList.add("has-member-bar");
}
fetch("/comunidad/sesion.json", { credentials: "same-origin" })
.then(function (response) {
return response.ok ? response.json() : null;
})
.then(function (state) {
if (state && state.signed_in) draw(state);
})
.catch(function () {
// The members area being down is not a reason for the public site to
// report anything. No bar, no message, no console noise.
});
})();

View File

@ -11,6 +11,11 @@
{{ range .AlternativeOutputFormats -}}
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">
{{ end -}}
{{/* The members' bar, drawn in the browser because these pages are files on
disk and get cached. It makes no request at all unless the reader has a
session — see the comment at the top of the file. */}}
{{ $bar := resources.Get "js/memberbar.js" | minify | fingerprint }}
<script src="{{ $bar.RelPermalink }}" integrity="{{ $bar.Data.Integrity }}" defer></script>
</head>
<body>

View File

@ -48,6 +48,25 @@
{{ .Content }}
</div>
{{/* Questions and answers, written in the editor as one
`pregunta|respuesta` per line. Rendered here as well as in the
FAQPage schema: structured data describing something a visitor
cannot see is exactly what search engines penalise. */}}
{{ with .Params.faq }}
<section class="faq">
<h2>Preguntas frecuentes</h2>
<dl>
{{ range . }}
{{ $parts := split . "|" }}
{{ if ge (len $parts) 2 }}
<dt>{{ trim (index $parts 0) " " }}</dt>
<dd>{{ trim (delimit (after 1 $parts) "|") " " }}</dd>
{{ end }}
{{ end }}
</dl>
</section>
{{ end }}
<a class="back-link" href="{{ .Site.Home.Permalink }}">
← Volver al inicio
</a>

View File

@ -6,6 +6,11 @@ Site home: {{ .Site.Home.Permalink }}
This site publishes in Spanish. Every article has server-rendered German (/de/) and Brazilian Portuguese (/pt-br/) translations, linked via hreflang.
## About this site
{{ range where .Site.RegularPages "Section" "page" -}}
- [{{ .Title }}]({{ .Permalink }}): {{ .Description | default (.Summary | plainify | truncate 200) }}
{{ end }}
## Recent articles
{{ range first 50 (where .Site.RegularPages "Section" "post") -}}

View File

@ -0,0 +1,34 @@
{{/* BreadcrumbList — where this page sits, for a search result and for an answer
engine deciding what a page is about.
Two levels for a page (Inicio → this), three for an article (Inicio → its
category → this). Nothing is rendered visibly: the site is shallow enough
that a visible trail would be clutter, while the machine-readable one still
answers "what is this page part of".
A subpage says Inicio → its parent → itself, read from the same `parent`
basename the menu is built from, so the trail and the menu cannot disagree. */}}
{{ $items := slice (dict "@type" "ListItem" "position" 1 "name" "Inicio" "item" .Site.Home.Permalink) }}
{{ $position := 2 }}
{{ if eq .Section "post" }}
{{ range first 1 (.GetTerms "categories") }}
{{ $items = $items | append (dict "@type" "ListItem" "position" $position "name" .LinkTitle "item" .Permalink) }}
{{ $position = add $position 1 }}
{{ end }}
{{ else }}
{{ with .Params.parent }}
{{ $base := . }}
{{ range where $.Site.RegularPages "Section" "page" }}
{{ with .File }}{{ if eq .ContentBaseName $base }}
{{ $items = $items | append (dict "@type" "ListItem" "position" $position "name" $.Page.Title "item" $.Permalink) }}
{{ end }}{{ end }}
{{ end }}
{{ end }}
{{ end }}
{{ $items = $items | append (dict "@type" "ListItem" "position" $position "name" .Title "item" .Permalink) }}
<script type="application/ld+json">{{ (dict
"@context" "https://schema.org"
"@type" "BreadcrumbList"
"itemListElement" $items) | jsonify (dict "indent" " ") | safeJS }}</script>

View File

@ -0,0 +1,29 @@
{{/* FAQPage — the single highest-value thing a community page can carry for an
answer engine, because a question with a short factual answer is exactly the
shape those engines quote.
Written in the editor as one `pregunta|respuesta` per line, the same shape
the profile links field uses, and parsed here: a line without a separator is
dropped rather than half-rendered. The questions are also shown on the page
by single.html — schema describing something a visitor cannot see is the
kind of thing search engines penalise, and rightly. */}}
{{ $entries := slice }}
{{ range .Params.faq }}
{{ $parts := split . "|" }}
{{ if ge (len $parts) 2 }}
{{ $question := trim (index $parts 0) " " }}
{{ $answer := trim (delimit (after 1 $parts) "|") " " }}
{{ if and $question $answer }}
{{ $entries = $entries | append (dict
"@type" "Question"
"name" $question
"acceptedAnswer" (dict "@type" "Answer" "text" $answer)) }}
{{ end }}
{{ end }}
{{ end }}
{{ with $entries }}
<script type="application/ld+json">{{ (dict
"@context" "https://schema.org"
"@type" "FAQPage"
"mainEntity" .) | jsonify (dict "indent" " ") | safeJS }}</script>
{{ end }}

View File

@ -12,10 +12,72 @@
</nav>
</div>
{{/* The menu is built from the pages themselves, not from a list in
config.yaml. It used to be three names written there, which meant a page
published from the members area never appeared on the site at all — and
that the German and Portuguese menus had to be kept in step by hand.
Built this way, a new page shows up when it is published, with its own
translated title in each language.
Two levels: a page with `parent: <basename>` in its frontmatter hangs
under the page with that basename. The basename is the one translate.py
already uses to pair siblings — `acerca` for acerca.es.md, acerca.de.md
and acerca.pt-br.md — so a parent set once holds in all three languages.
Only Inicio and Comunidad stay in config.yaml, before and after the
pages, which is what the weight split below is reading. */}}
{{ $current := . }}
{{/* A dict per page rather than sorting the pages directly: `weight` is
optional, and sorting on a key half of them do not carry puts the rest
in an order nobody chose. Defaulted here, once. */}}
{{ $pages := slice }}
{{ range where .Site.RegularPages "Section" "page" }}
{{ $base := "" }}
{{ with .File }}{{ $base = .ContentBaseName }}{{ end }}
{{ $pages = $pages | append (dict
"title" .LinkTitle
"url" .RelPermalink
"page" .
"base" $base
"parent" (.Params.parent | default "")
"w" (.Params.weight | default 50)) }}
{{ end }}
{{ $pages = sort $pages "w" }}
<nav class="site-bar__pages" id="site-bar-pages" aria-label="Secciones">
<ul class="page-nav">
{{ $current := . }}
{{ range .Site.Menus.main }}
{{ range where .Site.Menus.main "Weight" "<" 5 }}
<li{{ if $current.IsMenuCurrent "main" . }} class="current-menu-item"{{ end }}>
<a href="{{ .URL }}">{{ .Name }}</a>
</li>
{{ end }}
{{ range where $pages "parent" "" }}
{{ $children := where $pages "parent" .base }}
{{/* The class names are the ones main.css already styles — ported
from the WordPress theme, dropdown on hover and on focus-within,
inline on a phone, with a ▾ on anything that has children. There
was no reason to invent a second set. */}}
{{ $classes := slice }}
{{ if $children }}{{ $classes = $classes | append "menu-item-has-children" }}{{ end }}
{{ if eq $current.RelPermalink .url }}{{ $classes = $classes | append "current-menu-item" }}{{ end }}
<li{{ with $classes }} class="{{ delimit . " " }}"{{ end }}>
<a href="{{ .url }}">{{ .title }}</a>
{{ with $children }}
{{/* Opens on hover and on focus — CSS only, so it works with a
keyboard and needs no script. */}}
<ul class="sub-menu">
{{ range . }}
<li{{ if eq $current.RelPermalink .url }} class="current-menu-item"{{ end }}>
<a href="{{ .url }}">{{ .title }}</a>
</li>
{{ end }}
</ul>
{{ end }}
</li>
{{ end }}
{{ range where .Site.Menus.main "Weight" ">=" 5 }}
<li{{ if $current.IsMenuCurrent "main" . }} class="current-menu-item"{{ end }}>
<a href="{{ .URL }}">{{ .Name }}</a>
</li>

View File

@ -5,6 +5,20 @@
{{ $locale := index $localeMap .Language.Lang | default "es_ES" }}
{{ $desc := "" }}
{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = .Site.Params.description }}{{ end }}
{{/* One line, always. A summary pulled out of the body arrives with the line
breaks the prose had, and a newline inside og:description is a card that
renders raggedly in some readers and truncated in others. */}}
{{ $desc = trim ($desc | plainify | replaceRE "\\s+" " ") " " }}
{{/* The picture a share card shows. A page's own image when it has one, the
site default when it does not — `params.defaultImage` is empty until the
logo arrives, and a card with no picture is what happens meanwhile, which is
also what happens today. Absolute, because WhatsApp, Signal, Mastodon and
Bluesky all fetch it from outside and a relative path means nothing to
them. */}}
{{ $image := "" }}
{{ with .Params.image }}{{ $image = . | absURL }}
{{ else }}{{ with .Site.Params.defaultImage }}{{ $image = . | absURL }}{{ end }}{{ end }}
<meta name="description" content="{{ $desc }}">
@ -29,11 +43,19 @@
{{ range .Translations }}
{{ with index $localeMap .Language.Lang }}<meta property="og:locale:alternate" content="{{ . }}">{{ end }}
{{ end }}
{{ with .Params.image }}<meta property="og:image" content="{{ . | absURL }}">{{ end }}
{{ with $image }}
<meta property="og:image" content="{{ . }}">
<meta property="og:image:alt" content="{{ $.Params.image_alt | default $.Title }}">
{{ end }}
<meta property="article:published_time" content="{{ .Date.Format "2006-01-02T15:04:05-07:00" }}">
<meta property="article:modified_time" content="{{ .Lastmod.Format "2006-01-02T15:04:05-07:00" }}">
{{ with .Params.author }}<meta property="article:author" content="{{ . }}">{{ end }}
{{ range first 1 (.GetTerms "categories") }}<meta property="article:section" content="{{ .LinkTitle }}">{{ end }}
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:card" content="{{ if $image }}summary_large_image{{ else }}summary{{ end }}">
<meta name="twitter:title" content="{{ .Title }}">
<meta name="twitter:description" content="{{ $desc }}">
{{ with $image }}<meta name="twitter:image" content="{{ . }}">{{ end }}
{{ $schema := dict
"@context" "https://schema.org"
@ -46,10 +68,23 @@
"dateModified" (.Lastmod.Format "2006-01-02T15:04:05-07:00")
"author" (dict "@type" "Person" "name" (.Params.author | default .Site.Title))
"publisher" (dict "@type" "Organization" "name" .Site.Title "url" .Site.Home.Permalink)
"mainEntityOfPage" (dict "@type" "WebPage" "@id" .Permalink)
}}
{{ with .Params.image }}{{ $schema = merge $schema (dict "image" (. | absURL)) }}{{ end }}
{{/* The author's own page, when they have published one. An answer engine
citing this article can then say who wrote it and point somewhere real —
which is the whole reason the byline carries a URL. */}}
{{ with .Params.author_url }}
{{ $schema = merge $schema (dict "author" (dict
"@type" "Person"
"name" ($.Params.author | default $.Site.Title)
"url" (. | absURL))) }}
{{ end }}
{{ with $image }}{{ $schema = merge $schema (dict "image" .) }}{{ end }}
<script type="application/ld+json">{{ $schema | jsonify (dict "indent" " ") | safeJS }}</script>
{{ partial "breadcrumbs-schema.html" . }}
{{ partial "faq-schema.html" . }}
{{ else if .IsHome }}
{{/* ---- Home ---- */}}
<meta property="og:type" content="website">
@ -59,6 +94,18 @@
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:locale" content="{{ $locale }}">
{{ $org := dict
"@context" "https://schema.org"
"@type" "Organization"
"name" .Site.Title
"url" .Site.Home.Permalink
"description" .Site.Params.description
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
}}
{{ with .Site.Params.defaultImage }}{{ $org = merge $org (dict "logo" (. | absURL)) }}{{ end }}
{{ with .Site.Params.sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }}
<script type="application/ld+json">{{ $org | jsonify (dict "indent" " ") | safeJS }}</script>
{{ $posts := first 10 (where .Site.RegularPages "Section" "post") }}
{{ $blogPost := slice }}
{{ range $posts }}
@ -82,4 +129,46 @@
}}
{{ if $blogPost }}{{ $schema = merge $schema (dict "blogPost" $blogPost) }}{{ end }}
<script type="application/ld+json">{{ $schema | jsonify (dict "indent" " ") | safeJS }}</script>
{{ else if .IsPage }}
{{/* ---- A static page: Acerca de, Contacto, their subpages ----
This branch did not exist, so a page shared as a bare link — no title card,
no picture, nothing for an answer engine to read beyond the prose. It is a
document about the organisation rather than an article, hence WebPage
rather than BlogPosting, and no author: a page is the site speaking. */}}
<meta property="og:type" content="website">
<meta property="og:site_name" content="{{ .Site.Title }}">
<meta property="og:title" content="{{ .Title }}">
<meta property="og:description" content="{{ $desc }}">
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:locale" content="{{ $locale }}">
{{ range .Translations }}
{{ with index $localeMap .Language.Lang }}<meta property="og:locale:alternate" content="{{ . }}">{{ end }}
{{ end }}
{{ with $image }}
<meta property="og:image" content="{{ . }}">
<meta property="og:image:alt" content="{{ $.Params.image_alt | default $.Title }}">
{{ end }}
<meta name="twitter:card" content="{{ if $image }}summary_large_image{{ else }}summary{{ end }}">
<meta name="twitter:title" content="{{ .Title }}">
<meta name="twitter:description" content="{{ $desc }}">
{{ with $image }}<meta name="twitter:image" content="{{ . }}">{{ end }}
{{ $schema := dict
"@context" "https://schema.org"
"@type" "WebPage"
"inLanguage" .Site.Language.LanguageCode
"name" .Title
"description" $desc
"url" .Permalink
"dateModified" (.Lastmod.Format "2006-01-02T15:04:05-07:00")
"isPartOf" (dict "@type" "WebSite" "name" .Site.Title "url" .Site.Home.Permalink)
"publisher" (dict "@type" "Organization" "name" .Site.Title "url" .Site.Home.Permalink)
}}
{{ with $image }}{{ $schema = merge $schema (dict "image" .) }}{{ end }}
<script type="application/ld+json">{{ $schema | jsonify (dict "indent" " ") | safeJS }}</script>
{{ partial "breadcrumbs-schema.html" . }}
{{ partial "faq-schema.html" . }}
{{ end }}