From c84a996eef9bb6e8e50c1cab8d6ca9063a35c759 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 15:21:35 +0000 Subject: [PATCH] The bar, the share card, the writing box and subpages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **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//, 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 Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn --- apps/board/app.py | 7 +- apps/board/auth.py | 37 ++++- apps/board/content.py | 91 ++++++++++- apps/board/home.py | 78 ++++++++- apps/board/static/board.css | 57 +++++++ apps/board/static/board.js | 149 ++++++++++++++++++ apps/board/templates/comment_form.html | 2 +- apps/board/templates/content_form.html | 51 +++++- apps/board/templates/conversation.html | 2 +- apps/board/templates/profile_edit.html | 2 +- apps/board/templates/submission_form.html | 2 +- apps/board/templates/thread.html | 2 +- apps/board/templates/thread_form.html | 2 +- apps/board/tests/test_board.py | 37 +++++ apps/board/tests/test_content.py | 83 ++++++++++ apps/board/tests/test_navigation.py | 65 ++++++++ apps/board/tests/test_templates.py | 34 ++++ config.yaml | 47 +++--- docs/server-setup.md | 80 ++++++++++ scripts/translate.py | 25 ++- themes/vienalatina/assets/css/main.css | 101 ++++++++++++ themes/vienalatina/assets/js/memberbar.js | 87 ++++++++++ .../vienalatina/layouts/_default/baseof.html | 5 + .../vienalatina/layouts/_default/single.html | 19 +++ themes/vienalatina/layouts/index.llms.txt | 5 + .../layouts/partials/breadcrumbs-schema.html | 34 ++++ .../layouts/partials/faq-schema.html | 29 ++++ .../vienalatina/layouts/partials/header.html | 66 +++++++- .../layouts/partials/seo-head.html | 95 ++++++++++- 29 files changed, 1254 insertions(+), 40 deletions(-) create mode 100644 themes/vienalatina/assets/js/memberbar.js create mode 100644 themes/vienalatina/layouts/partials/breadcrumbs-schema.html create mode 100644 themes/vienalatina/layouts/partials/faq-schema.html diff --git a/apps/board/app.py b/apps/board/app.py index 15224f5..07c719a 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -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 diff --git a/apps/board/auth.py b/apps/board/auth.py index 7f9c489..d5bf348 100644 --- a/apps/board/auth.py +++ b/apps/board/auth.py @@ -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"))) diff --git a/apps/board/content.py b/apps/board/content.py index 3835c8c..3680b54 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -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 diff --git a/apps/board/home.py b/apps/board/home.py index 29446e3..40f149f 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -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(): diff --git a/apps/board/static/board.css b/apps/board/static/board.css index c2f6123..e5b25f1 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -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; +} diff --git a/apps/board/static/board.js b/apps/board/static/board.js index 07a6290..a69b6ad 100644 --- a/apps/board/static/board.js +++ b/apps/board/static/board.js @@ -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); + } + }); + }); +})(); diff --git a/apps/board/templates/comment_form.html b/apps/board/templates/comment_form.html index f40c9a7..3aebf46 100644 --- a/apps/board/templates/comment_form.html +++ b/apps/board/templates/comment_form.html @@ -7,7 +7,7 @@

Editar respuesta

- +
diff --git a/apps/board/templates/content_form.html b/apps/board/templates/content_form.html index 92ee012..53ec107 100644 --- a/apps/board/templates/content_form.html +++ b/apps/board/templates/content_form.html @@ -37,6 +37,34 @@ {% 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. #} + + {% set names = parents | map(attribute='base') | list %} + + + + +

Menor número, más a la izquierda. 50 si da igual.

+ {% endif %} + {% if collection == 'post' %}
Categorías @@ -51,6 +79,11 @@ +

+ 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. +

{% if f.image %} @@ -58,12 +91,28 @@ {% endif %} + + + +

+ Qué se ve en la foto, en una frase. Lo lee quien no puede ver la imagen y + lo leen también los buscadores. +

{% endif %} - + + +

+ Una por línea, con el formato pregunta|respuesta. + 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. +

+
- diff --git a/apps/board/templates/thread.html b/apps/board/templates/thread.html index cca3578..0a18f17 100644 --- a/apps/board/templates/thread.html +++ b/apps/board/templates/thread.html @@ -81,7 +81,7 @@ action="{{ url_for('board.comment', thread_id=thread.id) }}"> - diff --git a/apps/board/templates/thread_form.html b/apps/board/templates/thread_form.html index 0f4ee8e..b67f749 100644 --- a/apps/board/templates/thread_form.html +++ b/apps/board/templates/thread_form.html @@ -12,7 +12,7 @@ value="{{ thread.title if thread else '' }}"> - {# Only when writing, not when editing: the edit route does not read files, diff --git a/apps/board/tests/test_board.py b/apps/board/tests/test_board.py index 02b47bd..9083695 100644 --- a/apps/board/tests/test_board.py +++ b/apps/board/tests/test_board.py @@ -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"] == "

hola y adiós

\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": ""}).get_json()["html"] + + assert " diff --git a/themes/vienalatina/layouts/_default/single.html b/themes/vienalatina/layouts/_default/single.html index e4ea2d3..896f008 100644 --- a/themes/vienalatina/layouts/_default/single.html +++ b/themes/vienalatina/layouts/_default/single.html @@ -48,6 +48,25 @@ {{ .Content }}
+ {{/* 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 }} +
+

Preguntas frecuentes

+
+ {{ range . }} + {{ $parts := split . "|" }} + {{ if ge (len $parts) 2 }} +
{{ trim (index $parts 0) " " }}
+
{{ trim (delimit (after 1 $parts) "|") " " }}
+ {{ end }} + {{ end }} +
+
+ {{ end }} + ← Volver al inicio diff --git a/themes/vienalatina/layouts/index.llms.txt b/themes/vienalatina/layouts/index.llms.txt index 6caeec3..bc82ef3 100644 --- a/themes/vienalatina/layouts/index.llms.txt +++ b/themes/vienalatina/layouts/index.llms.txt @@ -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") -}} diff --git a/themes/vienalatina/layouts/partials/breadcrumbs-schema.html b/themes/vienalatina/layouts/partials/breadcrumbs-schema.html new file mode 100644 index 0000000..bb3fe83 --- /dev/null +++ b/themes/vienalatina/layouts/partials/breadcrumbs-schema.html @@ -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) }} + diff --git a/themes/vienalatina/layouts/partials/faq-schema.html b/themes/vienalatina/layouts/partials/faq-schema.html new file mode 100644 index 0000000..0f81d9d --- /dev/null +++ b/themes/vienalatina/layouts/partials/faq-schema.html @@ -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 }} + +{{ end }} diff --git a/themes/vienalatina/layouts/partials/header.html b/themes/vienalatina/layouts/partials/header.html index d46496f..435cf03 100644 --- a/themes/vienalatina/layouts/partials/header.html +++ b/themes/vienalatina/layouts/partials/header.html @@ -12,10 +12,72 @@ + {{/* 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: ` 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" }} +