The writing box shows the formatting, and raw HTML stops reaching the site
The box is now the finished text: bold is bold, a heading is a heading, a
list is a list. No preview pane — a second box beside the first is the
wrong shape on a phone — and nothing is sent anywhere while anybody
types, so the round trip the old «Vista previa» button made on every
press is gone.
Markdown is still the only thing stored, which is what keeps the file in
git, the translation pipeline, Decap and the XSS defence exactly as they
were. The two directions are deliberately not symmetrical:
opening — the server renders the stored markdown into a <template>
the editor adopts, so there is no markdown parser in the
browser and no second opinion about what text means;
saving — the browser walks a closed set of elements back into
markdown. Anything else contributes its text and nothing
more, which is why a paste brings no markup in.
Three heading levels (## ### ####), bold, italic, strikethrough, two
kinds of list, quote, link and clear formatting on the four post boxes;
bold, italic, link and clear on the short ones. A «Markdown» button
swaps to the raw text and back — the escape hatch, and the way to write
a table. With JavaScript off the plain textarea is still there and still
the field that submits; verified by driving the form with scripting
disabled.
Headings had no styles anywhere. `.article-single__body` styled `p` and
nothing else, so three levels would have rendered as three identical
bold lines. Both stylesheets now carry the ladder, along with lists,
quotes and rules.
Two renderer findings, both of which richer writing makes worse:
- config.yaml set Goldmark `unsafe: true`, for WordPress content that
no longer exists — no file under content/ holds a tag. A member's
proposal containing `<img src=x onerror=…>` renders as visible
characters in the moderation queue, which is the one screen a
moderator judges it on, and that flag is what would have run it on
the live site. Off now; the built output is byte-identical.
- A line break meant two things: `breaks: True` here, Goldmark's
hardWraps off there. Turning hardWraps on was the obvious fix and
the wrong one — the files are hard-wrapped at 78 characters, so it
would break every sentence in half. Instead there are two renderers,
one per destination, and the editor writes the hard break CommonMark
means (two spaces) so it survives either way.
Tested by running the serializer itself, in node, against the same
static/board.js the browser loads: 26 cases including the ones that go
wrong — a pasted span, a script, an empty box, a line starting with «-»,
a javascript: href — plus a round trip asserting markdown → HTML →
markdown renders identically for ten real documents.
Then by typing in a browser at 390px with touch emulation, which is what
found the one defect no fixture predicted: pressing Enter in a list
wraps it in a <div>, and reading that as a paragraph ran «uno» and «dos»
together into one word.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
This commit is contained in:
parent
59b595170f
commit
8e1ef8831c
@ -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():
|
||||||
|
|||||||
@ -631,7 +631,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]:
|
||||||
|
|||||||
@ -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 (
|
||||||
.enable("linkify")
|
MarkdownIt("commonmark", {"html": False, "linkify": True, "breaks": breaks})
|
||||||
.enable("table")
|
.enable("linkify")
|
||||||
.enable("strikethrough")
|
.enable("table")
|
||||||
)
|
.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:
|
||||||
|
|||||||
@ -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);
|
||||||
@ -664,17 +680,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 {
|
||||||
@ -1001,3 +1026,29 @@ input[type="file"] {
|
|||||||
min-height: 44px;
|
min-height: 44px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- said out loud: a machine wrote this -------------------------------- */
|
||||||
|
/*
|
||||||
|
* A pill beside the date, the same shape as the PÚBLICO tag in the calendar.
|
||||||
|
* Quiet, but above the text rather than under it: a disclosure nobody meets
|
||||||
|
* until after they have read the thing is not a disclosure.
|
||||||
|
*/
|
||||||
|
.tag--ai {
|
||||||
|
background: var(--surface-soft);
|
||||||
|
color: var(--muted);
|
||||||
|
border: 1px solid var(--border-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The switch in the form's action row. A checkbox and its words on one line,
|
||||||
|
beside the button that publishes — visible at the moment of publishing,
|
||||||
|
which is when it is answered, and costing one line rather than a fieldset. */
|
||||||
|
.switch {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--muted);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.switch input { margin: 0; }
|
||||||
|
.switch:has(input:checked) { color: var(--brand-dark); font-weight: 600; }
|
||||||
|
|||||||
@ -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");
|
|
||||||
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) {
|
// Only schemes that cannot execute. markdown-it refuses `javascript:` on its
|
||||||
var bar = document.createElement("div");
|
// own, so this is the second of two locks rather than the only one.
|
||||||
bar.className = "md-bar";
|
function safeHref(href) {
|
||||||
TOOLS.forEach(function (tool) {
|
return /^(https?:|mailto:|\/|#)/i.test(href || "") ? href : "";
|
||||||
var button = document.createElement("button");
|
}
|
||||||
button.type = "button"; // never a submit inside a form
|
|
||||||
button.className = "md-bar__button";
|
// «** bold **» is not bold in CommonMark, and a selection almost always
|
||||||
button.title = tool.title;
|
// carries a space at one end.
|
||||||
button.textContent = tool.label;
|
function wrapped(marker, inner) {
|
||||||
button.addEventListener("click", function () { apply(box, tool); });
|
var lead = inner.match(/^\s*/)[0];
|
||||||
bar.appendChild(button);
|
var tail = inner.match(/\s*$/)[0];
|
||||||
|
var core = inner.slice(lead.length, inner.length - tail.length);
|
||||||
|
return core ? lead + marker + core + marker + tail : inner;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Elements whose text is not writing. Nothing here can execute — the server
|
||||||
|
// renders markdown with raw HTML disabled — but a stylesheet pasted into the
|
||||||
|
// box should not come back as four hundred words of prose either.
|
||||||
|
var DROP = { SCRIPT: 1, STYLE: 1, TEMPLATE: 1, NOSCRIPT: 1, IFRAME: 1, OBJECT: 1, HEAD: 1 };
|
||||||
|
|
||||||
|
function inlineOne(node) {
|
||||||
|
if (node.nodeType === 3) { return escapeText(node.nodeValue); }
|
||||||
|
if (node.nodeType !== 1) { return ""; }
|
||||||
|
var tag = node.tagName;
|
||||||
|
if (DROP[tag]) { return ""; }
|
||||||
|
// Two spaces then a newline: the break CommonMark means wherever it is
|
||||||
|
// rendered. A bare newline is a break in the members area and a space on
|
||||||
|
// the public site, which would make the same post read differently in the
|
||||||
|
// two places.
|
||||||
|
if (tag === "BR") { return " \n"; }
|
||||||
|
if (tag === "CODE") { return "`" + node.textContent + "`"; }
|
||||||
|
if (tag === "IMG") { return escapeText(node.getAttribute("alt") || ""); }
|
||||||
|
|
||||||
|
var inner = inline(node);
|
||||||
|
if (!inner.trim()) { return inner; }
|
||||||
|
if (tag === "STRONG" || tag === "B") { return wrapped("**", inner); }
|
||||||
|
if (tag === "EM" || tag === "I") { return wrapped("_", inner); }
|
||||||
|
if (tag === "S" || tag === "DEL" || tag === "STRIKE") { return wrapped("~~", inner); }
|
||||||
|
if (tag === "A") {
|
||||||
|
var href = safeHref(node.getAttribute("href"));
|
||||||
|
return href ? "[" + inner.trim() + "](" + href + ")" : inner;
|
||||||
|
}
|
||||||
|
return inner; // span, font, and whatever else a paste left behind
|
||||||
|
}
|
||||||
|
|
||||||
|
function inline(node) {
|
||||||
|
var out = "";
|
||||||
|
Array.prototype.forEach.call(node.childNodes, function (child) {
|
||||||
|
out += inlineOne(child);
|
||||||
});
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
var preview = document.createElement("button");
|
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) {
|
||||||
|
|||||||
@ -8,6 +8,11 @@
|
|||||||
|
|
||||||
<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>
|
||||||
|
|||||||
@ -114,8 +114,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"
|
||||||
|
|||||||
@ -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/*">
|
||||||
|
|||||||
@ -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"
|
||||||
|
|||||||
@ -48,8 +48,13 @@
|
|||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
<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/*">
|
||||||
|
|||||||
@ -12,8 +12,13 @@
|
|||||||
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
|
||||||
|
|||||||
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));
|
||||||
|
});
|
||||||
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}"
|
||||||
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/
|
||||||
|
|||||||
@ -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;
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user