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

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

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

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

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

463 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-10-02 15:21:35 +00:00

165 lines
6.5 KiB
JavaScript

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