Content display, requests and Google Workspace (v1.9.5 to v1.9.11-content-display) #15
16 changed files with 656 additions and 6 deletions
|
|
@ -34,6 +34,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
|
||||
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
|
||||
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
|
||||
- Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`.
|
||||
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
|
||||
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
|
||||
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`.
|
||||
|
|
|
|||
63
docs/importing.md
Normal file
63
docs/importing.md
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# Importing a Word document as a blog post
|
||||
|
||||
Admin → Pages → Blog posts → **Import from Word** (editors and up). Pick
|
||||
a `.docx`; the server turns it into a new blog post, **unpublished**, and
|
||||
opens it in the editor with a note of what came over. Check it, add the
|
||||
authors and a cover, then tick Published.
|
||||
|
||||
## What becomes what
|
||||
|
||||
| In the document | In the post |
|
||||
| --- | --- |
|
||||
| The Title, or the first Heading 1 | The post's title (the file name if there's neither) |
|
||||
| A date line right under the title, eg. "Sep 28, 2026 · @Aidan" | The post's date (the rest of that line is dropped) |
|
||||
| Heading 1 and Heading 2 | Heading blocks |
|
||||
| Heading 3 and smaller | Subheading blocks |
|
||||
| Paragraphs | Paragraph blocks |
|
||||
| A run of bulleted or numbered paragraphs | One List block, one item each |
|
||||
| Tables | Table blocks: a row per line, cells split by `\|`, the first row the header |
|
||||
| Bold, italic, links (http, https, mailto) | `**bold**`, `*italic*`, `[text](url)`, in paragraphs, list items and table cells |
|
||||
|
||||
A post with three headings or more gets **Show contents** turned on. The
|
||||
URL ID is the title as a slug, with `-2`, `-3` when it's taken.
|
||||
|
||||
Not carried over: images and drawings (the note says how many; add them
|
||||
as Image blocks), text boxes, footnotes, comments, colours and fonts.
|
||||
Numbered lists come over as bulleted lists.
|
||||
|
||||
The conversion is `server/src/docx.js`; the route is
|
||||
`server/src/routes/import.js`.
|
||||
|
||||
## PDFs
|
||||
|
||||
A PDF has no headings, lists or tables inside it, only positioned
|
||||
text, so it can't be converted the same way. Open it in Word (or Google
|
||||
Docs) and save it as `.docx` first, or have it converted by hand.
|
||||
|
||||
## Table blocks
|
||||
|
||||
Any page's content blocks can have one (Content blocks → Type → Table):
|
||||
|
||||
```
|
||||
Platform | Monthly cost | Best for
|
||||
Zeffy | Free | Fee-free giving
|
||||
[Breeze](https://www.breezechms.com) | $72 | **Small churches**
|
||||
```
|
||||
|
||||
A literal `|` inside a cell is written `\|`. On a phone a wide table
|
||||
scrolls sideways in its box.
|
||||
|
||||
## nginx
|
||||
|
||||
nginx caps `/api/` bodies at 64k, so the upload needs its own block
|
||||
(in the site's `server` block, beside `/api/admin/media`; `nginx-dev`
|
||||
has it):
|
||||
|
||||
```nginx
|
||||
location = /api/admin/import/docx {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
# the usual proxy_set_header lines
|
||||
proxy_read_timeout 60s;
|
||||
client_max_body_size 11m;
|
||||
}
|
||||
```
|
||||
|
|
@ -176,7 +176,7 @@ also in `server/src/admin-schema/` and a CHECK):
|
|||
| Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` |
|
||||
| Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. |
|
||||
| Content blocks → Shown in (slot) | card, body | **yes** | `paragraphs()` in `server/src/shape.js` (card), `ContentBlocks.tsx` (body) |
|
||||
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema/shared.ts`). |
|
||||
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule, table | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema/shared.ts`). |
|
||||
| Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` |
|
||||
| Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` |
|
||||
| Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping |
|
||||
|
|
|
|||
|
|
@ -148,6 +148,7 @@ export const blocksChild = (ownerKind) => ({
|
|||
"button",
|
||||
"callout",
|
||||
"schedule",
|
||||
"table",
|
||||
],
|
||||
{ required: true },
|
||||
),
|
||||
|
|
|
|||
249
server/src/docx.js
Normal file
249
server/src/docx.js
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
DOCX → CONTENT BLOCKS
|
||||
|
||||
Reads a Word document and turns it into a blog post's content
|
||||
blocks (routes/import.js; Blog posts → Import from Word):
|
||||
|
||||
the Title, or the first Heading 1 the post's title
|
||||
a date line right under it the post's date
|
||||
Heading 1 and 2 heading blocks
|
||||
Heading 3 and below subheading blocks
|
||||
paragraphs paragraph blocks
|
||||
runs of list paragraphs one list block, one item each
|
||||
tables table blocks (a row per line,
|
||||
cells split by |)
|
||||
bold, italic, links **bold**, *italic*, [text](url)
|
||||
|
||||
Images, text boxes, footnotes and comments aren't carried over;
|
||||
the result counts what was skipped so the editor can say so.
|
||||
|
||||
A .docx is a zip of XML. Both are read here with no library: the
|
||||
zip through Node's own zlib, the XML with a small tokenizer. The
|
||||
file is someone's upload, so every size is capped and the XML is
|
||||
walked once, with no pattern that rescans it.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { inflateRawSync } from "node:zlib";
|
||||
|
||||
export class DocxError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.status = 400;
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_PART_BYTES = 20 * 1024 * 1024; // any one XML part, unpacked
|
||||
const PARTS = ["word/document.xml", "word/styles.xml", "word/_rels/document.xml.rels"];
|
||||
|
||||
/* ── Zip ───────────────────────────────────────────────────────── */
|
||||
|
||||
/* The named entries of a zip, unpacked. Reads the central directory
|
||||
(the index at the end), so it never walks the whole file. */
|
||||
function unzip(buf, wanted) {
|
||||
const out = {};
|
||||
// End of central directory: the last 0x06054b50 in the final 64 KB.
|
||||
let eocd = -1;
|
||||
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
|
||||
if (buf.readUInt32LE(i) === 0x06054b50) {
|
||||
eocd = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocd === -1) throw new DocxError("That file isn't a Word document (.docx).");
|
||||
const count = buf.readUInt16LE(eocd + 10);
|
||||
let at = buf.readUInt32LE(eocd + 16);
|
||||
for (let n = 0; n < count && at + 46 <= buf.length; n++) {
|
||||
if (buf.readUInt32LE(at) !== 0x02014b50) break;
|
||||
const method = buf.readUInt16LE(at + 10);
|
||||
const packed = buf.readUInt32LE(at + 20);
|
||||
const size = buf.readUInt32LE(at + 24);
|
||||
const nameLen = buf.readUInt16LE(at + 28);
|
||||
const extraLen = buf.readUInt16LE(at + 30);
|
||||
const commentLen = buf.readUInt16LE(at + 32);
|
||||
const local = buf.readUInt32LE(at + 42);
|
||||
const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
|
||||
at += 46 + nameLen + extraLen + commentLen;
|
||||
if (!wanted.includes(name)) continue;
|
||||
if (size > MAX_PART_BYTES) throw new DocxError("That document is too large to import.");
|
||||
const dataAt = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
|
||||
const data = buf.subarray(dataAt, dataAt + packed);
|
||||
if (method === 0) out[name] = data.toString("utf8");
|
||||
else if (method === 8) out[name] = inflateRawSync(data, { maxOutputLength: MAX_PART_BYTES }).toString("utf8");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ── XML ───────────────────────────────────────────────────────── */
|
||||
|
||||
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
||||
const decode = (s) =>
|
||||
s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos);/gi, (_, e) => {
|
||||
if (e[0] !== "#") return ENTITY[e.toLowerCase()];
|
||||
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1));
|
||||
return String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
|
||||
});
|
||||
|
||||
/* A tree of { name, attrs, children, text }. One pass of one global
|
||||
regex over the tags, so its cost is the file's length. */
|
||||
function parseXml(xml) {
|
||||
const root = { name: "#root", attrs: {}, children: [] };
|
||||
const stack = [root];
|
||||
const token = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([^\s>/]+)([^>]*?)(\/?)>|([^<]+)/g;
|
||||
let m;
|
||||
while ((m = token.exec(xml))) {
|
||||
const top = stack[stack.length - 1];
|
||||
if (m[1] !== undefined) top.children.push({ name: "#text", text: m[1] });
|
||||
else if (m[6] !== undefined) top.children.push({ name: "#text", text: decode(m[6]) });
|
||||
else if (m[3]) {
|
||||
if (m[2]) {
|
||||
if (stack.length > 1) stack.pop();
|
||||
} else {
|
||||
const attrs = {};
|
||||
for (const a of m[4].matchAll(/([\w:.-]+)\s*=\s*"([^"]*)"/g)) attrs[a[1]] = decode(a[2]);
|
||||
const node = { name: m[3], attrs, children: [] };
|
||||
top.children.push(node);
|
||||
if (!m[5]) stack.push(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
const kids = (node, name) => (node?.children ?? []).filter((c) => c.name === name);
|
||||
const kid = (node, name) => (node?.children ?? []).find((c) => c.name === name);
|
||||
function* all(node, name) {
|
||||
for (const c of node?.children ?? []) {
|
||||
if (c.name === name) yield c;
|
||||
yield* all(c, name);
|
||||
}
|
||||
}
|
||||
const on = (el) => el && !["0", "false"].includes(el.attrs["w:val"]);
|
||||
|
||||
/* ── Text ──────────────────────────────────────────────────────── */
|
||||
|
||||
function runText(r) {
|
||||
let t = "";
|
||||
for (const c of r.children) {
|
||||
if (c.name === "w:t") t += c.children.map((x) => x.text ?? "").join("");
|
||||
else if (c.name === "w:tab") t += " ";
|
||||
else if (c.name === "w:br" || c.name === "w:cr") t += " ";
|
||||
}
|
||||
if (!t.trim()) return t;
|
||||
const rpr = kid(r, "w:rPr");
|
||||
const b = on(kid(rpr, "w:b"));
|
||||
const i = on(kid(rpr, "w:i"));
|
||||
const lead = t.match(/^\s*/)[0];
|
||||
const trail = t.match(/\s*$/)[0];
|
||||
const core = t.trim();
|
||||
const marked = b && i ? `***${core}***` : b ? `**${core}**` : i ? `*${core}*` : core;
|
||||
return lead + marked + trail;
|
||||
}
|
||||
|
||||
const SAFE_LINK = /^(https?:|mailto:)/i;
|
||||
|
||||
function paragraphText(p, rels, counts) {
|
||||
let out = "";
|
||||
for (const c of p.children) {
|
||||
if (c.name === "w:r") {
|
||||
if (kid(c, "w:drawing") || kid(c, "w:pict")) counts.images++;
|
||||
out += runText(c);
|
||||
} else if (c.name === "w:hyperlink") {
|
||||
const label = [...all(c, "w:r")].map(runText).join("").trim();
|
||||
const href = rels[c.attrs["r:id"]];
|
||||
out += href && SAFE_LINK.test(href) && label ? `[${label.replace(/[[\]]/g, "")}](${href})` : label;
|
||||
} else if (c.name === "w:ins" || c.name === "w:smartTag" || c.name === "w:sdt") {
|
||||
out += [...all(c, "w:r")].map(runText).join("");
|
||||
}
|
||||
}
|
||||
// Word splits a phrase into runs; adjacent bold runs meet as "** **".
|
||||
return out.replace(/\*\*(\s*)\*\*/g, "$1").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/* ── Document ──────────────────────────────────────────────────── */
|
||||
|
||||
const DATE_LINE = /^([A-Z][a-z]{2,8}\.? \d{1,2},? \d{4}|\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8} \d{4})\b/;
|
||||
|
||||
export function readDocx(buf) {
|
||||
const parts = unzip(buf, PARTS);
|
||||
if (!parts["word/document.xml"]) throw new DocxError("That file isn't a Word document (.docx).");
|
||||
|
||||
const rels = {};
|
||||
for (const r of all(parseXml(parts["word/_rels/document.xml.rels"] ?? ""), "Relationship")) {
|
||||
if (r.attrs.TargetMode === "External" || /^https?:|^mailto:/i.test(r.attrs.Target ?? "")) rels[r.attrs.Id] = r.attrs.Target;
|
||||
}
|
||||
const styleName = {};
|
||||
for (const s of all(parseXml(parts["word/styles.xml"] ?? ""), "w:style")) {
|
||||
styleName[s.attrs["w:styleId"]] = (kid(s, "w:name")?.attrs["w:val"] ?? s.attrs["w:styleId"]).toLowerCase();
|
||||
}
|
||||
|
||||
const body = kid(kid(parseXml(parts["word/document.xml"]), "w:document"), "w:body");
|
||||
if (!body) throw new DocxError("That document has no body to import.");
|
||||
|
||||
const counts = { images: 0 };
|
||||
const blocks = [];
|
||||
let title = null;
|
||||
let date = null;
|
||||
let list = null; // the list block being filled
|
||||
|
||||
const close = () => {
|
||||
if (list) blocks.push(list);
|
||||
list = null;
|
||||
};
|
||||
|
||||
for (const el of body.children) {
|
||||
if (el.name === "w:tbl") {
|
||||
close();
|
||||
const rows = kids(el, "w:tr").map((tr) =>
|
||||
kids(tr, "w:tc")
|
||||
.map((tc) =>
|
||||
kids(tc, "w:p")
|
||||
.map((p) => paragraphText(p, rels, counts))
|
||||
.filter(Boolean)
|
||||
.join(" / ")
|
||||
.replace(/\|/g, "\\|"),
|
||||
)
|
||||
.join(" | "),
|
||||
);
|
||||
if (rows.some((r) => r.replace(/[|\s]/g, ""))) blocks.push({ type: "table", text: rows.join("\n") });
|
||||
continue;
|
||||
}
|
||||
if (el.name !== "w:p") continue;
|
||||
|
||||
const ppr = kid(el, "w:pPr");
|
||||
const style = styleName[kid(ppr, "w:pStyle")?.attrs["w:val"]] ?? "";
|
||||
const text = paragraphText(el, rels, counts);
|
||||
if (!text) continue;
|
||||
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
|
||||
|
||||
if (!title && (level === 0 || level === 1)) {
|
||||
close();
|
||||
title = text.replace(/\*/g, "");
|
||||
continue;
|
||||
}
|
||||
// The line under the title, when it starts with a date ("Sep 28,
|
||||
// 2026 · @Aidan"), is the post's date, not part of the body.
|
||||
if (title && !date && blocks.length === 0 && !list) {
|
||||
const d = DATE_LINE.exec(text.replace(/\*/g, ""));
|
||||
const parsed = d && new Date(d[1]);
|
||||
if (parsed && !Number.isNaN(parsed.getTime())) {
|
||||
date = parsed.toISOString().slice(0, 10);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (level >= 1) {
|
||||
close();
|
||||
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
|
||||
continue;
|
||||
}
|
||||
if (kid(ppr, "w:numPr") || /list/.test(style)) {
|
||||
if (!list) list = { type: "list", items: [] };
|
||||
list.items.push({ text });
|
||||
continue;
|
||||
}
|
||||
close();
|
||||
blocks.push({ type: "paragraph", text });
|
||||
}
|
||||
close();
|
||||
|
||||
return { title, date, blocks, skipped: counts };
|
||||
}
|
||||
|
|
@ -34,6 +34,7 @@ import panel from "./routes/panel.js";
|
|||
import adminEntities from "./routes/admin-entities.js";
|
||||
import media from "./routes/media.js";
|
||||
import clips from "./routes/clips.js";
|
||||
import imports from "./routes/import.js";
|
||||
import { CLIPS_DIR, startClipWorker } from "./clips.js";
|
||||
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
|
||||
import { logSafe, startSessionSweeper } from "./auth.js";
|
||||
|
|
@ -179,6 +180,7 @@ app.route("/api/auth", auth);
|
|||
app.route("/api/admin", admin);
|
||||
// Before the entity routes, whose /:entity would claim /media.
|
||||
app.route("/api/admin", media);
|
||||
app.route("/api/admin", imports);
|
||||
app.route("/api/admin", clips);
|
||||
app.route("/api/admin", adminEntities);
|
||||
|
||||
|
|
|
|||
72
server/src/migrations/044_table_block.sql
Normal file
72
server/src/migrations/044_table_block.sql
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 044 TABLE BLOCKS
|
||||
--
|
||||
-- A content block of type 'table': a grid of text, for comparison
|
||||
-- charts and the like (a blog post imported from Word, say). The
|
||||
-- grid is the block's text, one row per line, cells split by "|",
|
||||
-- the first row the header; cells take the same inline formatting as
|
||||
-- a paragraph (**bold**, *italic*, [link](url)). ContentBlocks.tsx
|
||||
-- draws it.
|
||||
--
|
||||
-- Only the type's CHECK changes, and SQLite can't alter a CHECK, so
|
||||
-- the table is rebuilt the way 031, 032 and 034 did it
|
||||
-- (legacy_alter_table around the rename, then its index and owner
|
||||
-- trigger again).
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE content_blocks_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
owner_kind TEXT NOT NULL
|
||||
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
|
||||
owner_id TEXT NOT NULL,
|
||||
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
type TEXT NOT NULL
|
||||
CHECK (type IN ('heading', 'subheading', 'paragraph',
|
||||
'list', 'links', 'quote', 'image', 'divider',
|
||||
'video', 'button', 'callout', 'schedule', 'table')),
|
||||
text TEXT,
|
||||
media TEXT,
|
||||
href TEXT,
|
||||
alt TEXT,
|
||||
cite TEXT
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO content_blocks_new
|
||||
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
|
||||
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
|
||||
FROM content_blocks;
|
||||
|
||||
PRAGMA legacy_alter_table = ON;
|
||||
DROP TABLE content_blocks;
|
||||
ALTER TABLE content_blocks_new RENAME TO content_blocks;
|
||||
PRAGMA legacy_alter_table = OFF;
|
||||
|
||||
CREATE INDEX content_blocks_owner_idx
|
||||
ON content_blocks (owner_kind, owner_id, slot, sort_order);
|
||||
|
||||
|
||||
-- ── Triggers last (see CLAUDE.md, Migrations) ──
|
||||
|
||||
CREATE TRIGGER content_blocks_owner_exists
|
||||
BEFORE INSERT ON content_blocks
|
||||
BEGIN
|
||||
SELECT CASE
|
||||
WHEN new.owner_kind = 'event'
|
||||
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
|
||||
THEN RAISE(ABORT, 'content_blocks: no such event')
|
||||
WHEN new.owner_kind = 'organization'
|
||||
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
|
||||
THEN RAISE(ABORT, 'content_blocks: no such organization')
|
||||
WHEN new.owner_kind = 'person'
|
||||
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
|
||||
THEN RAISE(ABORT, 'content_blocks: no such person')
|
||||
WHEN new.owner_kind = 'team'
|
||||
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
|
||||
THEN RAISE(ABORT, 'content_blocks: no such team')
|
||||
WHEN new.owner_kind = 'blog_post'
|
||||
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
|
||||
THEN RAISE(ABORT, 'content_blocks: no such blog post')
|
||||
END;
|
||||
END;
|
||||
121
server/src/routes/import.js
Normal file
121
server/src/routes/import.js
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
IMPORT ROUTES (mounted under /api/admin)
|
||||
|
||||
POST /import/docx a Word document → a new blog post, unpublished
|
||||
|
||||
Blog posts → Import from Word. The document becomes a draft post
|
||||
(docx.js decides what each part becomes), created through the same
|
||||
CRUD engine as the editor, so it's validated the same way. The
|
||||
reply says what came over and what didn't (images), and the admin
|
||||
opens the new post for review before anyone publishes it.
|
||||
|
||||
nginx caps /api/ bodies at 64k; this path needs its own block
|
||||
with a larger client_max_body_size (docs/media-uploads.md).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
|
||||
import { requireAuth, requireRole } from "../auth.js";
|
||||
import { createRow, HttpError } from "../admin-crud.js";
|
||||
import { ENTITIES } from "../admin-schema.js";
|
||||
import { DocxError, readDocx } from "../docx.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
|
||||
const MAX_DOCX_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const imports = new Hono();
|
||||
imports.use("*", requireAuth);
|
||||
|
||||
const slug = (text) =>
|
||||
String(text ?? "")
|
||||
.toLowerCase()
|
||||
.normalize("NFKD")
|
||||
.replace(/[^\w\s-]/g, "")
|
||||
.trim()
|
||||
.replace(/[\s_]+/g, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.slice(0, 64)
|
||||
.replace(/-$/, "") || "imported-post";
|
||||
|
||||
/* A free URL ID: the title's slug, or it with -2, -3... */
|
||||
function freeId(db, base) {
|
||||
const taken = (id) => db.prepare(`SELECT 1 FROM blog_posts WHERE id = ?`).get(id);
|
||||
let id = base;
|
||||
for (let n = 2; taken(id); n++) id = `${base.slice(0, 60)}-${n}`;
|
||||
return id;
|
||||
}
|
||||
|
||||
imports.post(
|
||||
"/import/docx",
|
||||
requireRole("editor"),
|
||||
bodyLimit({
|
||||
maxSize: MAX_DOCX_BYTES + 64 * 1024,
|
||||
onError: (c) => c.json({ error: "That document is too large (10 MB at most)." }, 413),
|
||||
}),
|
||||
async (c) => {
|
||||
const db = c.get("db");
|
||||
let body;
|
||||
try {
|
||||
body = await c.req.parseBody();
|
||||
} catch {
|
||||
return c.json({ error: "Expected a file upload." }, 400);
|
||||
}
|
||||
const file = body.file;
|
||||
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
|
||||
|
||||
let doc;
|
||||
try {
|
||||
doc = readDocx(Buffer.from(await file.arrayBuffer()));
|
||||
} catch (err) {
|
||||
if (err instanceof DocxError) return c.json({ error: err.message }, 400);
|
||||
return c.json({ error: "That document couldn't be read. Save it again as .docx and retry." }, 400);
|
||||
}
|
||||
if (doc.blocks.length === 0) return c.json({ error: "That document has no text to import." }, 400);
|
||||
|
||||
const title = doc.title || String(file.name ?? "").replace(/\.docx$/i, "") || "Imported post";
|
||||
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
|
||||
|
||||
const payload = {
|
||||
id: freeId(db, slug(title)),
|
||||
title: title.slice(0, 200),
|
||||
published_on: doc.date,
|
||||
is_published: 0,
|
||||
is_listed: 1,
|
||||
// A long document with sections reads better with its contents.
|
||||
show_contents: headings >= 3 ? 1 : 0,
|
||||
content_blocks: doc.blocks.map((block) => ({
|
||||
slot: "body",
|
||||
type: block.type,
|
||||
text: block.text ?? null,
|
||||
items: block.items ?? [],
|
||||
})),
|
||||
};
|
||||
|
||||
try {
|
||||
const row = createRow(db, ENTITIES.blog_posts, payload);
|
||||
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
|
||||
console.log(`blog_posts ${row.id} imported from Word by ${c.get("user").email}`);
|
||||
return c.json(
|
||||
{
|
||||
id: row.id,
|
||||
summary: {
|
||||
blocks: doc.blocks.length,
|
||||
headings,
|
||||
paragraphs: count("paragraph"),
|
||||
lists: count("list"),
|
||||
tables: count("table"),
|
||||
skipped: doc.skipped,
|
||||
},
|
||||
},
|
||||
201,
|
||||
NO_STORE,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export default imports;
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -66,6 +66,23 @@ export default function ContentBlocks({
|
|||
)
|
||||
}
|
||||
|
||||
/* A table block's text as rows of cells: one row per line, cells
|
||||
split by "|" (a literal bar is "\|"), blank lines skipped. A
|
||||
leading and trailing bar, as in Markdown, is allowed. */
|
||||
export function tableRows(text: string): string[][] {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.map((line) =>
|
||||
line
|
||||
.replace(/^\|/, '')
|
||||
.replace(/(?<!\\)\|$/, '')
|
||||
.split(/(?<!\\)\|/)
|
||||
.map((cell) => cell.replace(/\\\|/g, '|').trim()),
|
||||
)
|
||||
}
|
||||
|
||||
function Caption({ text }: { text?: string | null }) {
|
||||
if (!text) return null
|
||||
return (
|
||||
|
|
@ -165,6 +182,47 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string;
|
|||
</figure>
|
||||
)
|
||||
|
||||
case 'table': {
|
||||
const rows = tableRows(text)
|
||||
if (rows.length === 0) return null
|
||||
const [head, ...body] = rows
|
||||
const width = Math.max(...rows.map((row) => row.length))
|
||||
return (
|
||||
// Wide tables scroll sideways inside their box on a phone
|
||||
// rather than squeezing every column to a word.
|
||||
<div className="overflow-x-auto rounded-2xl border border-brand/15">
|
||||
<table className="min-w-full text-left text-sm leading-snug">
|
||||
<thead className="bg-tint">
|
||||
<tr>
|
||||
{Array.from({ length: width }, (_, i) => (
|
||||
<th key={i} scope="col" className="min-w-[8rem] px-4 py-3 font-semibold text-ink">
|
||||
<Inline text={head[i] ?? ''} accent={accent} />
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{body.map((row, r) => (
|
||||
<tr key={r} className={r % 2 ? 'bg-tint-soft' : ''}>
|
||||
{Array.from({ length: width }, (_, i) =>
|
||||
i === 0 ? (
|
||||
<th key={i} scope="row" className="min-w-[8rem] px-4 py-3 align-top font-semibold text-ink">
|
||||
<Inline text={row[i] ?? ''} accent={accent} />
|
||||
</th>
|
||||
) : (
|
||||
<td key={i} className="min-w-[8rem] px-4 py-3 align-top" style={{ color: BODY }}>
|
||||
<Inline text={row[i] ?? ''} accent={accent} />
|
||||
</td>
|
||||
),
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
case 'callout':
|
||||
if (!text) return null
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ export const blogPosts = {
|
|||
singular: "blog post",
|
||||
idLabel: "URL ID",
|
||||
slugFrom: "title",
|
||||
// Blog posts → Import from Word (server/src/routes/import.js).
|
||||
importer: { label: "Import from Word", endpoint: "/admin/import/docx", accept: ".docx" },
|
||||
|
||||
list: {
|
||||
columns: [
|
||||
|
|
|
|||
|
|
@ -278,6 +278,7 @@ export const BLOCK_TYPES = [
|
|||
["image", "Image", "A picture, with alt text and an optional caption and link."],
|
||||
["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."],
|
||||
["schedule", "Schedule", "Entries in one tab per day, each folding out for more. The text is an optional intro."],
|
||||
["table", "Table", "A grid of text, eg. a comparison chart: one row per line, cells split by |, the first row the header."],
|
||||
["divider", "Divider", "A thin line between parts."],
|
||||
];
|
||||
|
||||
|
|
@ -286,7 +287,7 @@ export const SCHEDULE_ENTRY = { scope: "parent", path: "type", value: "schedule"
|
|||
|
||||
export const blockTypeLabel = (type) => BLOCK_TYPES.find(([value]) => value === type)?.[1] ?? type;
|
||||
|
||||
export const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video", "schedule"];
|
||||
export const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video", "schedule", "table"];
|
||||
|
||||
export const TEXT_HELP = {
|
||||
paragraph: FORMATTING_HELP,
|
||||
|
|
@ -296,9 +297,12 @@ export const TEXT_HELP = {
|
|||
image: "Caption shown under the image. Optional.",
|
||||
video: "Caption shown under the video. Optional.",
|
||||
schedule: "Optional intro above the tabs. " + FORMATTING_HELP,
|
||||
table:
|
||||
"One row per line; cells split by |. The first row is the header. eg. Platform | Price | Best for. " +
|
||||
"Cells take the same formatting as a paragraph. A | inside a cell is written \|.",
|
||||
};
|
||||
|
||||
export const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption", schedule: "Intro" };
|
||||
export const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption", schedule: "Intro", table: "Rows" };
|
||||
|
||||
export const HREF_HELP = {
|
||||
paragraph: "Optional. Makes the whole paragraph one link. For a link inside the text, use [text](url).",
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ export type ContentBlock = {
|
|||
| 'button'
|
||||
| 'callout'
|
||||
| 'schedule'
|
||||
| 'table'
|
||||
text?: string | null
|
||||
media?: string | null
|
||||
href?: string | null
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@
|
|||
|
||||
import { ArrowLeft } from "@phosphor-icons/react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
import { get, post, patch, del, ApiError } from "../../lib/api.ts";
|
||||
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
||||
|
|
@ -367,6 +367,8 @@ export default function EntityEdit() {
|
|||
{isNew ? `New ${manifest.singular}` : heading}
|
||||
</h1>
|
||||
|
||||
<ImportedNote />
|
||||
|
||||
{/* Straight in the page, not wrapped: a sticky element only
|
||||
travels within its parent, so its parent has to be tall. */}
|
||||
<SectionJump sections={sections} />
|
||||
|
|
@ -527,3 +529,25 @@ export default function EntityEdit() {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* After Import from Word (EntityList's ImportButton): what came over,
|
||||
and what's left to do before publishing. Gone on the next visit. */
|
||||
function ImportedNote() {
|
||||
const summary = (useLocation().state as any)?.imported;
|
||||
if (!summary) return null;
|
||||
const parts = [
|
||||
`${summary.headings} headings`,
|
||||
`${summary.paragraphs} paragraphs`,
|
||||
`${summary.lists} lists`,
|
||||
`${summary.tables} tables`,
|
||||
];
|
||||
return (
|
||||
<p role="status" className="mt-4 rounded-xl border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
|
||||
Imported from Word: {parts.join(", ")}.
|
||||
{summary.skipped?.images
|
||||
? ` ${summary.skipped.images} image${summary.skipped.images === 1 ? " was" : "s were"} not carried over; add them as Image blocks.`
|
||||
: ""}{" "}
|
||||
It's saved unpublished: check it, add the authors and a cover, then tick Published.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, Navigate, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
|
||||
import { get, ApiError } from "../../lib/api.ts";
|
||||
import { get, upload, ApiError } from "../../lib/api.ts";
|
||||
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
||||
import { ADMIN_ENTITIES } from "../../lib/adminSchema.ts";
|
||||
import { atLeast } from "../../lib/roles.ts";
|
||||
|
|
@ -93,10 +93,11 @@ export default function EntityList() {
|
|||
<div>
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<h1 className="text-3xl font-bold text-link">{manifest.label}</h1>
|
||||
{canWrite && manifest.importer && <ImportButton manifest={manifest} />}
|
||||
{canWrite && (
|
||||
<Link
|
||||
to={`/admin/${manifest.key}/new`}
|
||||
className="ml-auto rounded-full bg-action px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-action-hover"
|
||||
className={`${manifest.importer ? "" : "ml-auto "}rounded-full bg-action px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-action-hover`}
|
||||
>
|
||||
New {manifest.singular}
|
||||
</Link>
|
||||
|
|
@ -213,3 +214,54 @@ export default function EntityList() {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* A manifest's `importer`: pick a file, the server turns it into a
|
||||
new record, and its editor opens with a note of what came over
|
||||
(EntityEdit shows it). Blog posts take Word documents. */
|
||||
function ImportButton({ manifest }: { manifest: any }) {
|
||||
const navigate = useNavigate();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function send(file: File) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const form = new FormData();
|
||||
form.set("file", file);
|
||||
try {
|
||||
const result = await upload(manifest.importer.endpoint, form);
|
||||
navigate(`/admin/${manifest.key}/${result.id}`, { state: { imported: result.summary } });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ml-auto flex items-center gap-3">
|
||||
{error && (
|
||||
<span role="alert" className="text-sm text-danger">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
<label
|
||||
className={`cursor-pointer rounded-full border border-link px-4 py-2 text-sm font-semibold text-link transition-colors hover:bg-tint ${
|
||||
busy ? "pointer-events-none opacity-60" : ""
|
||||
}`}
|
||||
>
|
||||
{busy ? "Importing…" : manifest.importer.label}
|
||||
<input
|
||||
type="file"
|
||||
accept={manifest.importer.accept}
|
||||
className="sr-only"
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (file) send(file);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue