Import a Word document as a blog post, and add table blocks

- Table content blocks (migration 044): a grid of text, a row per
  line, cells split by |, the first row the header; cells take the
  same formatting as a paragraph; wide tables scroll on a phone
- Blog posts -> Import from Word: the server reads the .docx (zip and
  XML read without a library, sizes capped) and creates an unpublished
  post through the CRUD engine: title, date, headings, paragraphs,
  lists, tables, bold, italic and links; the editor opens with a note
  of what came over and what didn't (images)
- docs/importing.md, and an nginx block for the upload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 12:44:20 -05:00
parent adc88e5714
commit 7f12824c93
16 changed files with 656 additions and 6 deletions

View file

@ -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 (

View file

@ -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: [

View file

@ -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).",

View file

@ -35,6 +35,7 @@ export type ContentBlock = {
| 'button'
| 'callout'
| 'schedule'
| 'table'
text?: string | null
media?: string | null
href?: string | null

View file

@ -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>
);
}

View file

@ -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>
);
}