Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina

This commit is contained in:
admin 2026-10-06 20:33:07 +00:00
commit aaf3e9e3fe
37 changed files with 1648 additions and 143 deletions

View File

@ -14,6 +14,7 @@ from flask import Flask, render_template, request
from werkzeug.middleware.proxy_fix import ProxyFix
from .db import TOMBSTONE_LOGIN, close_db, init_db
from .render import to_html
from .security import check_csrf, csrf_token, is_at_least
URL_PREFIX = "/comunidad"
@ -132,6 +133,10 @@ def create_app(overrides: dict | None = None) -> Flask:
# from the superadministrator's own navigation — the exact failure
# `is_at_least` was introduced to end on the Python side.
app.jinja_env.globals["is_at_least"] = is_at_least
# For the writing boxes: each form renders the stored markdown into a
# <template> that the editor adopts, so the browser never has to parse
# markdown and cannot disagree with the server about what text means.
app.jinja_env.globals["to_html"] = to_html
@app.context_processor
def _year():

View File

@ -204,8 +204,10 @@ def new_thread():
title, body = cleaned
cursor = get_db().execute(
"INSERT INTO threads (author_id, title, body_md) VALUES (?, ?, ?)",
(g.member["id"], title, body),
"""INSERT INTO threads (author_id, title, body_md, ai_generated)
VALUES (?, ?, ?, ?)""",
(g.member["id"], title, body,
1 if request.form.get("ai_generated") == "on" else 0),
)
uploads.save(staged, g.member["id"], thread_id=cursor.lastrowid)
return redirect(url_for("board.thread", thread_id=cursor.lastrowid))
@ -225,8 +227,11 @@ def edit_thread(thread_id: int):
return redirect(url_for("board.edit_thread", thread_id=thread_id))
title, body = cleaned
get_db().execute(
"UPDATE threads SET title = ?, body_md = ?, edited_at = datetime('now') WHERE id = ?",
(title, body, thread_id),
"""UPDATE threads SET title = ?, body_md = ?, ai_generated = ?,
edited_at = datetime('now')
WHERE id = ?""",
(title, body, 1 if request.form.get("ai_generated") == "on" else 0,
thread_id),
)
return redirect(url_for("board.thread", thread_id=thread_id))

View File

@ -159,6 +159,11 @@ def frontmatter_for(collection: str, form: dict) -> dict:
fields["author"] = form["author"]
if form.get("author_url"):
fields["author_url"] = form["author_url"]
# Only when true, for both collections: a line reading `ai_generated: false`
# on every post ever written is noise in the repository and a question in
# the mind of anybody reading the file.
if form.get("ai_generated"):
fields["ai_generated"] = True
return fields
@ -173,13 +178,15 @@ def _cache_read(path: str, sha: str):
def _cache_write(path: str, sha: str, fm: dict) -> None:
get_db().execute(
"""INSERT INTO content_cache (path, sha, title, date, generated, image,
event_date, event_time, event_location)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
event_date, event_time, event_location,
ai_generated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(path) DO UPDATE SET
sha = excluded.sha, title = excluded.title, date = excluded.date,
generated = excluded.generated, image = excluded.image,
event_date = excluded.event_date, event_time = excluded.event_time,
event_location = excluded.event_location,
ai_generated = excluded.ai_generated,
updated_at = datetime('now')""",
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
1 if fm.get("translated_from") else 0,
@ -192,7 +199,8 @@ def _cache_write(path: str, sha: str, fm: dict) -> None:
# internal ones and would otherwise read every post's frontmatter on
# every page view to find out when they are.
str(fm.get("event_date", "") or ""), str(fm.get("event_time", "") or ""),
str(fm.get("event_location", "") or "")),
str(fm.get("event_location", "") or ""),
1 if fm.get("ai_generated") else 0),
)
@ -220,6 +228,7 @@ def listing(collection: str) -> list[dict]:
"name": name, "path": path, "sha": sha,
"title": row["title"] or name,
"date": row["date"],
"ai_generated": bool(row["ai_generated"]),
"event_date": row["event_date"] or "",
"event_time": row["event_time"] or "",
"event_location": row["event_location"] or "",
@ -320,6 +329,10 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
"description": request.form.get("description", "").strip(),
"image": image,
"manual_translation": request.form.get("manual_translation") == "on",
# Said by whoever is publishing, about this post. It travels in the
# frontmatter rather than in a database, because the file in the
# repository is the record of what was published.
"ai_generated": request.form.get("ai_generated") == "on",
"author": author, "author_url": author_url,
"parent": parent, "weight": weight,
"faq": faq, "image_alt": image_alt,
@ -551,6 +564,11 @@ def edit(collection: str, name: str):
"description": fm.get("description", ""),
"image": fm.get("image", ""),
"manual_translation": bool(fm.get("manual_translation")),
# Loaded so the switch comes back the way it was left. A flag read
# into the form but not written back out again is a flag that one
# correction quietly removes — which is the whole failure the
# byline below was given its comment for.
"ai_generated": bool(fm.get("ai_generated")),
# Carried through the form untouched. Correcting a typo in somebody
# else's post must not re-sign it with the name of whoever is
# fixing it — the same rule the board has about editing other
@ -631,7 +649,7 @@ def preview(collection: str):
today=date_type.today().isoformat(),
parents=possible_parents(collection,
item["name"] if item else ""),
preview_html=to_html(body))
preview_html=to_html(body, breaks=False))
def public_events() -> list[dict]:

View File

