vienalatina/apps/board/static/board.js
Pablo Volenski 7e70004e7b
Marca: the admin owns the look, logo included
The brand colours were two identical `:root` blocks — one in the theme, one in
the members area's stylesheet — with a comment in the second reading *"If the
brand colours change, change them in both."* There was no logo anywhere, no
favicon in either `<head>`, and `params.defaultImage` was the empty string with
a comment saying it was waiting for one. Every one of those was a change only
somebody with the repository could make.

`brand.FACTORY` is the single source of truth for the palette now, and
`test_brand.py` parses both stylesheets and fails the build if either drifts
from it. That is what retires the comment: not by merging the two files — they
are served by different things and each has to stand alone — but by making a
divergence fail a test instead of going unnoticed for a month.

**Gestión → Marca**, admins only, saves to two places in one submit, because
the two halves of the site cannot read the same store: SQLite for the members
area, which must render when the git server is down, and `data/brand.yaml` plus
`static/brand/` in the content repository for the public site, which is files
on disk. SQLite is written first and the commits follow — if Gitea is
unreachable the change still takes effect here, `published_at` stays NULL, and
the screen offers to try the publish again. The other order would let a git
outage block a change that does not need git.

The easy half is six colour pickers, each with the name of what it changes, and
a live preview of the real chrome. The three brand shades are worked out from
the brand colour in HLS, so one picked colour gives a coherent set rather than
one red button on an orange background; scaling RGB towards white would have
washed the hue out. A WCAG contrast warning names any pair that will be hard to
read, with its ratio, and saves it anyway: an admin may have a reason, and what
this prevents is shipping an unreadable site without once being told.

The advanced half, behind a fold, is every token as a text field and a free CSS
box appended last so it wins. **The Marca screen deliberately does not load the
generated stylesheet** — every other page does — which is what keeps *Restaurar
lo de fábrica* reachable after somebody writes `* { display: none }` into that
box, and the reason the colours an admin picks do not show on the page where
they pick them. The preview block is where they do.

Only differences from the factory are stored, so a token added later arrives
with its default already in place for every existing install. Both halves serve
a generated stylesheet rather than an inline `<style>`, because the CSP has no
'unsafe-inline' and an inline block would simply not apply.

The logo also fills the gap phase I left: it is the share-card fallback and the
`Organization` logo, ahead of `defaultImage`, and the home page carries
`og:image` for the first time — the front page of the site was the last place
that should share as a bare link.

No SVG and no ICO: the logo takes PNG, JPG or WebP and the favicon PNG, both
identified from their bytes by the sniffer the wall already uses. An SVG is XML
that can carry script and would be served from our own origin.

A new table, so `CREATE TABLE IF NOT EXISTS` is enough and no migration is
involved. `FakeRepo` moved from test_content.py into conftest.py, since two
features commit to the content repository now. Verified by building with Hugo
0.135.0 and the pipeline's flags both ways: with a brand.yaml the second
stylesheet, the favicon and the logo appear, and without one the output is
byte-for-byte identical to the build before any of this existed.

545 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-10-03 20:25:52 +00:00

192 lines
7.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);
});
}
// --- the brand preview --------------------------------------------------
//
// Setting the custom properties on one element, from the colour pickers above
// it. A DOM write rather than a `style=""` attribute in the template, which
// is what makes it work under a policy with no 'unsafe-inline' — and it is
// also why the preview exists at all: the Marca screen itself is deliberately
// rendered in the factory colours, so this block is the only place an admin
// sees their own.
function brandPreview() {
var target = document.querySelector("[data-brand-preview-target]");
if (!target) { return; }
var pickers = document.querySelectorAll("[data-brand-preview] [data-token]");
function paint() {
Array.prototype.forEach.call(pickers, function (picker) {
target.style.setProperty("--" + picker.getAttribute("data-token"),
picker.value);
});
}
Array.prototype.forEach.call(pickers, function (picker) {
picker.addEventListener("input", paint);
});
paint();
}
document.addEventListener("DOMContentLoaded", function () {
Array.prototype.forEach.call(
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
brandPreview();
document.addEventListener("change", function (event) {
var input = event.target;
if (input.tagName === "INPUT" && input.type === "file" &&
(input.accept || "").indexOf("image") !== -1) {
previewFiles(input);
}
});
});
})();