Compare commits
10 Commits
ef57443508
...
d2978cc68c
| Author | SHA1 | Date | |
|---|---|---|---|
| d2978cc68c | |||
| 7063c473e7 | |||
|
|
3e610ac5d2 | ||
|
|
864d36bfb0 | ||
| aaf3e9e3fe | |||
|
|
ff115c1d6b | ||
|
|
8e1ef8831c | ||
|
|
59b595170f | ||
| cacc7c20bb | |||
| 64b9d3b805 |
@ -14,6 +14,7 @@ from flask import Flask, render_template, request
|
|||||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||||
|
|
||||||
from .db import TOMBSTONE_LOGIN, close_db, init_db
|
from .db import TOMBSTONE_LOGIN, close_db, init_db
|
||||||
|
from .render import to_html
|
||||||
from .security import check_csrf, csrf_token, is_at_least
|
from .security import check_csrf, csrf_token, is_at_least
|
||||||
|
|
||||||
URL_PREFIX = "/comunidad"
|
URL_PREFIX = "/comunidad"
|
||||||
@ -132,6 +133,10 @@ def create_app(overrides: dict | None = None) -> Flask:
|
|||||||
# from the superadministrator's own navigation — the exact failure
|
# from the superadministrator's own navigation — the exact failure
|
||||||
# `is_at_least` was introduced to end on the Python side.
|
# `is_at_least` was introduced to end on the Python side.
|
||||||
app.jinja_env.globals["is_at_least"] = is_at_least
|
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
|
@app.context_processor
|
||||||
def _year():
|
def _year():
|
||||||
|
|||||||
@ -20,6 +20,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
|||||||
|
|
||||||
from . import auth, uploads
|
from . import auth, uploads
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
|
from . import titles
|
||||||
from .render import excerpt, to_html
|
from .render import excerpt, to_html
|
||||||
from .security import admin_required, is_at_least, login_required
|
from .security import admin_required, is_at_least, login_required
|
||||||
|
|
||||||
@ -69,9 +70,16 @@ def cooldown_remaining() -> int:
|
|||||||
def _clean(title: str, body: str) -> tuple[str, str] | None:
|
def _clean(title: str, body: str) -> tuple[str, str] | None:
|
||||||
title = title.strip()[:TITLE_MAX]
|
title = title.strip()[:TITLE_MAX]
|
||||||
body = body.strip()[:BODY_MAX]
|
body = body.strip()[:BODY_MAX]
|
||||||
if not title or not body:
|
if not body:
|
||||||
flash("El título y el mensaje no pueden estar vacíos.", "error")
|
flash("El mensaje no puede estar vacío.", "error")
|
||||||
return None
|
return None
|
||||||
|
if not title:
|
||||||
|
# Counting the deleted ones too: a number that comes back is a thread
|
||||||
|
# that looks like one somebody remembers reading. See titles.py.
|
||||||
|
rows = get_db().execute(
|
||||||
|
"SELECT title FROM threads WHERE title LIKE ?",
|
||||||
|
(titles.UNTITLED + "%",)).fetchall()
|
||||||
|
title = titles.next_untitled(row["title"] for row in rows)
|
||||||
return title, body
|
return title, body
|
||||||
|
|
||||||
|
|
||||||
@ -204,8 +212,10 @@ def new_thread():
|
|||||||
|
|
||||||
title, body = cleaned
|
title, body = cleaned
|
||||||
cursor = get_db().execute(
|
cursor = get_db().execute(
|
||||||
"INSERT INTO threads (author_id, title, body_md) VALUES (?, ?, ?)",
|
"""INSERT INTO threads (author_id, title, body_md, ai_generated)
|
||||||
(g.member["id"], title, body),
|
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)
|
uploads.save(staged, g.member["id"], thread_id=cursor.lastrowid)
|
||||||
return redirect(url_for("board.thread", thread_id=cursor.lastrowid))
|
return redirect(url_for("board.thread", thread_id=cursor.lastrowid))
|
||||||
@ -225,8 +235,11 @@ def edit_thread(thread_id: int):
|
|||||||
return redirect(url_for("board.edit_thread", thread_id=thread_id))
|
return redirect(url_for("board.edit_thread", thread_id=thread_id))
|
||||||
title, body = cleaned
|
title, body = cleaned
|
||||||
get_db().execute(
|
get_db().execute(
|
||||||
"UPDATE threads SET title = ?, body_md = ?, edited_at = datetime('now') WHERE id = ?",
|
"""UPDATE threads SET title = ?, body_md = ?, ai_generated = ?,
|
||||||
(title, body, thread_id),
|
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))
|
return redirect(url_for("board.thread", thread_id=thread_id))
|
||||||
|
|
||||||
|
|||||||
@ -30,7 +30,7 @@ import yaml
|
|||||||
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
||||||
render_template, request, url_for)
|
render_template, request, url_for)
|
||||||
|
|
||||||
from . import gitea
|
from . import gitea, titles
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .render import to_html
|
from .render import to_html
|
||||||
from .security import is_at_least, moderator_required
|
from .security import is_at_least, moderator_required
|
||||||
@ -99,6 +99,34 @@ def filename_for(collection: str, title: str, when: date_type | None) -> str:
|
|||||||
return f"{slug}.es.md"
|
return f"{slug}.es.md"
|
||||||
|
|
||||||
|
|
||||||
|
def untitled_for(collection: str, when, skip: str = "") -> str:
|
||||||
|
"""A name for a post nobody titled, free in the folder it is going into.
|
||||||
|
|
||||||
|
Numbered against the *filenames* rather than against the titles, because in
|
||||||
|
a repository the filename is what collides: two «Sin Título» posts on one
|
||||||
|
day would both be `<fecha>-sin-titulo.es.md`, and the second would come back
|
||||||
|
as "somebody else saved this file while you were editing it" — a message
|
||||||
|
about a conflict that never happened.
|
||||||
|
|
||||||
|
A git server that cannot be reached gives the plain name. Publishing fails
|
||||||
|
in that case anyway, and the failure should say what it is rather than be a
|
||||||
|
naming error wearing its coat.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
names = {entry["name"] for entry in gitea.list_directory(
|
||||||
|
COLLECTIONS[collection]["folder"], gitea.content_token())}
|
||||||
|
except gitea.GiteaError:
|
||||||
|
return titles.UNTITLED
|
||||||
|
names.discard(skip) # editing a post does not collide with itself
|
||||||
|
|
||||||
|
number = 1
|
||||||
|
while True:
|
||||||
|
title = titles.UNTITLED if number == 1 else f"{titles.UNTITLED} {number}"
|
||||||
|
if filename_for(collection, title, when) not in names:
|
||||||
|
return title
|
||||||
|
number += 1
|
||||||
|
|
||||||
|
|
||||||
def split_frontmatter(text: str) -> tuple[dict, str]:
|
def split_frontmatter(text: str) -> tuple[dict, str]:
|
||||||
match = re.match(r"\A---\n(.*?)\n---\n?(.*)\Z", text, re.DOTALL)
|
match = re.match(r"\A---\n(.*?)\n---\n?(.*)\Z", text, re.DOTALL)
|
||||||
if not match:
|
if not match:
|
||||||
@ -159,6 +187,11 @@ def frontmatter_for(collection: str, form: dict) -> dict:
|
|||||||
fields["author"] = form["author"]
|
fields["author"] = form["author"]
|
||||||
if form.get("author_url"):
|
if form.get("author_url"):
|
||||||
fields["author_url"] = form["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
|
return fields
|
||||||
|
|
||||||
|
|
||||||
@ -173,13 +206,15 @@ def _cache_read(path: str, sha: str):
|
|||||||
def _cache_write(path: str, sha: str, fm: dict) -> None:
|
def _cache_write(path: str, sha: str, fm: dict) -> None:
|
||||||
get_db().execute(
|
get_db().execute(
|
||||||
"""INSERT INTO content_cache (path, sha, title, date, generated, image,
|
"""INSERT INTO content_cache (path, sha, title, date, generated, image,
|
||||||
event_date, event_time, event_location)
|
event_date, event_time, event_location,
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
ai_generated)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(path) DO UPDATE SET
|
ON CONFLICT(path) DO UPDATE SET
|
||||||
sha = excluded.sha, title = excluded.title, date = excluded.date,
|
sha = excluded.sha, title = excluded.title, date = excluded.date,
|
||||||
generated = excluded.generated, image = excluded.image,
|
generated = excluded.generated, image = excluded.image,
|
||||||
event_date = excluded.event_date, event_time = excluded.event_time,
|
event_date = excluded.event_date, event_time = excluded.event_time,
|
||||||
event_location = excluded.event_location,
|
event_location = excluded.event_location,
|
||||||
|
ai_generated = excluded.ai_generated,
|
||||||
updated_at = datetime('now')""",
|
updated_at = datetime('now')""",
|
||||||
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
|
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
|
||||||
1 if fm.get("translated_from") else 0,
|
1 if fm.get("translated_from") else 0,
|
||||||
@ -192,7 +227,8 @@ def _cache_write(path: str, sha: str, fm: dict) -> None:
|
|||||||
# internal ones and would otherwise read every post's frontmatter on
|
# internal ones and would otherwise read every post's frontmatter on
|
||||||
# every page view to find out when they are.
|
# 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_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 +256,7 @@ def listing(collection: str) -> list[dict]:
|
|||||||
"name": name, "path": path, "sha": sha,
|
"name": name, "path": path, "sha": sha,
|
||||||
"title": row["title"] or name,
|
"title": row["title"] or name,
|
||||||
"date": row["date"],
|
"date": row["date"],
|
||||||
|
"ai_generated": bool(row["ai_generated"]),
|
||||||
"event_date": row["event_date"] or "",
|
"event_date": row["event_date"] or "",
|
||||||
"event_time": row["event_time"] or "",
|
"event_time": row["event_time"] or "",
|
||||||
"event_location": row["event_location"] or "",
|
"event_location": row["event_location"] or "",
|
||||||
@ -310,8 +347,8 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
|
|||||||
errors.append("La imagen no es válida.")
|
errors.append("La imagen no es válida.")
|
||||||
image = ""
|
image = ""
|
||||||
|
|
||||||
if not title:
|
# A title is not required. An untitled post is named when it is saved, by
|
||||||
errors.append("El título no puede estar vacío.")
|
# untitled_for() — see titles.py for why the form does not insist.
|
||||||
if not body:
|
if not body:
|
||||||
errors.append("El cuerpo no puede estar vacío.")
|
errors.append("El cuerpo no puede estar vacío.")
|
||||||
|
|
||||||
@ -320,6 +357,10 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
|
|||||||
"description": request.form.get("description", "").strip(),
|
"description": request.form.get("description", "").strip(),
|
||||||
"image": image,
|
"image": image,
|
||||||
"manual_translation": request.form.get("manual_translation") == "on",
|
"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,
|
"author": author, "author_url": author_url,
|
||||||
"parent": parent, "weight": weight,
|
"parent": parent, "weight": weight,
|
||||||
"faq": faq, "image_alt": image_alt,
|
"faq": faq, "image_alt": image_alt,
|
||||||
@ -474,6 +515,8 @@ def publish(collection: str, fields: dict, body: str, author) -> str:
|
|||||||
approved submission keeps the member's name in git history.
|
approved submission keeps the member's name in git history.
|
||||||
"""
|
"""
|
||||||
fields = dict(fields, **byline(author))
|
fields = dict(fields, **byline(author))
|
||||||
|
if not fields.get("title"):
|
||||||
|
fields["title"] = untitled_for(collection, fields["date"])
|
||||||
name = filename_for(collection, fields["title"], fields["date"])
|
name = filename_for(collection, fields["title"], fields["date"])
|
||||||
path = f"{COLLECTIONS[collection]['folder']}/{name}"
|
path = f"{COLLECTIONS[collection]['folder']}/{name}"
|
||||||
document = build_document(frontmatter_for(collection, fields), body)
|
document = build_document(frontmatter_for(collection, fields), body)
|
||||||
@ -551,6 +594,11 @@ def edit(collection: str, name: str):
|
|||||||
"description": fm.get("description", ""),
|
"description": fm.get("description", ""),
|
||||||
"image": fm.get("image", ""),
|
"image": fm.get("image", ""),
|
||||||
"manual_translation": bool(fm.get("manual_translation")),
|
"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
|
# Carried through the form untouched. Correcting a typo in somebody
|
||||||
# else's post must not re-sign it with the name of whoever is
|
# 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
|
# fixing it — the same rule the board has about editing other
|
||||||
@ -583,6 +631,11 @@ def edit(collection: str, name: str):
|
|||||||
fields["image"] = picture
|
fields["image"] = picture
|
||||||
# Deliberately not through publish(): that stamps the byline of whoever
|
# Deliberately not through publish(): that stamps the byline of whoever
|
||||||
# is publishing, and an edit keeps the author the file already names.
|
# is publishing, and an edit keeps the author the file already names.
|
||||||
|
if not fields.get("title"):
|
||||||
|
# `skip` is this post's own file: a title cleared on an edit must
|
||||||
|
# not count the thing being edited as the collision it has to
|
||||||
|
# avoid, or every save would walk the number up by one.
|
||||||
|
fields["title"] = untitled_for(collection, fields["date"], skip=name)
|
||||||
document = build_document(frontmatter_for(collection, fields), body)
|
document = build_document(frontmatter_for(collection, fields), body)
|
||||||
gitea.write_file(path, document.encode("utf-8"),
|
gitea.write_file(path, document.encode("utf-8"),
|
||||||
f"content: actualizar «{fields['title']}»",
|
f"content: actualizar «{fields['title']}»",
|
||||||
@ -631,7 +684,7 @@ def preview(collection: str):
|
|||||||
today=date_type.today().isoformat(),
|
today=date_type.today().isoformat(),
|
||||||
parents=possible_parents(collection,
|
parents=possible_parents(collection,
|
||||||
item["name"] if item else ""),
|
item["name"] if item else ""),
|
||||||
preview_html=to_html(body))
|
preview_html=to_html(body, breaks=False))
|
||||||
|
|
||||||
|
|
||||||
def public_events() -> list[dict]:
|
def public_events() -> list[dict]:
|
||||||
|
|||||||
@ -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")
|
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
|
# (number, description, function). The number is the value written to
|
||||||
# user_version once the step succeeds.
|
# user_version once the step succeeds.
|
||||||
STEPS = [
|
STEPS = [
|
||||||
@ -350,6 +376,7 @@ STEPS = [
|
|||||||
(7, "a superadministrator above the responsable", _a_superadmin_above_the_owner),
|
(7, "a superadministrator above the responsable", _a_superadmin_above_the_owner),
|
||||||
(8, "room for the identity, a typeface and the media library",
|
(8, "room for the identity, a typeface and the media library",
|
||||||
_room_for_identity_and_a_typeface),
|
_room_for_identity_and_a_typeface),
|
||||||
|
(9, "a post can say a machine wrote it", _room_to_say_a_machine_wrote_it),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -20,16 +20,36 @@ from __future__ import annotations
|
|||||||
from markdown_it import MarkdownIt
|
from markdown_it import MarkdownIt
|
||||||
from markupsafe import Markup
|
from markupsafe import Markup
|
||||||
|
|
||||||
_md = (
|
def _renderer(breaks: bool) -> MarkdownIt:
|
||||||
MarkdownIt("commonmark", {"html": False, "linkify": True, "breaks": True})
|
return (
|
||||||
|
MarkdownIt("commonmark", {"html": False, "linkify": True, "breaks": breaks})
|
||||||
.enable("linkify")
|
.enable("linkify")
|
||||||
.enable("table")
|
.enable("table")
|
||||||
.enable("strikethrough")
|
.enable("strikethrough")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def to_html(text: str) -> Markup:
|
# Two of them, because a line break means two different things depending on
|
||||||
return Markup(_md.render(text or ""))
|
# 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:
|
def excerpt(text: str, limit: int = 220) -> str:
|
||||||
|
|||||||
@ -54,6 +54,10 @@ CREATE TABLE IF NOT EXISTS threads (
|
|||||||
edited_at TEXT,
|
edited_at TEXT,
|
||||||
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)),
|
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)),
|
||||||
locked INTEGER NOT NULL DEFAULT 0 CHECK (locked 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
|
-- Soft delete: a moderator's mistake stays recoverable, and removing one
|
||||||
-- comment does not tear a hole in the conversation around it.
|
-- comment does not tear a hole in the conversation around it.
|
||||||
deleted_at TEXT
|
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
|
-- draft. Recorded here so the listing can skip them without re-reading
|
||||||
-- every file to find out what it already knew.
|
-- every file to find out what it already knew.
|
||||||
generated INTEGER NOT NULL DEFAULT 0 CHECK (generated IN (0, 1)),
|
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'))
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -260,6 +268,10 @@ CREATE TABLE IF NOT EXISTS submissions (
|
|||||||
event_time TEXT,
|
event_time TEXT,
|
||||||
event_location TEXT,
|
event_location TEXT,
|
||||||
photo_name 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'
|
state TEXT NOT NULL DEFAULT 'pending'
|
||||||
CHECK (state IN ('pending', 'approved', 'rejected')),
|
CHECK (state IN ('pending', 'approved', 'rejected')),
|
||||||
-- Why it was rejected, in the moderator's words, shown to the author. A
|
-- Why it was rejected, in the moderator's words, shown to the author. A
|
||||||
|
|||||||
@ -170,6 +170,22 @@ button, input, select, textarea { font: inherit; }
|
|||||||
.prose { line-height: 1.65; }
|
.prose { line-height: 1.65; }
|
||||||
.prose :first-child { margin-top: 0; }
|
.prose :first-child { margin-top: 0; }
|
||||||
.prose :last-child { margin-bottom: 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 img { max-width: 100%; height: auto; border-radius: var(--radius-md); }
|
||||||
.prose pre {
|
.prose pre {
|
||||||
background: var(--surface-soft);
|
background: var(--surface-soft);
|
||||||
@ -233,6 +249,23 @@ textarea { resize: vertical; line-height: 1.55; }
|
|||||||
}
|
}
|
||||||
.btn:hover { background: var(--brand-dark); }
|
.btn:hover { background: var(--brand-dark); }
|
||||||
|
|
||||||
|
/* The second button in a row of them — Cancelar, mostly. It was a link, which
|
||||||
|
made leaving look like a footnote next to a filled pill; it is the other
|
||||||
|
half of a decision and should be the same size and shape as the half beside
|
||||||
|
it. Quiet rather than loud: same geometry, no fill, so the eye still knows
|
||||||
|
which one publishes. */
|
||||||
|
.btn--quiet {
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--muted);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
padding: calc(0.6rem - 1px) calc(1.4rem - 1px); /* the border, given back */
|
||||||
|
}
|
||||||
|
.btn--quiet:hover {
|
||||||
|
background: var(--surface-soft);
|
||||||
|
color: var(--text);
|
||||||
|
border-color: var(--brand);
|
||||||
|
}
|
||||||
|
|
||||||
/* A button sitting straight in a card, rather than in an .actions row, still
|
/* A button sitting straight in a card, rather than in an .actions row, still
|
||||||
* needs air above it. Five of them did not have any — the one under the "escribir
|
* needs air above it. Five of them did not have any — the one under the "escribir
|
||||||
* a" picker was flush against the select — because the space every other form
|
* a" picker was flush against the select — because the space every other form
|
||||||
@ -309,9 +342,35 @@ textarea { resize: vertical; line-height: 1.55; }
|
|||||||
word-break: break-all;
|
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) {
|
@media (max-width: 640px) {
|
||||||
.feed-head { flex-direction: column; align-items: flex-start; }
|
.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 ----------------------------------------------------------- */
|
/* --- editor ----------------------------------------------------------- */
|
||||||
@ -340,6 +399,33 @@ textarea { resize: vertical; line-height: 1.55; }
|
|||||||
.fieldset legend { padding: 0 0.4rem; font-weight: 600; font-size: 0.9rem; }
|
.fieldset legend { padding: 0 0.4rem; font-weight: 600; font-size: 0.9rem; }
|
||||||
.fieldset .check { margin: 0.35rem 0; }
|
.fieldset .check { margin: 0.35rem 0; }
|
||||||
|
|
||||||
|
/* The same box, folded shut. Most posts are not events, and three date
|
||||||
|
pickers between the title and the text are three fields most people scroll
|
||||||
|
past — the form should ask what it needs and keep the rest within reach
|
||||||
|
rather than in the way. A <details>, like the account menu: no script, and
|
||||||
|
it opens by itself when the post already has a date. */
|
||||||
|
.fold {
|
||||||
|
border: 1px solid var(--border-light);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
padding: 0 1rem;
|
||||||
|
margin: 1rem 0 0;
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.fold > summary {
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.8rem 0;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.fold > summary:hover { color: var(--brand-dark); }
|
||||||
|
.fold[open] > summary {
|
||||||
|
color: var(--text);
|
||||||
|
border-bottom: 1px solid var(--border-light);
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
.fold > :last-child { margin-bottom: 1rem; }
|
||||||
|
|
||||||
input[type="file"] {
|
input[type="file"] {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
padding: 0.5rem 0;
|
padding: 0.5rem 0;
|
||||||
@ -638,17 +724,26 @@ input[type="file"] {
|
|||||||
.md-bar__button:hover { border-color: var(--brand); color: var(--brand-dark); }
|
.md-bar__button:hover { border-color: var(--brand); color: var(--brand-dark); }
|
||||||
.md-bar__button--wide { margin-left: auto; }
|
.md-bar__button--wide { margin-left: auto; }
|
||||||
|
|
||||||
.md-preview {
|
/* The writing surface itself, which is also the finished text: it carries
|
||||||
margin: 0.5rem 0 1rem;
|
.prose as well, so what is being written is drawn by the same rules as what
|
||||||
padding: 0.85rem 1rem;
|
is published. Sized like the textarea it replaces — a box you can see a
|
||||||
border: 1px dashed var(--border);
|
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);
|
border-radius: var(--radius-md);
|
||||||
background: var(--surface-soft);
|
background: var(--surface);
|
||||||
line-height: 1.6;
|
line-height: 1.65;
|
||||||
|
overflow-wrap: break-word;
|
||||||
}
|
}
|
||||||
.md-preview :first-child { margin-top: 0; }
|
.rich:focus { outline: 2px solid var(--brand-soft); outline-offset: 1px; border-color: var(--brand); }
|
||||||
.md-preview :last-child { margin-bottom: 0; }
|
.rich :first-child { margin-top: 0; }
|
||||||
.md-preview img { max-width: 100%; border-radius: var(--radius-sm); }
|
.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. */
|
/* What you just chose, before it is uploaded. */
|
||||||
.file-strip {
|
.file-strip {
|
||||||
@ -709,6 +804,12 @@ input[type="file"] {
|
|||||||
.cal__pad { background: transparent; border-color: transparent; }
|
.cal__pad { background: transparent; border-color: transparent; }
|
||||||
.cal__day--today { border-color: var(--brand); background: var(--brand-softer); }
|
.cal__day--today { border-color: var(--brand); background: var(--brand-softer); }
|
||||||
.cal__number { color: var(--subtle); font-weight: 700; }
|
.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 {
|
.cal__event {
|
||||||
display: block;
|
display: block;
|
||||||
@ -735,15 +836,44 @@ input[type="file"] {
|
|||||||
|
|
||||||
.event-facts p { margin: 0 0 0.25rem; }
|
.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) {
|
@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 thead { display: none; }
|
||||||
.cal__pad { display: none; }
|
.cal td.cal__pad { display: none; }
|
||||||
.cal__day { height: auto; margin-bottom: 0.4rem; }
|
.cal td.cal__day {
|
||||||
.cal__day:not(:has(.cal__event)) { display: none; }
|
display: flex;
|
||||||
.cal__number { display: inline-block; margin-right: 0.5rem; }
|
align-items: baseline;
|
||||||
.cal__add { display: inline; }
|
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 ---------------------------------------------------- */
|
/* --- Gestión → Marca ---------------------------------------------------- */
|
||||||
@ -879,3 +1009,149 @@ input[type="file"] {
|
|||||||
.tag--ok { background: #e4f2e4; color: #1b5e20; }
|
.tag--ok { background: #e4f2e4; color: #1b5e20; }
|
||||||
.tag--warn { background: var(--brand-soft); color: var(--brand-dark); }
|
.tag--warn { background: var(--brand-soft); color: var(--brand-dark); }
|
||||||
.tag--bad { background: #f6dcdc; color: var(--danger); }
|
.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. */
|
||||||
|
/* The switch and its words, which were 16px of line box before this. The
|
||||||
|
track is already 22px tall and does not need to grow — the label around
|
||||||
|
it does, so the whole thing is one target. */
|
||||||
|
.toggle { padding: 0.65rem 0; }
|
||||||
|
|
||||||
|
.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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A real switch rather than a checkbox, because what it says is not a detail
|
||||||
|
* of the form — it is a statement about the text, made at the moment of
|
||||||
|
* publishing, and it should look like something that is on or off.
|
||||||
|
*
|
||||||
|
* Drawn entirely from the checkbox's own `:checked` state. There is no script
|
||||||
|
* anywhere near it: under a policy with no 'unsafe-inline' a control that
|
||||||
|
* needs one is a control that silently does nothing. The input is visually
|
||||||
|
* hidden but not `display: none` — it keeps its place in the tab order and is
|
||||||
|
* still announced with its label, so the switch works from a keyboard.
|
||||||
|
*/
|
||||||
|
.toggle {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.55rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--muted);
|
||||||
|
cursor: pointer;
|
||||||
|
/* So the hidden input below is positioned against this label and not
|
||||||
|
against whatever happens to be the nearest positioned ancestor — a 1px
|
||||||
|
invisible control adrift somewhere else on the page is a thing that gets
|
||||||
|
clicked by accident exactly once and is never explained. */
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
.toggle input {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
.toggle__track {
|
||||||
|
position: relative;
|
||||||
|
flex: none;
|
||||||
|
width: 40px;
|
||||||
|
height: 22px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--border);
|
||||||
|
transition: background 140ms ease;
|
||||||
|
}
|
||||||
|
.toggle__track::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
top: 3px;
|
||||||
|
left: 3px;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
|
||||||
|
transition: transform 140ms ease;
|
||||||
|
}
|
||||||
|
.toggle input:checked + .toggle__track { background: var(--brand); }
|
||||||
|
.toggle input:checked + .toggle__track::after { transform: translateX(18px); }
|
||||||
|
/* Focus has to land somewhere visible: the thing with the outline is hidden. */
|
||||||
|
.toggle input:focus-visible + .toggle__track {
|
||||||
|
outline: 2px solid var(--brand-dark);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
.toggle input:checked ~ .toggle__text { color: var(--brand-dark); font-weight: 600; }
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.toggle__track, .toggle__track::after { transition: none; }
|
||||||
|
}
|
||||||
|
|||||||
@ -16,104 +16,357 @@ document.addEventListener("submit", function (event) {
|
|||||||
|
|
||||||
// --- the writing boxes ----------------------------------------------------
|
// --- the writing boxes ----------------------------------------------------
|
||||||
//
|
//
|
||||||
// A toolbar, a preview and thumbnails, all of it ours. Not because a library
|
// The box shows the formatting as it is typed: bold is bold, a heading is a
|
||||||
// would be wrong, but because the Content-Security-Policy here loads scripts
|
// heading. There is no preview pane — a second box beside the first is the
|
||||||
// from this origin only, and vendoring an editor means owning its updates
|
// wrong shape on a phone — and nothing is sent anywhere while anybody writes.
|
||||||
// forever — for buttons that wrap a selection in asterisks.
|
|
||||||
//
|
//
|
||||||
// Everything below attaches on load and leaves anything it does not recognise
|
// What is stored is still markdown, which is what keeps everything downstream
|
||||||
// alone, so a form that has not opted in behaves exactly as it did.
|
// 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 () {
|
(function () {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
// What each button does to the selected text. `wrap` goes on both sides,
|
// --- markdown out of the document ---------------------------------------
|
||||||
// `prefix` goes at the start of every selected line.
|
|
||||||
var TOOLS = [
|
|
||||||
{ label: "N", title: "Negrita", wrap: "**" },
|
|
||||||
{ label: "I", title: "Cursiva", wrap: "_" },
|
|
||||||
{ label: "H", title: "Título", prefix: "## " },
|
|
||||||
{ label: "“”", title: "Cita", prefix: "> " },
|
|
||||||
{ label: "•", title: "Lista", prefix: "- " },
|
|
||||||
{ label: "🔗", title: "Enlace", link: true }
|
|
||||||
];
|
|
||||||
|
|
||||||
function apply(box, tool) {
|
var BLOCKS = { H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1, P: 1, DIV: 1,
|
||||||
var start = box.selectionStart;
|
UL: 1, OL: 1, BLOCKQUOTE: 1, PRE: 1, HR: 1, TABLE: 1 };
|
||||||
var end = box.selectionEnd;
|
// H1 becomes ## on purpose: the page's heading is the post's title, and a
|
||||||
var selected = box.value.slice(start, end);
|
// pasted h1 should not compete with it.
|
||||||
var replacement;
|
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) {
|
function escapeText(text) {
|
||||||
var url = window.prompt("Dirección del enlace", "https://");
|
return text.replace(/\s+/g, " ").replace(/([\\`*_[\]])/g, "\\$1");
|
||||||
if (!url) return;
|
|
||||||
replacement = "[" + (selected || "texto") + "](" + url + ")";
|
|
||||||
} else if (tool.prefix) {
|
|
||||||
// Line by line, so marking three lines as a list marks three lines.
|
|
||||||
replacement = (selected || "").split("\n").map(function (line) {
|
|
||||||
return line.indexOf(tool.prefix) === 0 ? line : tool.prefix + line;
|
|
||||||
}).join("\n");
|
|
||||||
} else {
|
|
||||||
replacement = tool.wrap + (selected || "texto") + tool.wrap;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
box.setRangeText(replacement, start, end, "end");
|
// Only schemes that cannot execute. markdown-it refuses `javascript:` on its
|
||||||
box.focus();
|
// own, so this is the second of two locks rather than the only one.
|
||||||
// Fires the input event frameworks and our own counters would expect; the
|
function safeHref(href) {
|
||||||
// browser does not fire one for a programmatic change.
|
return /^(https?:|mailto:|\/|#)/i.test(href || "") ? href : "";
|
||||||
box.dispatchEvent(new Event("input", { bubbles: true }));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function toolbarFor(box) {
|
// «** bold **» is not bold in CommonMark, and a selection almost always
|
||||||
var bar = document.createElement("div");
|
// carries a space at one end.
|
||||||
bar.className = "md-bar";
|
function wrapped(marker, inner) {
|
||||||
TOOLS.forEach(function (tool) {
|
var lead = inner.match(/^\s*/)[0];
|
||||||
var button = document.createElement("button");
|
var tail = inner.match(/\s*$/)[0];
|
||||||
button.type = "button"; // never a submit inside a form
|
var core = inner.slice(lead.length, inner.length - tail.length);
|
||||||
button.className = "md-bar__button";
|
return core ? lead + marker + core + marker + tail : inner;
|
||||||
button.title = tool.title;
|
}
|
||||||
button.textContent = tool.label;
|
|
||||||
button.addEventListener("click", function () { apply(box, tool); });
|
// Elements whose text is not writing. Nothing here can execute — the server
|
||||||
bar.appendChild(button);
|
// 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");
|
function paragraph(text, indent) {
|
||||||
preview.type = "button";
|
// Trimmed at the two ends only. Stripping trailing spaces line by line —
|
||||||
preview.className = "md-bar__button md-bar__button--wide";
|
// which is the tidy-looking thing to do — would eat the two spaces that
|
||||||
preview.textContent = "Vista previa";
|
// *are* the hard break a <br> turns into.
|
||||||
var panel = document.createElement("div");
|
var body = text.replace(/^\s+|\s+$/g, "");
|
||||||
panel.className = "md-preview";
|
if (!body.trim()) { return ""; }
|
||||||
panel.hidden = true;
|
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 () {
|
function list(el, indent) {
|
||||||
if (!panel.hidden) {
|
var ordered = el.tagName === "OL";
|
||||||
panel.hidden = true;
|
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;
|
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();
|
var data = new FormData();
|
||||||
data.append("body", box.value);
|
data.append("body", box.value);
|
||||||
data.append("csrf_token", token ? token.value : "");
|
data.append("csrf_token", token ? token.value : "");
|
||||||
panel.textContent = "Un momento…";
|
|
||||||
panel.hidden = false;
|
|
||||||
fetch("/comunidad/previsualizar", {
|
fetch("/comunidad/previsualizar", {
|
||||||
method: "POST", body: data, credentials: "same-origin"
|
method: "POST", body: data, credentials: "same-origin"
|
||||||
}).then(function (response) {
|
}).then(function (response) {
|
||||||
return response.ok ? response.json() : null;
|
return response.ok ? response.json() : null;
|
||||||
}).then(function (result) {
|
}).then(function (result) {
|
||||||
// The server rendered this with the same markdown the site uses, with
|
// Rendered by the same function the site renders with, raw HTML
|
||||||
// raw HTML disabled, so what comes back is already safe to insert —
|
// disabled, so what comes back carries no markup of anybody else's.
|
||||||
// and inserting it as text would show the tags instead of the writing.
|
if (result) { surface.innerHTML = result.html; }
|
||||||
panel.innerHTML = result ? result.html : "";
|
surface.hidden = false;
|
||||||
if (!result) panel.textContent = "No se pudo generar la vista previa.";
|
box.hidden = true;
|
||||||
|
raw = false;
|
||||||
|
swap.textContent = "Markdown";
|
||||||
}).catch(function () {
|
}).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);
|
if (form) {
|
||||||
box.parentNode.insertBefore(bar, box);
|
form.addEventListener("submit", function (event) {
|
||||||
box.parentNode.insertBefore(panel, box.nextSibling);
|
sync();
|
||||||
|
if (required && !box.value.trim()) {
|
||||||
|
event.preventDefault();
|
||||||
|
surface.focus();
|
||||||
|
surface.classList.add("rich--empty");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- thumbnails of what was just chosen ---------------------------------
|
// --- thumbnails of what was just chosen ---------------------------------
|
||||||
@ -176,8 +429,12 @@ document.addEventListener("submit", function (event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", function () {
|
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(
|
Array.prototype.forEach.call(
|
||||||
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
|
document.querySelectorAll("textarea[data-markdown]"), enrich);
|
||||||
brandPreview();
|
brandPreview();
|
||||||
|
|
||||||
document.addEventListener("change", function (event) {
|
document.addEventListener("change", function (event) {
|
||||||
|
|||||||
@ -40,22 +40,35 @@ from .security import superadmin_required
|
|||||||
|
|
||||||
bp = Blueprint("status", __name__)
|
bp = Blueprint("status", __name__)
|
||||||
|
|
||||||
# Where deploy-board.sh puts them. Read-only, and missing is an answer.
|
# Where the compose file mounts them, read-only. **Not** the host path: this
|
||||||
BACKUP_DIR = "/srv/board/backups"
|
# runs in a container, and `/srv/board/backups` exists on the host and nowhere
|
||||||
|
# inside it. Reading the host path from in here reported "no hay carpeta de
|
||||||
|
# copias" twenty seconds after deploy-board.sh had written one — a diagnostic
|
||||||
|
# page crying wolf about backups is a page you learn to scroll past, which is
|
||||||
|
# the one habit it exists to prevent.
|
||||||
|
BACKUP_DIR = "/backups"
|
||||||
|
|
||||||
# Settings whose absence turns a feature off rather than breaking the app. The
|
# Settings whose absence matters, and the config key each one lands in — so the
|
||||||
# names are the ones in infra/board/.env.example; the sentence is what stops
|
# value actually in force is read from the app rather than restated here, where
|
||||||
# working. Checked against os.environ because the container cannot read
|
# the two could disagree.
|
||||||
# /srv/board/.env — compose substitutes it in and the file never arrives.
|
#
|
||||||
|
# The third column separates the two facts this panel used to merge: **absent
|
||||||
|
# and nothing works** from **absent and defaulted**. `CONTENT_REPO` is unset on
|
||||||
|
# the real server and publishing works, because app.py defaults it; reporting
|
||||||
|
# that as a problem is how a page full of orange teaches you to ignore orange.
|
||||||
|
# A config key of None means there is no fallback and the feature is simply off.
|
||||||
|
#
|
||||||
|
# Checked against os.environ because the container cannot read /srv/board/.env —
|
||||||
|
# compose substitutes it in and the file itself never arrives.
|
||||||
EXPECTED = (
|
EXPECTED = (
|
||||||
("BOARD_SECRET_KEY", "las sesiones (sin esto la app no arranca)"),
|
("BOARD_SECRET_KEY", "las sesiones (sin esto la app no arranca)", None),
|
||||||
("CONTENT_TOKEN", "publicar en el sitio: el editor y la marca"),
|
("CONTENT_TOKEN", "publicar en el sitio: el editor y la marca", None),
|
||||||
("MAIL_HOST", "invitaciones y recuperar contraseña"),
|
("MAIL_HOST", "invitaciones y recuperar contraseña", None),
|
||||||
("MAIL_USER", "autenticarse en el servidor de correo"),
|
("MAIL_USER", "autenticarse en el servidor de correo", None),
|
||||||
("MAIL_PASSWORD", "autenticarse en el servidor de correo"),
|
("MAIL_PASSWORD", "autenticarse en el servidor de correo", None),
|
||||||
("BOARD_OWNER", "sembrar al superadministrador en el primer arranque"),
|
("BOARD_OWNER", "sembrar al superadministrador en el primer arranque", None),
|
||||||
("GITEA_URL", "hablar con el servidor de git"),
|
("GITEA_URL", "hablar con el servidor de git", "GITEA_URL"),
|
||||||
("CONTENT_REPO", "saber en qué repositorio se publica"),
|
("CONTENT_REPO", "saber en qué repositorio se publica", "CONTENT_REPO"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -150,12 +163,30 @@ def _disk() -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def _settings() -> dict:
|
def _settings() -> dict:
|
||||||
missing = [(name, why) for name, why in EXPECTED if not os.environ.get(name)]
|
"""Which expected settings the container does not have, and whether it
|
||||||
if not missing:
|
matters — which are two different questions."""
|
||||||
return _ok("Todos los ajustes esperados están puestos")
|
missing, defaulted = [], []
|
||||||
|
for name, why, key in EXPECTED:
|
||||||
|
if os.environ.get(name):
|
||||||
|
continue
|
||||||
|
if key:
|
||||||
|
defaulted.append(f"{name} — usando «{current_app.config.get(key)}» "
|
||||||
|
"(valor por defecto)")
|
||||||
|
else:
|
||||||
|
missing.append(f"{name} — {why}")
|
||||||
|
|
||||||
|
detail = "; ".join(missing + defaulted)
|
||||||
|
if missing:
|
||||||
return _warn(
|
return _warn(
|
||||||
f"{len(missing)} ajuste{'s' if len(missing) > 1 else ''} sin poner",
|
f"{len(missing)} ajuste{'s' if len(missing) > 1 else ''} sin poner",
|
||||||
"; ".join(f"{name} — {why}" for name, why in missing))
|
detail)
|
||||||
|
if defaulted:
|
||||||
|
# Green: nothing is broken. The values are still named, because "it
|
||||||
|
# works and here is the value it is working with" is the answer, and
|
||||||
|
# silence would leave somebody wondering which repository it publishes
|
||||||
|
# to.
|
||||||
|
return _ok("Todos los ajustes necesarios están puestos", detail)
|
||||||
|
return _ok("Todos los ajustes esperados están puestos")
|
||||||
|
|
||||||
|
|
||||||
def _counts() -> dict:
|
def _counts() -> dict:
|
||||||
|
|||||||
@ -30,7 +30,7 @@ from datetime import date as date_type
|
|||||||
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
||||||
render_template, request, send_from_directory, url_for)
|
render_template, request, send_from_directory, url_for)
|
||||||
|
|
||||||
from . import activity, content, gitea, uploads
|
from . import activity, content, gitea, titles, uploads
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .render import excerpt, to_html
|
from .render import excerpt, to_html
|
||||||
from .security import is_at_least, login_required, moderator_required
|
from .security import is_at_least, login_required, moderator_required
|
||||||
@ -97,12 +97,22 @@ def _read_proposal() -> tuple[dict, list[str]]:
|
|||||||
"title": request.form.get("title", "").strip()[:TITLE_MAX],
|
"title": request.form.get("title", "").strip()[:TITLE_MAX],
|
||||||
"body": request.form.get("body", "").strip()[:BODY_MAX],
|
"body": request.form.get("body", "").strip()[:BODY_MAX],
|
||||||
"description": request.form.get("description", "").strip()[:300],
|
"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:
|
# 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.
|
# a member's event and a moderator's have to produce the same post.
|
||||||
**content.read_event_fields(request.form, errors),
|
**content.read_event_fields(request.form, errors),
|
||||||
}
|
}
|
||||||
if not fields["title"]:
|
if not fields["title"]:
|
||||||
errors.append("El título no puede estar vacío.")
|
# Not an error: a proposal without a headline is named when it is sent,
|
||||||
|
# the same way a thread is. See titles.py.
|
||||||
|
rows = get_db().execute(
|
||||||
|
"SELECT title FROM submissions WHERE title LIKE ?",
|
||||||
|
(titles.UNTITLED + "%",)).fetchall()
|
||||||
|
fields["title"] = titles.next_untitled(row["title"] for row in rows)
|
||||||
if not fields["body"]:
|
if not fields["body"]:
|
||||||
errors.append("El texto no puede estar vacío.")
|
errors.append("El texto no puede estar vacío.")
|
||||||
return fields, errors
|
return fields, errors
|
||||||
@ -176,11 +186,12 @@ def propose():
|
|||||||
get_db().execute(
|
get_db().execute(
|
||||||
"""INSERT INTO submissions
|
"""INSERT INTO submissions
|
||||||
(author_id, title, body_md, description, photo_name,
|
(author_id, title, body_md, description, photo_name,
|
||||||
event_date, event_time, event_location)
|
event_date, event_time, event_location, ai_generated)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
(g.member["id"], fields["title"], fields["body"], fields["description"],
|
(g.member["id"], fields["title"], fields["body"], fields["description"],
|
||||||
photo_name,
|
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")
|
flash("Enviado. Un moderador lo leerá antes de publicarlo.", "ok")
|
||||||
return redirect(url_for("submissions.index"))
|
return redirect(url_for("submissions.index"))
|
||||||
@ -242,13 +253,15 @@ def edit(submission_id: int):
|
|||||||
"""UPDATE submissions
|
"""UPDATE submissions
|
||||||
SET title = ?, body_md = ?, description = ?,
|
SET title = ?, body_md = ?, description = ?,
|
||||||
photo_name = ?, event_date = ?, event_time = ?,
|
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,
|
reviewed_by = NULL, reviewed_at = NULL,
|
||||||
updated_at = datetime('now')
|
updated_at = datetime('now')
|
||||||
WHERE id = ?""",
|
WHERE id = ?""",
|
||||||
(fields["title"], fields["body"], fields["description"],
|
(fields["title"], fields["body"], fields["description"],
|
||||||
photo_name, fields["event_date"],
|
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
|
# 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
|
# rejected post that has been rewritten is waiting again, and leaving it
|
||||||
@ -322,6 +335,10 @@ def approve(submission_id: int):
|
|||||||
"event_date": row["event_date"] or "",
|
"event_date": row["event_date"] or "",
|
||||||
"event_time": row["event_time"] or "",
|
"event_time": row["event_time"] or "",
|
||||||
"event_location": row["event_location"] 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
|
# 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
|
# it says. The first version wrapped everything in `except OSError`, which
|
||||||
|
|||||||
@ -25,6 +25,13 @@
|
|||||||
<a href="{{ url_for('events.month', mes=this_month) }}">Ir a este mes</a>
|
<a href="{{ url_for('events.month', mes=this_month) }}">Ir a este mes</a>
|
||||||
</p>
|
</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">
|
<table class="cal">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>{% for day in weekdays %}<th scope="col">{{ day }}</th>{% endfor %}</tr>
|
<tr>{% for day in weekdays %}<th scope="col">{{ day }}</th>{% endfor %}</tr>
|
||||||
@ -39,7 +46,18 @@
|
|||||||
<td class="cal__pad"></td>
|
<td class="cal__pad"></td>
|
||||||
{% else %}
|
{% else %}
|
||||||
<td class="cal__day {{ 'cal__day--today' if day == today }}">
|
<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 class="cal__number">{{ day }}</span>
|
||||||
|
</span>
|
||||||
|
<span class="cal__events">
|
||||||
{% for item in by_day.get(day, []) %}
|
{% for item in by_day.get(day, []) %}
|
||||||
<a class="cal__event {{ 'cal__event--public' if item.public }}"
|
<a class="cal__event {{ 'cal__event--public' if item.public }}"
|
||||||
href="{{ item.url }}">
|
href="{{ item.url }}">
|
||||||
@ -47,6 +65,7 @@
|
|||||||
{% if item.public %}<span class="tag tag--quiet">público</span>{% endif %}
|
{% if item.public %}<span class="tag tag--quiet">público</span>{% endif %}
|
||||||
</a>
|
</a>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
</span>
|
||||||
{% if may_edit %}
|
{% if may_edit %}
|
||||||
{# The day is carried into the form, so adding something to the
|
{# The day is carried into the form, so adding something to the
|
||||||
24th starts with the 24th already filled in. #}
|
24th starts with the 24th already filled in. #}
|
||||||
|
|||||||
@ -8,10 +8,15 @@
|
|||||||
|
|
||||||
<label for="body">Mensaje</label>
|
<label for="body">Mensaje</label>
|
||||||
<textarea id="body" data-markdown name="body" rows="10" required>{{ comment.body_md }}</textarea>
|
<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">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">Guardar</button>
|
<button class="btn" type="submit">Guardar</button>
|
||||||
<a class="linkish" href="{{ url_for('board.thread', thread_id=comment.thread_id) }}">Cancelar</a>
|
<a class="btn btn--quiet" href="{{ url_for('board.thread', thread_id=comment.thread_id) }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@ -30,7 +30,7 @@
|
|||||||
<h1>{{ ('Editar ' ~ meta.singular|lower) if item else meta.new_label }}</h1>
|
<h1>{{ ('Editar ' ~ meta.singular|lower) if item else meta.new_label }}</h1>
|
||||||
|
|
||||||
<label for="title">Título</label>
|
<label for="title">Título</label>
|
||||||
<input id="title" name="title" maxlength="140" required value="{{ f.title or '' }}">
|
<input id="title" name="title" maxlength="140" value="{{ f.title or '' }}">
|
||||||
|
|
||||||
{% if meta.dated %}
|
{% if meta.dated %}
|
||||||
<label for="date">Fecha</label>
|
<label for="date">Fecha</label>
|
||||||
@ -69,8 +69,12 @@
|
|||||||
{# An event's own date, which is not the day the post goes up. The date is
|
{# An event's own date, which is not the day the post goes up. The date is
|
||||||
also what makes this post an event: there is nothing to tick first, so
|
also what makes this post an event: there is nothing to tick first, so
|
||||||
there is no way to say "this is an event" and then not say when. #}
|
there is no way to say "this is an event" and then not say when. #}
|
||||||
<fieldset class="fieldset">
|
{#- A fold rather than a fieldset: most posts are not events, and six
|
||||||
<legend>Si es un evento</legend>
|
inches of date pickers between the title and the text is six inches
|
||||||
|
most people scroll past. Open by itself when the post already has a
|
||||||
|
date, so editing an event does not hide the thing being edited. -#}
|
||||||
|
<details class="fold" {{ 'open' if f.event_date }}>
|
||||||
|
<summary>Si es un evento <span class="muted small">(fecha, hora, lugar)</span></summary>
|
||||||
<p class="muted small">
|
<p class="muted small">
|
||||||
Pon la fecha y será un evento: aparecerá en la agenda del sitio, con el
|
Pon la fecha y será un evento: aparecerá en la agenda del sitio, con el
|
||||||
día y el lugar destacados, y se podrá añadir al calendario del móvil.
|
día y el lugar destacados, y se podrá añadir al calendario del móvil.
|
||||||
@ -88,7 +92,7 @@
|
|||||||
<input id="event_location" name="event_location" maxlength="200"
|
<input id="event_location" name="event_location" maxlength="200"
|
||||||
value="{{ f.event_location or '' }}">
|
value="{{ f.event_location or '' }}">
|
||||||
<p class="muted small">Dónde es: el sitio, la calle, el barrio.</p>
|
<p class="muted small">Dónde es: el sitio, la calle, el barrio.</p>
|
||||||
</fieldset>
|
</details>
|
||||||
|
|
||||||
<label for="description">Resumen</label>
|
<label for="description">Resumen</label>
|
||||||
<textarea id="description" name="description" rows="2">{{ f.description or '' }}</textarea>
|
<textarea id="description" name="description" rows="2">{{ f.description or '' }}</textarea>
|
||||||
@ -114,8 +118,13 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<label for="body">Cuerpo</label>
|
<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>
|
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>
|
<label for="faq">Preguntas frecuentes <span class="muted small">(opcional)</span></label>
|
||||||
<textarea id="faq" name="faq" rows="5"
|
<textarea id="faq" name="faq" rows="5"
|
||||||
@ -133,11 +142,25 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">{{ 'Guardar' if item else 'Publicar' }}</button>
|
<button class="btn" type="submit">{{ 'Guardar' if item else 'Publicar' }}</button>
|
||||||
<button class="linkish" type="submit"
|
{#- 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="toggle">
|
||||||
|
<input type="checkbox" name="ai_generated" {{ 'checked' if f.ai_generated }}>
|
||||||
|
{#- The switch itself is drawn by board.css from the checkbox's own
|
||||||
|
state. No script: a control that needs one is a control that
|
||||||
|
does nothing under this Content-Security-Policy. -#}
|
||||||
|
<span class="toggle__track" aria-hidden="true"></span>
|
||||||
|
<span class="toggle__text">Contenido generado con IA</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{#- Beside Cancelar and shaped like it: both are things you press in this
|
||||||
|
row, and a bare link wedged between two buttons reads as unfinished. -#}
|
||||||
|
<button class="btn btn--quiet" type="submit"
|
||||||
formaction="{{ url_for('content.preview', collection=collection) }}">
|
formaction="{{ url_for('content.preview', collection=collection) }}">
|
||||||
Vista previa
|
Vista previa
|
||||||
</button>
|
</button>
|
||||||
<a class="linkish" href="{{ url_for('content.index', collection=collection) }}">Cancelar</a>
|
<a class="btn btn--quiet" href="{{ url_for('content.index', collection=collection) }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@ -29,12 +29,15 @@
|
|||||||
<td>
|
<td>
|
||||||
<a href="{{ url_for('content.edit', collection=collection, name=item.name) }}">{{ item.title }}</a>
|
<a href="{{ url_for('content.edit', collection=collection, name=item.name) }}">{{ item.title }}</a>
|
||||||
<div class="muted small mono">{{ item.name }}</div>
|
<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>
|
</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
|
{# 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
|
one thing left that changes what a post is, and it is what a
|
||||||
moderator scanning this list is looking for. #}
|
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
|
{# 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
|
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
|
table cell: it leaves the row's layout and draws its bottom border
|
||||||
|
|||||||
@ -33,8 +33,13 @@
|
|||||||
<input id="location" name="location" maxlength="200" value="{{ (f.location if f else '') or '' }}">
|
<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>
|
<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>
|
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>
|
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>
|
||||||
<input id="picture" name="picture" type="file" accept="image/*">
|
<input id="picture" name="picture" type="file" accept="image/*">
|
||||||
@ -44,7 +49,7 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">Guardar</button>
|
<button class="btn" type="submit">Guardar</button>
|
||||||
<a class="linkish" href="{{ url_for('events.month') }}">Cancelar</a>
|
<a class="btn btn--quiet" href="{{ url_for('events.month') }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@ -43,7 +43,7 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">Dar de alta</button>
|
<button class="btn" type="submit">Dar de alta</button>
|
||||||
<a class="linkish" href="{{ url_for('members.index') }}">Cancelar</a>
|
<a class="btn btn--quiet" href="{{ url_for('members.index') }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@ -21,6 +21,11 @@
|
|||||||
<label for="bio">Sobre ti</label>
|
<label for="bio">Sobre ti</label>
|
||||||
<textarea id="bio" data-markdown name="bio" rows="8"
|
<textarea id="bio" data-markdown name="bio" rows="8"
|
||||||
placeholder="Se puede usar Markdown.">{{ g.member.bio or '' }}</textarea>
|
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>
|
<label for="links">Enlaces</label>
|
||||||
<textarea id="links" name="links" rows="5"
|
<textarea id="links" name="links" rows="5"
|
||||||
|
|||||||
@ -41,7 +41,7 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">Enviar enlace</button>
|
<button class="btn" type="submit">Enviar enlace</button>
|
||||||
<a class="linkish" href="{{ url_for('auth.login') }}">Cancelar</a>
|
<a class="btn btn--quiet" href="{{ url_for('auth.login') }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@ -13,6 +13,9 @@
|
|||||||
<span class="tag tag--{{ item.state }}">{{ labels[item.state] }}</span>
|
<span class="tag tag--{{ item.state }}">{{ labels[item.state] }}</span>
|
||||||
<span>{{ person(item.author, item.author_login) }}</span> · <time>{{ item.created_at }}</time>
|
<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 %}
|
{% 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>
|
</div>
|
||||||
{% if item.description %}<p class="muted">{{ item.description }}</p>{% endif %}
|
{% if item.description %}<p class="muted">{{ item.description }}</p>{% endif %}
|
||||||
{% if item.photo_name %}
|
{% if item.photo_name %}
|
||||||
|
|||||||
@ -16,7 +16,7 @@
|
|||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
|
||||||
<label for="title">Título</label>
|
<label for="title">Título</label>
|
||||||
<input id="title" name="title" type="text" required maxlength="140"
|
<input id="title" name="title" type="text" maxlength="140"
|
||||||
value="{{ fields.title if fields else '' }}">
|
value="{{ fields.title if fields else '' }}">
|
||||||
|
|
||||||
<label for="description">Resumen <span class="muted small">(opcional)</span></label>
|
<label for="description">Resumen <span class="muted small">(opcional)</span></label>
|
||||||
@ -27,8 +27,12 @@
|
|||||||
{# An event's own date, which is not the day the post goes up. The date is
|
{# An event's own date, which is not the day the post goes up. The date is
|
||||||
also what makes this an event: there is nothing to tick first, so there is
|
also what makes this an event: there is nothing to tick first, so there is
|
||||||
no way to say "this is an event" and then not say when. #}
|
no way to say "this is an event" and then not say when. #}
|
||||||
<fieldset class="fieldset">
|
{#- A fold rather than a fieldset: most posts are not events, and six
|
||||||
<legend>Si es un evento</legend>
|
inches of date pickers between the title and the text is six inches
|
||||||
|
most people scroll past. Open by itself when the post already has a
|
||||||
|
date, so editing an event does not hide the thing being edited. -#}
|
||||||
|
<details class="fold" {{ 'open' if fields.event_date }}>
|
||||||
|
<summary>Si es un evento <span class="muted small">(fecha, hora, lugar)</span></summary>
|
||||||
<p class="muted small">
|
<p class="muted small">
|
||||||
Pon la fecha y será un evento: aparecerá en la agenda del sitio, con el
|
Pon la fecha y será un evento: aparecerá en la agenda del sitio, con el
|
||||||
día y el lugar destacados. Déjala vacía y es un artículo normal.
|
día y el lugar destacados. Déjala vacía y es un artículo normal.
|
||||||
@ -45,11 +49,16 @@
|
|||||||
<input id="event_location" name="event_location" maxlength="200"
|
<input id="event_location" name="event_location" maxlength="200"
|
||||||
value="{{ fields.event_location or '' }}">
|
value="{{ fields.event_location or '' }}">
|
||||||
<p class="muted small">Dónde es: el sitio, la calle, el barrio.</p>
|
<p class="muted small">Dónde es: el sitio, la calle, el barrio.</p>
|
||||||
</fieldset>
|
</details>
|
||||||
|
|
||||||
<label for="body">Texto</label>
|
<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>
|
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>
|
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>
|
||||||
<input id="picture" name="picture" type="file" accept="image/*">
|
<input id="picture" name="picture" type="file" accept="image/*">
|
||||||
@ -61,7 +70,19 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">{{ 'Guardar' if item else 'Enviar a revisión' }}</button>
|
<button class="btn" type="submit">{{ 'Guardar' if item else 'Enviar a revisión' }}</button>
|
||||||
<a class="linkish" href="{{ url_for('submissions.index') }}">Cancelar</a>
|
{#- 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="toggle">
|
||||||
|
<input type="checkbox" name="ai_generated" {{ 'checked' if (fields.ai_generated if fields else False) }}>
|
||||||
|
{#- The switch itself is drawn by board.css from the checkbox's own
|
||||||
|
state. No script: a control that needs one is a control that
|
||||||
|
does nothing under this Content-Security-Policy. -#}
|
||||||
|
<span class="toggle__track" aria-hidden="true"></span>
|
||||||
|
<span class="toggle__text">Contenido generado con IA</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<a class="btn btn--quiet" href="{{ url_for('submissions.index') }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@ -9,6 +9,7 @@
|
|||||||
<div class="card__meta">
|
<div class="card__meta">
|
||||||
{% if thread.pinned %}<span class="tag">Fijado</span>{% endif %}
|
{% if thread.pinned %}<span class="tag">Fijado</span>{% endif %}
|
||||||
{% if thread.locked %}<span class="tag tag--quiet">Cerrado</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>
|
<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 %}
|
{% if thread.edited_at %}<span class="muted small">(editado)</span>{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -8,12 +8,17 @@
|
|||||||
<h1>{{ 'Editar tema' if thread else 'Nuevo tema' }}</h1>
|
<h1>{{ 'Editar tema' if thread else 'Nuevo tema' }}</h1>
|
||||||
|
|
||||||
<label for="title">Título</label>
|
<label for="title">Título</label>
|
||||||
<input id="title" name="title" maxlength="140" required
|
<input id="title" name="title" maxlength="140"
|
||||||
value="{{ thread.title if thread else '' }}">
|
value="{{ thread.title if thread else '' }}">
|
||||||
|
|
||||||
<label for="body">Mensaje</label>
|
<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>
|
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,
|
{# 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
|
and an input that silently does nothing is worse than no input. Photos
|
||||||
@ -25,7 +30,19 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn" type="submit">{{ 'Guardar' if thread else 'Publicar' }}</button>
|
<button class="btn" type="submit">{{ 'Guardar' if thread else 'Publicar' }}</button>
|
||||||
<a class="linkish" href="{{ url_for('board.thread', thread_id=thread.id) if thread else url_for('board.threads') }}">Cancelar</a>
|
{#- 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="toggle">
|
||||||
|
<input type="checkbox" name="ai_generated" {{ 'checked' if (thread.ai_generated if thread else False) }}>
|
||||||
|
{#- The switch itself is drawn by board.css from the checkbox's own
|
||||||
|
state. No script: a control that needs one is a control that
|
||||||
|
does nothing under this Content-Security-Policy. -#}
|
||||||
|
<span class="toggle__track" aria-hidden="true"></span>
|
||||||
|
<span class="toggle__text">Contenido generado con IA</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<a class="btn btn--quiet" href="{{ url_for('board.thread', thread_id=thread.id) if thread else url_for('board.threads') }}">Cancelar</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@ -20,6 +20,7 @@
|
|||||||
<div class="card__meta">
|
<div class="card__meta">
|
||||||
{% if t.pinned %}<span class="tag">Fijado</span>{% endif %}
|
{% if t.pinned %}<span class="tag">Fijado</span>{% endif %}
|
||||||
{% if t.locked %}<span class="tag tag--quiet">Cerrado</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>
|
<span>{{ person(t.author, t.author_login) }}</span> · <time>{{ t.created_at }}</time>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="card__title">
|
<h2 class="card__title">
|
||||||
|
|||||||
46
apps/board/tests/serialize_harness.js
Normal file
46
apps/board/tests/serialize_harness.js
Normal 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));
|
||||||
|
});
|
||||||
@ -145,3 +145,100 @@ def test_the_preview_is_never_cached(post, make_member, sign_in):
|
|||||||
sign_in(make_member("maria"))
|
sign_in(make_member("maria"))
|
||||||
response = post("/comunidad/previsualizar", {"body": "hola"})
|
response = post("/comunidad/previsualizar", {"body": "hola"})
|
||||||
assert response.headers["Cache-Control"] == "no-store"
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
# --- a post nobody titled -------------------------------------------------
|
||||||
|
|
||||||
|
def test_a_thread_with_no_title_gets_one(client, post, make_member, sign_in):
|
||||||
|
"""Asking for a headline before a sentence is how a form stops somebody
|
||||||
|
writing. The ones people leave blank are often the best writing on a
|
||||||
|
wall — somebody answering a question, somebody saying a thing happened."""
|
||||||
|
sign_in(make_member("maria"))
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Ya está arreglado, gracias."})
|
||||||
|
|
||||||
|
page = client.get("/comunidad/tema/1").get_data(as_text=True)
|
||||||
|
assert "Sin Título" in page
|
||||||
|
assert "Ya está arreglado" in page
|
||||||
|
|
||||||
|
|
||||||
|
def test_untitled_threads_are_numbered_so_they_can_be_told_apart(
|
||||||
|
client, post, make_member, sign_in):
|
||||||
|
sign_in(make_member("maria"))
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Uno."})
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Dos."})
|
||||||
|
post("/comunidad/nuevo", {"title": "Con título", "body": "Tres."})
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Cuatro."})
|
||||||
|
|
||||||
|
wall = client.get("/comunidad/muro").get_data(as_text=True)
|
||||||
|
for expected in ("Sin Título", "Sin Título 2", "Sin Título 3"):
|
||||||
|
assert expected in wall
|
||||||
|
assert "Sin Título 4" not in wall
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_deleted_untitled_thread_does_not_give_its_number_back(
|
||||||
|
client, post, db, make_member, sign_in):
|
||||||
|
"""A number that comes back is a thread that looks like one somebody
|
||||||
|
remembers reading. The soft-deleted row keeps its title, and counting it
|
||||||
|
is what prevents that."""
|
||||||
|
sign_in(make_member("maria"))
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Uno."})
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Dos."})
|
||||||
|
post("/comunidad/tema/2/eliminar")
|
||||||
|
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Tres."})
|
||||||
|
titles = [row["title"] for row in db.execute("SELECT title FROM threads ORDER BY id")]
|
||||||
|
assert titles == ["Sin Título", "Sin Título 2", "Sin Título 3"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_title_that_only_looks_numbered_is_left_alone(client, post, db,
|
||||||
|
make_member, sign_in):
|
||||||
|
sign_in(make_member("maria"))
|
||||||
|
post("/comunidad/nuevo", {"title": "Sin Título ni ganas", "body": "Uno."})
|
||||||
|
post("/comunidad/nuevo", {"title": "", "body": "Dos."})
|
||||||
|
titles = [row["title"] for row in db.execute("SELECT title FROM threads ORDER BY id")]
|
||||||
|
assert titles == ["Sin Título ni ganas", "Sin Título"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_thread_still_needs_something_to_say(client, post, make_member, sign_in):
|
||||||
|
"""The title is optional; the message is the post."""
|
||||||
|
sign_in(make_member("maria"))
|
||||||
|
post("/comunidad/nuevo", {"title": "Solo el título", "body": " "})
|
||||||
|
assert client.get("/comunidad/tema/1").status_code == 404
|
||||||
|
|||||||
@ -629,3 +629,132 @@ def test_an_event_keeps_its_date_when_edited(repo, editor, post, client):
|
|||||||
front = yaml.safe_load(
|
front = yaml.safe_load(
|
||||||
repo.files["content/post/2026-10-03-feria.es.md"].decode().split("---")[1])
|
repo.files["content/post/2026-10-03-feria.es.md"].decode().split("---")[1])
|
||||||
assert front["event_date"] == "2026-10-24"
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# --- a post nobody titled -------------------------------------------------
|
||||||
|
|
||||||
|
def test_an_untitled_post_is_named_when_it_is_published(repo, editor, post):
|
||||||
|
publish(post, title="")
|
||||||
|
path, = repo.files
|
||||||
|
assert path == "content/post/2026-09-25-sin-titulo.es.md"
|
||||||
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
||||||
|
assert fm["title"] == "Sin Título"
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_untitled_posts_on_one_day_do_not_collide(repo, editor, post):
|
||||||
|
"""The filename is what collides in a repository, not the title: both
|
||||||
|
would be `<fecha>-sin-titulo.es.md`, and the second would come back as
|
||||||
|
"somebody else saved this file while you were editing it" — a message
|
||||||
|
about a conflict that never happened. So the numbering is done against
|
||||||
|
the names already in the folder."""
|
||||||
|
publish(post, title="")
|
||||||
|
publish(post, title="")
|
||||||
|
assert sorted(repo.files) == [
|
||||||
|
"content/post/2026-09-25-sin-titulo-2.es.md",
|
||||||
|
"content/post/2026-09-25-sin-titulo.es.md",
|
||||||
|
]
|
||||||
|
fm, _ = translate.split_frontmatter(
|
||||||
|
repo.files["content/post/2026-09-25-sin-titulo-2.es.md"].decode())
|
||||||
|
assert fm["title"] == "Sin Título 2"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_same_name_is_free_again_on_another_day(repo, editor, post):
|
||||||
|
"""A dated collection only collides within its own day, so the number
|
||||||
|
starts over rather than counting up forever."""
|
||||||
|
publish(post, title="", date="2026-09-25")
|
||||||
|
publish(post, title="", date="2026-10-25")
|
||||||
|
assert sorted(repo.files) == [
|
||||||
|
"content/post/2026-09-25-sin-titulo.es.md",
|
||||||
|
"content/post/2026-10-25-sin-titulo.es.md",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_clearing_the_title_on_an_edit_does_not_walk_the_number_up(
|
||||||
|
repo, editor, post):
|
||||||
|
"""The post being edited must not count as the collision it has to avoid,
|
||||||
|
or every save would rename it one higher."""
|
||||||
|
publish(post, title="")
|
||||||
|
path, = repo.files
|
||||||
|
name = path.rsplit("/", 1)[1]
|
||||||
|
for _ in range(3):
|
||||||
|
post(f"/comunidad/contenido/post/editar/{name}",
|
||||||
|
{"title": "", "body": "Otra corrección.", "date": "2026-09-25",
|
||||||
|
"sha": repo._sha(repo.files[path])})
|
||||||
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
||||||
|
assert fm["title"] == "Sin Título"
|
||||||
|
assert list(repo.files) == [path]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_post_still_needs_a_body(repo, editor, post):
|
||||||
|
response = publish(post, title="", body="")
|
||||||
|
assert not repo.files
|
||||||
|
assert "cuerpo no puede estar vacío" in response.get_data(as_text=True)
|
||||||
|
|||||||
205
apps/board/tests/test_editor.py
Normal file
205
apps/board/tests/test_editor.py
Normal 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}"
|
||||||
@ -9,6 +9,7 @@ easy to get subtly wrong and hard to notice.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import pytest
|
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
|
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 ------------------------------------
|
# --- what the git server does to this ------------------------------------
|
||||||
|
|
||||||
def test_the_private_events_survive_a_git_server_that_is_down(
|
def test_the_private_events_survive_a_git_server_that_is_down(
|
||||||
|
|||||||
@ -440,3 +440,50 @@ def test_a_second_superadmin_is_not_seeded_over_the_first(tmp_path):
|
|||||||
assert db.execute(
|
assert db.execute(
|
||||||
"SELECT COUNT(*) FROM members WHERE gitea_login = 'intruso'").fetchone()[0] == 0
|
"SELECT COUNT(*) FROM members WHERE gitea_login = 'intruso'").fetchone()[0] == 0
|
||||||
db.close()
|
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()
|
||||||
|
|||||||
@ -501,3 +501,71 @@ def test_a_proposal_with_a_nonsense_event_date_is_refused(db, post, maria, sign_
|
|||||||
|
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_untitled_proposal_is_named_rather_than_refused(db, post, maria, sign_in):
|
||||||
|
"""Same rule as the wall: the text is the post, the headline is optional."""
|
||||||
|
sign_in(maria)
|
||||||
|
propose(post, title="")
|
||||||
|
assert only_submission(db)["title"] == "Sin Título"
|
||||||
|
|
||||||
|
|
||||||
|
def test_untitled_proposals_are_numbered(db, post, maria, sign_in):
|
||||||
|
sign_in(maria)
|
||||||
|
propose(post, title="")
|
||||||
|
propose(post, title="")
|
||||||
|
rows = [row["title"] for row in
|
||||||
|
db.execute("SELECT title FROM submissions ORDER BY id")]
|
||||||
|
assert rows == ["Sin Título", "Sin Título 2"]
|
||||||
|
|||||||
@ -211,8 +211,8 @@ def test_the_form_rule_is_an_exclusion_and_not_a_list_of_accepted_types():
|
|||||||
|
|
||||||
# --- the theme's own chrome -----------------------------------------------
|
# --- the theme's own chrome -----------------------------------------------
|
||||||
#
|
#
|
||||||
# These two read the Hugo theme rather than the members area, which no other
|
# These read the Hugo theme rather than the members area, which no other test
|
||||||
# test here does. They are here because the bug they guard against is this
|
# 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
|
# 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.
|
# 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")
|
header = (THEME / "layouts" / "partials" / "header.html").read_text(encoding="utf-8")
|
||||||
bar = header.split('<nav class="site-bar__pages"')[0]
|
bar = header.split('<nav class="site-bar__pages"')[0]
|
||||||
assert "site-bar__cta" in bar and "/comunidad/" in bar
|
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")
|
||||||
|
|||||||
@ -258,3 +258,89 @@ def test_the_status_screen_counts_what_is_there(client, db, boss, make_member, r
|
|||||||
|
|
||||||
assert "3 miembros" in body # the superadministrator and the two
|
assert "3 miembros" in body # the superadministrator and the two
|
||||||
assert "2 con algún cargo" in body # superadministrator + moderator
|
assert "2 con algún cargo" in body # superadministrator + moderator
|
||||||
|
|
||||||
|
|
||||||
|
# --- the status screen tells the truth about the container it is in --------
|
||||||
|
|
||||||
|
def test_the_backup_check_reads_a_path_the_container_can_see(tmp_path, monkeypatch):
|
||||||
|
"""The bug this file gained a section for.
|
||||||
|
|
||||||
|
`BACKUP_DIR` was `/srv/board/backups` — a **host** path, read from inside a
|
||||||
|
container that mounts only `./data`. On the real server it reported "no hay
|
||||||
|
carpeta de copias" twenty seconds after `deploy-board.sh` had written one.
|
||||||
|
The compose file now mounts the folder read-only at `/backups`, and this
|
||||||
|
asserts the constant points at the mount rather than at the host.
|
||||||
|
"""
|
||||||
|
from apps.board import status
|
||||||
|
assert status.BACKUP_DIR == "/backups", (
|
||||||
|
"BACKUP_DIR must be the path inside the container, not the host's — "
|
||||||
|
"see infra/board/docker-compose.yml")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_backup_is_found_reported_and_dated(app, tmp_path, monkeypatch):
|
||||||
|
from apps.board import status
|
||||||
|
folder = tmp_path / "backups"
|
||||||
|
folder.mkdir()
|
||||||
|
(folder / "board-20261006-030000.db.gz").write_bytes(b"x" * 4096)
|
||||||
|
monkeypatch.setattr(status, "BACKUP_DIR", str(folder))
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
check = status._backups()
|
||||||
|
|
||||||
|
assert check["state"] == "ok"
|
||||||
|
assert "board-20261006-030000.db.gz" in check["detail"]
|
||||||
|
assert "4 KB" in check["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_empty_backup_folder_is_the_real_alarm(app, tmp_path, monkeypatch):
|
||||||
|
"""The folder existing and holding nothing is the state worth shouting
|
||||||
|
about — unlike the folder simply not being visible, which was mine."""
|
||||||
|
from apps.board import status
|
||||||
|
folder = tmp_path / "backups"
|
||||||
|
folder.mkdir()
|
||||||
|
monkeypatch.setattr(status, "BACKUP_DIR", str(folder))
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
assert status._backups()["state"] == "bad"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_setting_with_a_fallback_is_not_reported_as_missing(app, monkeypatch):
|
||||||
|
"""`CONTENT_REPO` is unset on the real server and publishing works, because
|
||||||
|
app.py defaults it. Reporting that as a problem is how a panel full of
|
||||||
|
orange teaches somebody to ignore orange.
|
||||||
|
|
||||||
|
The ones with no fallback are set here so that the only thing left absent is
|
||||||
|
the defaulted one — which is the state the real server is in."""
|
||||||
|
from apps.board import status
|
||||||
|
for name, _why, key in status.EXPECTED:
|
||||||
|
if key is None:
|
||||||
|
monkeypatch.setenv(name, "puesto")
|
||||||
|
monkeypatch.delenv("CONTENT_REPO", raising=False)
|
||||||
|
|
||||||
|
with app.test_request_context():
|
||||||
|
check = status._settings()
|
||||||
|
|
||||||
|
assert check["state"] == "ok"
|
||||||
|
assert "CONTENT_REPO" in check["detail"]
|
||||||
|
assert "por defecto" in check["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_setting_with_no_fallback_still_warns(app, monkeypatch):
|
||||||
|
monkeypatch.delenv("MAIL_HOST", raising=False)
|
||||||
|
from apps.board import status
|
||||||
|
with app.test_request_context():
|
||||||
|
check = status._settings()
|
||||||
|
|
||||||
|
assert check["state"] == "warn"
|
||||||
|
assert "MAIL_HOST" in check["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_expected_setting_names_a_real_config_key(app):
|
||||||
|
"""The third column is read back out of `current_app.config`, so a typo
|
||||||
|
would render «usando None» on the page rather than failing anywhere."""
|
||||||
|
from apps.board import status
|
||||||
|
with app.app_context():
|
||||||
|
for name, _why, key in status.EXPECTED:
|
||||||
|
if key:
|
||||||
|
assert key in app.config, (name, key)
|
||||||
|
assert app.config[key], (name, key)
|
||||||
|
|||||||
46
apps/board/titles.py
Normal file
46
apps/board/titles.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
"""The name a post gets when nobody gives it one.
|
||||||
|
|
||||||
|
A title is not required anywhere a member writes. Most things people post have
|
||||||
|
one, and the ones that do not are usually the best writing on a wall: somebody
|
||||||
|
answering a question, somebody saying a thing happened. Demanding a headline
|
||||||
|
first is how a form stops a person mid-sentence.
|
||||||
|
|
||||||
|
So an untitled post is called «Sin Título», and the second one is «Sin Título
|
||||||
|
2». The number is there to keep them apart — in a list of twenty threads, three
|
||||||
|
rows reading the same four characters are three rows nobody can tell apart or
|
||||||
|
link to with any confidence.
|
||||||
|
|
||||||
|
Numbers are never reused. A deleted thread keeps its title in the database, and
|
||||||
|
counting it is what stops a new post inheriting the name of one somebody
|
||||||
|
remembers reading.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
UNTITLED = "Sin Título"
|
||||||
|
|
||||||
|
# «Sin Título», «Sin Título 2». Anchored, so a post somebody deliberately
|
||||||
|
# called «Sin Título ni ganas» is not read as a number and does not take one.
|
||||||
|
NUMBERED = re.compile(r"^Sin Título(?:\s+(\d+))?$")
|
||||||
|
|
||||||
|
|
||||||
|
def next_untitled(taken: Iterable[str]) -> str:
|
||||||
|
"""The first «Sin Título» name not in `taken`.
|
||||||
|
|
||||||
|
`taken` is every title already in that place — the wall's threads, the
|
||||||
|
queue's proposals — including deleted ones, because a number that comes
|
||||||
|
back is a post that looks like a different post.
|
||||||
|
"""
|
||||||
|
used = set()
|
||||||
|
for title in taken:
|
||||||
|
match = NUMBERED.match((title or "").strip())
|
||||||
|
if match:
|
||||||
|
used.add(int(match.group(1) or 1))
|
||||||
|
|
||||||
|
number = 1
|
||||||
|
while number in used:
|
||||||
|
number += 1
|
||||||
|
return UNTITLED if number == 1 else f"{UNTITLED} {number}"
|
||||||
14
config.yaml
14
config.yaml
@ -120,6 +120,18 @@ sitemap:
|
|||||||
markup:
|
markup:
|
||||||
goldmark:
|
goldmark:
|
||||||
renderer:
|
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/
|
enableRobotsTXT: false # robots.txt is a static file in static/
|
||||||
|
|||||||
@ -39,6 +39,51 @@ Check propagation (repeat until it prints the server IP):
|
|||||||
local$ dig +short git.vienalatina.com
|
local$ dig +short git.vienalatina.com
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 1.1 A second domain that leads here
|
||||||
|
|
||||||
|
`vielac.at` is the second name, and it redirects: everything that arrives goes
|
||||||
|
to the same path on vienalatina.com. Two A records in that domain's **zone
|
||||||
|
editor**, both at the server:
|
||||||
|
|
||||||
|
| Name | Type | Value | TTL |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `@` | A | `<SERVER-IP>` | 300 |
|
||||||
|
| `www` | A | `<SERVER-IP>` | 300 |
|
||||||
|
|
||||||
|
**Not the nameserver page.** On Hetzner's Konsole H those fields hand the whole
|
||||||
|
zone to another provider's DNS, which is a different thing entirely and turns
|
||||||
|
off the zone editor you want. *Standard Nameserver eintragen*, save, then edit
|
||||||
|
the zone.
|
||||||
|
|
||||||
|
Then the block in `infra/caddy/Caddyfile`, which carries both spellings and
|
||||||
|
answers with a **301** — a permanent redirect is what folds the two names into
|
||||||
|
one site for a search engine rather than two copies of it, and `{uri}` keeps
|
||||||
|
the path so a shared link still lands where it was pointing.
|
||||||
|
|
||||||
|
**Order matters, and it is the same order as the cutover above**: the A records
|
||||||
|
go in first, because Caddy asks Let's Encrypt for the certificate the first time
|
||||||
|
the name resolves to this server. A reload before DNS has propagated is not
|
||||||
|
harmful — nothing reaches the block — but it does not get a certificate either,
|
||||||
|
so reload again afterwards.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo cp ~/vienalatina/infra/caddy/Caddyfile /etc/caddy/Caddyfile
|
||||||
|
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||||
|
sudo systemctl reload caddy
|
||||||
|
```
|
||||||
|
|
||||||
|
`validate` before every `reload`, without exception: it is the one command
|
||||||
|
between a typo in that file and vienalatina.com going down with it.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -sI https://vielac.at/ | head -3 # 301 → vienalatina.com
|
||||||
|
curl -sI https://www.vielac.at/page/agenda/ | grep -i location # the path survives
|
||||||
|
curl -sI https://vienalatina.com/ | head -1 # 200, unchanged
|
||||||
|
```
|
||||||
|
|
||||||
|
The third is the one that matters. A Caddyfile edit that breaks the site it was
|
||||||
|
meant to leave alone is the failure this ordering exists to prevent.
|
||||||
|
|
||||||
## 2. First login + basic hardening
|
## 2. First login + basic hardening
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@ -1034,17 +1079,102 @@ the `|` survives.
|
|||||||
### 11.17 Writing boxes
|
### 11.17 Writing boxes
|
||||||
|
|
||||||
Every box where somebody writes prose — the wall, a comment, a private message, a
|
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
|
proposal, the editor, a profile bio — shows the formatting while it is being
|
||||||
previa*, opted in with `data-markdown` and attached by `static/board.js`. The
|
typed. Bold is bold, a heading is a heading. Opted in with `data-markdown` and
|
||||||
preview POSTs to `/comunidad/previsualizar`, which renders with `render.to_html`:
|
attached by `static/board.js`; `data-rich="full"` on the four boxes that hold a
|
||||||
the same function the board and the site use, so the preview cannot promise
|
post adds the three heading levels, both kinds of list and the quote, and the
|
||||||
something publishing will not deliver. A markdown parser in the browser would be
|
rest get bold, italic, link and clear formatting.
|
||||||
a second opinion about what somebody's text means.
|
|
||||||
|
**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
|
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
|
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.
|
bytes already in the page, which reaches no network.
|
||||||
|
|
||||||
|
### 11.17a A title is optional
|
||||||
|
|
||||||
|
Nowhere a member writes insists on a headline — not the wall, not a proposal,
|
||||||
|
not the editor. The ones people leave blank are often the best writing on a
|
||||||
|
wall: somebody answering a question, somebody saying a thing happened. Asking
|
||||||
|
for a title first is how a form stops a person mid-sentence, and the field says
|
||||||
|
nothing about being optional, because a field labelled *(opcional)* is a field
|
||||||
|
asking to be filled in.
|
||||||
|
|
||||||
|
An untitled post is called **Sin Título**, and the next one **Sin Título 2**.
|
||||||
|
`apps/board/titles.py` holds the rule; the numbering is done per place, against
|
||||||
|
what is already there:
|
||||||
|
|
||||||
|
| Where | Numbered against |
|
||||||
|
|---|---|
|
||||||
|
| The wall, the queue | Every title in that table, **including deleted rows** — a number that comes back is a thread that looks like one somebody remembers reading |
|
||||||
|
| A public post | The **filenames** in the folder, not the titles: two untitled posts on one day would both be `<fecha>-sin-titulo.es.md`, and the second would fail as "somebody else saved this file while you were editing it" — a message about a conflict that never happened |
|
||||||
|
|
||||||
|
A post deliberately called «Sin Título ni ganas» is left alone: the pattern is
|
||||||
|
anchored, so it is not read as a number and does not take one. Editing a post
|
||||||
|
and clearing its title does not walk the number up either — the file being
|
||||||
|
edited is excluded from its own collision check.
|
||||||
|
|
||||||
|
### 11.17b «Contenido generado con IA»
|
||||||
|
|
||||||
|
A real switch — drawn by `board.css` from the checkbox's own `:checked` state,
|
||||||
|
with no script anywhere near it — 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
|
### 11.18 Marca: the superadministrator owns the look
|
||||||
|
|
||||||
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
|
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
|
||||||
@ -1193,9 +1323,52 @@ 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
|
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.
|
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
|
### 11.20 The three admin tools
|
||||||
|
|
||||||
**Estado del sistema** (superadministrator). WordPress's Site Health, and it
|
**Estado del sistema** (superadministrator). The backups panel reads
|
||||||
|
`/backups`, **not** `/srv/board/backups`: this runs in a container, the host
|
||||||
|
path exists nowhere inside it, and pointing at the host path made the page
|
||||||
|
report "no hay carpeta de copias" twenty seconds after `deploy-board.sh` had
|
||||||
|
written one. `infra/board/docker-compose.yml` mounts the folder **read-only** —
|
||||||
|
a page that reports on backups must never be able to touch them.
|
||||||
|
|
||||||
|
The settings panel separates *absent and nothing works* from *absent and
|
||||||
|
defaulted*: `CONTENT_REPO` is unset on this server and publishing works, because
|
||||||
|
`app.py` defaults it, so the panel names the value in force rather than warning.
|
||||||
|
Merging those two facts is how a page full of orange teaches somebody to ignore
|
||||||
|
orange.
|
||||||
|
|
||||||
|
WordPress's Site Health, and it
|
||||||
earns its place for a specific reason: every outage in this project has been a
|
earns its place for a specific reason: every outage in this project has been a
|
||||||
configuration fact invisible until somebody hit it. It asks the running system
|
configuration fact invisible until somebody hit it. It asks the running system
|
||||||
rather than a file — the content token is **exercised** against the repository
|
rather than a file — the content token is **exercised** against the repository
|
||||||
|
|||||||
@ -54,5 +54,15 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
|
# The backups, read-only, so Gestión → Estado del sistema can say whether
|
||||||
|
# there are any and how old they are. Read-only deliberately: that page
|
||||||
|
# reports on these files and must never be able to touch them — a
|
||||||
|
# diagnostic screen that can delete what it measures is a worse failure
|
||||||
|
# than no screen.
|
||||||
|
#
|
||||||
|
# Without this the check reads /srv/board/backups from inside a container
|
||||||
|
# that mounts only ./data, finds nothing, and cries wolf about the one
|
||||||
|
# thing you most want to be true.
|
||||||
|
- ./backups:/backups:ro
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8080:8080"
|
- "127.0.0.1:8080:8080"
|
||||||
|
|||||||
@ -21,6 +21,22 @@ www.vienalatina.com {
|
|||||||
redir https://vienalatina.com{uri} 301
|
redir https://vienalatina.com{uri} 301
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# The second name, which leads here rather than somewhere else.
|
||||||
|
#
|
||||||
|
# Both spellings in one block, and 301 rather than 302: a permanent redirect is
|
||||||
|
# what makes a search engine fold the two names into one site instead of
|
||||||
|
# indexing them as duplicates of each other, and what makes a browser stop
|
||||||
|
# asking after the first visit. `{uri}` carries the path, so a link somebody
|
||||||
|
# shared to vielac.at/page/agenda/ lands on the agenda rather than on the home
|
||||||
|
# page.
|
||||||
|
#
|
||||||
|
# Caddy asks Let's Encrypt for this certificate the first time the name
|
||||||
|
# resolves to this server, so the A records go in before this file is reloaded.
|
||||||
|
# Until they do, the block is harmless: nothing reaches it.
|
||||||
|
vielac.at, www.vielac.at {
|
||||||
|
redir https://vienalatina.com{uri} 301
|
||||||
|
}
|
||||||
|
|
||||||
vienalatina.com {
|
vienalatina.com {
|
||||||
root * /var/www/vienalatina.com
|
root * /var/www/vienalatina.com
|
||||||
encode zstd gzip
|
encode zstd gzip
|
||||||
|
|||||||
@ -1468,6 +1468,44 @@ a.group-pill:hover {
|
|||||||
|
|
||||||
.article-single__body p { margin: 0 0 1.1em; }
|
.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 {
|
.like-section {
|
||||||
margin: 22px 0 16px;
|
margin: 22px 0 16px;
|
||||||
padding: 16px 0 0;
|
padding: 16px 0 0;
|
||||||
@ -3805,10 +3843,18 @@ a.notif-card__message:hover {
|
|||||||
.cal-event-item__title { font-size: 1.02rem; }
|
.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) {
|
@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__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 ---------------------------------------------- */
|
/* --- preguntas frecuentes ---------------------------------------------- */
|
||||||
@ -4018,6 +4064,11 @@ a.notif-card__message:hover {
|
|||||||
}
|
}
|
||||||
.agenda__pad { background: transparent; border-color: transparent; }
|
.agenda__pad { background: transparent; border-color: transparent; }
|
||||||
.agenda__number { color: var(--subtle, #9a7870); font-weight: 700; }
|
.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__day--busy { background: var(--brand-softer, #fdf1ed); border-color: var(--brand-soft, #fbe2db); }
|
||||||
|
|
||||||
.agenda__event {
|
.agenda__event {
|
||||||
@ -4032,14 +4083,26 @@ a.notif-card__message:hover {
|
|||||||
|
|
||||||
.agenda__empty { text-align: center; margin: -12px 0 24px; }
|
.agenda__empty { text-align: center; margin: -12px 0 24px; }
|
||||||
|
|
||||||
/* A seven-column grid on a phone is seven columns of nothing. Below 640px the
|
/* A seven-column grid on a phone is seven columns of nothing, so below 640px
|
||||||
month becomes a list of the days that have something in them. */
|
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) {
|
@media (max-width: 640px) {
|
||||||
.agenda__grid { display: block; }
|
.agenda__grid { display: block; }
|
||||||
.agenda__pad { display: none; }
|
.agenda__pad { display: none; }
|
||||||
.agenda__day { display: none; min-height: 0; margin-bottom: 6px; }
|
.agenda__day {
|
||||||
.agenda__day--busy { display: block; }
|
display: flex;
|
||||||
.agenda__number { display: inline-block; margin-right: 8px; }
|
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
|
/* The association's accounts elsewhere, in the footer. Set in
|
||||||
@ -4052,3 +4115,48 @@ a.notif-card__message:hover {
|
|||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
font-size: 0.85rem;
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@ -7,6 +7,7 @@
|
|||||||
<article class="article-card">
|
<article class="article-card">
|
||||||
<div class="article-card__meta">
|
<div class="article-card__meta">
|
||||||
<time datetime="{{ .Date.Format "2006-01-02" }}">{{ .Date.Format "2 Jan 2006" }}</time>
|
<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>
|
</div>
|
||||||
<h2 class="article-card__title"><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
|
<h2 class="article-card__title"><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
|
||||||
<p class="article-card__excerpt">{{ .Description | default (.Summary | plainify | truncate 200) }}</p>
|
<p class="article-card__excerpt">{{ .Description | default (.Summary | plainify | truncate 200) }}</p>
|
||||||
|
|||||||
@ -27,6 +27,14 @@
|
|||||||
{{ end }}
|
{{ end }}
|
||||||
</span>
|
</span>
|
||||||
{{ end }}
|
{{ 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>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@ -5,6 +5,7 @@
|
|||||||
<article class="article-card">
|
<article class="article-card">
|
||||||
<div class="article-card__meta">
|
<div class="article-card__meta">
|
||||||
<time datetime="{{ .Date.Format "2006-01-02" }}">{{ .Date.Format "2 Jan 2006" }}</time>
|
<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>
|
</div>
|
||||||
<h2 class="article-card__title"><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
|
<h2 class="article-card__title"><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
|
||||||
<p class="article-card__excerpt">{{ .Description | default (.Summary | plainify | truncate 200) }}</p>
|
<p class="article-card__excerpt">{{ .Description | default (.Summary | plainify | truncate 200) }}</p>
|
||||||
|
|||||||
@ -80,13 +80,23 @@
|
|||||||
{{ range $day := seq 1 $days }}
|
{{ range $day := seq 1 $days }}
|
||||||
{{ $date := printf "%s-%02d" $key $day }}
|
{{ $date := printf "%s-%02d" $key $day }}
|
||||||
{{ $onThisDay := where $events "Params.event_date" $date }}
|
{{ $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 }}">
|
<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 class="agenda__number">{{ $day }}</span>
|
||||||
|
</span>
|
||||||
|
<span class="agenda__events">
|
||||||
{{ range $onThisDay }}
|
{{ range $onThisDay }}
|
||||||
<a class="agenda__event" href="{{ .RelPermalink }}">
|
<a class="agenda__event" href="{{ .RelPermalink }}">
|
||||||
{{ with .Params.event_time }}<time>{{ . }}</time> {{ end }}{{ .Title }}
|
{{ with .Params.event_time }}<time>{{ . }}</time> {{ end }}{{ .Title }}
|
||||||
</a>
|
</a>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
|
</span>
|
||||||
</li>
|
</li>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
</ol>
|
</ol>
|
||||||
|
|||||||
@ -18,6 +18,10 @@
|
|||||||
"next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês")
|
"next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês")
|
||||||
"noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.")
|
"noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.")
|
||||||
"allevents" (dict "es" "Todos los eventos" "de" "Alle Termine" "pt-br" "Todos os eventos")
|
"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")
|
"community" (dict "es" "Comunidad" "de" "Community" "pt-br" "Comunidade")
|
||||||
"menu" (dict "es" "Menú" "de" "Menü" "pt-br" "Menu")
|
"menu" (dict "es" "Menú" "de" "Menü" "pt-br" "Menu")
|
||||||
-}}
|
-}}
|
||||||
|
|||||||
15
themes/vienalatina/layouts/partials/weekday-name.html
Normal file
15
themes/vienalatina/layouts/partials/weekday-name.html
Normal 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) -}}
|
||||||
Loading…
Reference in New Issue
Block a user