@tansy/blog 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/blog
4
+
5
+ Turns tansy into a blog: posts, categories, tags, authors, comments and feeds.
6
+
7
+ ```bash
8
+ npm install @tansy/blog
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the blog plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/blog.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/admin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tansy/admin").AdminPluginParts;
2
+ export default _default;
package/admin.js ADDED
@@ -0,0 +1,44 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { defineAdminPlugin, PageHeader } from "tansy/admin";
3
+ import { getT } from "tansy/server";
4
+ import { ModerateButtons } from "./moderate";
5
+ const text = (value) => (typeof value === "string" ? value : "");
6
+ /** As the signed-in person, so someone without access to a collection gets null rather than another person's view. */
7
+ async function count(records, slug, filter) {
8
+ return records.list(slug, { filter, perPage: 1, fields: "id" }).then((page) => page.totalItems).catch(() => null);
9
+ }
10
+ async function CommentQueue({ records, user }) {
11
+ const { t } = await getT(user.id);
12
+ const pending = await records.list("blog-comments", { filter: 'state = "pending"', sort: "createdAt", perPage: 100, expand: "post", fields: "id,name,body,createdAt,expand.post.title" }).catch(() => null);
13
+ return (_jsxs("div", { className: "cms-gutter", children: [_jsx(PageHeader, { title: t("ext.blog.pages.blog/comments"), description: t("ext.blog.queue.intro") }), pending === null && _jsx("p", { className: "cms-empty", children: t("ext.blog.queue.cantRead") }), pending?.items.length === 0 && _jsx("p", { className: "cms-empty", children: t("ext.blog.queue.empty") }), pending && pending.items.length > 0 && (_jsx("ul", { className: "cms-panel cms-divide", children: pending.items.map((comment) => {
14
+ const post = comment.expand?.post;
15
+ return (_jsxs("li", { className: "cms-cell", children: [_jsx("p", { className: "cms-text-sm cms-faded cms-mb-1", children: t("ext.blog.queue.on", { name: text(comment.name), post: text(post?.title) || t("ext.blog.queue.aPost") }) }), _jsx("p", { className: "cms-mb-2", style: { whiteSpace: "pre-line" }, children: text(comment.body) }), _jsx(ModerateButtons, { id: Number(comment.id) })] }, String(comment.id)));
16
+ }) })), pending && pending.totalItems > pending.items.length && _jsx("p", { className: "cms-muted cms-mt-4", children: t("ext.blog.queue.showing", { shown: pending.items.length, total: pending.totalItems }) })] }));
17
+ }
18
+ async function Overview({ records, user }) {
19
+ const { t } = await getT(user.id);
20
+ const [pending, drafts, published] = await Promise.all([
21
+ count(records, "blog-comments", 'state = "pending"'),
22
+ count(records, "blog-posts", 'status = "draft"'),
23
+ count(records, "blog-posts", 'status = "published"'),
24
+ ]);
25
+ const line = (value, key) => _jsx("li", { children: value === null ? t("ext.blog.overview.unknown", { label: t(`ext.blog.overview.${key}Label`) }) : t(`ext.blog.overview.${key}`, { count: value }) });
26
+ return _jsxs("ul", { className: "cms-muted cms-text-sm", children: [line(pending, "pending"), line(drafts, "drafts"), line(published, "published")] });
27
+ }
28
+ export default defineAdminPlugin({
29
+ pages: [{ path: "blog/comments", title: "Comments to review", permission: "ext.blog:moderate", component: CommentQueue }],
30
+ section: {
31
+ title: "Blog",
32
+ icon: "newspaper",
33
+ items: [
34
+ { collection: "blog-posts" },
35
+ { collection: "blog-categories" },
36
+ { collection: "blog-tags" },
37
+ { page: "blog/comments" },
38
+ { collection: "blog-comments", title: "All comments" },
39
+ { collection: "blog-home", title: "Blog home page" },
40
+ { settings: true },
41
+ ],
42
+ },
43
+ widgets: [{ id: "blog-overview", title: "Blog", permission: "ext.blog:moderate", component: Overview }],
44
+ });
package/blog.css ADDED
@@ -0,0 +1,53 @@
1
+ /* The blog plugin's pages. Colours, fonts and widths come from the active theme's --site-* tokens, with plain fallbacks. */
2
+ .bl-main {
3
+ max-width: var(--site-size-measure, 42rem);
4
+ margin: 0 auto;
5
+ padding: var(--site-space-section, 3rem) 1rem;
6
+ color: var(--site-color-text, inherit);
7
+ font-family: var(--site-font-body, inherit);
8
+ line-height: 1.6;
9
+ }
10
+ .bl-main h1 { font-size: 2.25rem; line-height: 1.2; margin: 0 0 0.5rem; }
11
+ .bl-main a { color: var(--site-color-accent, inherit); }
12
+ .bl-muted, .bl-meta { color: var(--site-color-muted, #666); }
13
+ .bl-meta { font-size: 0.875rem; margin: 0 0 1rem; }
14
+ .bl-kicker { font-size: 0.8125rem; letter-spacing: 0.04em; text-transform: uppercase; margin: 0 0 0.5rem; display: flex; gap: 0.75rem; flex-wrap: wrap; }
15
+ .bl-cover { width: 100%; height: auto; border-radius: var(--site-radius-card, 0.5rem); margin: 0 0 1.5rem; }
16
+ .bl-body > * + * { margin-top: var(--site-space-gap, 1.25rem); }
17
+ .bl-list { list-style: none; padding: 0; margin: 2rem 0 0; display: grid; gap: var(--site-space-gap, 1.5rem); }
18
+ .bl-item { padding-bottom: var(--site-space-gap, 1.5rem); border-bottom: 1px solid var(--site-color-border, #e5e5e5); }
19
+ .bl-item-title { font-size: 1.375rem; margin: 0 0 0.25rem; }
20
+ .bl-featured .bl-item-title::before { content: "★ "; color: var(--site-color-accent, currentColor); }
21
+ .bl-tags { list-style: none; padding: 0; margin: 2rem 0 0; display: flex; flex-wrap: wrap; gap: 0.5rem; }
22
+ .bl-tags a, .bl-tags span { display: inline-block; padding: 0.125rem 0.625rem; border: 1px solid var(--site-color-border, #ddd); border-radius: 999px; font-size: 0.8125rem; text-decoration: none; }
23
+ .bl-quote { margin: 0; padding-left: 1rem; border-left: 3px solid var(--site-color-accent, currentColor); font-style: italic; }
24
+ .bl-quote cite { display: block; font-style: normal; color: var(--site-color-muted, #666); margin-top: 0.25rem; }
25
+ .bl-quote cite::before { content: "— "; }
26
+ .bl-callout { padding: 0.75rem 1rem; border-radius: var(--site-radius-card, 0.5rem); border: 1px solid var(--site-color-border, #ddd); }
27
+ .bl-callout-tip { border-color: #2f855a; }
28
+ .bl-callout-warning { border-color: #b7791f; }
29
+ .bl-figure { margin: 0; }
30
+ .bl-figure img { width: 100%; height: auto; border-radius: var(--site-radius-card, 0.5rem); }
31
+ .bl-figure figcaption { font-size: 0.875rem; color: var(--site-color-muted, #666); margin-top: 0.5rem; }
32
+ .bl-embed { position: relative; aspect-ratio: 16 / 9; }
33
+ .bl-embed iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; border-radius: var(--site-radius-card, 0.5rem); }
34
+ /* The editor's canvas: the parts of a block shown only while it's edited. */
35
+ .bl-quote-source { display: flex; gap: 0.35em; margin-top: 0.25rem; font-style: normal; color: var(--site-color-muted, #666); }
36
+ .bl-quote-source::before { content: "—"; }
37
+ .bl-editor-note { margin-top: 0.5rem; font-size: 0.875rem; color: var(--site-color-muted, #666); }
38
+ .bl-editor-placeholder { padding: 1rem; border: 1px dashed var(--site-color-border, #ccc); border-radius: var(--site-radius-card, 0.5rem); }
39
+ .bl-editor-placeholder p { margin: 0; }
40
+ .bl-code { overflow-x: auto; padding: 1rem; border-radius: var(--site-radius-card, 0.5rem); background: color-mix(in srgb, var(--site-color-text, #222) 6%, transparent); font-size: 0.875rem; }
41
+ .bl-more, .bl-comments { margin-top: var(--site-space-section, 3rem); padding-top: 1.5rem; border-top: 1px solid var(--site-color-border, #e5e5e5); }
42
+ .bl-thread { list-style: none; padding: 0; margin: 1rem 0; display: grid; gap: 1rem; }
43
+ .bl-thread .bl-thread { margin-left: 1.5rem; }
44
+ .bl-comment-body { white-space: pre-line; overflow-wrap: anywhere; margin: 0 0 0.25rem; }
45
+ .bl-form { display: grid; gap: 0.375rem; margin: 1rem 0; }
46
+ .bl-form input, .bl-form textarea { font: inherit; padding: 0.5rem; border: 1px solid var(--site-color-border, #ccc); border-radius: 0.375rem; background: transparent; color: inherit; }
47
+ .bl-actions { display: flex; gap: 0.5rem; margin: 0.5rem 0 0; }
48
+ .bl-form button { font: inherit; padding: 0.5rem 1rem; border-radius: 0.375rem; border: 0; background: var(--site-color-accent, #222); color: var(--site-color-on-accent, #fff); cursor: pointer; }
49
+ .bl-form button[type="button"] { background: transparent; color: inherit; border: 1px solid var(--site-color-border, #ccc); }
50
+ .bl-form button:disabled { opacity: 0.6; cursor: default; }
51
+ .bl-link { font: inherit; font-size: 0.875rem; background: none; border: 0; padding: 0; color: var(--site-color-accent, inherit); cursor: pointer; text-decoration: underline; }
52
+ .bl-error { color: #c53030; margin: 0; }
53
+ .bl-pager { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-top: var(--site-space-section, 3rem); font-size: 0.875rem; color: var(--site-color-muted, #666); }
package/client.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tansy/admin").AdminClientParts;
2
+ export default _default;
package/client.js ADDED
@@ -0,0 +1,17 @@
1
+ import { defineAdminClient, translate } from "tansy/admin";
2
+ import { blockEditors } from "./editors";
3
+ import { setCommentState } from "./moderate";
4
+ const action = (id, label, state) => ({
5
+ id,
6
+ label,
7
+ permission: "ext.blog:moderate",
8
+ collections: ["blog-comments"],
9
+ run: async ({ ids, refresh }) => {
10
+ await setCommentState(ids, state, translate);
11
+ refresh();
12
+ },
13
+ });
14
+ export default defineAdminClient({
15
+ bulkActions: [action("blog-approve", "Approve", "approved"), action("blog-spam", "Mark as spam", "spam")],
16
+ blockEditors,
17
+ });
package/comments.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { type SiteWords } from "tansy/react";
2
+ export interface PublicComment {
3
+ id: number;
4
+ name: string;
5
+ body: string;
6
+ parent: number | null;
7
+ createdAt: string;
8
+ pending?: boolean;
9
+ }
10
+ /** Approved comments from the page, plus the reader's own new ones. Replies go one level deep. */
11
+ export declare function Comments({ postId, initial, words: given }: {
12
+ postId: number;
13
+ initial: PublicComment[];
14
+ words?: SiteWords;
15
+ }): import("react").JSX.Element;
package/comments.js ADDED
@@ -0,0 +1,60 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useId, useState } from "react";
4
+ import { apiPath } from "tansy/react";
5
+ import { blogWords } from "./site-messages";
6
+ function CommentForm({ postId, parent, onPosted, onCancel, words }) {
7
+ const { t } = words;
8
+ const id = useId();
9
+ const [name, setName] = useState("");
10
+ const [body, setBody] = useState("");
11
+ const [error, setError] = useState(null);
12
+ const [sending, setSending] = useState(false);
13
+ async function submit(event) {
14
+ event.preventDefault();
15
+ setSending(true);
16
+ setError(null);
17
+ try {
18
+ const response = await fetch(apiPath("/collections/blog-comments/records"), {
19
+ method: "POST",
20
+ headers: { "content-type": "application/json" },
21
+ body: JSON.stringify({ post: postId, name, body, ...(parent ? { parent } : {}) }),
22
+ });
23
+ const json = await response.json().catch(() => null);
24
+ if (response.status === 401 || response.status === 403)
25
+ return setError(t("blog.signIn"));
26
+ if (!response.ok || typeof json?.id !== "number")
27
+ return setError(t("blog.failed"));
28
+ onPosted({ id: json.id, name, body, parent, createdAt: json.createdAt ?? new Date().toISOString(), pending: json.state !== "approved" });
29
+ setBody("");
30
+ }
31
+ catch {
32
+ setError(t("blog.offline"));
33
+ }
34
+ finally {
35
+ setSending(false);
36
+ }
37
+ }
38
+ return (_jsxs("form", { className: "bl-form", onSubmit: submit, children: [_jsx("label", { htmlFor: `${id}-name`, children: t("blog.name") }), _jsx("input", { id: `${id}-name`, value: name, onChange: (event) => setName(event.target.value), maxLength: 80, required: true, autoComplete: "name" }), _jsx("label", { htmlFor: `${id}-body`, children: parent ? t("blog.reply") : t("blog.comment") }), _jsx("textarea", { id: `${id}-body`, value: body, onChange: (event) => setBody(event.target.value), maxLength: 5000, rows: 4, required: true }), error && _jsx("p", { className: "bl-error", role: "alert", children: error }), _jsxs("p", { className: "bl-actions", children: [_jsx("button", { type: "submit", disabled: sending, children: sending ? t("blog.posting") : parent ? t("blog.postReply") : t("blog.postComment") }), onCancel && _jsx("button", { type: "button", onClick: onCancel, children: t("blog.cancel") })] })] }));
39
+ }
40
+ function Entry({ comment, children, words }) {
41
+ return (_jsxs("li", { className: "bl-comment", children: [_jsxs("p", { className: "bl-meta", children: [_jsx("strong", { children: comment.name }), " \u00B7 ", _jsx("time", { dateTime: comment.createdAt, children: comment.createdAt ? words.formatDate(comment.createdAt) : "" }), comment.pending && _jsxs(_Fragment, { children: [" \u00B7 ", words.t("blog.waiting")] })] }), _jsx("p", { className: "bl-comment-body", children: comment.body }), children] }));
42
+ }
43
+ /** Approved comments from the page, plus the reader's own new ones. Replies go one level deep. */
44
+ export function Comments({ postId, initial, words: given }) {
45
+ const words = blogWords(given);
46
+ const { t } = words;
47
+ const [comments, setComments] = useState(initial);
48
+ const [replyingTo, setReplyingTo] = useState(null);
49
+ const add = (comment) => {
50
+ setComments((current) => [...current, comment]);
51
+ setReplyingTo(null);
52
+ };
53
+ const topLevel = comments.filter((comment) => !comment.parent);
54
+ return (_jsxs("section", { className: "bl-comments", "aria-labelledby": "bl-comments-title", children: [_jsx("h2", { id: "bl-comments-title", children: t("blog.comments") }), topLevel.length === 0 && _jsx("p", { className: "bl-muted", children: t("blog.noComments") }), _jsx("ol", { className: "bl-thread", children: topLevel.map((comment) => {
55
+ const replies = comments.filter((reply) => reply.parent === comment.id);
56
+ return (_jsxs(Entry, { comment: comment, words: words, children: [replies.length > 0 && _jsx("ol", { className: "bl-thread", children: replies.map((reply) => _jsx(Entry, { comment: reply, words: words }, reply.id)) }), !comment.pending && (replyingTo === comment.id
57
+ ? _jsx(CommentForm, { postId: postId, parent: comment.id, onPosted: add, onCancel: () => setReplyingTo(null), words: words })
58
+ : _jsx("button", { type: "button", className: "bl-link", onClick: () => setReplyingTo(comment.id), children: t("blog.reply") }))] }, comment.id));
59
+ }) }), _jsx("h3", { children: t("blog.leaveComment") }), _jsx(CommentForm, { postId: postId, parent: null, onPosted: add, words: words })] }));
60
+ }
package/editors.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { type BlockEditorDefinition } from "tansy/admin";
2
+ import "./blog.css";
3
+ export declare const blockEditors: BlockEditorDefinition[];
package/editors.js ADDED
@@ -0,0 +1,48 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useT } from "tansy/admin";
4
+ import { embedUrl } from "./text";
5
+ import "./blog.css";
6
+ /*
7
+ * The blog's blocks on the editor's canvas, built from the same markup and classes as
8
+ * render.tsx, so they look as they will on the site and are edited in place.
9
+ */
10
+ const text = (value) => (typeof value === "string" ? value : "");
11
+ const TONES = ["info", "tip", "warning"];
12
+ function TextEditor({ Field }) {
13
+ const { t } = useT();
14
+ return _jsx(Field, { name: "body", placeholder: t("ext.blog.editors.startWriting") });
15
+ }
16
+ function QuoteEditor({ block, selected, Field }) {
17
+ const { t } = useT();
18
+ return (_jsxs("blockquote", { className: "bl-quote", children: [_jsx(Field, { name: "text", placeholder: t("ext.blog.editors.quote") }), (selected || text(block.value.source)) && _jsx("div", { className: "bl-quote-source", children: _jsx(Field, { name: "source", placeholder: t("ext.blog.editors.source") }) })] }));
19
+ }
20
+ function CalloutEditor({ block, Field }) {
21
+ const { t } = useT();
22
+ const tone = TONES.includes(text(block.value.tone)) ? text(block.value.tone) : "info";
23
+ return _jsx("aside", { className: `bl-callout bl-callout-${tone}`, children: _jsx(Field, { name: "body", placeholder: t("ext.blog.editors.note") }) });
24
+ }
25
+ function ImageEditor({ block, selected, Field }) {
26
+ const { t } = useT();
27
+ return (_jsxs("figure", { className: "bl-figure", children: [_jsx(Field, { name: "image", placeholder: t("ext.blog.editors.image") }), (selected || text(block.value.caption)) && _jsx("figcaption", { children: _jsx(Field, { name: "caption", placeholder: t("ext.blog.editors.caption") }) }), selected && _jsx("div", { className: "bl-editor-note", children: _jsx(Field, { name: "alt", placeholder: t("ext.blog.editors.alt") }) })] }));
28
+ }
29
+ function EmbedEditor({ block, selected, Field }) {
30
+ const { t } = useT();
31
+ const src = embedUrl(text(block.value.url));
32
+ return (_jsxs("figure", { className: "bl-figure", children: [src
33
+ // Inert until selected, so a click selects the block rather than playing the video.
34
+ ? _jsx("div", { className: "bl-embed", inert: !selected, children: _jsx("iframe", { src: src, title: text(block.value.caption) || t("ext.blog.editors.video"), loading: "lazy", allow: "encrypted-media; picture-in-picture; fullscreen", referrerPolicy: "strict-origin-when-cross-origin", sandbox: "allow-scripts allow-same-origin allow-presentation" }) })
35
+ : _jsxs("div", { className: "bl-editor-placeholder", children: [_jsx("p", { children: t("ext.blog.editors.pasteVideo") }), _jsx(Field, { name: "url" })] }), (selected || text(block.value.caption)) && _jsx("figcaption", { children: _jsx(Field, { name: "caption", placeholder: t("ext.blog.editors.caption") }) })] }));
36
+ }
37
+ function CodeEditor({ block, selected, Field }) {
38
+ const { t } = useT();
39
+ return (_jsxs("div", { className: "bl-code", children: [_jsx(Field, { name: "code", placeholder: t("ext.blog.editors.code") }), (selected || text(block.value.language)) && _jsx("div", { className: "bl-editor-note", children: _jsx(Field, { name: "language", placeholder: t("ext.blog.editors.language") }) })] }));
40
+ }
41
+ export const blockEditors = [
42
+ { blocks: ["blog_text"], component: TextEditor },
43
+ { blocks: ["blog_quote"], component: QuoteEditor },
44
+ { blocks: ["blog_callout"], component: CalloutEditor },
45
+ { blocks: ["blog_image"], component: ImageEditor },
46
+ { blocks: ["blog_embed"], component: EmbedEditor },
47
+ { blocks: ["blog_code"], component: CodeEditor },
48
+ ];
package/index.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export interface BlogOptions {
2
+ /** Where the public site lives, such as https://example.com. Feeds need absolute links. */
3
+ siteUrl: string;
4
+ /** The prefix of the addresses created on first install. After that, edit URL patterns in the dashboard. */
5
+ basePath?: string;
6
+ /** "moderated" holds new comments for review, "open" shows them straight away, and "off" refuses them. Until changed under Blog → Settings. */
7
+ comments?: "off" | "moderated" | "open";
8
+ /** Entries in each feed, until changed under Blog → Settings. */
9
+ feedItems?: number;
10
+ /** Who to email when a comment is waiting for review, until changed under Blog → Settings. */
11
+ notify?: string;
12
+ }
13
+ /** Turns the CMS into a blog: posts, categories, tags, comments, feeds, and author and editor roles. See docs/plugins/blog.md. */
14
+ export declare function blog(options: BlogOptions): import("tansy/plugin").CmsPlugin;
package/index.js ADDED
@@ -0,0 +1,295 @@
1
+ import { z } from "zod";
2
+ import { defineBlock, definePlugin, defineRoute } from "tansy/plugin";
3
+ import { blogRoles, blogSchema, BYLINE_FIELD, COLLECTIONS, CONTRACT } from "./schema";
4
+ import { COLLECTION_LABELS, FIELD_LABELS, messages } from "./messages";
5
+ import { atom, excerptOf, readingMinutes, rss, slugify } from "./text";
6
+ const optionsSchema = z.strictObject({
7
+ siteUrl: z.url({ protocol: /^https?$/ }),
8
+ basePath: z.string().regex(/^\/[a-z0-9-]+(?:\/[a-z0-9-]+)*$/, 'Use a path such as "/blog".'),
9
+ comments: z.enum(["off", "moderated", "open"]),
10
+ feedItems: z.number().int().min(1).max(100),
11
+ notify: z.email().optional(),
12
+ });
13
+ /** How many comments one person may post a minute. */
14
+ const COMMENTS_PER_MINUTE = 5;
15
+ /** The field a missing slug is made from, by collection. */
16
+ const SLUG_SOURCE = { "blog-posts": "title", "blog-categories": "name", "blog-tags": "name" };
17
+ const str = (value) => (typeof value === "string" ? value : "");
18
+ const idOf = (value) => (typeof value === "number" && Number.isSafeInteger(value) ? value : null);
19
+ /** Fields the owner may have removed are left alone, or the save would fail on a field that isn't there. */
20
+ async function fieldsOf(context, slug) {
21
+ return new Set((await context.schema.describe(slug))?.fields.map((field) => field.name) ?? []);
22
+ }
23
+ async function uniqueSlug(records, slug, base, ownId) {
24
+ for (let attempt = 1; attempt <= 50; attempt++) {
25
+ const candidate = attempt === 1 ? base : `${base.slice(0, 75)}-${attempt}`;
26
+ // slugify only produces letters, digits and hyphens, so the filter can't be broken out of.
27
+ const { items } = await records.list(slug, { filter: `slug = "${candidate}"`, perPage: 2, fields: "id" });
28
+ if (!items.some((item) => item.id !== ownId))
29
+ return candidate;
30
+ }
31
+ return `${base.slice(0, 60)}-${Date.now().toString(36)}`;
32
+ }
33
+ /** Fills a missing slug, excerpt and reading time. On an update, `values` holds only what changed. */
34
+ async function prepareContent(context) {
35
+ const { collection, values, record } = context;
36
+ const source = SLUG_SOURCE[collection.slug];
37
+ if (!source)
38
+ return;
39
+ const fields = await fieldsOf(context, collection.slug);
40
+ const current = (name) => (Object.hasOwn(values, name) ? values[name] : record?.[name]);
41
+ if (fields.has("slug") && !str(current("slug"))) {
42
+ values.slug = await uniqueSlug(context.system.records, collection.slug, slugify(str(current(source))), record?.id);
43
+ }
44
+ if (collection.slug !== "blog-posts")
45
+ return;
46
+ const body = current("body");
47
+ if (fields.has("readingMinutes") && (Object.hasOwn(values, "body") || !record))
48
+ values.readingMinutes = readingMinutes(body);
49
+ if (fields.has("excerpt") && !str(current("excerpt")).trim()) {
50
+ const excerpt = excerptOf(body);
51
+ if (excerpt)
52
+ values.excerpt = excerpt;
53
+ }
54
+ }
55
+ /** Choosing whose name is on a post. Editors hold it, authors don't. */
56
+ const CREDIT = "ext.blog:credit";
57
+ const changes = (context, name) => Object.hasOwn(context.values, name) && (context.values[name] ?? null) !== (context.record?.[name] ?? null);
58
+ /**
59
+ * A post's author is the person who wrote it, and its byline shows their name, taken from
60
+ * their account when the post is created. Someone who may credit others can write any
61
+ * byline, such as a guest's. Anyone else always gets their own name, and can't change it.
62
+ */
63
+ async function credit(context) {
64
+ const { collection, values, userId, event } = context;
65
+ if (collection.slug !== "blog-posts" || !(await fieldsOf(context, "blog-posts")).has("byline"))
66
+ return;
67
+ const credits = context.can(CREDIT);
68
+ if (event === "record.beforeUpdate") {
69
+ if (!credits && changes(context, "byline"))
70
+ context.reject("Only an editor can change a post's byline.", "byline");
71
+ return;
72
+ }
73
+ if (event !== "record.beforeCreate" || (credits && str(values.byline).trim()))
74
+ return;
75
+ const name = userId ? (await context.system.users.get(userId))?.name.trim().slice(0, 120) : "";
76
+ values.byline = name || null;
77
+ }
78
+ async function underRateLimit(context, userId) {
79
+ const key = `comments-by:${userId}`;
80
+ const now = Date.now();
81
+ const recent = ((await context.store.get(key)) ?? []).filter((at) => typeof at === "number" && now - at < 60_000);
82
+ if (recent.length >= COMMENTS_PER_MINUTE)
83
+ return false;
84
+ await context.store.set(key, [...recent, now]);
85
+ return true;
86
+ }
87
+ const settingsOf = async (context) => (await context.settings.get());
88
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
89
+ function commentHooks() {
90
+ const prepare = async (context) => {
91
+ const { values, reject, userId } = context;
92
+ const mode = (await settingsOf(context)).comments;
93
+ if (mode === "off")
94
+ reject("Comments are closed.");
95
+ if (!userId)
96
+ reject("Sign in to comment.");
97
+ // Read as a visitor, so only a published post can be commented on.
98
+ const postId = idOf(values.post);
99
+ const post = postId === null ? null : await context.records.get("blog-posts", postId).catch(() => null);
100
+ if (!post || post.allowComments === false)
101
+ reject("This post isn't taking comments.", "post");
102
+ const parentId = idOf(values.parent);
103
+ if (parentId !== null) {
104
+ const parent = await context.system.records.get("blog-comments", parentId).catch(() => null);
105
+ if (!parent || parent.post !== postId || parent.state !== "approved" || idOf(parent.parent) !== null)
106
+ reject("You can reply only to an approved comment on the same post, one level deep.", "parent");
107
+ }
108
+ if (!(await underRateLimit(context, userId)))
109
+ reject("You're commenting too quickly. Wait a minute, then try again.");
110
+ values.name = str(values.name).trim();
111
+ values.body = str(values.body).trim();
112
+ // Never what the commenter sent: only moderators decide this.
113
+ values.state = mode === "open" ? "approved" : "pending";
114
+ };
115
+ const keepPlace = ({ values, record, reject }) => {
116
+ for (const name of ["post", "parent"]) {
117
+ if (Object.hasOwn(values, name) && (values[name] ?? null) !== (record?.[name] ?? null))
118
+ reject("A comment can't move to another post or thread.", name);
119
+ }
120
+ };
121
+ const announce = async (context) => {
122
+ const { record, mail } = context;
123
+ const notify = (await settingsOf(context)).notify.trim();
124
+ if (!EMAIL.test(notify) || record.state !== "pending")
125
+ return;
126
+ await mail.send({
127
+ to: notify,
128
+ subject: "A comment is waiting for review",
129
+ body: `${str(record.name)} commented on post ${String(record.post)}:\n\n${str(record.body).slice(0, 1000)}\n\nApprove it or mark it as spam under Blog → Comments to review in the dashboard.`,
130
+ });
131
+ };
132
+ return { prepare, keepPlace, announce };
133
+ }
134
+ async function feedItems(records, siteUrl, limit, language) {
135
+ // The list rule already hides drafts from visitors. The filter keeps them out for a signed-in editor too.
136
+ const { items } = await records.list("blog-posts", { filter: 'status = "published"', sort: "-publishedAt", perPage: limit, fields: "id,title,excerpt,publishedAt,updatedAt", urls: "1", ...(language ? { locale: language.locale, fallback: "none" } : {}) });
137
+ const address = (path) => {
138
+ const href = language ? language.href(path) : path;
139
+ return /^https?:\/\//.test(href) ? href : `${siteUrl}${href}`;
140
+ };
141
+ const iso = (value, fallback) => {
142
+ const date = new Date(str(value) || fallback);
143
+ return Number.isNaN(date.getTime()) ? new Date(0).toISOString() : date.toISOString();
144
+ };
145
+ return items.filter((item) => typeof item.recordPath === "string").map((item) => {
146
+ const publishedAt = iso(item.publishedAt, "");
147
+ return { title: str(item.title), url: address(str(item.recordPath)), summary: str(item.excerpt), publishedAt, updatedAt: iso(item.updatedAt, publishedAt) };
148
+ });
149
+ }
150
+ async function feedTitle(records, locale) {
151
+ const home = await records.list("blog-home", { perPage: 1, fields: "title", ...(locale ? { locale } : {}) }).catch(() => null);
152
+ return str(home?.items[0]?.title) || "Blog";
153
+ }
154
+ const FEED_REASON = "Feed readers fetch it signed out. It lists only published posts the list rule shows the caller.";
155
+ /** Turns the CMS into a blog: posts, categories, tags, comments, feeds, and author and editor roles. See docs/plugins/blog.md. */
156
+ export function blog(options) {
157
+ const value = { basePath: "/blog", comments: "moderated", feedItems: 20, ...options, siteUrl: options.siteUrl.replace(/\/+$/, "") };
158
+ const comments = commentHooks();
159
+ const forContent = (hook) => async (context) => {
160
+ if (SLUG_SOURCE[context.collection.slug])
161
+ await prepareContent(context);
162
+ await credit(context);
163
+ if (context.collection.slug === "blog-comments")
164
+ await hook(context);
165
+ };
166
+ const feed = (path, render, type) => defineRoute({
167
+ method: "GET",
168
+ path,
169
+ root: true,
170
+ access: "public",
171
+ reason: FEED_REASON,
172
+ handler: async (context) => {
173
+ const { records, schema } = context;
174
+ // One feed per language, as ?locale=fr. Without it, or on a site with one language, the default.
175
+ const languages = await schema.languages();
176
+ const asked = new URL(context.request.url).searchParams.get("locale");
177
+ const locale = languages.items.find((item) => item.code === asked)?.code ?? languages.defaultLocale;
178
+ const language = languages.items.length > 1 ? { locale, href: (to) => languages.href(to, locale) } : null;
179
+ // A tenant's feed links to its own domain, or under its path prefix until it has one
180
+ // (core/scope). Written one after the other: new URL() would drop a path on the base.
181
+ const siteUrl = (await context.scope.siteUrl()) ?? value.siteUrl;
182
+ // The feed's own address, which is served at the root of a domain rather than under a
183
+ // path prefix, so the self link starts at the origin.
184
+ const feedUrl = `${new URL(siteUrl).origin}${path}${language && locale !== languages.defaultLocale ? `?locale=${encodeURIComponent(locale)}` : ""}`;
185
+ const body = render({ title: await feedTitle(records, language?.locale), siteUrl, feedUrl, items: await feedItems(records, siteUrl, (await settingsOf(context)).feedItems, language) });
186
+ return new Response(body, { headers: { "content-type": `${type}; charset=utf-8`, "cache-control": "public, max-age=300" } });
187
+ },
188
+ });
189
+ return definePlugin({
190
+ name: "blog",
191
+ version: "0.1.0",
192
+ apiVersion: 1,
193
+ requires: { cms: "^0.1.0" },
194
+ admin: { server: "@tansy/blog/admin", client: "@tansy/blog/client", render: "@tansy/blog/render" },
195
+ csp: { frame: ["https://www.youtube-nocookie.com", "https://player.vimeo.com"] },
196
+ options: { schema: optionsSchema, value },
197
+ settings: {
198
+ permission: "ext.blog:moderate",
199
+ fields: [
200
+ { name: "comments", type: "select", perScope: true, default: value.comments, label: "Comments", options: [{ label: "Held for review", value: "moderated" }, { label: "Shown straight away", value: "open" }, { label: "Off", value: "off" }] },
201
+ { name: "notify", type: "text", perScope: true, default: value.notify ?? "", maxLength: 320, label: "Email for comments to review", description: "Who to tell when a comment is waiting. Leave empty for nobody." },
202
+ { name: "feedItems", type: "number", perScope: true, integer: true, min: 1, max: 100, default: value.feedItems, label: "Posts in feeds", description: "How many of the latest posts the RSS and Atom feeds list." },
203
+ ],
204
+ },
205
+ messages,
206
+ permissions: { "ext.blog": ["moderate", "credit"] },
207
+ contract: CONTRACT,
208
+ blocks: [
209
+ // Same fields as the blocks the blog theme used to create, so a site that had them keeps its stored blocks as they are.
210
+ defineBlock({ name: "blog_text", label: "Text", labels: { ar: "نص" }, category: "Text", fields: [{ name: "body", type: "rich_text", config: { labels: { ar: "النص" } } }] }),
211
+ defineBlock({ name: "blog_quote", label: "Quote", labels: { ar: "اقتباس" }, category: "Text", fields: [{ name: "text", type: "text", config: { required: true, labels: { ar: "النص" } } }, { name: "source", type: "text", config: { labels: { ar: "المصدر" } } }] }),
212
+ defineBlock({
213
+ name: "blog_callout",
214
+ label: "Callout",
215
+ labels: { ar: "تنبيه" },
216
+ category: "Text",
217
+ defaults: { tone: "info" },
218
+ fields: [
219
+ { name: "tone", type: "radio", config: { labels: { ar: "النوع" }, options: [{ label: "Note", labels: { ar: "ملاحظة" }, value: "info" }, { label: "Tip", labels: { ar: "نصيحة" }, value: "tip" }, { label: "Warning", labels: { ar: "تحذير" }, value: "warning" }] } },
220
+ { name: "body", type: "rich_text", config: { labels: { ar: "النص" } } },
221
+ ],
222
+ }),
223
+ defineBlock({
224
+ name: "blog_image",
225
+ label: "Image",
226
+ labels: { ar: "صورة" },
227
+ category: "Media",
228
+ fields: [
229
+ { name: "image", type: "image", config: { required: true, labels: { ar: "الصورة" } } },
230
+ { name: "alt", type: "text", config: { maxLength: 200, labels: { ar: "النص البديل" } } },
231
+ { name: "caption", type: "text", config: { maxLength: 300, labels: { ar: "التعليق" } } },
232
+ ],
233
+ }),
234
+ defineBlock({
235
+ name: "blog_embed",
236
+ label: "Video",
237
+ labels: { ar: "فيديو" },
238
+ category: "Media",
239
+ fields: [
240
+ { name: "url", type: "url", config: { required: true, allowedProtocols: ["https"], allowedDomains: ["youtube.com", "youtu.be", "vimeo.com"], labels: { ar: "الرابط" } } },
241
+ { name: "caption", type: "text", config: { maxLength: 300, labels: { ar: "التعليق" } } },
242
+ ],
243
+ }),
244
+ defineBlock({
245
+ name: "blog_code",
246
+ label: "Code",
247
+ labels: { ar: "رمز برمجي" },
248
+ category: "Text",
249
+ fields: [
250
+ { name: "code", type: "code", config: { required: true, labels: { ar: "الرمز" } } },
251
+ { name: "language", type: "text", config: { maxLength: 30, labels: { ar: "اللغة" } } },
252
+ ],
253
+ }),
254
+ ],
255
+ hooks: {
256
+ "record.beforeCreate": forContent(comments.prepare),
257
+ "record.beforeUpdate": forContent(comments.keepPlace),
258
+ "record.afterCreate": async (context) => { if (context.collection.slug === "blog-comments")
259
+ await comments.announce(context); },
260
+ },
261
+ routes: [feed("/feed.xml", rss, "application/rss+xml"), feed("/atom.xml", atom, "application/atom+xml")],
262
+ migrations: [{
263
+ id: "001-collections",
264
+ up: async ({ schema, system }) => {
265
+ for (const slug of COLLECTIONS) {
266
+ if (await schema.describe(slug))
267
+ throw new Error(`A collection called "${slug}" already exists, and the blog plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
268
+ }
269
+ await schema.apply(blogSchema(value.basePath));
270
+ await system.records.create("blog-home", { status: "published", title: "Blog" });
271
+ },
272
+ }, {
273
+ // Authors are people with a role, so a post names its writer instead of linking a profile.
274
+ id: "002-authors-are-people",
275
+ up: async ({ schema, roles }) => {
276
+ if (await schema.describe("blog-posts"))
277
+ await schema.addFields("blog-posts", [BYLINE_FIELD]);
278
+ for (const role of blogRoles())
279
+ await roles.ensure(role);
280
+ },
281
+ }, {
282
+ id: "003-names-in-languages",
283
+ up: async ({ schema }) => {
284
+ for (const [slug, labels] of Object.entries(COLLECTION_LABELS))
285
+ await schema.addLabels(slug, labels);
286
+ },
287
+ }, {
288
+ id: "004-field-names-in-languages",
289
+ up: async ({ schema }) => {
290
+ for (const [slug, fields] of Object.entries(FIELD_LABELS))
291
+ await schema.addFieldLabels(slug, fields);
292
+ },
293
+ }],
294
+ });
295
+ }