@ -338,6 +338,32 @@ def _room_for_identity_and_a_typeface(db: sqlite3.Connection) -> None:
db.execute(f"ALTER TABLE {table} ADD COLUMN {column} TEXT")
def _room_to_say_a_machine_wrote_it(db: sqlite3.Connection) -> None:
"""One flag per place a post can live, so the disclosure survives the trip.
Plain ADD COLUMNs again. A public post carries the flag in its own
frontmatter — the file in the repository is the record, not this database —
and `content_cache.ai_generated` is only the copy that lets the editor's
list show it without re-reading every file from the git server.
`submissions.ai_generated` is the one that has to exist rather than be
derived: a proposal is a draft in SQLite for as long as it is in the queue,
and the flag has to survive moderation to reach the frontmatter of the post
it becomes.
"""
for table, columns in (("threads", ("ai_generated",)),
("submissions", ("ai_generated",)),
("content_cache", ("ai_generated",))):
existing = _columns(db, table)
if not existing:
continue
for column in columns:
if column not in existing:
db.execute(
f"ALTER TABLE {table} ADD COLUMN {column} "
"INTEGER NOT NULL DEFAULT 0")
# (number, description, function). The number is the value written to
# user_version once the step succeeds.
STEPS = [
@ -350,6 +376,7 @@ STEPS = [
(7, "a superadministrator above the responsable", _a_superadmin_above_the_owner),
(8, "room for the identity, a typeface and the media library",
_room_for_identity_and_a_typeface),
(9, "a post can say a machine wrote it", _room_to_say_a_machine_wrote_it),
]

View File

@ -20,16 +20,36 @@ from __future__ import annotations
from markdown_it import MarkdownIt
from markupsafe import Markup
_md = (
MarkdownIt("commonmark", {"html": False, "linkify": True, "breaks": True})
def _renderer(breaks: bool) -> MarkdownIt:
return (
MarkdownIt("commonmark", {"html": False, "linkify": True, "breaks": breaks})
.enable("linkify")
.enable("table")
.enable("strikethrough")
)
)
def to_html(text: str) -> Markup:
return Markup(_md.render(text or ""))
# Two of them, because a line break means two different things depending on
# where the text is going.
#
# On the wall, in a private message, in a calendar entry — text this app both
# stores and renders — people write the way they write to each other, and a
# newline they typed is a newline they meant. `breaks=True`.
#
# A public post is a file in the repository rendered by Hugo, whose Goldmark
# has hardWraps off; and the files are hard-wrapped at about 78 characters,
# by the pipeline and by anything that has ever edited them. Rendering those
# with breaks on puts a line break in the middle of every sentence, so the
# editor would show something the site will never produce. `breaks=False`
# there, and a break somebody actually wants is written the way CommonMark
# writes one — two spaces at the end of the line — which both renderers honour.
_md = _renderer(True)
_md_site = _renderer(False)
def to_html(text: str, breaks: bool = True) -> Markup:
"""Markdown as HTML. `breaks=False` for anything bound for the public site."""
return Markup((_md if breaks else _md_site).render(text or ""))
def excerpt(text: str, limit: int = 220) -> str:

View File

@ -54,6 +54,10 @@ CREATE TABLE IF NOT EXISTS threads (
edited_at TEXT,
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)),
locked INTEGER NOT NULL DEFAULT 0 CHECK (locked IN (0, 1)),
-- Said out loud where the post is read. The association's own words and a
-- machine's are both welcome here; which is which is not the reader's job
-- to guess.
ai_generated INTEGER NOT NULL DEFAULT 0 CHECK (ai_generated IN (0, 1)),
-- Soft delete: a moderator's mistake stays recoverable, and removing one
-- comment does not tear a hole in the conversation around it.
deleted_at TEXT
@ -202,6 +206,10 @@ CREATE TABLE IF NOT EXISTS content_cache (
-- draft. Recorded here so the listing can skip them without re-reading
-- every file to find out what it already knew.
generated INTEGER NOT NULL DEFAULT 0 CHECK (generated IN (0, 1)),
-- A copy of the post's own frontmatter flag, so the editor's list can show
-- it without re-reading every file from the git server. The file is the
-- record; this is the cache.
ai_generated INTEGER NOT NULL DEFAULT 0 CHECK (ai_generated IN (0, 1)),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
@ -260,6 +268,10 @@ CREATE TABLE IF NOT EXISTS submissions (
event_time TEXT,
event_location TEXT,
photo_name TEXT,
-- Carried through moderation into the published post's frontmatter: a
-- proposal is a draft in this database until it is approved, so the flag
-- has nowhere else to wait.
ai_generated INTEGER NOT NULL DEFAULT 0 CHECK (ai_generated IN (0, 1)),
state TEXT NOT NULL DEFAULT 'pending'
CHECK (state IN ('pending', 'approved', 'rejected')),
-- Why it was rejected, in the moderator's words, shown to the author. A

View File

@ -170,6 +170,22 @@ button, input, select, textarea { font: inherit; }
.prose { line-height: 1.65; }
.prose :first-child { margin-top: 0; }
.prose :last-child { margin-bottom: 0; }
/* The post's own title is the h1 on the page, so a body starts at h2. The
ladder is deliberately wide: at 1.35 / 1.12 / 0.98 of the body size, with
the third one carried by weight and colour rather than by size, three
levels are still three levels on a phone. */
.prose h2, .rich h2 { margin: 1.6rem 0 0.6rem; font-size: 1.35rem; line-height: 1.25; }
.prose h3, .rich h3 { margin: 1.3rem 0 0.5rem; font-size: 1.12rem; line-height: 1.3; }
.prose h4, .rich h4 {
margin: 1.1rem 0 0.4rem;
font-size: 0.98rem;
letter-spacing: 0.02em;
text-transform: uppercase;
color: var(--muted);
}
.prose h2 + h3, .rich h2 + h3 { margin-top: 0.8rem; }
.prose ol, .prose ul, .rich ol, .rich ul { padding-left: 1.3rem; }
.prose hr, .rich hr { border: 0; border-top: 1px solid var(--border-light); margin: 1.6rem 0; }
.prose img { max-width: 100%; height: auto; border-radius: var(--radius-md); }
.prose pre {
background: var(--surface-soft);
@ -309,9 +325,35 @@ textarea { resize: vertical; line-height: 1.55; }
word-break: break-all;
}
/* A table on a phone becomes one card per row.
*
* It used to be `display: block; overflow-x: auto`, which is a sideways scroll
* inside the page: on Contenido, four columns at 390px put «Editar» and
* «Eliminar» off the right edge with nothing on screen saying they were there,
* and the timestamp column of the Registro broke across three lines. Stacking
* keeps every cell reachable and costs the markup nothing — the same table
* serves both widths.
*
* The columns that do not describe themselves (a bare date, a bare event date)
* carry a `data-label` in the template, drawn here by `attr()`. The ones that
* do — a title, a name, a sentence — are left alone, because a label on every
* line is a form, not a list. */
@media (max-width: 640px) {
.feed-head { flex-direction: column; align-items: flex-start; }
.table { display: block; overflow-x: auto; }
.table, .table tbody, .table tr, .table td { display: block; width: auto; }
.table thead { display: none; }
.table tr { padding: 0.85rem 1rem; border-bottom: 1px solid var(--border-light); }
.table tr:last-child { border-bottom: 0; }
.table td { padding: 0.15rem 0; border: 0; }
/* An empty cell would otherwise be a blank line in the middle of the card —
an article with no event date, a row with no actions. */
.table td:empty { display: none; }
.table td[data-label]::before {
content: attr(data-label) " ";
color: var(--muted);
font-size: 0.8rem;
}
}
/* --- editor ----------------------------------------------------------- */
@ -638,17 +680,26 @@ input[type="file"] {
.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);
/* The writing surface itself, which is also the finished text: it carries
.prose as well, so what is being written is drawn by the same rules as what
is published. Sized like the textarea it replaces — a box you can see a
paragraph in — and it grows as the writing does. */
.rich {
min-height: 11rem;
padding: 0.65rem 0.8rem;
border: 1px solid var(--border);
border-radius: var(--radius-md);
background: var(--surface-soft);
line-height: 1.6;
background: var(--surface);
line-height: 1.65;
overflow-wrap: break-word;
}
.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); }
.rich:focus { outline: 2px solid var(--brand-soft); outline-offset: 1px; border-color: var(--brand); }
.rich :first-child { margin-top: 0; }
.rich :last-child { margin-bottom: 0; }
.rich img { max-width: 100%; border-radius: var(--radius-sm); }
/* Marked when a required box was submitted empty — the browser cannot report
that against a field it has been told to hide. */
.rich--empty { border-color: var(--danger); }
/* What you just chose, before it is uploaded. */
.file-strip {
@ -709,6 +760,12 @@ input[type="file"] {
.cal__pad { background: transparent; border-color: transparent; }
.cal__day--today { border-color: var(--brand); background: var(--brand-softer); }
.cal__number { color: var(--subtle); font-weight: 700; }
/* The column header carries the weekday at this width, so saying it again in
every one of thirty-one cells would be noise. The phone block below, where
there is no header row, is the only place it shows. */
.cal__weekday { display: none; }
.cal__events { display: block; }
.cal__empty { margin: -0.5rem 0 1rem; text-align: center; }
.cal__event {
display: block;
@ -735,15 +792,44 @@ input[type="file"] {
.event-facts p { margin: 0 0 0.25rem; }
/* Seven columns of nothing is what a month grid is on a phone. */
/* Seven columns of nothing is what a month grid is on a phone, so the month
* becomes a column of days — every day, in order, with its weekday beside it.
*
* Every rule here that decides `display` names the cell's own class, and that
* is the point rather than a style preference. The version that shipped opened
* with `.cal td { display: block }` — specificity (0,1,1) — which outranked
* `.cal__pad { display: none }` at (0,1,0), so the padding cells stayed on
* screen as 92px empty boxes; while `.cal__day:not(:has(.cal__event))` at
* (0,2,0) won, so every real day disappeared. A month with no events drew four
* blank boxes and nothing else, which is exactly what a phone showed. The two
* rules were adjacent and had opposite outcomes, which is why reading them
* looked right. */
@media (max-width: 640px) {
.cal, .cal tbody, .cal tr, .cal td { display: block; width: auto; }
.cal, .cal tbody, .cal tr { display: block; width: auto; }
.cal thead { display: none; }
.cal__pad { display: none; }
.cal__day { height: auto; margin-bottom: 0.4rem; }
.cal__day:not(:has(.cal__event)) { display: none; }
.cal__number { display: inline-block; margin-right: 0.5rem; }
.cal__add { display: inline; }
.cal td.cal__pad { display: none; }
.cal td.cal__day {
display: flex;
align-items: baseline;
gap: 0.6rem;
height: auto;
min-height: 44px;
margin-bottom: 0.3rem;
}
/* A week still reads as a week. */
.cal tr + tr { margin-top: 0.5rem; }
/* Fixed, so the dates line up down the page rather than stepping in and
out as the weekday names change length. */
.cal__date { flex: 0 0 4.2rem; }
/* `display` and not only the colour: the base rule hides this, because up
there the column header says the weekday. Leaving it out left every row
reading as a bare number — the same shape of mistake as the pads, caught
the same way, by looking at the rendered page. */
.cal__weekday { display: inline; color: var(--subtle); }
.cal__events { flex: 1; min-width: 0; }
/* No hover on a phone, so the + is simply there; `float` would take it out
of the flex row it is now part of. */
.cal__add { display: inline-flex; float: none; }
}
/* --- Gestión → Marca ---------------------------------------------------- */
@ -879,3 +965,96 @@ input[type="file"] {
.tag--ok { background: #e4f2e4; color: #1b5e20; }
.tag--warn { background: var(--brand-soft); color: var(--brand-dark); }
.tag--bad { background: #f6dcdc; color: var(--danger); }
/* --- a thumb is not a mouse --------------------------------------------- */
/*
* A coarse pointer is a touchscreen, not a narrow window — so this is keyed on
* the pointer rather than on width, and a phone held in landscape gets it too.
*
* Everything in here is padding. No type size, colour or spacing changes, so
* the desktop is untouched and the pages look identical; only the hit boxes
* grow. The numbers come from measuring the rendered pages at 390px: the
* navigation links were 37x17, the calendar's + was 7x15, and «Editar»,
* «Eliminar» and «Vista previa» were 16px tall.
*
* `.linkish` is deliberately not raised everywhere: it is used mid-sentence in
* several places, where a 44px line box overlaps the lines above and below it.
* It is raised where it is a control rather than a word — which covers every
* one of the measured cases.
*/
@media (pointer: coarse) {
.page-nav { gap: 0.1rem 1.5rem; }
/* Every number here was measured rather than guessed: the padding is
whatever that control's own line box needs to reach 44px, which is the
part of a fingertip a phone can actually locate. 0.7rem on the
navigation came out at 40, so it is 0.85rem. */
.page-nav a { display: inline-block; padding: 0.85rem 0; }
.account__menu a, .account__menu button { padding: 0.8rem 0.5rem; }
.actions .linkish,
.feed-head .linkish,
.cal-bar .linkish,
.cal-bar__today a,
.pager a {
display: inline-block;
padding: 0.9rem 0;
}
.tab { padding: 0.9rem 1.1rem; }
.md-bar__button { min-height: 44px; min-width: 44px; }
.reaction__button { padding: 0.65rem 0.9rem; }
/* The buttons and the two links that live in the chrome: the brand at the
top left, which is how you get back to the public site, and the footer's
own link to it. Both were a line of text with no padding at all. */
.btn { padding-top: 0.85rem; padding-bottom: 0.85rem; }
.site-bar__brand { display: inline-block; padding: 0.7rem 0; }
.site-foot a { display: inline-block; padding: 0.9rem 0; }
/* Every fold in the members area — Gestionar on a member, Bloquear, the
typeface warning, Avanzado on Marca. A <summary> is the control, and at
15px it is a control you miss and then press something else. */
summary { padding: 0.95rem 0; }
.account__name { padding: 0.9rem 0; }
/* The disclosure switch: 16px of words and a 13px box before this. The
checkbox itself grows too — a label you can hit around a box you
cannot is a control that looks broken when it misses. */
.switch { padding: 0.7rem 0; }
.switch input { width: 20px; height: 20px; }
.cal__add {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 44px;
min-height: 44px;
}
}
/* --- said out loud: a machine wrote this -------------------------------- */
/*
* A pill beside the date, the same shape as the PÚBLICO tag in the calendar.
* Quiet, but above the text rather than under it: a disclosure nobody meets
* until after they have read the thing is not a disclosure.
*/
.tag--ai {
background: var(--surface-soft);
color: var(--muted);
border: 1px solid var(--border-light);
}
/* The switch in the form's action row. A checkbox and its words on one line,
beside the button that publishes — visible at the moment of publishing,
which is when it is answered, and costing one line rather than a fieldset. */
.switch {
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-size: 0.9rem;
color: var(--muted);
cursor: pointer;
}
.switch input { margin: 0; }
.switch:has(input:checked) { color: var(--brand-dark); font-weight: 600; }

View File

@ -16,104 +16,357 @@ document.addEventListener("submit", function (event) {
// --- 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.
// The box shows the formatting as it is typed: bold is bold, a heading is a
// heading. There is no preview pane — a second box beside the first is the
// wrong shape on a phone — and nothing is sent anywhere while anybody writes.
//
// 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.
// What is stored is still markdown, which is what keeps everything downstream
// as it is: the file committed to git, the pipeline that translates it, Decap,
// and above all `render.to_html` with raw HTML disabled, which is the whole of
// the XSS defence. The server receives markdown and renders it itself; nothing
// the browser sends is ever treated as HTML.
//
// The two directions are deliberately not symmetrical:
//
// opening something to edit — the *server* renders the stored markdown into
// a <template> beside the box and the editor adopts it, so there is no
// markdown parser in the browser and no second opinion about what
// somebody's text means;
// saving — the browser walks a closed set of elements back into markdown
// (`serialize` below). Anything it does not recognise contributes its text
// and nothing else, which is why a paste from Word brings no markup in.
//
// With JavaScript off, or if any of this throws, the plain <textarea> is still
// there and still the field that submits: nothing here is hidden by CSS.
(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 }
];
// --- markdown out of the document ---------------------------------------
function apply(box, tool) {
var start = box.selectionStart;
var end = box.selectionEnd;
var selected = box.value.slice(start, end);
var replacement;
var BLOCKS = { H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1, P: 1, DIV: 1,
UL: 1, OL: 1, BLOCKQUOTE: 1, PRE: 1, HR: 1, TABLE: 1 };
// H1 becomes ## on purpose: the page's heading is the post's title, and a
// pasted h1 should not compete with it.
var HEADING = { H1: "## ", H2: "## ", H3: "### ", H4: "#### ",
H5: "#### ", H6: "#### " };
// A line that opens with something markdown reads as a marker is escaped, or
// «- 20 € por persona» comes back as a bullet the next time it is opened.
var MARKER = /^(\s*)(#{1,6}|>|[-+*]|\d{1,9}[.)])(\s)/;
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;
function escapeText(text) {
return text.replace(/\s+/g, " ").replace(/([\\`*_[\]])/g, "\\$1");
}
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 }));
// Only schemes that cannot execute. markdown-it refuses `javascript:` on its
// own, so this is the second of two locks rather than the only one.
function safeHref(href) {
return /^(https?:|mailto:|\/|#)/i.test(href || "") ? href : "";
}
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);
// «** bold **» is not bold in CommonMark, and a selection almost always
// carries a space at one end.
function wrapped(marker, inner) {
var lead = inner.match(/^\s*/)[0];
var tail = inner.match(/\s*$/)[0];
var core = inner.slice(lead.length, inner.length - tail.length);
return core ? lead + marker + core + marker + tail : inner;
}
// Elements whose text is not writing. Nothing here can execute — the server
// renders markdown with raw HTML disabled — but a stylesheet pasted into the
// box should not come back as four hundred words of prose either.
var DROP = { SCRIPT: 1, STYLE: 1, TEMPLATE: 1, NOSCRIPT: 1, IFRAME: 1, OBJECT: 1, HEAD: 1 };
function inlineOne(node) {
if (node.nodeType === 3) { return escapeText(node.nodeValue); }
if (node.nodeType !== 1) { return ""; }
var tag = node.tagName;
if (DROP[tag]) { return ""; }
// Two spaces then a newline: the break CommonMark means wherever it is
// rendered. A bare newline is a break in the members area and a space on
// the public site, which would make the same post read differently in the
// two places.
if (tag === "BR") { return " \n"; }
if (tag === "CODE") { return "`" + node.textContent + "`"; }
if (tag === "IMG") { return escapeText(node.getAttribute("alt") || ""); }
var inner = inline(node);
if (!inner.trim()) { return inner; }
if (tag === "STRONG" || tag === "B") { return wrapped("**", inner); }
if (tag === "EM" || tag === "I") { return wrapped("_", inner); }
if (tag === "S" || tag === "DEL" || tag === "STRIKE") { return wrapped("~~", inner); }
if (tag === "A") {
var href = safeHref(node.getAttribute("href"));
return href ? "[" + inner.trim() + "](" + href + ")" : inner;
}
return inner; // span, font, and whatever else a paste left behind
}
function inline(node) {
var out = "";
Array.prototype.forEach.call(node.childNodes, function (child) {
out += inlineOne(child);
});
return out;
}
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;
function paragraph(text, indent) {
// Trimmed at the two ends only. Stripping trailing spaces line by line —
// which is the tidy-looking thing to do — would eat the two spaces that
// *are* the hard break a <br> turns into.
var body = text.replace(/^\s+|\s+$/g, "");
if (!body.trim()) { return ""; }
return body.split("\n").map(function (line) {
return indent + line.replace(MARKER, function (whole, space, token, after) {
return /^\d/.test(token)
? space + token.slice(0, -1) + "\\" + token.slice(-1) + after
: space + "\\" + token + after;
});
}).join("\n");
}
preview.addEventListener("click", function () {
if (!panel.hidden) {
panel.hidden = true;
function list(el, indent) {
var ordered = el.tagName === "OL";
var number = 1;
var lines = [];
Array.prototype.forEach.call(el.children, function (item) {
if (item.tagName !== "LI") { return; }
var marker = ordered ? (number++) + ". " : "- ";
var head = "";
var nested = [];
Array.prototype.forEach.call(item.childNodes, function (child) {
if (child.nodeType === 1 && (child.tagName === "UL" || child.tagName === "OL")) {
nested.push(list(child, indent + " "));
} else {
head += inlineOne(child);
}
});
head = head.replace(/\s+/g, " ").trim();
if (head || nested.length) { lines.push(indent + marker + head); }
nested.forEach(function (block) { if (block) { lines.push(block); } });
});
return lines.join("\n");
}
function blockFor(el, indent) {
var tag = el.tagName;
if (HEADING[tag]) {
var title = inline(el).replace(/\s+/g, " ").trim();
return title ? indent + HEADING[tag] + title : "";
}
if (tag === "UL" || tag === "OL") { return list(el, indent); }
if (tag === "BLOCKQUOTE") {
return serialize(el, indent).split("\n").map(function (line) {
return line ? "> " + line : ">";
}).join("\n");
}
if (tag === "PRE") { return indent + "```\n" + el.textContent + "\n```"; }
if (tag === "HR") { return indent + "---"; }
// A pasted table keeps its words and loses its grid. Writing one is what
// the markdown view is for; silently dropping the text would not be.
if (tag === "TABLE") { return paragraph(escapeText(el.textContent), indent); }
// A <div> holding blocks is a container, not a paragraph — which is what
// a contenteditable produces constantly: pressing Enter on a list wrapped
// it in one, and reading it as a paragraph ran «uno» and «dos» together
// into a single word.
if (Array.prototype.some.call(el.children, function (child) { return BLOCKS[child.tagName]; })) {
return serialize(el, indent);
}
return paragraph(inline(el), indent);
}
function serialize(root, indent) {
indent = indent || "";
var blocks = [];
var loose = [];
function flush() {
if (!loose.length) { return; }
var text = loose.map(inlineOne).join("");
var para = paragraph(text, indent);
if (para) { blocks.push(para); }
loose = [];
}
Array.prototype.forEach.call(root.childNodes, function (node) {
if (node.nodeType === 1 && DROP[node.tagName]) {
return;
}
var token = box.form && box.form.querySelector("input[name=csrf_token]");
if (node.nodeType === 1 && BLOCKS[node.tagName]) {
flush();
var out = blockFor(node, indent);
if (out.trim()) { blocks.push(out); }
} else {
loose.push(node); // text sitting straight in the box
}
});
flush();
return blocks.join("\n\n");
}
// Exposed for the test suite, which runs this file in node and compares the
// markdown it produces against a table of documents. A browser never reads
// this line.
if (typeof module !== "undefined" && module.exports) {
module.exports = { serialize: serialize };
}
// --- the toolbar ---------------------------------------------------------
var TOOLS = {
h2: { label: "T1", title: "Título", block: "<h2>" },
h3: { label: "T2", title: "Subtítulo", block: "<h3>" },
h4: { label: "T3", title: "Apartado", block: "<h4>" },
bold: { label: "N", title: "Negrita", cmd: "bold" },
italic: { label: "I", title: "Cursiva", cmd: "italic" },
strike: { label: "S", title: "Tachado", cmd: "strikeThrough" },
ul: { label: "•", title: "Lista", cmd: "insertUnorderedList" },
ol: { label: "1.", title: "Lista numerada", cmd: "insertOrderedList" },
quote: { label: "“”", title: "Cita", block: "<blockquote>" },
link: { label: "🔗", title: "Enlace", link: true },
clear: { label: "✕", title: "Quitar formato", clear: true }
};
var SETS = {
full: ["h2", "h3", "h4", "bold", "italic", "strike", "ul", "ol", "quote", "link", "clear"],
basic: ["bold", "italic", "link", "clear"]
};
function button(label, title, onClick, extra) {
var element = document.createElement("button");
element.type = "button"; // never a submit inside a form
element.className = "md-bar__button" + (extra ? " " + extra : "");
element.title = title;
element.textContent = label;
element.addEventListener("click", onClick);
return element;
}
function enrich(box) {
var set = SETS[box.getAttribute("data-rich") || "basic"] || SETS.basic;
var form = box.form;
var surface = document.createElement("div");
var bar = document.createElement("div");
var seed = box.id && document.querySelector('template[data-rich-html="' + box.id + '"]');
surface.className = "rich prose";
surface.contentEditable = "true";
surface.setAttribute("role", "textbox");
surface.setAttribute("aria-multiline", "true");
if (box.id) { surface.id = box.id + "-rich"; }
// A <label for> does not reach a contenteditable, so the label is wired by
// hand and the surface says what it is to a screen reader.
var label = box.id && document.querySelector('label[for="' + box.id + '"]');
if (label) {
if (!label.id) { label.id = box.id + "-label"; }
surface.setAttribute("aria-labelledby", label.id);
label.addEventListener("click", function () { surface.focus(); });
}
if (seed && seed.innerHTML.trim()) {
surface.innerHTML = seed.innerHTML;
} else if (box.value.trim()) {
// No markdown parser here: this is the fallback for a box whose template
// is missing, and plain text is the one reading that cannot be wrong.
box.value.split(/\n{2,}/).forEach(function (chunk) {
var p = document.createElement("p");
p.textContent = chunk;
surface.appendChild(p);
});
}
if (!surface.firstChild) { surface.appendChild(document.createElement("p")); }
function sync() {
try { box.value = serialize(surface); } catch (error) { /* last good value stands */ }
}
function run(tool) {
surface.focus();
if (tool.link) {
var url = window.prompt("Dirección del enlace", "https://");
if (!url || !safeHref(url)) { return; }
document.execCommand("createLink", false, url);
} else if (tool.block) {
document.execCommand("formatBlock", false, tool.block);
} else if (tool.clear) {
document.execCommand("removeFormat", false, null);
document.execCommand("formatBlock", false, "<p>");
} else {
document.execCommand(tool.cmd, false, null);
}
sync();
}
bar.className = "md-bar";
set.forEach(function (name) {
var tool = TOOLS[name];
bar.appendChild(button(tool.label, tool.title, function () { run(tool); }));
});
// The escape hatch. It is how anybody writes a table, or anything else the
// buttons do not offer, and it is the way out if this editor ever mangles
// something. Going back renders through the server, for the same reason
// opening does: there is no markdown parser here.
var raw = false;
var swap = button("Markdown", "Escribir en markdown", function () {
if (!raw) {
sync();
surface.hidden = true;
box.hidden = false;
box.focus();
raw = true;
swap.textContent = "Con formato";
return;
}
var token = form && 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.";
// Rendered by the same function the site renders with, raw HTML
// disabled, so what comes back carries no markup of anybody else's.
if (result) { surface.innerHTML = result.html; }
surface.hidden = false;
box.hidden = true;
raw = false;
swap.textContent = "Markdown";
}).catch(function () {
panel.textContent = "No se pudo generar la vista previa.";
// Stay in markdown rather than lose what is in the box.
});
}, "md-bar__button--wide");
bar.appendChild(swap);
var required = box.required;
box.required = false; // a hidden required field refuses to submit and
box.hidden = true; // reports it on an element nobody can see
box.parentNode.insertBefore(bar, box);
box.parentNode.insertBefore(surface, box);
surface.addEventListener("input", sync);
surface.addEventListener("blur", sync);
// A paste arrives as text: no stylesheet, no script, no forty nested spans,
// and what lands looks like what was typed.
surface.addEventListener("paste", function (event) {
event.preventDefault();
var text = (event.clipboardData || window.clipboardData).getData("text/plain");
document.execCommand("insertText", false, text);
});
bar.appendChild(preview);
box.parentNode.insertBefore(bar, box);
box.parentNode.insertBefore(panel, box.nextSibling);
if (form) {
form.addEventListener("submit", function (event) {
sync();
if (required && !box.value.trim()) {
event.preventDefault();
surface.focus();
surface.classList.add("rich--empty");
}
});
}
}
// --- thumbnails of what was just chosen ---------------------------------
@ -176,8 +429,12 @@ document.addEventListener("submit", function (event) {
}
document.addEventListener("DOMContentLoaded", function () {
// Tags rather than inline styles: <b>, not <span style="font-weight:700">,
// which the serializer would have to guess at. Harmless where the whole
// command set is unsupported, since nothing below runs then either.
try { document.execCommand("styleWithCSS", false, false); } catch (error) { /* older engines */ }
Array.prototype.forEach.call(
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
document.querySelectorAll("textarea[data-markdown]"), enrich);
brandPreview();
document.addEventListener("change", function (event) {

View File

@ -97,6 +97,11 @@ def _read_proposal() -> tuple[dict, list[str]]:
"title": request.form.get("title", "").strip()[:TITLE_MAX],
"body": request.form.get("body", "").strip()[:BODY_MAX],
"description": request.form.get("description", "").strip()[:300],
# Said by the member about their own text, and carried through the queue
# unchanged. A moderator can see it and can refuse the proposal; what
# they cannot do is quietly publish it without the line, which is the
# only way this disclosure is worth anything.
"ai_generated": request.form.get("ai_generated") == "on",
# The same three fields the editor asks for, read by the same function:
# a member's event and a moderator's have to produce the same post.
**content.read_event_fields(request.form, errors),
@ -176,11 +181,12 @@ def propose():
get_db().execute(
"""INSERT INTO submissions
(author_id, title, body_md, description, photo_name,
event_date, event_time, event_location)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
event_date, event_time, event_location, ai_generated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(g.member["id"], fields["title"], fields["body"], fields["description"],
photo_name,
fields["event_date"], fields["event_time"], fields["event_location"]),
fields["event_date"], fields["event_time"], fields["event_location"],
1 if fields["ai_generated"] else 0),
)
flash("Enviado. Un moderador lo leerá antes de publicarlo.", "ok")
return redirect(url_for("submissions.index"))
@ -242,13 +248,15 @@ def edit(submission_id: int):
"""UPDATE submissions
SET title = ?, body_md = ?, description = ?,
photo_name = ?, event_date = ?, event_time = ?,
event_location = ?, state = 'pending', note = NULL,
event_location = ?, ai_generated = ?,
state = 'pending', note = NULL,
reviewed_by = NULL, reviewed_at = NULL,
updated_at = datetime('now')
WHERE id = ?""",
(fields["title"], fields["body"], fields["description"],
photo_name, fields["event_date"],
fields["event_time"], fields["event_location"], submission_id),
fields["event_time"], fields["event_location"],
1 if fields["ai_generated"] else 0, submission_id),
)
# Back to pending on every edit, including one made after a rejection: a
# rejected post that has been rewritten is waiting again, and leaving it
@ -322,6 +330,10 @@ def approve(submission_id: int):
"event_date": row["event_date"] or "",
"event_time": row["event_time"] or "",
"event_location": row["event_location"] or "",
# The one field here the author set about their own writing. It has to
# survive the queue or the disclosure is lost at the exact moment the
# text stops being private.
"ai_generated": bool(row["ai_generated"]),
}
# Read the picture before the try, and catch only the error that means what
# it says. The first version wrapped everything in `except OSError`, which

View File

@ -25,6 +25,13 @@
<a href="{{ url_for('events.month', mes=this_month) }}">Ir a este mes</a>
</p>
{# Said above the grid rather than below it: on a phone the month is a column
of days, and a line under thirty-one empty rows is a line nobody reads. The
public agenda says the same thing in its own words (agenda.html). #}
{% if not by_day %}
<p class="muted cal__empty">No hay nada en {{ label }}.</p>
{% endif %}
<table class="cal">
<thead>
<tr>{% for day in weekdays %}<th scope="col">{{ day }}</th>{% endfor %}</tr>
@ -39,7 +46,18 @@
<td class="cal__pad"></td>
{% else %}
<td class="cal__day {{ 'cal__day--today' if day == today }}">
{# The weekday travels with the number because on a phone the
header row is hidden — the grid is a column there, and a day
without its weekday is just an integer. `loop.index0` of this
loop *is* the weekday, since each week is seven cells
starting on Monday, so nothing has to be computed in Python.
Above 640px .cal__weekday is display:none and the column
header says it instead. #}
<span class="cal__date">
<span class="cal__weekday">{{ weekdays[loop.index0] }}</span>
<span class="cal__number">{{ day }}</span>
</span>
<span class="cal__events">
{% for item in by_day.get(day, []) %}
<a class="cal__event {{ 'cal__event--public' if item.public }}"
href="{{ item.url }}">
@ -47,6 +65,7 @@
{% if item.public %}<span class="tag tag--quiet">público</span>{% endif %}
</a>
{% endfor %}
</span>
{% if may_edit %}
{# The day is carried into the form, so adding something to the
24th starts with the 24th already filled in. #}

View File

@ -8,6 +8,11 @@
<label for="body">Mensaje</label>
<textarea id="body" data-markdown name="body" rows="10" required>{{ comment.body_md }}</textarea>
{#- The stored markdown, rendered by the server for the editor to adopt.
There is no markdown parser in the browser: this is how the box can
show the formatting without a second opinion about what somebody's
text means. Ignored entirely when scripting is off. -#}
<template data-rich-html="body">{{ to_html(comment.body_md) }}</template>
<div class="actions">
<button class="btn" type="submit">Guardar</button>

View File

@ -114,8 +114,13 @@
{% endif %}
<label for="body">Cuerpo</label>
<textarea id="body" data-markdown name="body" rows="18" required
<textarea id="body" data-markdown data-rich="full" name="body" rows="18" required
placeholder="Markdown: **negrita**, ## títulos, listas, [enlaces](https://…).">{{ body }}</textarea>
{#- The stored markdown, rendered by the server for the editor to adopt.
There is no markdown parser in the browser: this is how the box can
show the formatting without a second opinion about what somebody's
text means. Ignored entirely when scripting is off. -#}
<template data-rich-html="body">{{ to_html(body, breaks=False) }}</template>
<label for="faq">Preguntas frecuentes <span class="muted small">(opcional)</span></label>
<textarea id="faq" name="faq" rows="5"
@ -133,6 +138,14 @@
<div class="actions">
<button class="btn" type="submit">{{ 'Guardar' if item else 'Publicar' }}</button>
{#- Beside the button that publishes, because that is the moment it is
answered. One line rather than a fieldset: it has to be seen, not
to take up the form. -#}
<label class="switch">
<input type="checkbox" name="ai_generated" {{ 'checked' if f.ai_generated }}>
Contenido generado con IA
</label>
<button class="linkish" type="submit"
formaction="{{ url_for('content.preview', collection=collection) }}">
Vista previa

View File

@ -29,12 +29,15 @@
<td>
<a href="{{ url_for('content.edit', collection=collection, name=item.name) }}">{{ item.title }}</a>
<div class="muted small mono">{{ item.name }}</div>
{% if item.ai_generated %}<span class="tag tag--ai" title="Quien lo publicó marcó este texto como generado con inteligencia artificial.">Generado con IA</span>{% endif %}
</td>
{% if meta.dated %}<td>{{ item.date }}</td>{% endif %}
{# data-label is drawn by board.css under 640px, where the header row
is hidden and a bare date in a stacked card says nothing. #}
{% if meta.dated %}<td data-label="Fecha">{{ item.date }}</td>{% endif %}
{# The column that used to hold the categories. An event date is the
one thing left that changes what a post is, and it is what a
moderator scanning this list is looking for. #}
{% if meta.dated %}<td>{{ item.event_date }}</td>{% endif %}
{% if meta.dated %}<td data-label="Evento">{{ item.event_date }}</td>{% endif %}
{# The flex row goes INSIDE the cell, never on it. `.actions` is
display:flex, and a <td> told to be a flex container stops being a
table cell: it leaves the row's layout and draws its bottom border

View File

@ -33,8 +33,13 @@
<input id="location" name="location" maxlength="200" value="{{ (f.location if f else '') or '' }}">
<label for="body">Detalles <span class="muted small">(opcional)</span></label>
<textarea id="body" name="body" rows="8" data-markdown
<textarea id="body" name="body" rows="8" data-markdown data-rich="full"
placeholder="Qué llevar, cómo llegar, a quién avisar.">{{ (f.body_md if event and not fields else (f.body if f else '')) or '' }}</textarea>
{#- The stored markdown, rendered by the server for the editor to adopt.
There is no markdown parser in the browser: this is how the box can
show the formatting without a second opinion about what somebody's
text means. Ignored entirely when scripting is off. -#}
<template data-rich-html="body">{{ to_html((f.body_md if event and not fields else (f.body if f else '')) or '') }}</template>
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>
<input id="picture" name="picture" type="file" accept="image/*">

View File

@ -21,6 +21,11 @@
<label for="bio">Sobre ti</label>
<textarea id="bio" data-markdown name="bio" rows="8"
placeholder="Se puede usar Markdown.">{{ g.member.bio or '' }}</textarea>
{#- The stored markdown, rendered by the server for the editor to adopt.
There is no markdown parser in the browser: this is how the box can
show the formatting without a second opinion about what somebody's
text means. Ignored entirely when scripting is off. -#}
<template data-rich-html="bio">{{ to_html(g.member.bio or '') }}</template>
<label for="links">Enlaces</label>
<textarea id="links" name="links" rows="5"

View File

@ -13,6 +13,9 @@
<span class="tag tag--{{ item.state }}">{{ labels[item.state] }}</span>
<span>{{ person(item.author, item.author_login) }}</span> · <time>{{ item.created_at }}</time>
{% if item.event_date %} · <span>Evento el {{ item.event_date }}</span>{% endif %}
{#- Shown to the moderator before they decide: a disclosure the reviewer
cannot see is one they cannot weigh. -#}
{% if item.ai_generated %}<span class="tag tag--ai" title="Quien lo publicó marcó este texto como generado con inteligencia artificial.">Generado con IA</span>{% endif %}
</div>
{% if item.description %}<p class="muted">{{ item.description }}</p>{% endif %}
{% if item.photo_name %}

View File

@ -48,8 +48,13 @@
</fieldset>
<label for="body">Texto</label>
<textarea id="body" data-markdown name="body" rows="16" required
<textarea id="body" data-markdown data-rich="full" name="body" rows="16" required
placeholder="Se puede usar Markdown: **negrita**, ## títulos, listas, enlaces.">{{ fields.body if fields else '' }}</textarea>
{#- The stored markdown, rendered by the server for the editor to adopt.
There is no markdown parser in the browser: this is how the box can
show the formatting without a second opinion about what somebody's
text means. Ignored entirely when scripting is off. -#}
<template data-rich-html="body">{{ to_html(fields.body if fields else '', breaks=False) }}</template>
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>
<input id="picture" name="picture" type="file" accept="image/*">
@ -61,6 +66,14 @@
<div class="actions">
<button class="btn" type="submit">{{ 'Guardar' if item else 'Enviar a revisión' }}</button>
{#- Beside the button that publishes, because that is the moment it is
answered. One line rather than a fieldset: it has to be seen, not
to take up the form. -#}
<label class="switch">
<input type="checkbox" name="ai_generated" {{ 'checked' if (fields.ai_generated if fields else False) }}>
Contenido generado con IA
</label>
<a class="linkish" href="{{ url_for('submissions.index') }}">Cancelar</a>
</div>
</form>

View File

@ -9,6 +9,7 @@
<div class="card__meta">
{% if thread.pinned %}<span class="tag">Fijado</span>{% endif %}
{% if thread.locked %}<span class="tag tag--quiet">Cerrado</span>{% endif %}
{% if thread.ai_generated %}<span class="tag tag--ai" title="Quien lo publicó marcó este texto como generado con inteligencia artificial.">Generado con IA</span>{% endif %}
<span>{{ person(author.display_name, author.gitea_login) }}</span> · <time>{{ thread.created_at }}</time>
{% if thread.edited_at %}<span class="muted small">(editado)</span>{% endif %}
</div>

View File

@ -12,8 +12,13 @@
value="{{ thread.title if thread else '' }}">
<label for="body">Mensaje</label>
<textarea id="body" data-markdown name="body" rows="14" required
<textarea id="body" data-markdown data-rich="full" name="body" rows="14" required
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces.">{{ thread.body_md if thread else '' }}</textarea>
{#- The stored markdown, rendered by the server for the editor to adopt.
There is no markdown parser in the browser: this is how the box can
show the formatting without a second opinion about what somebody's
text means. Ignored entirely when scripting is off. -#}
<template data-rich-html="body">{{ to_html(thread.body_md if thread else '') }}</template>
{# Only when writing, not when editing: the edit route does not read files,
and an input that silently does nothing is worse than no input. Photos
@ -25,6 +30,14 @@
<div class="actions">
<button class="btn" type="submit">{{ 'Guardar' if thread else 'Publicar' }}</button>
{#- Beside the button that publishes, because that is the moment it is
answered. One line rather than a fieldset: it has to be seen, not
to take up the form. -#}
<label class="switch">
<input type="checkbox" name="ai_generated" {{ 'checked' if (thread.ai_generated if thread else False) }}>
Contenido generado con IA
</label>
<a class="linkish" href="{{ url_for('board.thread', thread_id=thread.id) if thread else url_for('board.threads') }}">Cancelar</a>
</div>
</form>

View File

@ -20,6 +20,7 @@
<div class="card__meta">
{% if t.pinned %}<span class="tag">Fijado</span>{% endif %}
{% if t.locked %}<span class="tag tag--quiet">Cerrado</span>{% endif %}
{% if t.ai_generated %}<span class="tag tag--ai" title="Quien lo publicó marcó este texto como generado con inteligencia artificial.">Generado con IA</span>{% endif %}
<span>{{ person(t.author, t.author_login) }}</span> · <time>{{ t.created_at }}</time>
</div>
<h2 class="card__title">

View File

@ -0,0 +1,46 @@
// Runs the editor's DOM → markdown serializer outside a browser, so the part
// of it that is pure logic can be tested by the same `pytest` run as the rest
// of the project rather than only by looking at a page.
//
// board.js expects a document to attach to and a DOM to walk. Both are stubbed
// here with the handful of members the serializer actually reads — nodeType,
// nodeValue, tagName, childNodes, children, getAttribute, textContent — built
// from the JSON tree the test sends in. A real DOM implementation would be a
// dependency; this is thirty lines and cannot drift, because the test fails the
// moment the serializer reaches for something it does not provide.
"use strict";
globalThis.document = { addEventListener: function () {} };
globalThis.window = {};
var path = require("path");
var board = require(path.join(__dirname, "..", "static", "board.js"));
function text(node) {
if (node.nodeType === 3) { return node.nodeValue; }
return node.childNodes.map(text).join("");
}
function build(spec) {
if (typeof spec === "string") { return { nodeType: 3, nodeValue: spec }; }
var node = {
nodeType: 1,
tagName: String(spec.tag).toUpperCase(),
attrs: spec.attrs || {},
childNodes: (spec.children || []).map(build)
};
node.children = node.childNodes.filter(function (child) { return child.nodeType === 1; });
node.getAttribute = function (name) {
return Object.prototype.hasOwnProperty.call(this.attrs, name) ? this.attrs[name] : null;
};
Object.defineProperty(node, "textContent", { get: function () { return text(this); } });
return node;
}
var input = "";
process.stdin.on("data", function (chunk) { input += chunk; });
process.stdin.on("end", function () {
var root = build({ tag: "div", children: JSON.parse(input) });
process.stdout.write(board.serialize(root));
});

View File

@ -145,3 +145,41 @@ 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"
# --- said out loud on the wall too ----------------------------------------
def test_a_thread_can_say_a_machine_wrote_it(client, post, make_member, sign_in):
"""The same disclosure inside the members area as on the public site. The
people here know each other, which makes it more useful rather than less:
nobody wants to answer a machine thinking they are answering a neighbour.
"""
sign_in(make_member("maria"))
post("/comunidad/nuevo", {"title": "Resumen de la reunión",
"body": "Lo que se decidió.", "ai_generated": "on"})
page = client.get("/comunidad/muro").get_data(as_text=True)
assert "Generado con IA" in page
assert "Generado con IA" in client.get("/comunidad/tema/1").get_data(as_text=True)
def test_an_ordinary_thread_says_nothing_of_the_kind(client, post, make_member, sign_in):
sign_in(make_member("maria"))
post("/comunidad/nuevo", {"title": "Resumen", "body": "Escrito a mano."})
assert "Generado con IA" not in client.get("/comunidad/muro").get_data(as_text=True)
def test_editing_a_thread_can_add_or_remove_the_disclosure(client, post, make_member, sign_in):
"""It is the author's statement about their own text, so it stays theirs
to change — and an edit that forgets the field must not silently keep a
mark the author has taken off."""
member = make_member("maria")
sign_in(member)
post("/comunidad/nuevo", {"title": "Resumen", "body": "Primera versión.",
"ai_generated": "on"})
post("/comunidad/tema/1/editar", {"title": "Resumen", "body": "Reescrito a mano."})
assert "Generado con IA" not in client.get("/comunidad/tema/1").get_data(as_text=True)
post("/comunidad/tema/1/editar", {"title": "Resumen", "body": "Otra vez con ayuda.",
"ai_generated": "on"})
assert "Generado con IA" in client.get("/comunidad/tema/1").get_data(as_text=True)

View File

@ -629,3 +629,72 @@ def test_an_event_keeps_its_date_when_edited(repo, editor, post, client):
front = yaml.safe_load(
repo.files["content/post/2026-10-03-feria.es.md"].decode().split("---")[1])
assert front["event_date"] == "2026-10-24"
# --- said out loud: a machine wrote this ----------------------------------
def test_a_post_marked_as_ai_says_so_in_its_own_frontmatter(repo, editor, post):
"""The file in the repository is the record of what was published, so the
disclosure travels with it rather than living in a database the public
site cannot read."""
publish(post, ai_generated="on")
path, = repo.files
fm, _ = translate.split_frontmatter(repo.files[path].decode())
assert fm["ai_generated"] is True
def test_an_ordinary_post_carries_no_such_line(repo, editor, post):
"""`ai_generated: false` on every post ever written is noise in the
repository and a question in the mind of whoever reads the file."""
publish(post)
path, = repo.files
fm, _ = translate.split_frontmatter(repo.files[path].decode())
assert "ai_generated" not in fm
def test_correcting_a_typo_does_not_quietly_remove_the_disclosure(
repo, editor, post, client):
"""The failure this is shaped around: a flag loaded into the form but not
written back out again survives exactly until somebody fixes a comma.
"""
publish(post, ai_generated="on")
path, = repo.files
name = path.rsplit("/", 1)[1]
form = client.get(f"/comunidad/contenido/post/editar/{name}").get_data(as_text=True)
assert 'name="ai_generated" checked' in form.replace(" ", " ")
post(f"/comunidad/contenido/post/editar/{name}",
{"title": "Sabores del barrio", "body": "Texto corregido.",
"date": "2026-09-25", "sha": repo._sha(repo.files[path]), "ai_generated": "on"})
fm, _ = translate.split_frontmatter(repo.files[path].decode())
assert fm["ai_generated"] is True
def test_the_disclosure_can_be_taken_off_again(repo, editor, post, client):
"""Somebody rewrites the text themselves. The switch is theirs to turn
off, and the line goes with it."""
publish(post, ai_generated="on")
path, = repo.files
name = path.rsplit("/", 1)[1]
post(f"/comunidad/contenido/post/editar/{name}",
{"title": "Sabores del barrio", "body": "Reescrito a mano.",
"date": "2026-09-25", "sha": repo._sha(repo.files[path])})
fm, _ = translate.split_frontmatter(repo.files[path].decode())
assert "ai_generated" not in fm
def test_the_disclosure_is_not_one_of_the_keys_translation_rewrites(repo, editor, post):
"""A translated post was still machine-written, so the flag has to reach
the German and Portuguese siblings untouched.
`translate_file` copies the whole frontmatter (`new_fm = dict(fm)`) and
rewrites only TRANSLATED_KEYS, so this needs no change to the pipeline —
asserted against the real list rather than assumed, because a key quietly
added to it would send the flag through a translation engine.
"""
publish(post, ai_generated="on")
path, = repo.files
fm, _ = translate.split_frontmatter(repo.files[path].decode())
assert fm["ai_generated"] is True
assert "ai_generated" not in translate.TRANSLATED_KEYS

View File

@ -0,0 +1,205 @@
"""The writing box: what comes back out of it.
The editor shows formatting as it is typed, but markdown is still the only
thing stored — so the one piece of new logic that can lose somebody's work is
the walk from the document back to markdown. It is a pure function, and this
runs it for real, in node, against the same `static/board.js` the browser
loads. No second implementation, no mock of the thing under test.
The last test is the one that matters most: markdown → HTML → markdown has to
mean the same thing at both ends, for every document a member can produce.
Exact string equality is the wrong assertion there (escaping is a choice, not a
meaning), so it compares what the two render to.
"""
from __future__ import annotations
import json
import shutil
import subprocess
from html.parser import HTMLParser
from pathlib import Path
import pytest
from apps.board.render import to_html
HARNESS = Path(__file__).resolve().parent / "serialize_harness.js"
NODE = shutil.which("node")
pytestmark = pytest.mark.skipif(
NODE is None,
reason="node is not installed here; the serializer is JavaScript")
def serialize(*nodes) -> str:
"""The markdown the editor would put in the textarea for these nodes."""
done = subprocess.run([NODE, str(HARNESS)], input=json.dumps(list(nodes)),
capture_output=True, text=True, timeout=30)
assert done.returncode == 0, done.stderr
return done.stdout
def tag(name, *children, **attrs):
return {"tag": name, "attrs": attrs, "children": list(children)}
class _Tree(HTMLParser):
"""HTML into the same shape `tag()` builds, for the round-trip test."""
VOID = {"br", "hr", "img", "input"}
def __init__(self):
super().__init__(convert_charrefs=True)
self.stack = [{"tag": "root", "attrs": {}, "children": []}]
def handle_starttag(self, name, attrs):
node = {"tag": name, "attrs": dict(attrs), "children": []}
self.stack[-1]["children"].append(node)
if name not in self.VOID:
self.stack.append(node)
def handle_endtag(self, name):
if len(self.stack) > 1 and self.stack[-1]["tag"] == name:
self.stack.pop()
def handle_data(self, data):
self.stack[-1]["children"].append(data)
def parse(html: str) -> list:
tree = _Tree()
tree.feed(html)
return tree.stack[0]["children"]
# --- one document at a time ------------------------------------------------
def test_a_paragraph_keeps_its_emphasis():
assert serialize(tag("p", "Hola ", tag("strong", "mundo"), ".")) == "Hola **mundo**."
def test_the_three_heading_levels():
assert serialize(tag("h2", "Título"), tag("h3", "Subtítulo"),
tag("h4", "Apartado")) == "## Título\n\n### Subtítulo\n\n#### Apartado"
def test_a_pasted_h1_does_not_compete_with_the_post_title():
"""The page's own heading is the title. Two h1s is the one hierarchy
mistake a screen reader cannot work around."""
assert serialize(tag("h1", "Pegado")) == "## Pegado"
def test_a_space_inside_the_markers_moves_outside_them():
"""«** negrita **» is not bold in CommonMark, and a double click almost
always takes the space after the word with it."""
assert serialize(tag("p", tag("strong", "negrita "), "y más")) == "**negrita** y más"
def test_a_line_break_is_a_commonmark_hard_break():
"""Two spaces then a newline, which is a break in the members area and on
the public site alike — a bare newline is a break in one and a space in
the other."""
assert serialize(tag("p", "uno", tag("br"), "dos")) == "uno \ndos"
def test_lists_keep_their_order_and_their_nesting():
assert serialize(tag("ul", tag("li", "uno"), tag("li", "dos"))) == "- uno\n- dos"
assert serialize(tag("ol", tag("li", "uno"), tag("li", "dos"))) == "1. uno\n2. dos"
nested = tag("ul", tag("li", "fuera", tag("ul", tag("li", "dentro"))))
assert serialize(nested) == "- fuera\n - dentro"
def test_a_quote_marks_every_line():
assert serialize(tag("blockquote", tag("p", "uno"), tag("p", "dos"))) == "> uno\n>\n> dos"
def test_a_link_keeps_its_address():
link = tag("a", "la agenda", href="https://vienalatina.com/page/agenda/")
assert serialize(tag("p", "Mira ", link)) == "Mira [la agenda](https://vienalatina.com/page/agenda/)"
def test_a_link_that_could_run_something_loses_its_address():
"""markdown-it refuses `javascript:` on its own. This is the second lock,
and it is here because the href is written by whatever the browser's
execCommand did with what somebody typed into a prompt."""
link = tag("a", "pulsa", href="javascript:alert(1)")
assert serialize(tag("p", link)) == "pulsa"
def test_a_line_that_looks_like_a_marker_is_escaped():
"""«- 20 € por persona» is a sentence, and it would come back as a bullet
the next time the post was opened."""
assert serialize(tag("p", "- 20 € por persona")) == "\\- 20 € por persona"
assert serialize(tag("p", "1. nunca más")) == "1\\. nunca más"
assert serialize(tag("p", "# no es un título")) == "\\# no es un título"
def test_what_a_paste_leaves_behind_contributes_its_words_and_nothing_else():
"""A paste arrives as plain text, so this should never happen — but an
engine's own execCommand leaves spans and fonts behind, and they must not
reach the file."""
span = tag("span", "texto", style="font-weight: 700; color: red")
assert serialize(tag("p", span)) == "texto"
def test_a_script_or_a_stylesheet_leaves_nothing():
assert serialize(tag("p", tag("script", "alert(1)"), "hola")) == "hola"
assert serialize(tag("style", "body { display: none }")) == ""
def test_an_empty_box_is_an_empty_string():
assert serialize(tag("p")) == ""
assert serialize(tag("p", tag("br"))) == ""
def test_a_div_around_blocks_is_a_container_and_not_a_paragraph():
"""What a contenteditable does constantly: pressing Enter inside a list
wrapped the whole list in a <div>, and reading that as a paragraph ran
«uno» and «dos» together into «unodos». Found by typing in a browser —
no fixture would have predicted the wrapper."""
wrapped = tag("div", tag("ul", tag("li", "uno"), tag("li", "dos")))
assert serialize(wrapped) == "- uno\n- dos"
mixed = tag("div", tag("h2", "Título"), tag("p", "Texto."))
assert serialize(mixed) == "## Título\n\nTexto."
def test_a_div_around_words_is_still_a_paragraph():
assert serialize(tag("div", "una línea")) == "una línea"
def test_a_table_keeps_its_words():
"""The buttons do not make tables; the markdown view does. A pasted one
loses its grid, which is a loss — losing the text would be worse."""
table = tag("table", tag("tr", tag("td", "uno"), tag("td", "dos")))
assert "uno" in serialize(table) and "dos" in serialize(table)
# --- and the whole way round -----------------------------------------------
DOCUMENTS = [
"Un párrafo corriente, sin nada dentro.",
"Con **negrita**, _cursiva_ y ~~tachado~~ en la misma línea.",
"## Un título\n\nY su párrafo.\n\n### Y un subtítulo\n\nCon más texto.",
"- uno\n- dos\n- tres",
"1. primero\n2. segundo",
"> Lo que alguien dijo.\n\nY la respuesta.",
"Mira [la agenda](https://vienalatina.com/page/agenda/) antes de venir.",
"Una línea \ny otra debajo.",
"Texto con un `trozo de código` dentro.",
"## Reunión\n\n- 20 € por persona\n- Traer el acta\n\n> Y puntuales.",
]
@pytest.mark.parametrize("document", DOCUMENTS, ids=range(len(DOCUMENTS)))
def test_markdown_survives_the_round_trip(document):
"""Open a post, change nothing, save it: it must still mean what it meant.
Rendered, serialized, rendered again — and the two renderings compared,
rather than the two markdown strings, because where a backslash goes is a
choice and what the reader sees is not.
"""
once = to_html(document)
back = serialize(*parse(once))
assert to_html(back) == once, f"{document!r} became {back!r}"

View File

@ -9,6 +9,7 @@ easy to get subtly wrong and hard to notice.
from __future__ import annotations
import re
from datetime import date
import pytest
@ -117,6 +118,52 @@ def test_february_in_a_leap_year_has_twenty_nine_days(client, superadmin_id, sig
assert ">30<" not in page
def test_a_month_with_nothing_in_it_says_so_and_still_draws_its_days(
client, superadmin_id, sign_in, quiet_gitea):
"""On a phone the month is a column of days rather than a grid, so an empty
month is thirty-one empty rows — which is how you see that it is empty. The
line above them says it in words, as the public agenda does.
The HTML has always been right here; what shipped was a stylesheet that hid
every day and kept the cells belonging to the neighbouring months, so the
page was six hundred pixels of nothing. The rule that catches that one is in
test_templates.py, where it can be seen.
"""
sign_in(superadmin_id)
page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True)
assert "No hay nada en diciembre 2026." in page
assert page.count('class="cal__day') == 31
def test_a_month_with_something_in_it_does_not_claim_to_be_empty(
client, an_event, superadmin_id, sign_in):
an_event("Asamblea", "2026-10-24")
sign_in(superadmin_id)
page = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
assert "No hay nada" not in page
assert "Asamblea" in page
def test_every_day_carries_its_weekday_for_the_phone(
client, superadmin_id, sign_in, quiet_gitea):
"""The column header is hidden at phone width, so without this a day is a
bare number in a list. It comes from the loop position rather than from a
date calculation, which is why this checks the pairing and not the markup:
an off-by-one would put Sunday's name on Monday's row."""
sign_in(superadmin_id)
page = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
assert page.count('class="cal__weekday"') == 31
# 1 October 2026 is a Thursday, and the grid starts on Monday.
assert re.search(r'cal__weekday">jue</span>\s*<span class="cal__number">1</span>',
page)
assert re.search(r'cal__weekday">dom</span>\s*<span class="cal__number">4</span>',
page)
# --- what the git server does to this ------------------------------------
def test_the_private_events_survive_a_git_server_that_is_down(

View File

@ -440,3 +440,50 @@ def test_a_second_superadmin_is_not_seeded_over_the_first(tmp_path):
assert db.execute(
"SELECT COUNT(*) FROM members WHERE gitea_login = 'intruso'").fetchone()[0] == 0
db.close()
def test_step_nine_gives_every_post_somewhere_to_say_a_machine_wrote_it(tmp_path):
"""Three plain ADD COLUMNs, and the rows around them untouched.
Built on the current schema and then wound back, like step six's test: the
question here is not whether an old database survives — steps 5 and 7 cover
that — but that a database with threads and proposals already in it gains
the flag without losing any of them.
"""
from apps.board.app import create_app
from apps.board.db import connect
path = str(tmp_path / "board.db")
create_app({"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "salvador",
"UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True})
db = connect(path)
member = db.execute("SELECT id FROM members WHERE role = 'superadmin'").fetchone()["id"]
db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, ?, ?)",
(member, "Un tema de antes", "Escrito antes de todo esto."))
db.execute("""INSERT INTO submissions (author_id, title, body_md, description)
VALUES (?, 'Una propuesta', 'Texto.', '')""", (member,))
db.execute("""INSERT INTO content_cache (path, sha, title, date)
VALUES ('content/post/2026-01-01-algo.es.md', 'abc', 'Algo', '2026-01-01')""")
# Wind the version back and drop the columns, as a server that has been
# running since before this phase has it.
for table in ("threads", "submissions", "content_cache"):
db.execute(f"ALTER TABLE {table} DROP COLUMN ai_generated")
db.execute("PRAGMA user_version = 8")
db.commit()
db.close()
create_app({"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "salvador",
"UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True})
db = connect(path)
for table in ("threads", "submissions", "content_cache"):
columns = {row[1] for row in db.execute(f"PRAGMA table_info({table})")}
assert "ai_generated" in columns, table
# Nothing written before the step is marked, and nothing is missing.
assert db.execute("SELECT title, ai_generated FROM threads").fetchone()[:] == (
"Un tema de antes", 0)
assert db.execute("SELECT count(*) FROM submissions").fetchone()[0] == 1
assert db.execute("PRAGMA user_version").fetchone()[0] == max(
number for number, _, _ in migrations.STEPS)
db.close()

View File

@ -501,3 +501,55 @@ def test_a_proposal_with_a_nonsense_event_date_is_refused(db, post, maria, sign_
assert response.status_code == 400
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
# --- the disclosure through the queue -------------------------------------
def test_a_members_disclosure_survives_moderation(repo, db, post, maria, luisa,
sign_in):
"""The member says it about their own writing; the moderator publishes it.
This is the only place the flag has to be carried by hand — a proposal is
a draft in SQLite until it is approved, so the frontmatter it ends up in
does not exist yet while the decision is being made. Losing it here would
lose it at the exact moment the text stops being private.
"""
import yaml
sign_in(maria)
propose(post, ai_generated="on")
submission_id = only_submission(db)["id"]
assert only_submission(db)["ai_generated"] == 1
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
path, = repo.files
front = yaml.safe_load(repo.files[path].decode("utf-8").split("---")[1])
assert front["ai_generated"] is True
def test_a_proposal_nobody_marked_publishes_without_the_line(repo, db, post,
maria, luisa, sign_in):
import yaml
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
path, = repo.files
front = yaml.safe_load(repo.files[path].decode("utf-8").split("---")[1])
assert "ai_generated" not in front
def test_the_moderator_can_see_what_they_are_approving(client, db, post, maria,
luisa, sign_in):
"""A disclosure the reviewer cannot see is one they cannot weigh."""
sign_in(maria)
propose(post, ai_generated="on")
submission_id = only_submission(db)["id"]
sign_in(luisa)
page = client.get(f"/comunidad/publicaciones/{submission_id}").get_data(as_text=True)
assert "IA" in page

View File

@ -211,8 +211,8 @@ def test_the_form_rule_is_an_exclusion_and_not_a_list_of_accepted_types():
# --- the theme's own chrome -----------------------------------------------
#
# These two read the Hugo theme rather than the members area, which no other
# test here does. They are here because the bug they guard against is this
# These read the Hugo theme rather than the members area, which no other test
# here does. They are here because the bug they guard against is this
# suite's recurring shape — CSS that expects markup nobody wrote — and because
# pytest is the only thing in this repository that runs on every commit.
@ -252,3 +252,139 @@ def test_the_way_into_the_members_area_is_in_the_bar_itself():
header = (THEME / "layouts" / "partials" / "header.html").read_text(encoding="utf-8")
bar = header.split('<nav class="site-bar__pages"')[0]
assert "site-bar__cta" in bar and "/comunidad/" in bar
# --- the calendar on a phone ----------------------------------------------
#
# A stylesheet guard, like the form rule above, and for the same reason: the
# bug it is about produced correct HTML and a blank page, so no request-level
# test in this suite could ever have seen it.
CALENDAR_PHONE_BLOCK = re.compile(
r"@media \(max-width: 640px\) \{(?P<body>(?:[^{}]|\{[^{}]*\})*?\.cal(?:[^{}]|\{[^{}]*\})*?)\n\}",
re.DOTALL)
RULE = re.compile(r"(?P<selectors>[^{}]+)\{(?P<body>[^{}]*)\}")
def _specificity(selector):
"""(ids, classes, elements) for one selector, near enough for this guard.
`:not()` and `:has()` contribute their own contents, which is how the
cascade actually counts them.
"""
inner = re.sub(r":(?:not|has|is)\(", " ", selector).replace(")", " ")
ids = len(re.findall(r"#[\w-]+", inner))
classes = (len(re.findall(r"\.[\w-]+", inner))
+ len(re.findall(r"\[[^\]]+\]", inner))
+ len(re.findall(r"(?<!:):[a-z-]+", inner)))
elements = len(re.findall(r"(?:^|[\s>+~])([a-z]+)(?![\w-]*\()", inner))
return ids, classes, elements
def _winning_display(rules, ending_in):
"""What `display` an element whose last compound is `ending_in` ends up with.
Only the rules whose own last compound could match it are considered, which
is all this guard needs: the question is which of two neighbouring rules
wins, not whether the ancestors line up.
"""
winner = None
for order, (selector, body) in enumerate(rules):
# The pseudo-classes come off before comparing but stay in the
# specificity: `.cal__day:not(:has(.cal__event))` is a rule about a day
# cell, and it is the one that hid every day on a phone.
last = re.sub(r":[\w-]+(\([^()]*(?:\([^()]*\))?[^()]*\))?", "",
selector.strip().split()[-1])
if last not in ending_in:
continue
display = re.search(r"display\s*:\s*([\w-]+)", body)
if not display:
continue
key = (_specificity(selector), order)
if winner is None or key > winner[0]:
winner = (key, selector.strip(), display.group(1))
return winner
@pytest.fixture(scope="module")
def calendar_phone_rules():
css = (Path(__file__).resolve().parents[1] / "static" / "board.css").read_text(encoding="utf-8")
block = CALENDAR_PHONE_BLOCK.search(css)
assert block, "board.css has no phone block for the calendar"
body = re.sub(r"/\*.*?\*/", "", block.group("body"), flags=re.DOTALL)
rules = []
for rule in RULE.finditer(body):
for selector in rule.group("selectors").split(","):
if selector.strip():
rules.append((selector.strip(), rule.group("body")))
return rules
def test_the_padding_cells_are_actually_hidden_on_a_phone(calendar_phone_rules):
"""The one that shipped: `.cal td { display: block }` is (0,1,1) and
`.cal__pad { display: none }` is (0,1,0), so the padding cells stayed as
92px empty boxes — while `.cal__day:not(:has(.cal__event))` at (0,2,0) won
and hid every real day. A month with no events drew four blank boxes and
nothing else, and the HTML was correct throughout.
"""
winner = _winning_display(calendar_phone_rules, {"td.cal__pad", ".cal__pad", "td"})
assert winner, "nothing in the phone block decides what a padding cell does"
assert winner[2] == "none", (
f"a padding cell ends up `display: {winner[2]}` from `{winner[1]}`. "
"A rule naming td outranks one naming only the class, so every cell "
"belonging to the neighbouring month is drawn as an empty box."
)
def test_every_day_of_the_month_is_drawn_on_a_phone(calendar_phone_rules):
"""The month is a column of days there, not only the days with something in
them: an empty day is how you see the month is empty, and how an admin taps
the 14th to put something on it."""
winner = _winning_display(calendar_phone_rules, {"td.cal__day", ".cal__day"})
assert winner and winner[2] != "none", (
f"a day cell ends up hidden on a phone (`{winner[1] if winner else '—'}`)."
)
def test_the_weekday_shows_on_a_phone(calendar_phone_rules):
"""The header row is hidden at that width, and the base stylesheet hides
`.cal__weekday` because up there the header says it. If the phone block
only restyles it without turning it back on, every row of the month reads
as a bare number — which is how it was first rendered."""
winner = _winning_display(calendar_phone_rules, {".cal__weekday", "span.cal__weekday"})
assert winner and winner[2] != "none", (
"the phone block never gives .cal__weekday a display of its own, so the "
"base `display: none` stands and the days lose their weekday."
)
AGENDA_PHONE_BLOCK = re.compile(
r"@media \(max-width: 640px\) \{(?P<body>(?:[^{}]|\{[^{}]*\})*?\.agenda__(?:[^{}]|\{[^{}]*\})*?)\n\}",
re.DOTALL)
def test_the_public_agenda_draws_every_day_on_a_phone_too():
"""The same rule as the members area's calendar, in the other stylesheet.
The two are one feature seen from two sides — the private calendar lists
the public events — so a member who moves between them should not meet two
designs. The agenda used to show only the days with something in them,
which made an empty month a heading and one sentence.
"""
css = (THEME / "assets" / "css" / "main.css").read_text(encoding="utf-8")
block = AGENDA_PHONE_BLOCK.search(css)
assert block, "main.css has no phone block for the agenda"
body = re.sub(r"/\*.*?\*/", "", block.group("body"), flags=re.DOTALL)
rules = [(selector.strip(), rule.group("body"))
for rule in RULE.finditer(body)
for selector in rule.group("selectors").split(",") if selector.strip()]
day = _winning_display(rules, {".agenda__day", "li.agenda__day"})
assert day and day[2] != "none", (
f"a day of the month is hidden on a phone (`{day[1] if day else '—'}`)")
pad = _winning_display(rules, {".agenda__pad", "li.agenda__pad"})
assert pad and pad[2] == "none", "the neighbouring months' padding cells are drawn"
weekday = _winning_display(rules, {".agenda__weekday", "span.agenda__weekday"})
assert weekday and weekday[2] != "none", (
"the phone block never shows .agenda__weekday, so every row of the "
"month is a bare number — there is no column header at that width")

View File

@ -120,6 +120,18 @@ sitemap:
markup:
goldmark:
renderer:
unsafe: true # WP-migrated content contains inline HTML
# Raw HTML in a post is not rendered as HTML. It was on, for content
# migrated from WordPress that carried inline markup; that content is
# gone — no file under content/ holds a single tag — and leaving it on
# had a cost that grew with the members area: a proposal written by a
# member is rendered here with `html=False`, so a moderator reviewing
# `<img src=x onerror=…>` sees the characters and approves them, and
# this flag is what would have run them on the live site.
#
# hardWraps is deliberately left off: the files are hard-wrapped at
# about 78 characters, so turning it on would break every sentence in
# half. apps/board/render.py says how the two renderers are kept
# honest about that.
unsafe: false
enableRobotsTXT: false # robots.txt is a static file in static/

View File

@ -1034,17 +1034,77 @@ 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.
proposal, the editor, a profile bio — shows the formatting while it is being
typed. Bold is bold, a heading is a heading. Opted in with `data-markdown` and
attached by `static/board.js`; `data-rich="full"` on the four boxes that hold a
post adds the three heading levels, both kinds of list and the quote, and the
rest get bold, italic, link and clear formatting.
**Markdown is still the only thing stored.** That is what keeps the file in git,
the pipeline, Decap and the XSS defence exactly as they were — and the two
directions are deliberately not symmetrical:
- **opening** something to edit: the *server* renders the stored markdown into a
`<template>` beside the box, which the editor adopts. There is no markdown
parser in the browser, so there is no second opinion about what text means;
- **saving**: the browser walks a closed set of elements back into markdown.
Anything it does not recognise contributes its text and nothing else, and a
paste arrives as plain text — so nothing anybody pastes brings markup in.
The **Markdown** button swaps the box for the raw text and back. It is the
escape hatch if the editor ever mangles something, and the way to write a table
or anything else the buttons do not offer. Coming back renders through
`/comunidad/previsualizar` — the same `render.to_html`, for the same reason
opening does. The editor's own *Vista previa*, which returns a whole page, is
unrelated and still there: it needs no JavaScript and shows the published look.
**With scripting off the plain `<textarea>` is still there** and still the field
that submits. Nothing is hidden by CSS; the script hides the textarea itself,
and moves `required` off it first, because a hidden required field makes the
browser refuse to submit and report the error on an element nobody can see.
The serializer is tested by running `static/board.js` in node against a table of
documents (`apps/board/tests/test_editor.py`), including a round trip asserting
markdown → HTML → markdown renders identically. Those tests skip where node is
not installed.
**A line break means two different things**, so `render.py` has two renderers.
Text this app stores and renders — the wall, messages, events — uses
`breaks=True`: a newline somebody typed is a newline they meant. A public post
is a file Hugo renders with hardWraps off, and the files are hard-wrapped at
about 78 characters, so rendering those with breaks on would show a line break
in the middle of every sentence. The editor writes the break CommonMark means,
two spaces at the end of a line, which survives either way.
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.
### 11.17b «Contenido generado con IA»
A switch beside the button that publishes, on the three boxes that hold a post:
the editor, a member's proposal and a wall thread. Where the post is read it is
a pill next to the date — on the article, on the cards in the listings, on the
thread and in the wall's list — because a disclosure somebody meets after
reading the thing is not a disclosure.
| Where | How it is stored |
|---|---|
| A public post or page | `ai_generated: true` in the frontmatter, written only when true. The file in the repository is the record |
| A member's proposal | `submissions.ai_generated`, carried into the published post on approval — the only place it has to be carried by hand, because a proposal is a draft in SQLite until the frontmatter exists |
| A wall thread | `threads.ai_generated` |
| The editor's list | `content_cache.ai_generated`, a copy so *Contenido* can show it without re-reading every file from the git server |
Migration 9, three plain `ADD COLUMN`s. The pipeline needs nothing: `translate.py`
copies the whole frontmatter and rewrites only `TRANSLATED_KEYS`, so the flag
reaches the German and Portuguese siblings by itself — which is right, since a
translated post was still machine-written. The three words are in
`partials/t.html` with the theme's other labels.
This is also the shape the EU AI Act's Article 50 asks for — telling people when
they are reading machine-generated material — which is worth knowing for whoever
installs this for the second organisation.
### 11.18 Marca: the superadministrator owns the look
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
@ -1193,6 +1253,36 @@ In the members area the navigation **wraps** on a phone rather than scrolling:
six sections over two lines shows all six, where a swipe strip would have left
Calendario and Gestión off the right edge with nothing to say they were there.
**Both calendars become a column of days below 640px** — every day of the month,
in order, with its weekday beside it, the days carrying something standing out,
and a line saying so when the month is empty. The private one
(`/comunidad/calendario`, a `<table>`) and the public agenda (`/page/agenda/`,
an `<ol>`) are deliberately the same shape, because the private one lists the
public events and a member moves between the two.
Both phone blocks are written so that **every rule deciding `display` names the
cell's own class**, and `apps/board/tests/test_templates.py` fails if one does
not. That is the shape of the bug it replaces: the calendar's block opened with
`.cal td { display: block }` — specificity (0,1,1) — which outranked
`.cal__pad { display: none }` at (0,1,0), while `.cal__day:not(:has(…))` at
(0,2,0) won and hid every real day. A month with no events therefore drew four
empty boxes and nothing else, with correct HTML throughout. The guard computes
the specificity and runs the cascade for a padding cell, a day cell and the
weekday label, which is as close as pytest gets to looking at a page.
**Tap targets are raised under `@media (pointer: coarse)`** in both stylesheets,
and both blocks are **padding only** — no type size, colour or spacing changes,
so the desktop is untouched. The numbers were measured in a headless browser
rather than guessed: the members-area navigation links were 37×17, the
calendar's `+` was 7×15, the footer links 16px tall. A link inside a sentence is
deliberately left alone; a 44px line box mid-paragraph overlaps the lines around
it, which is why WCAG exempts one.
The theme's coarse block sits at the **end** of `main.css` on purpose:
`.site-bar__cta` takes its phone padding inside the `max-width: 768px` block, a
media query changes nothing about specificity, and a coarse rule written before
it loses silently.
### 11.20 The three admin tools
**Estado del sistema** (superadministrator). The backups panel reads

View File

@ -1468,6 +1468,44 @@ a.group-pill:hover {
.article-single__body p { margin: 0 0 1.1em; }
/* Headings inside an article, which have never had any style of their own —
a post with three levels in it rendered as three identical lines of bold.
The article's own title is the h1 on the page, so a body starts at h2; the
editor's buttons produce exactly these three. */
.article-single__body h2 {
margin: 1.8em 0 0.5em;
font-size: 1.45rem;
line-height: 1.25;
color: var(--text, #1a0d09);
}
.article-single__body h3 {
margin: 1.5em 0 0.4em;
font-size: 1.18rem;
line-height: 1.3;
}
.article-single__body h4 {
margin: 1.3em 0 0.35em;
font-size: 0.95rem;
letter-spacing: 0.03em;
text-transform: uppercase;
color: var(--muted, #5c3d37);
}
.article-single__body h2 + h3 { margin-top: 0.9em; }
.article-single__body ul,
.article-single__body ol { margin: 0 0 1.1em; padding-left: 1.4em; }
.article-single__body li { margin-bottom: 0.3em; }
.article-single__body blockquote {
margin: 1.2em 0;
padding: 0.2em 0 0.2em 1em;
border-left: 3px solid var(--brand-soft, #fbe2db);
color: var(--muted, #5c3d37);
}
.article-single__body hr {
border: 0;
border-top: 1px solid var(--border-light, #e0cec8);
margin: 2em 0;
}
.like-section {
margin: 22px 0 16px;
padding: 16px 0 0;
@ -3805,10 +3843,18 @@ a.notif-card__message:hover {
.cal-event-item__title { font-size: 1.02rem; }
}
/* Site bar: prevent overflow on very narrow screens */
/* Site bar: prevent overflow on very narrow screens.
*
* The ☰ ran off the right edge of a 320px screen on the Portuguese home page
* and nowhere else, because «Comunidade» is three letters longer than
* «Comunidad» and the bar had no room left to give. A layout that depends on
* how long a word is in one of three languages breaks in the language nobody
* tests in, so the gap and the button both give way here. */
@media (max-width: 360px) {
.site-bar__inner { padding: 8px 12px; }
.site-bar__inner { padding: 8px 12px; gap: 8px; }
.site-bar__btn { padding: 7px 12px; font-size: 0.82rem; }
.site-bar__brand-text { font-size: 1rem; min-width: 0; }
.site-bar__cta { padding-left: 10px; padding-right: 10px; font-size: 0.75rem; }
}
/* --- preguntas frecuentes ---------------------------------------------- */
@ -4018,6 +4064,11 @@ a.notif-card__message:hover {
}
.agenda__pad { background: transparent; border-color: transparent; }
.agenda__number { color: var(--subtle, #9a7870); font-weight: 700; }
/* The column a day sits in is its weekday here, so naming it would be saying
the same thing twice. The phone block below, where the month is a column of
days and a column position means nothing, is the only place it shows. */
.agenda__weekday { display: none; }
.agenda__events { display: block; }
.agenda__day--busy { background: var(--brand-softer, #fdf1ed); border-color: var(--brand-soft, #fbe2db); }
.agenda__event {
@ -4032,14 +4083,26 @@ a.notif-card__message:hover {
.agenda__empty { text-align: center; margin: -12px 0 24px; }
/* A seven-column grid on a phone is seven columns of nothing. Below 640px the
month becomes a list of the days that have something in them. */
/* A seven-column grid on a phone is seven columns of nothing, so below 640px
the month becomes a column: every day, in order, with its weekday beside it
and the days that have something in them standing out.
It used to show only the busy days, which made an empty month a heading and
a sentence — and this is the shape the members area's calendar now has too,
because a member who moves between the two should not meet two designs. */
@media (max-width: 640px) {
.agenda__grid { display: block; }
.agenda__pad { display: none; }
.agenda__day { display: none; min-height: 0; margin-bottom: 6px; }
.agenda__day--busy { display: block; }
.agenda__number { display: inline-block; margin-right: 8px; }
.agenda__day {
display: flex;
align-items: baseline;
gap: 10px;
min-height: 44px;
margin-bottom: 6px;
}
.agenda__date { flex: 0 0 4.2rem; } /* the dates line up down the page */
.agenda__weekday { display: inline; }
.agenda__events { flex: 1; min-width: 0; }
.agenda__number { display: inline-block; margin-left: 4px; }
}
/* The association's accounts elsewhere, in the footer. Set in
@ -4052,3 +4115,48 @@ a.notif-card__message:hover {
margin-bottom: 10px;
font-size: 0.85rem;
}
/* --- a thumb is not a mouse ---------------------------------------------
*
* Controls raised to 44px where the pointer is coarse — a touchscreen, not a
* narrow window, so a phone in landscape gets it too. Padding only: no type
* size, colour or spacing changes, and the desktop is untouched.
*
* At the end of the file on purpose. `.site-bar__cta` is given its phone
* padding inside the max-width: 768px block further up, and a media query
* changes nothing about specificity — so a coarse rule written before it
* loses, silently, and the button stays 33px tall. Every number here is what
* that control's own line box needs, measured in a browser.
*
* Links inside a paragraph are left alone deliberately. A 44px line box
* mid-sentence overlaps the lines around it, which is why WCAG exempts a link
* that is part of a line of text.
*/
@media (pointer: coarse) {
.site-bar__cta { padding-top: 15px; padding-bottom: 15px; }
.site-bar__hamburger { min-width: 44px; min-height: 44px; }
.page-nav a { display: inline-block; padding: 14px 0; }
.site-foot a { display: inline-block; padding: 15px 0; }
.back-link { display: inline-block; padding: 14px 0; }
.agenda__move { min-width: 44px; min-height: 44px; }
}
/* --- said out loud: a machine wrote this -------------------------------- */
/*
* Beside the date on the post and on its card. Quiet enough not to shout and
* placed above the text rather than under it: a disclosure somebody meets
* after reading the thing is not a disclosure. The words are in t.html, in
* the three languages, because a post translated by the pipeline was still
* machine-written and the label travels with it.
*/
.tag-ai {
display: inline-block;
padding: 2px 8px;
border: 1px solid var(--border-light, #e0cec8);
border-radius: 999px;
background: var(--surface-soft, #faf2ef);
color: var(--muted, #5c3d37);
font-size: 0.72rem;
letter-spacing: 0.02em;
vertical-align: middle;
}

View File

@ -7,6 +7,7 @@
<article class="article-card">
<div class="article-card__meta">
<time datetime="{{ .Date.Format "2006-01-02" }}">{{ .Date.Format "2 Jan 2006" }}</time>
{{ if .Params.ai_generated }}<span class="tag-ai" title="{{ partial "t.html" (dict "key" "aifull" "lang" .Site.Language.Lang) }}">{{ partial "t.html" (dict "key" "ai" "lang" .Site.Language.Lang) }}</span>{{ end }}
</div>
<h2 class="article-card__title"><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
<p class="article-card__excerpt">{{ .Description | default (.Summary | plainify | truncate 200) }}</p>

View File

@ -27,6 +27,14 @@
{{ end }}
</span>
{{ end }}
{{/* Said where the post is read, beside the date — not under the text,
where a disclosure arrives after the thing it discloses. Written by
whoever published it, in the frontmatter; translate.py copies the key
into the German and Portuguese siblings by itself, which is right:
a translated post was still machine-written. */}}
{{ if .Params.ai_generated }}
<span class="tag-ai" title="{{ partial "t.html" (dict "key" "aifull" "lang" .Site.Language.Lang) }}">{{ partial "t.html" (dict "key" "ai" "lang" .Site.Language.Lang) }}</span>
{{ end }}
</div>
</div>
</header>

View File

@ -5,6 +5,7 @@
<article class="article-card">
<div class="article-card__meta">
<time datetime="{{ .Date.Format "2006-01-02" }}">{{ .Date.Format "2 Jan 2006" }}</time>
{{ if .Params.ai_generated }}<span class="tag-ai" title="{{ partial "t.html" (dict "key" "aifull" "lang" .Site.Language.Lang) }}">{{ partial "t.html" (dict "key" "ai" "lang" .Site.Language.Lang) }}</span>{{ end }}
</div>
<h2 class="article-card__title"><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
<p class="article-card__excerpt">{{ .Description | default (.Summary | plainify | truncate 200) }}</p>

View File

@ -80,13 +80,23 @@
{{ range $day := seq 1 $days }}
{{ $date := printf "%s-%02d" $key $day }}
{{ $onThisDay := where $events "Params.event_date" $date }}
{{/* The column a day falls in is its weekday, Monday first — the
same arithmetic the padding above is made of. On a phone the
grid becomes one day per row, where a column position says
nothing and the name has to be written out. */}}
{{ $weekday := mod (add (sub $day 1) $lead) 7 }}
<li class="agenda__day {{ if $onThisDay }}agenda__day--busy{{ end }}">
<span class="agenda__date">
<span class="agenda__weekday">{{ partial "weekday-name.html" (dict "weekday" $weekday "lang" $lang) }}</span>
<span class="agenda__number">{{ $day }}</span>
</span>
<span class="agenda__events">
{{ range $onThisDay }}
<a class="agenda__event" href="{{ .RelPermalink }}">
{{ with .Params.event_time }}<time>{{ . }}</time> {{ end }}{{ .Title }}
</a>
{{ end }}
</span>
</li>
{{ end }}
</ol>

View File

@ -18,6 +18,10 @@
"next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês")
"noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.")
"allevents" (dict "es" "Todos los eventos" "de" "Alle Termine" "pt-br" "Todos os eventos")
"ai" (dict "es" "Generado con IA" "de" "Mit KI erstellt" "pt-br" "Gerado com IA")
"aifull" (dict "es" "Quien lo publicó marcó este texto como generado con inteligencia artificial."
"de" "Wer diesen Beitrag veröffentlicht hat, hat ihn als mit künstlicher Intelligenz erstellt gekennzeichnet."
"pt-br" "Quem publicou marcou este texto como gerado com inteligência artificial.")
"community" (dict "es" "Comunidad" "de" "Community" "pt-br" "Comunidade")
"menu" (dict "es" "Menú" "de" "Menü" "pt-br" "Menu")
-}}

View File

@ -0,0 +1,15 @@
{{- /* The weekday, abbreviated, in the page's own language.
Same arrangement as month-name.html and for the same reason: this theme
ships no i18n files, and three languages of seven short words is a table
rather than a dependency.
Monday is 0, as in the agenda's own column order — Austria and most of
Latin America start the week there. */ -}}
{{- $names := dict
"es" (slice "lun" "mar" "mié" "jue" "vie" "sáb" "dom")
"de" (slice "Mo" "Di" "Mi" "Do" "Fr" "Sa" "So")
"pt-br" (slice "seg" "ter" "qua" "qui" "sex" "sáb" "dom")
-}}
{{- $table := index $names .lang | default (index $names "es") -}}
{{- index $table (int .weekday) -}}