@basicbenframework/cms 0.7.3 → 0.8.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.
Files changed (37) hide show
  1. package/db/migrations/043_add_private_content.js +32 -0
  2. package/db/migrations/044_add_post_autosave_key.js +20 -0
  3. package/lib/client/components/admin/MediaPicker.js +3 -1
  4. package/lib/client/components/admin/SnippetPicker.js +3 -1
  5. package/lib/client/components/admin/SocialImageField.d.ts +24 -0
  6. package/lib/client/components/admin/SocialImageField.js +70 -0
  7. package/lib/client/i18n/locales/es/content.js +2 -0
  8. package/lib/client/i18n/locales/es/editor.js +18 -1
  9. package/lib/client/pages/admin/Pages.js +2 -2
  10. package/lib/client/pages/admin/PostEditor.js +103 -9
  11. package/lib/client/pages/admin/Posts.js +2 -2
  12. package/lib/controllers/FeedController.js +2 -2
  13. package/lib/controllers/MediaController.js +18 -1
  14. package/lib/controllers/PageController.js +5 -1
  15. package/lib/controllers/PostController.d.ts +14 -0
  16. package/lib/controllers/PostController.js +83 -1
  17. package/lib/helpers/autosave.d.ts +13 -0
  18. package/lib/helpers/autosave.js +19 -0
  19. package/lib/helpers/comment-mail.js +8 -3
  20. package/lib/helpers/redirects.d.ts +7 -1
  21. package/lib/helpers/redirects.js +7 -1
  22. package/lib/helpers/seo-fields.d.ts +7 -0
  23. package/lib/helpers/seo-fields.js +9 -0
  24. package/lib/models/Media.d.ts +4 -1
  25. package/lib/models/Media.js +18 -1
  26. package/lib/models/Menu.js +4 -4
  27. package/lib/models/Page.d.ts +2 -0
  28. package/lib/models/Page.js +6 -3
  29. package/lib/models/Post.d.ts +16 -0
  30. package/lib/models/Post.js +21 -1
  31. package/lib/models/PublicContent.d.ts +1 -1
  32. package/lib/models/PublicContent.js +5 -5
  33. package/lib/models/visibility.d.ts +9 -0
  34. package/lib/models/visibility.js +15 -1
  35. package/lib/routes/api/posts.js +3 -0
  36. package/lib/types/index.d.ts +4 -0
  37. package/package.json +1 -1
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Private posts and pages, the WordPress way.
3
+ *
4
+ * A private item is published but not public. Signed-in people who can edit it
5
+ * (editors and admins, and a post's own author) see it in the admin; nobody
6
+ * else sees it anywhere — not the content API, the theme, the feeds, the
7
+ * sitemap, oEmbed, search, menus, comments or newsletters.
8
+ *
9
+ * A flag rather than a fourth `status` or a `visibility` level, on purpose:
10
+ *
11
+ * - `status` is the editorial workflow (draft, pending, published) and is kept
12
+ * in step with the `published` flag every query reads. Private is not a
13
+ * step in that workflow: a private post can still be scheduled, and making
14
+ * one public again must not mean republishing it.
15
+ * - `visibility` (migration 034) says who may read the *body* of a post that
16
+ * is still listed, and its levels belong to the access policy a feature
17
+ * registers. Private hides the whole item, and must hold with no feature
18
+ * installed at all.
19
+ *
20
+ * Enforced in one place: `livePost()` and `livePage()` in
21
+ * `src/models/visibility.ts`, which every public read goes through.
22
+ */
23
+
24
+ export const up = async (db) => {
25
+ await db.exec('ALTER TABLE posts ADD COLUMN is_private INTEGER NOT NULL DEFAULT 0')
26
+ await db.exec('ALTER TABLE pages ADD COLUMN is_private INTEGER NOT NULL DEFAULT 0')
27
+ }
28
+
29
+ export const down = async (db) => {
30
+ await db.exec('ALTER TABLE pages DROP COLUMN is_private')
31
+ await db.exec('ALTER TABLE posts DROP COLUMN is_private')
32
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Makes the editor's first autosave of a new post idempotent.
3
+ *
4
+ * The editor turns a new post into a draft with one request
5
+ * (`POST /api/posts/autosave`). If the row is written but the response is lost,
6
+ * the editor cannot know, and its next try would make a second draft. It now
7
+ * sends a key it generated once per screen; the server stores it here and
8
+ * answers a repeat with the draft it already made. Unique per author, and
9
+ * null on every post written any other way.
10
+ */
11
+
12
+ export const up = async (db) => {
13
+ await db.exec('ALTER TABLE posts ADD COLUMN autosave_key TEXT')
14
+ await db.exec('CREATE UNIQUE INDEX idx_posts_autosave_key ON posts(user_id, autosave_key)')
15
+ }
16
+
17
+ export const down = async (db) => {
18
+ await db.exec('DROP INDEX IF EXISTS idx_posts_autosave_key')
19
+ await db.exec('ALTER TABLE posts DROP COLUMN autosave_key')
20
+ }
@@ -22,7 +22,9 @@ export default function MediaPicker({ onSelect, onClose }) {
22
22
  display: 'flex',
23
23
  alignItems: 'center',
24
24
  justifyContent: 'center',
25
- zIndex: 50,
25
+ // Above the admin sidebar (z-index 100), which is fixed at every width
26
+ // and otherwise covers the left of the dialog — and takes its clicks.
27
+ zIndex: 200,
26
28
  padding: '1rem'
27
29
  }, children: _jsxs("div", { onClick: event => event.stopPropagation(), onDragOver: event => {
28
30
  event.preventDefault();
@@ -41,7 +41,9 @@ export default function SnippetPicker({ onInsert, disabled }) {
41
41
  display: 'flex',
42
42
  alignItems: 'center',
43
43
  justifyContent: 'center',
44
- zIndex: 50,
44
+ // Above the admin sidebar (z-index 100), which is fixed at every width
45
+ // and otherwise covers the left of the dialog — and takes its clicks.
46
+ zIndex: 200,
45
47
  padding: '1rem'
46
48
  }, children: _jsxs("div", { onClick: event => event.stopPropagation(), style: {
47
49
  background: 'var(--surface)',
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The image on a social card — Open Graph or Twitter / X — for posts and pages.
3
+ *
4
+ * The same media library picker as the featured image, because the column is
5
+ * the same kind of thing: a media id, which the server turns into a URL
6
+ * through the storage adapter. A pasted URL is accepted too, and resolved to
7
+ * the library item it serves (`GET /api/media?url=`): the column cannot hold a
8
+ * URL from somewhere else, and storing one would put an address on every
9
+ * shared link that nothing here can check or move.
10
+ *
11
+ * Empty is the common case and means "fall back" — to the Open Graph image,
12
+ * then the featured image — so the empty state says which.
13
+ */
14
+ interface SocialImageFieldProps {
15
+ id: string;
16
+ label: string;
17
+ /** What a blank field falls back to, said in the empty state. */
18
+ fallback: string;
19
+ value: number | null;
20
+ onChange: (id: number | null) => void;
21
+ disabled?: boolean;
22
+ }
23
+ export default function SocialImageField({ id, label, fallback, value, onChange, disabled }: SocialImageFieldProps): import("react").JSX.Element;
24
+ export {};
@@ -0,0 +1,70 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useState } from 'react';
3
+ import MediaPicker from "./MediaPicker.js";
4
+ import { isImage, mediaUrl } from "../../hooks/useMediaLibrary.js";
5
+ import { api } from "../../../helpers/api.js";
6
+ import { useT } from "../../i18n/index.js";
7
+ export default function SocialImageField({ id, label, fallback, value, onChange, disabled }) {
8
+ const { t } = useT();
9
+ const [picking, setPicking] = useState(false);
10
+ const [url, setUrl] = useState(null);
11
+ const [pasted, setPasted] = useState('');
12
+ const [error, setError] = useState(null);
13
+ const [resolving, setResolving] = useState(false);
14
+ // A saved post carries only the id, so the preview asks for the rest.
15
+ useEffect(() => {
16
+ if (!value) {
17
+ setUrl(null);
18
+ return;
19
+ }
20
+ let current = true;
21
+ api.get(`/api/media/${value}`)
22
+ .then(res => { if (current && res?.media)
23
+ setUrl(mediaUrl(res.media)); })
24
+ .catch(() => { if (current)
25
+ setUrl(null); });
26
+ return () => { current = false; };
27
+ }, [value]);
28
+ const choose = (item) => {
29
+ if (!isImage(item.mime_type)) {
30
+ setError(t('A social card image has to be an image.'));
31
+ return;
32
+ }
33
+ setError(null);
34
+ setUrl(mediaUrl(item));
35
+ onChange(item.id);
36
+ setPicking(false);
37
+ };
38
+ const applyPasted = async () => {
39
+ const address = pasted.trim();
40
+ if (!address || resolving)
41
+ return;
42
+ setResolving(true);
43
+ setError(null);
44
+ try {
45
+ const res = await api.get(`/api/media?${new URLSearchParams({ url: address, per_page: '5' })}`);
46
+ const match = (res?.media ?? []).find(item => isImage(item.mime_type));
47
+ if (match) {
48
+ choose(match);
49
+ setPasted('');
50
+ }
51
+ else {
52
+ setError(t('That URL is not an image in the media library. Upload it first, then choose it here.'));
53
+ }
54
+ }
55
+ catch {
56
+ setError(t('Could not look that URL up.'));
57
+ }
58
+ finally {
59
+ setResolving(false);
60
+ }
61
+ };
62
+ return (_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: `${id}-url`, children: label }), value ? (_jsxs("div", { children: [url && (_jsx("img", { src: url, alt: "", style: { width: '100%', maxWidth: '320px', borderRadius: '0.375rem', display: 'block', marginBottom: '0.5rem' } })), _jsxs("div", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", disabled: disabled, onClick: () => setPicking(true), children: t('Replace') }), _jsx("button", { type: "button", className: "admin-btn admin-btn-danger", disabled: disabled, onClick: () => { setUrl(null); onChange(null); }, children: t('Remove') })] })] })) : (_jsxs("div", { style: { display: 'grid', gap: '0.5rem' }, children: [_jsx("small", { style: { color: 'var(--fg-muted)' }, children: fallback }), _jsxs("div", { style: { display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }, children: [_jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", disabled: disabled, onClick: () => setPicking(true), children: t('Choose image') }), _jsx("input", { id: `${id}-url`, type: "url", value: pasted, disabled: disabled, onChange: event => { setPasted(event.target.value); setError(null); },
63
+ // Enter here would submit the whole post.
64
+ onKeyDown: event => {
65
+ if (event.key === 'Enter') {
66
+ event.preventDefault();
67
+ void applyPasted();
68
+ }
69
+ }, className: "admin-input", style: { flex: '1 1 12rem' }, placeholder: t('or paste the URL of a library image') }), pasted.trim() && (_jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", disabled: disabled || resolving, onClick: () => void applyPasted(), children: resolving ? t('Looking…') : t('Use URL') }))] })] })), error && _jsx("small", { role: "alert", style: { color: 'var(--danger)', display: 'block', marginTop: '0.25rem' }, children: error }), picking && _jsx(MediaPicker, { onSelect: choose, onClose: () => setPicking(false) })] }));
70
+ }
@@ -22,6 +22,8 @@ const strings = {
22
22
  'Key': 'Clave',
23
23
  'Published': 'Publicada',
24
24
  'Draft': 'Borrador',
25
+ '(no title)': '(sin título)',
26
+ 'Only people who can edit it can see it': 'Solo la ven quienes pueden editarla',
25
27
  'Edit {name}': 'Editar {name}',
26
28
  'New {name}': 'Añadir {name}',
27
29
  'Select {name}': 'Seleccionar {name}',
@@ -139,6 +139,23 @@ const strings = {
139
139
  'Write': 'Escribir',
140
140
  'Preview failed: {message}': 'Error en la vista previa: {message}',
141
141
  'Nothing to preview yet.': 'Aún no hay nada que previsualizar.',
142
- 'Markdown supported — headings, lists, links, tables, and fenced code. HTML is shown as text rather than rendered.': 'Se admite Markdown: encabezados, listas, enlaces, tablas y bloques de código. El HTML se muestra como texto, no se interpreta.'
142
+ 'Markdown supported — headings, lists, links, tables, and fenced code. HTML is shown as text rather than rendered.': 'Se admite Markdown: encabezados, listas, enlaces, tablas y bloques de código. El HTML se muestra como texto, no se interpreta.',
143
+ // Visibility: public or private (migration 043)
144
+ 'Visibility': 'Visibilidad',
145
+ 'Public': 'Público',
146
+ 'Only its author, editors and admins see it, here in the admin. It is left out of the site, the API, feeds, the sitemap and search.': 'Solo la ven su autor, los editores y los administradores, aquí en el panel. Queda fuera del sitio, la API, los feeds, el mapa del sitio y la búsqueda.',
147
+ 'Only people who can edit pages see it, here in the admin. It is left out of the site, the API, feeds, the sitemap and search.': 'Solo la ven quienes pueden editar páginas, aquí en el panel. Queda fuera del sitio, la API, los feeds, el mapa del sitio y la búsqueda.',
148
+ // Social card images
149
+ 'Open Graph image': 'Imagen de Open Graph',
150
+ 'Twitter / X image': 'Imagen de Twitter / X',
151
+ 'Falls back to the featured image.': 'Si se deja vacía, se usa la imagen destacada.',
152
+ 'Falls back to the Open Graph image.': 'Si se deja vacía, se usa la imagen de Open Graph.',
153
+ 'A social card image has to be an image.': 'La imagen de una tarjeta social tiene que ser una imagen.',
154
+ 'Choose image': 'Elegir imagen',
155
+ 'or paste the URL of a library image': 'o pega la URL de una imagen de la biblioteca',
156
+ 'Use URL': 'Usar URL',
157
+ 'Looking…': 'Buscando…',
158
+ 'That URL is not an image in the media library. Upload it first, then choose it here.': 'Esa URL no es una imagen de la biblioteca de medios. Súbela primero y luego elígela aquí.',
159
+ 'Could not look that URL up.': 'No se pudo buscar esa URL.'
143
160
  };
144
161
  export default strings;
@@ -1,4 +1,4 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useState, useEffect } from 'react';
3
3
  import { api } from "../../../helpers/api.js";
4
4
  import AdminLayout from "../../layouts/AdminLayout.js";
@@ -49,5 +49,5 @@ export default function AdminPages() {
49
49
  if (loading) {
50
50
  return (_jsx(AdminLayout, { title: t('Pages'), children: _jsx("div", { className: "admin-loading", children: t('Loading...') }) }));
51
51
  }
52
- return (_jsx(AdminLayout, { title: t('Pages'), actions: _jsx(Link, { href: "/admin/pages/new", className: "admin-btn admin-btn-primary", children: t('+ New Page') }), children: _jsxs("div", { className: "admin-card", children: [pages.length === 0 ? (_jsx("p", { style: { color: 'var(--fg-muted)', textAlign: 'center', padding: '2rem' }, children: t('No pages yet. Create your first page!') })) : (_jsxs("table", { className: "admin-table", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { children: t('Title') }), _jsx("th", { children: t('Slug') }), _jsx("th", { children: t('Template') }), _jsx("th", { children: t('Status') }), _jsx("th", { children: t('Actions') })] }) }), _jsx("tbody", { children: pages.map(page => (_jsxs("tr", { children: [_jsx("td", { children: _jsx(Link, { href: `/admin/pages/${page.id}/edit`, style: { color: 'var(--accent)', fontWeight: 500 }, children: page.title }) }), _jsx("td", { children: _jsxs("code", { children: ["/", page.slug] }) }), _jsx("td", { children: page.template }), _jsx("td", { children: _jsx("span", { className: `admin-badge ${page.published ? 'admin-badge-success' : 'admin-badge-warning'}`, children: page.published ? t('Published') : t('Draft') }) }), _jsx("td", { children: _jsxs("div", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx(Link, { href: `/admin/pages/${page.id}/edit`, className: "admin-btn admin-btn-secondary", children: t('Edit') }), _jsx("button", { onClick: () => handleDelete(page.id), className: "admin-btn admin-btn-danger", children: t('Delete') })] }) })] }, page.id))) })] })), meta && _jsx(Pagination, { meta: meta, onChange: setPage, noun: t('pages') })] }) }));
52
+ return (_jsx(AdminLayout, { title: t('Pages'), actions: _jsx(Link, { href: "/admin/pages/new", className: "admin-btn admin-btn-primary", children: t('+ New Page') }), children: _jsxs("div", { className: "admin-card", children: [pages.length === 0 ? (_jsx("p", { style: { color: 'var(--fg-muted)', textAlign: 'center', padding: '2rem' }, children: t('No pages yet. Create your first page!') })) : (_jsxs("table", { className: "admin-table", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { children: t('Title') }), _jsx("th", { children: t('Slug') }), _jsx("th", { children: t('Template') }), _jsx("th", { children: t('Status') }), _jsx("th", { children: t('Actions') })] }) }), _jsx("tbody", { children: pages.map(page => (_jsxs("tr", { children: [_jsx("td", { children: _jsx(Link, { href: `/admin/pages/${page.id}/edit`, style: { color: 'var(--accent)', fontWeight: 500 }, children: page.title }) }), _jsx("td", { children: _jsxs("code", { children: ["/", page.slug] }) }), _jsx("td", { children: page.template }), _jsxs("td", { children: [_jsx("span", { className: `admin-badge ${page.published ? 'admin-badge-success' : 'admin-badge-warning'}`, children: page.published ? t('Published') : t('Draft') }), Number(page.is_private) ? (_jsxs(_Fragment, { children: [' ', _jsx("span", { className: "admin-badge admin-badge-info", title: t('Only people who can edit it can see it'), children: t('Private') })] })) : null] }), _jsx("td", { children: _jsxs("div", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx(Link, { href: `/admin/pages/${page.id}/edit`, className: "admin-btn admin-btn-secondary", children: t('Edit') }), _jsx("button", { onClick: () => handleDelete(page.id), className: "admin-btn admin-btn-danger", children: t('Delete') })] }) })] }, page.id))) })] })), meta && _jsx(Pagination, { meta: meta, onChange: setPage, noun: t('pages') })] }) }));
53
53
  }
@@ -6,6 +6,7 @@ import AdminLayout from "../../layouts/AdminLayout.js";
6
6
  import MarkdownEditor from "../../components/MarkdownEditor.js";
7
7
  import { excerpt, slugify } from '@basicbenframework/core/content';
8
8
  import FeaturedImageBox from "../../components/admin/FeaturedImageBox.js";
9
+ import SocialImageField from "../../components/admin/SocialImageField.js";
9
10
  import { Slot, hasFills } from "../../host/index.js";
10
11
  import TermPicker from "../../components/admin/TermPicker.js";
11
12
  import SnippetPicker from "../../components/admin/SnippetPicker.js";
@@ -15,8 +16,15 @@ import { CustomFieldsPanel, CustomTermsPanel } from "../../components/admin/Cont
15
16
  import { Link } from "../../components/Link.js";
16
17
  import { can } from '@basicbenframework/core/auth/permissions';
17
18
  import { useT, slots } from "../../i18n/index.js";
19
+ import { worthAutosaving } from "../../../helpers/autosave.js";
18
20
  /** How often an unsaved change is autosaved, in milliseconds. */
19
21
  const AUTOSAVE_EVERY = 30_000;
22
+ /**
23
+ * How long after the first words of a new post it is saved as a draft. Short,
24
+ * because until then a closed tab loses it; not instant, so the draft starts
25
+ * with more than its first letter.
26
+ */
27
+ const FIRST_AUTOSAVE_AFTER = 3_000;
20
28
  /** A stored UTC timestamp as the value a datetime-local input wants. */
21
29
  function toLocalInput(value) {
22
30
  if (!value)
@@ -112,12 +120,16 @@ export default function AdminPostEditor() {
112
120
  publish_at: '',
113
121
  og_title: '',
114
122
  og_description: '',
123
+ // Media ids, like the featured image; SocialImageField shows them.
115
124
  og_image: null,
116
- og_image_url: null,
117
125
  twitter_title: '',
118
126
  twitter_description: '',
127
+ twitter_image: null,
119
128
  canonical_url: '',
120
129
  noindex: false,
130
+ // Private: published, but only for people who can edit it, in the admin.
131
+ // Posts and pages both; the server leaves it out of every public read.
132
+ is_private: false,
121
133
  // Posts only: who may read the body. The levels beyond public, and what
122
134
  // they mean, belong to a feature (see the post.editor.sidebar slot below).
123
135
  visibility: 'public',
@@ -144,11 +156,76 @@ export default function AdminPostEditor() {
144
156
  // The post as loaded, and the fields the sidebar's feature panels set.
145
157
  const [loaded, setLoaded] = useState(null);
146
158
  const [extra, setExtra] = useState({});
159
+ // The latest form, for timers that outlive the render that set them.
160
+ const latest = useRef(formData);
161
+ latest.current = formData;
162
+ // The draft this editor created for a new post (see createDraft). Its id is
163
+ // in the URL now, but what is on screen is newer than what was saved, so it
164
+ // is not loaded back over the top of the typing.
165
+ const adopted = useRef(null);
166
+ const creatingDraft = useRef(null);
167
+ // One per screen, so a retry after a lost response returns the draft the
168
+ // first try made instead of making another. randomUUID needs a secure
169
+ // context; an admin served over plain http elsewhere gets the fallback.
170
+ const autosaveKey = useRef(typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
171
+ ? crypto.randomUUID()
172
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`);
147
173
  useEffect(() => {
174
+ if (postId && postId === adopted.current)
175
+ return;
148
176
  loadData();
149
177
  }, [postId]);
150
- // Autosave an existing post while it is being edited. A new post has no id
151
- // to autosave against until its first save.
178
+ /**
179
+ * Save a new post as a draft, so autosave has something to save against.
180
+ *
181
+ * Once, on the first title or body: an untouched New post screen creates
182
+ * nothing. The editor then becomes the editor for that post — the URL is
183
+ * replaced with its edit URL in place, the way WordPress does it, so the
184
+ * component, the focus and whatever is being typed stay exactly where they
185
+ * are. Saving waits for this if it is still in flight, so a quick Save does
186
+ * not create the post twice.
187
+ */
188
+ const createDraft = () => {
189
+ if (creatingDraft.current)
190
+ return creatingDraft.current;
191
+ const sent = { title: latest.current.title, content: latest.current.content, excerpt: latest.current.excerpt };
192
+ creatingDraft.current = api
193
+ .post('/api/posts/autosave', { ...sent, post_type: postType, autosave_key: autosaveKey.current })
194
+ .then(res => {
195
+ const id = res?.post?.id;
196
+ if (!id)
197
+ throw new Error('No id');
198
+ adopted.current = id;
199
+ setLastAutosaved(new Date().toISOString());
200
+ // Only typing since the request left needs the next autosave.
201
+ const now = latest.current;
202
+ dirty.current = now.title !== sent.title || now.content !== sent.content || now.excerpt !== sent.excerpt;
203
+ // navigate() scrolls to the top, which is not where the writer is.
204
+ const scrolled = window.scrollY;
205
+ navigateWithType(to => navigate(to, { replace: true }), `/admin/posts/${id}/edit`, postType);
206
+ window.scrollTo(0, scrolled);
207
+ return id;
208
+ })
209
+ .catch(error => {
210
+ console.error('Failed to autosave the new post:', error);
211
+ // Try again on the next edit rather than never.
212
+ creatingDraft.current = null;
213
+ return null;
214
+ });
215
+ return creatingDraft.current;
216
+ };
217
+ // A new post's first autosave: a few seconds after there is a title or a
218
+ // body worth keeping (helpers/autosave.ts — a stray keystroke is not),
219
+ // timed from that point rather than reset by every keystroke.
220
+ const hasText = worthAutosaving(formData.title, formData.content);
221
+ useEffect(() => {
222
+ if (isPage || postId || !hasText)
223
+ return;
224
+ const timer = setTimeout(() => void createDraft(), FIRST_AUTOSAVE_AFTER);
225
+ return () => clearTimeout(timer);
226
+ }, [isPage, postId, hasText]);
227
+ // Autosave an existing post while it is being edited — including a new one
228
+ // once createDraft has given it an id.
152
229
  useEffect(() => {
153
230
  if (isPage || !postId)
154
231
  return;
@@ -237,11 +314,12 @@ export default function AdminPostEditor() {
237
314
  og_title: record.og_title || '',
238
315
  og_description: record.og_description || '',
239
316
  og_image: record.og_image ?? null,
240
- og_image_url: null,
241
317
  twitter_title: record.twitter_title || '',
242
318
  twitter_description: record.twitter_description || '',
319
+ twitter_image: record.twitter_image ?? null,
243
320
  canonical_url: record.canonical_url || '',
244
321
  noindex: Boolean(Number(record.noindex ?? 0)),
322
+ is_private: Boolean(Number(record.is_private ?? 0)),
245
323
  visibility: String(record.visibility || 'public'),
246
324
  featured_image: record.featured_image ?? null,
247
325
  featured_image_url: record.featured_image_url ?? null,
@@ -330,7 +408,7 @@ export default function AdminPostEditor() {
330
408
  // `featured_image_url` is the server's answer, not the editor's input —
331
409
  // sending it back would be asking the API to store a URL in a column that
332
410
  // holds a media id.
333
- const { featured_image_url, og_image_url, user_id, category_ids, tags, excerpt, status, publish_at, published, ...common } = formData;
411
+ const { featured_image_url, user_id, category_ids, tags, excerpt, status, publish_at, published, ...common } = formData;
334
412
  const finalStatus = submitStatus ?? status;
335
413
  // Posts only: a page has no visibility. `extra` is what the sidebar's
336
414
  // feature panels set; see PostEditorSidebarProps.
@@ -361,8 +439,10 @@ export default function AdminPostEditor() {
361
439
  ...(contentType?.supports.custom_fields && contentType.fields.length ? { fields: customFields } : {}),
362
440
  ...(termsReady ? { term_ids: termIds } : {})
363
441
  };
364
- if (isEditing) {
365
- await api.put(`/api/${resource}/${postId}`, payload);
442
+ // A new post whose first autosave is on its way is that post now.
443
+ const id = postId ?? (creatingDraft.current ? await creatingDraft.current : null);
444
+ if (id) {
445
+ await api.put(`/api/${resource}/${id}`, payload);
366
446
  }
367
447
  else {
368
448
  await api.post(`/api/${resource}`, payload);
@@ -394,6 +474,12 @@ export default function AdminPostEditor() {
394
474
  [name]: type === 'checkbox' ? checked : value
395
475
  }));
396
476
  };
477
+ const setImage = (key, id) => {
478
+ if (lockedOut)
479
+ return;
480
+ dirty.current = true;
481
+ setFormData(prev => ({ ...prev, [key]: id }));
482
+ };
397
483
  // What the main button will do, so its label can say so.
398
484
  const scheduledFor = formData.publish_at ? new Date(formData.publish_at) : null;
399
485
  const isFuture = Boolean(scheduledFor && scheduledFor.getTime() > Date.now());
@@ -507,11 +593,19 @@ export default function AdminPostEditor() {
507
593
  : slots(t('{name} is editing this post. You can read it, but saving is paused so neither of you overwrites the other.'), { name: _jsx("strong", { children: lock.holder }) }) }), _jsxs("span", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx("button", { type: "button", className: "admin-btn admin-btn-primary", onClick: takeOver, children: t('Take over') }), _jsx(Link, { href: "/admin/posts", className: "admin-btn admin-btn-secondary", children: t('Back to posts') })] })] })), lock.status === 'free' && (_jsxs("div", { className: "admin-card", role: "status", style: { display: 'flex', gap: '0.75rem', alignItems: 'center', justifyContent: 'space-between' }, children: [_jsx("span", { children: t('{name} has finished editing. Reload to see their changes and start editing.', { name: lock.holder || t('The other editor') }) }), _jsx("button", { type: "button", className: "admin-btn admin-btn-primary", onClick: reloadAndEdit, children: t('Reload and edit') })] })), autosave && (_jsxs("div", { className: "admin-card", role: "status", style: { display: 'flex', gap: '0.75rem', alignItems: 'center', justifyContent: 'space-between' }, children: [_jsx("span", { children: t('There is an autosave of this post from {date} that is newer than the saved version.', { date: new Date(autosave.created_at).toLocaleString() }) }), _jsxs("span", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx("button", { type: "button", className: "admin-btn admin-btn-primary", onClick: restoreAutosave, children: t('Restore it') }), _jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", onClick: () => setAutosave(null), children: t('Dismiss') })] })] })), _jsxs("div", { className: "admin-grid admin-grid-2", style: { gridTemplateColumns: '2fr 1fr' }, children: [_jsxs("div", { children: [_jsxs("div", { className: "admin-card", children: [_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Title') }), _jsx("input", { type: "text", name: "title", value: formData.title, onChange: handleChange, className: "admin-input", placeholder: pick(t('Enter page title'), t('Enter post title'), t('Enter {type} title', { type: customType?.toLowerCase() ?? '' })), required: true }), _jsxs("div", { className: "admin-slug", children: [_jsx("label", { htmlFor: "slug", children: t('Slug') }), _jsx("input", { id: "slug", type: "text", name: "slug", value: formData.slug, onChange: handleChange, className: "admin-slug-input", placeholder: slugify(formData.title) || pick(t('page-url-slug'), t('post-url-slug'), t('{type}-url-slug', { type: slugify(customType ?? '') })) }), !formData.slug.trim() && _jsx("span", { className: "admin-slug-note", children: t('from the title') })] })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Content') }), _jsx(MarkdownEditor, { name: "content", value: formData.content, onChange: handleChange, minHeight: "400px", placeholder: t('Write your content here. Markdown is supported.'), required: true, readOnly: lockedOut, tools: (insert, disabled) => _jsx(SnippetPicker, { onInsert: insert, disabled: disabled }) })] }), !isPage && supports('excerpt') && (_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Excerpt') }), _jsx("textarea", { name: "excerpt", value: formData.excerpt, onChange: handleChange, className: "admin-textarea", style: { minHeight: '100px' }, placeholder: summaryOf(formData.content) || t('Written for you from the content if you leave this blank') })] }))] }), !isPage && (_jsx(CustomFieldsPanel, { type: contentType, values: customFields, disabled: lockedOut, onChange: values => {
508
594
  dirty.current = true;
509
595
  setCustomFields(values);
510
- } })), _jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('SEO Settings') }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Meta Title') }), _jsx("input", { type: "text", name: "meta_title", value: formData.meta_title, onChange: handleChange, className: "admin-input", placeholder: t('SEO title') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Meta Description') }), _jsx("textarea", { name: "meta_description", value: formData.meta_description, onChange: handleChange, className: "admin-textarea", style: { minHeight: '80px' }, placeholder: t('SEO description') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Canonical URL') }), _jsx("input", { type: "url", name: "canonical_url", value: formData.canonical_url, onChange: handleChange, className: "admin-input", placeholder: t('Only if this was first published somewhere else') })] }), _jsx("div", { className: "admin-form-group", children: _jsxs("label", { style: { display: 'flex', alignItems: 'center', gap: '0.5rem' }, children: [_jsx("input", { type: "checkbox", name: "noindex", checked: formData.noindex, onChange: handleChange }), pick(t('Ask search engines not to index this page'), t('Ask search engines not to index this post'), t('Ask search engines not to index this {type}', { type: customType?.toLowerCase() ?? '' }))] }) })] }), _jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Social cards') }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Open Graph title') }), _jsx("input", { type: "text", name: "og_title", value: formData.og_title, onChange: handleChange, className: "admin-input", placeholder: formData.meta_title || formData.title || t('Falls back to the SEO title') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Open Graph description') }), _jsx("textarea", { name: "og_description", value: formData.og_description, onChange: handleChange, className: "admin-textarea", style: { minHeight: '60px' }, placeholder: formData.meta_description || t('Falls back to the SEO description') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Twitter / X title') }), _jsx("input", { type: "text", name: "twitter_title", value: formData.twitter_title, onChange: handleChange, className: "admin-input", placeholder: t('Falls back to the Open Graph title') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Twitter / X description') }), _jsx("textarea", { name: "twitter_description", value: formData.twitter_description, onChange: handleChange, className: "admin-textarea", style: { minHeight: '60px' }, placeholder: t('Falls back to the Open Graph description') })] })] }), !isPage && isEditing && revisions.length > 0 && (_jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Revisions') }), _jsx("ul", { style: { listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.5rem' }, children: revisions.slice(0, 20).map(revision => (_jsxs("li", { style: { display: 'flex', justifyContent: 'space-between', gap: '0.5rem', alignItems: 'center' }, children: [_jsxs("span", { children: [new Date(revision.created_at).toLocaleString(), revision.author_name ? ` — ${revision.author_name}` : '', _jsx("br", {}), _jsx("small", { style: { color: 'var(--fg-muted)' }, children: revision.title })] }), _jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", onClick: () => restoreRevision(revision), children: t('Restore') })] }, revision.id))) })] }))] }), _jsxs("div", { children: [_jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Publish') }), isPage ? (_jsx("div", { className: "admin-form-group", children: _jsxs("label", { style: { display: 'flex', alignItems: 'center', gap: '0.5rem' }, children: [_jsx("input", { type: "checkbox", name: "published", checked: formData.published, onChange: handleChange }), t('Published')] }) })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: "status", children: t('Status') }), _jsxs("select", { id: "status", name: "status", value: formData.status, onChange: handleChange, className: "admin-input", children: [_jsx("option", { value: "draft", children: t('Draft') }), _jsx("option", { value: "pending", children: t('Pending review') }), _jsx("option", { value: "published", disabled: !mayPublish && formData.status !== 'published', children: mayPublish ? t('Published') : t('Published (an editor publishes)') })] })] }), formData.status === 'published' && (_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: "publish_at", children: t('Publish on') }), _jsx("input", { id: "publish_at", type: "datetime-local", name: "publish_at", value: formData.publish_at, onChange: handleChange, className: "admin-input" }), _jsx("small", { style: { color: 'var(--fg-muted)' }, children: isFuture
596
+ } })), _jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('SEO Settings') }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Meta Title') }), _jsx("input", { type: "text", name: "meta_title", value: formData.meta_title, onChange: handleChange, className: "admin-input", placeholder: t('SEO title') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Meta Description') }), _jsx("textarea", { name: "meta_description", value: formData.meta_description, onChange: handleChange, className: "admin-textarea", style: { minHeight: '80px' }, placeholder: t('SEO description') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Canonical URL') }), _jsx("input", { type: "url", name: "canonical_url", value: formData.canonical_url, onChange: handleChange, className: "admin-input", placeholder: t('Only if this was first published somewhere else') })] }), _jsx("div", { className: "admin-form-group", children: _jsxs("label", { style: { display: 'flex', alignItems: 'center', gap: '0.5rem' }, children: [_jsx("input", { type: "checkbox", name: "noindex", checked: formData.noindex, onChange: handleChange }), pick(t('Ask search engines not to index this page'), t('Ask search engines not to index this post'), t('Ask search engines not to index this {type}', { type: customType?.toLowerCase() ?? '' }))] }) })] }), _jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Social cards') }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Open Graph title') }), _jsx("input", { type: "text", name: "og_title", value: formData.og_title, onChange: handleChange, className: "admin-input", placeholder: formData.meta_title || formData.title || t('Falls back to the SEO title') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Open Graph description') }), _jsx("textarea", { name: "og_description", value: formData.og_description, onChange: handleChange, className: "admin-textarea", style: { minHeight: '60px' }, placeholder: formData.meta_description || t('Falls back to the SEO description') })] }), _jsx(SocialImageField, { id: "og_image", label: t('Open Graph image'), fallback: t('Falls back to the featured image.'), value: formData.og_image, disabled: lockedOut, onChange: id => setImage('og_image', id) }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Twitter / X title') }), _jsx("input", { type: "text", name: "twitter_title", value: formData.twitter_title, onChange: handleChange, className: "admin-input", placeholder: t('Falls back to the Open Graph title') })] }), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", children: t('Twitter / X description') }), _jsx("textarea", { name: "twitter_description", value: formData.twitter_description, onChange: handleChange, className: "admin-textarea", style: { minHeight: '60px' }, placeholder: t('Falls back to the Open Graph description') })] }), _jsx(SocialImageField, { id: "twitter_image", label: t('Twitter / X image'), fallback: t('Falls back to the Open Graph image.'), value: formData.twitter_image, disabled: lockedOut, onChange: id => setImage('twitter_image', id) })] }), !isPage && isEditing && revisions.length > 0 && (_jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Revisions') }), _jsx("ul", { style: { listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: '0.5rem' }, children: revisions.slice(0, 20).map(revision => (_jsxs("li", { style: { display: 'flex', justifyContent: 'space-between', gap: '0.5rem', alignItems: 'center' }, children: [_jsxs("span", { children: [new Date(revision.created_at).toLocaleString(), revision.author_name ? ` — ${revision.author_name}` : '', _jsx("br", {}), _jsx("small", { style: { color: 'var(--fg-muted)' }, children: revision.title })] }), _jsx("button", { type: "button", className: "admin-btn admin-btn-secondary", onClick: () => restoreRevision(revision), children: t('Restore') })] }, revision.id))) })] }))] }), _jsxs("div", { children: [_jsxs("div", { className: "admin-card", children: [_jsx("h3", { className: "admin-card-title", children: t('Publish') }), isPage ? (_jsx("div", { className: "admin-form-group", children: _jsxs("label", { style: { display: 'flex', alignItems: 'center', gap: '0.5rem' }, children: [_jsx("input", { type: "checkbox", name: "published", checked: formData.published, onChange: handleChange }), t('Published')] }) })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: "status", children: t('Status') }), _jsxs("select", { id: "status", name: "status", value: formData.status, onChange: handleChange, className: "admin-input", children: [_jsx("option", { value: "draft", children: t('Draft') }), _jsx("option", { value: "pending", children: t('Pending review') }), _jsx("option", { value: "published", disabled: !mayPublish && formData.status !== 'published', children: mayPublish ? t('Published') : t('Published (an editor publishes)') })] })] }), formData.status === 'published' && (_jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: "publish_at", children: t('Publish on') }), _jsx("input", { id: "publish_at", type: "datetime-local", name: "publish_at", value: formData.publish_at, onChange: handleChange, className: "admin-input" }), _jsx("small", { style: { color: 'var(--fg-muted)' }, children: isFuture
511
597
  ? t('Scheduled — goes live {date}.', { date: scheduledFor.toLocaleString() })
512
598
  : formData.publish_at
513
599
  ? t('Already live.')
514
- : t('Blank publishes now. A future date schedules it.') })] })), lastAutosaved && (_jsx("p", { style: { color: 'var(--fg-muted)', fontSize: '0.8rem' }, children: t('Autosaved {time}', { time: new Date(lastAutosaved).toLocaleTimeString() }) }))] })), _jsxs("div", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx("button", { type: "submit", className: "admin-btn admin-btn-primary", disabled: saving || lockedOut, title: lockedOut ? t('Someone else is editing this post') : undefined, style: { flex: 1 }, children: submitLabel }), _jsx(Link, { href: `/admin/${resource}`, className: "admin-btn admin-btn-secondary", children: t('Cancel') })] })] }), !isPage && (_jsx(Slot, { name: "post.editor.sidebar", kind: "post", postId: postId, record: loaded, values: { visibility: formData.visibility, ...extra }, disabled: lockedOut, onChange: (changes) => {
600
+ : t('Blank publishes now. A future date schedules it.') })] })), lastAutosaved && (_jsx("p", { style: { color: 'var(--fg-muted)', fontSize: '0.8rem' }, children: t('Autosaved {time}', { time: new Date(lastAutosaved).toLocaleTimeString() }) }))] })), _jsxs("div", { className: "admin-form-group", children: [_jsx("label", { className: "admin-label", htmlFor: "is_private", children: t('Visibility') }), _jsxs("select", { id: "is_private", value: formData.is_private ? 'private' : 'public', onChange: event => {
601
+ if (lockedOut)
602
+ return;
603
+ dirty.current = true;
604
+ const isPrivate = event.target.value === 'private';
605
+ setFormData(prev => ({ ...prev, is_private: isPrivate }));
606
+ }, className: "admin-input", children: [_jsx("option", { value: "public", children: t('Public') }), _jsx("option", { value: "private", children: t('Private') })] }), formData.is_private && (_jsx("small", { style: { color: 'var(--fg-muted)' }, children: isPage
607
+ ? t('Only people who can edit pages see it, here in the admin. It is left out of the site, the API, feeds, the sitemap and search.')
608
+ : t('Only its author, editors and admins see it, here in the admin. It is left out of the site, the API, feeds, the sitemap and search.') }))] }), _jsxs("div", { style: { display: 'flex', gap: '0.5rem' }, children: [_jsx("button", { type: "submit", className: "admin-btn admin-btn-primary", disabled: saving || lockedOut, title: lockedOut ? t('Someone else is editing this post') : undefined, style: { flex: 1 }, children: submitLabel }), _jsx(Link, { href: `/admin/${resource}`, className: "admin-btn admin-btn-secondary", children: t('Cancel') })] })] }), !isPage && (_jsx(Slot, { name: "post.editor.sidebar", kind: "post", postId: postId, record: loaded, values: { visibility: formData.visibility, ...extra }, disabled: lockedOut, onChange: (changes) => {
515
609
  dirty.current = true;
516
610
  const { visibility, ...rest } = changes;
517
611
  if (typeof visibility === 'string')
@@ -145,8 +145,8 @@ export default function AdminPosts() {
145
145
  : t('Nothing here.') })) : (_jsxs("table", { className: "admin-table", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { style: { width: '2rem' }, children: _jsx("input", { type: "checkbox", "aria-label": t('Select all posts on this page'), checked: allSelected, onChange: () => setSelected(allSelected ? [] : posts.map(p => p.id)) }) }), _jsx("th", { children: t('Title') }), _jsx("th", { children: t('Author') }), _jsx("th", { children: t('Categories') }), _jsx("th", { children: t('Status') }), _jsx("th", { children: t('Date') }), _jsx("th", { children: t('Actions') })] }) }), _jsx("tbody", { children: posts.map(post => {
146
146
  const badge = badgeFor(post);
147
147
  const date = parseUtc(post.publish_at) ?? parseUtc(post.created_at);
148
- return (_jsxs("tr", { children: [_jsx("td", { children: _jsx("input", { type: "checkbox", "aria-label": t('Select {name}', { name: post.title }), checked: selected.includes(post.id), onChange: () => toggle(post.id) }) }), _jsx("td", { children: inTrash ? (_jsx("span", { style: { fontWeight: 500 }, children: post.title })) : (_jsx(Link, { href: `/admin/posts/${post.id}/edit`, style: { color: 'var(--accent)', fontWeight: 500 }, children: post.title })) }), _jsx("td", { children: post.author_name || '—' }), _jsx("td", { children: post.categories?.length
148
+ return (_jsxs("tr", { children: [_jsx("td", { children: _jsx("input", { type: "checkbox", "aria-label": t('Select {name}', { name: post.title }), checked: selected.includes(post.id), onChange: () => toggle(post.id) }) }), _jsx("td", { children: inTrash ? (_jsx("span", { style: { fontWeight: 500 }, children: post.title || t('(no title)') })) : (_jsx(Link, { href: `/admin/posts/${post.id}/edit`, style: { color: 'var(--accent)', fontWeight: 500 }, children: post.title || t('(no title)') })) }), _jsx("td", { children: post.author_name || '—' }), _jsx("td", { children: post.categories?.length
149
149
  ? post.categories.map(c => c.name).join(', ')
150
- : '—' }), _jsx("td", { children: _jsx("span", { className: `admin-badge ${badge.tone}`, children: badge.label }) }), _jsx("td", { children: date ? date.toLocaleDateString() : '—' }), _jsx("td", { children: _jsx("div", { style: { display: 'flex', gap: '0.5rem' }, children: inTrash ? (_jsxs(_Fragment, { children: [_jsx("button", { onClick: () => runBulk('restore', [post.id]), className: "admin-btn admin-btn-secondary", children: t('Restore') }), _jsx("button", { onClick: () => runBulk('delete', [post.id]), className: "admin-btn admin-btn-danger", children: t('Delete permanently') })] })) : (_jsxs(_Fragment, { children: [_jsx(Link, { href: `/admin/posts/${post.id}/edit`, className: "admin-btn admin-btn-secondary", children: t('Edit') }), _jsx("button", { onClick: () => trash(post.id), className: "admin-btn admin-btn-danger", children: t('Trash') })] })) }) })] }, post.id));
150
+ : '—' }), _jsxs("td", { children: [_jsx("span", { className: `admin-badge ${badge.tone}`, children: badge.label }), Number(post.is_private) ? (_jsxs(_Fragment, { children: [' ', _jsx("span", { className: "admin-badge admin-badge-info", title: t('Only people who can edit it can see it'), children: t('Private') })] })) : null] }), _jsx("td", { children: date ? date.toLocaleDateString() : '—' }), _jsx("td", { children: _jsx("div", { style: { display: 'flex', gap: '0.5rem' }, children: inTrash ? (_jsxs(_Fragment, { children: [_jsx("button", { onClick: () => runBulk('restore', [post.id]), className: "admin-btn admin-btn-secondary", children: t('Restore') }), _jsx("button", { onClick: () => runBulk('delete', [post.id]), className: "admin-btn admin-btn-danger", children: t('Delete permanently') })] })) : (_jsxs(_Fragment, { children: [_jsx(Link, { href: `/admin/posts/${post.id}/edit`, className: "admin-btn admin-btn-secondary", children: t('Edit') }), _jsx("button", { onClick: () => trash(post.id), className: "admin-btn admin-btn-danger", children: t('Trash') })] })) }) })] }, post.id));
151
151
  }) })] })), meta && _jsx(Pagination, { meta: meta, onChange: setPage, noun: t('posts') })] }) }));
152
152
  }
@@ -1,6 +1,6 @@
1
1
  import { getDb } from '@basicbenframework/core/db';
2
2
  import { Settings } from "../models/Settings.js";
3
- import { livePost } from "../models/visibility.js";
3
+ import { livePost, livePage } from "../models/visibility.js";
4
4
  import { siteUrl } from "../helpers/site.js";
5
5
  import { isGated, gatedFeedHtml, publicExcerpt } from "../helpers/gating.js";
6
6
  import { excerpt as plainText } from '@basicbenframework/core/content';
@@ -178,7 +178,7 @@ export const FeedController = {
178
178
  const baseOf = (key) => customTypes.find((type) => type.key === key)?.route_base ?? null;
179
179
  const pages = await db.all(`
180
180
  SELECT id, slug, updated_at FROM pages
181
- WHERE published = 1 AND (noindex IS NULL OR noindex = 0)
181
+ WHERE ${livePage('pages')} AND (noindex IS NULL OR noindex = 0)
182
182
  `);
183
183
  const categories = await db.all('SELECT id, slug FROM categories');
184
184
  const url = (loc, extra = '') => ` <url>
@@ -30,7 +30,8 @@ export const MediaController = {
30
30
  const perPage = Math.min(100, Math.max(1, parseInt(req.query.per_page) || 20));
31
31
  const search = req.query.search || undefined;
32
32
  const type = req.query.type || undefined;
33
- const { items, total } = await Media.all(page, perPage, { search, type });
33
+ const servedAt = servedPath(req.query.url);
34
+ const { items, total } = await Media.all(page, perPage, { search, type, servedAt });
34
35
  res.json({
35
36
  media: await withUrls(items),
36
37
  pagination: {
@@ -187,3 +188,19 @@ async function withUrls(items) {
187
188
  url: storage.publicUrl(item.path)
188
189
  }));
189
190
  }
191
+ /**
192
+ * The path part of a pasted URL, for `?url=`: the editor's "paste a URL" box
193
+ * finds the library item a URL serves. Absolute or root-relative; anything
194
+ * that is not a URL at all matches nothing.
195
+ */
196
+ function servedPath(value) {
197
+ if (typeof value !== 'string' || !value.trim())
198
+ return undefined;
199
+ try {
200
+ const path = decodeURIComponent(new URL(value.trim(), 'http://localhost').pathname).replace(/^\/+/, '');
201
+ return path ? path.slice(0, 1024) : undefined;
202
+ }
203
+ catch {
204
+ return undefined;
205
+ }
206
+ }
@@ -1,7 +1,7 @@
1
1
  import { validate, rules } from '@basicbenframework/core/validation';
2
2
  import { hooks, HOOKS } from '@basicbenframework/core/hooks';
3
3
  import { Page } from "../models/Page.js";
4
- import { seoFields } from "../helpers/seo-fields.js";
4
+ import { seoFields, privateFlag } from "../helpers/seo-fields.js";
5
5
  import { redirectIfSlugChanged, releasePath } from "../helpers/redirects.js";
6
6
  import { pagePath } from "../helpers/content-paths.js";
7
7
  import { paginationFrom, meta } from "../models/pagination.js";
@@ -69,6 +69,9 @@ export const PageController = {
69
69
  featured_image: mediaId(featured_image),
70
70
  template,
71
71
  published,
72
+ // Published for the people who can edit pages, hidden from every public
73
+ // surface. See migration 043 and `livePage`.
74
+ ...('is_private' in req.body ? { is_private: privateFlag(req.body.is_private) } : {}),
72
75
  parent_id,
73
76
  menu_order,
74
77
  meta_title,
@@ -121,6 +124,7 @@ export const PageController = {
121
124
  ...('featured_image' in req.body ? { featured_image: mediaId(featured_image) } : {}),
122
125
  template,
123
126
  published,
127
+ ...('is_private' in req.body ? { is_private: privateFlag(req.body.is_private) } : {}),
124
128
  parent_id,
125
129
  menu_order,
126
130
  meta_title,
@@ -46,6 +46,20 @@ export declare const PostController: {
46
46
  * editor offers it back if the page is reopened before a real save.
47
47
  */
48
48
  autosave(req: Request, res: Response): Promise<void>;
49
+ /**
50
+ * The first autosave of a post that has never been saved.
51
+ *
52
+ * Autosave needs a post to hang its copy on, so a new post had none: a tab
53
+ * closed before the first Save lost everything typed into it. The editor
54
+ * calls this once, on the first title or body worth keeping, and gets a
55
+ * draft back; from then on it autosaves against that id like any other post.
56
+ *
57
+ * Always a draft, whatever is sent — this never publishes, schedules or makes
58
+ * anything public — and only the text is taken. The rules a real save
59
+ * enforces on a title and body (three and ten characters) wait for that
60
+ * save: a draft is allowed to be the first few words of itself.
61
+ */
62
+ autosaveNew(req: Request, res: Response): Promise<void>;
49
63
  feed(req: Request, res: Response): Promise<void>;
50
64
  feedShow(req: Request, res: Response): Promise<void>;
51
65
  };
@@ -4,7 +4,8 @@ import { can } from '@basicbenframework/core/auth/permissions';
4
4
  import { Post } from "../models/Post.js";
5
5
  import { paginationFrom, meta } from "../models/pagination.js";
6
6
  import { PostRevision } from "../models/PostRevision.js";
7
- import { seoFields } from "../helpers/seo-fields.js";
7
+ import { seoFields, privateFlag } from "../helpers/seo-fields.js";
8
+ import { worthAutosaving, validAutosaveKey } from "../helpers/autosave.js";
8
9
  import { LISTING_FILTERS } from "../models/Post.js";
9
10
  import { POST_STATUSES, toStoredTimestamp } from "../models/visibility.js";
10
11
  import { lockConflict } from "./PostLockController.js";
@@ -322,6 +323,83 @@ export const PostController = {
322
323
  });
323
324
  res.json({ autosave: { id: saved?.id, created_at: saved?.created_at } });
324
325
  },
326
+ /**
327
+ * The first autosave of a post that has never been saved.
328
+ *
329
+ * Autosave needs a post to hang its copy on, so a new post had none: a tab
330
+ * closed before the first Save lost everything typed into it. The editor
331
+ * calls this once, on the first title or body worth keeping, and gets a
332
+ * draft back; from then on it autosaves against that id like any other post.
333
+ *
334
+ * Always a draft, whatever is sent — this never publishes, schedules or makes
335
+ * anything public — and only the text is taken. The rules a real save
336
+ * enforces on a title and body (three and ten characters) wait for that
337
+ * save: a draft is allowed to be the first few words of itself.
338
+ */
339
+ async autosaveNew(req, res) {
340
+ const { title, content, excerpt, post_type, autosave_key } = (req.body ?? {});
341
+ if (typeof title !== 'string' || typeof content !== 'string') {
342
+ return res.json({ error: 'title and content are required' }, 422);
343
+ }
344
+ // A stray keystroke is not a draft: see helpers/autosave.ts.
345
+ if (!worthAutosaving(title, content)) {
346
+ return res.json({ error: 'Nothing to save yet' }, 422);
347
+ }
348
+ // The editor's key for this screen. A repeat — its earlier response lost
349
+ // after the row was written — gets the draft that request made, not a
350
+ // second one.
351
+ const key = validAutosaveKey(autosave_key) ? autosave_key : null;
352
+ if (autosave_key !== undefined && !key)
353
+ return res.json({ errors: { autosave_key: ['Invalid key'] } }, 422);
354
+ if (key) {
355
+ const earlier = await Post.findByAutosaveKey(req.userId, key);
356
+ if (earlier)
357
+ return res.json({ post: earlier });
358
+ }
359
+ const typed = await typeAndFields(post_type === undefined ? {} : { post_type }, null);
360
+ if ('errors' in typed)
361
+ return res.json({ errors: typed.errors }, 422);
362
+ const creating = await guardWrite(HOOKS.POST_CREATING, {
363
+ user_id: req.userId,
364
+ title: title.slice(0, 200),
365
+ content,
366
+ ...(typeof excerpt === 'string' ? { excerpt } : {}),
367
+ ...typed.values,
368
+ status: 'draft',
369
+ published: 0
370
+ }, { req }, { refused: 'Post rejected.' });
371
+ if (!creating.ok)
372
+ return res.json({ error: creating.error }, creating.status);
373
+ // A listener may adjust the text, not the state: what comes out of here is
374
+ // a draft of the signed-in user's, whatever the filter returned.
375
+ const value = creating.value;
376
+ let post;
377
+ try {
378
+ post = await Post.create({
379
+ title: String(value.title ?? ''),
380
+ content: String(value.content ?? ''),
381
+ ...(typeof value.excerpt === 'string' ? { excerpt: value.excerpt } : {}),
382
+ ...(typeof value.post_type === 'string' ? { post_type: value.post_type } : {}),
383
+ ...(key ? { autosave_key: key } : {}),
384
+ user_id: req.userId,
385
+ status: 'draft',
386
+ published: false
387
+ });
388
+ }
389
+ catch (error) {
390
+ // Two requests with one key raced, and the unique index let one in.
391
+ const earlier = key ? await Post.findByAutosaveKey(req.userId, key) : undefined;
392
+ if (earlier)
393
+ return res.json({ post: earlier });
394
+ throw error;
395
+ }
396
+ // Its address is chosen on the first real save, from the title it has by
397
+ // then, not from the first few letters typed.
398
+ await Post.forgetSlug(post.id);
399
+ post.slug = null;
400
+ await hooks.fire(HOOKS.POST_CREATED, { post, userId: req.userId });
401
+ res.json({ post }, 201);
402
+ },
325
403
  async feed(req, res) {
326
404
  // The built-in blog's feed. Restricted bodies are withheld unless the
327
405
  // access policy lets this reader have them — see helpers/gating.ts.
@@ -395,6 +473,10 @@ function editableFields(body, existing) {
395
473
  Object.assign(errors, seo.errors);
396
474
  else
397
475
  Object.assign(fields, seo.values);
476
+ // Private: published for the people who can edit it, hidden from every
477
+ // public surface. See migration 043 and `livePost`.
478
+ if ('is_private' in payload)
479
+ fields.is_private = privateFlag(payload.is_private);
398
480
  // Who may read the body: `public` or a level the access policy offers. The
399
481
  // level the post already has is always accepted, so a post saved under a
400
482
  // feature that has since been removed can still be edited without being
@@ -0,0 +1,13 @@
1
+ /**
2
+ * When a new post has enough in it to be saved as a draft.
3
+ *
4
+ * Shared by the editor, which waits for it before its first autosave, and the
5
+ * server, which refuses anything less — so a stray keystroke on New post and a
6
+ * closed tab leave nothing behind. The same lengths a real save asks of a
7
+ * title and a body; either one is enough.
8
+ */
9
+ export declare const AUTOSAVE_MIN_TITLE = 3;
10
+ export declare const AUTOSAVE_MIN_CONTENT = 10;
11
+ export declare function worthAutosaving(title: unknown, content: unknown): boolean;
12
+ /** The shape of the editor's idempotency key: short, URL-safe, its own. */
13
+ export declare function validAutosaveKey(value: unknown): value is string;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * When a new post has enough in it to be saved as a draft.
3
+ *
4
+ * Shared by the editor, which waits for it before its first autosave, and the
5
+ * server, which refuses anything less — so a stray keystroke on New post and a
6
+ * closed tab leave nothing behind. The same lengths a real save asks of a
7
+ * title and a body; either one is enough.
8
+ */
9
+ export const AUTOSAVE_MIN_TITLE = 3;
10
+ export const AUTOSAVE_MIN_CONTENT = 10;
11
+ export function worthAutosaving(title, content) {
12
+ const t = typeof title === 'string' ? title.trim().length : 0;
13
+ const c = typeof content === 'string' ? content.trim().length : 0;
14
+ return t >= AUTOSAVE_MIN_TITLE || c >= AUTOSAVE_MIN_CONTENT;
15
+ }
16
+ /** The shape of the editor's idempotency key: short, URL-safe, its own. */
17
+ export function validAutosaveKey(value) {
18
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(value);
19
+ }
@@ -25,6 +25,7 @@ import { renderMail } from "./mail-templates.js";
25
25
  import { capabilitiesFor, ROLES } from '@basicbenframework/core/auth/permissions';
26
26
  import { getDb } from '@basicbenframework/core/db';
27
27
  import { Comment } from "../models/Comment.js";
28
+ import { livePost } from "../models/visibility.js";
28
29
  import { Settings } from "../models/Settings.js";
29
30
  import { issueUnsubscribeToken } from "./comment-guard.js";
30
31
  const appUrl = () => process.env.APP_URL || 'http://localhost:3000';
@@ -156,12 +157,16 @@ export async function notifyParentOfReply(replyId) {
156
157
  const sameAccount = reply.user_id && parent.user_id && Number(reply.user_id) === Number(parent.user_id);
157
158
  if (sameAccount || (replyEmail && replyEmail === to.toLowerCase()))
158
159
  return;
159
- if (!(await Comment.claimReplyNotification(Number(reply.id))))
160
- return;
160
+ // Only for a post readers can see. One made private (or unpublished, or
161
+ // trashed) since the comment was left must not be named, or linked, in a
162
+ // mail to someone who cannot open it. Checked before the claim, so nothing
163
+ // is marked sent that was not.
161
164
  const db = await getDb();
162
- const post = await db.get('SELECT id, title FROM posts WHERE id = ?', [reply.post_id]);
165
+ const post = await db.get(`SELECT id, title FROM posts WHERE id = ? AND ${livePost('posts')}`, [reply.post_id]);
163
166
  if (!post)
164
167
  return;
168
+ if (!(await Comment.claimReplyNotification(Number(reply.id))))
169
+ return;
165
170
  const unsubscribeUrl = `${appUrl()}/api/comments/unsubscribe?token=${encodeURIComponent(issueUnsubscribeToken(Number(parent.id)))}`;
166
171
  const replyUrl = `${appUrl()}/feed/${post.id}#comment-${reply.id}`;
167
172
  const name = parent.user_name || parent.author_name || 'there';
@@ -24,6 +24,8 @@ interface Movable {
24
24
  slug?: string | null;
25
25
  published?: boolean | number | null;
26
26
  deleted_at?: string | null;
27
+ /** Private (migration 043): published, but not public. */
28
+ is_private?: boolean | number | null;
27
29
  /** The post's content type key; absent or `post` means `/blog`. */
28
30
  post_type?: string | null;
29
31
  }
@@ -33,7 +35,11 @@ interface Movable {
33
35
  *
34
36
  * Only content that was public before the save: a draft's slug was never a
35
37
  * URL anyone could have linked to, so redirecting from it would only litter
36
- * the table. A post without a slug answered to its id, and still does — the
38
+ * the table. Nor a private one, on either side of the save: its slugs were
39
+ * never public, and `/api/v1/redirects` lists every redirect to anyone, so
40
+ * recording one would publish the old address and the new.
41
+ *
42
+ * A post without a slug answered to its id, and still does — the
37
43
  * content API accepts an id wherever it accepts a slug — so it needs nothing.
38
44
  */
39
45
  export declare function redirectIfSlugChanged(kind: 'post' | 'page', before: Movable, after: Movable | null | undefined, routeBases?: {
@@ -53,7 +53,11 @@ async function baseFor(type) {
53
53
  *
54
54
  * Only content that was public before the save: a draft's slug was never a
55
55
  * URL anyone could have linked to, so redirecting from it would only litter
56
- * the table. A post without a slug answered to its id, and still does — the
56
+ * the table. Nor a private one, on either side of the save: its slugs were
57
+ * never public, and `/api/v1/redirects` lists every redirect to anyone, so
58
+ * recording one would publish the old address and the new.
59
+ *
60
+ * A post without a slug answered to its id, and still does — the
57
61
  * content API accepts an id wherever it accepts a slug — so it needs nothing.
58
62
  */
59
63
  export async function redirectIfSlugChanged(kind, before, after,
@@ -65,6 +69,8 @@ routeBases = {}) {
65
69
  return;
66
70
  if (!before.published || before.deleted_at)
67
71
  return;
72
+ if (Number(before.is_private) || Number(after.is_private))
73
+ return;
68
74
  // Looked up from the rows themselves when the caller did not say, so the
69
75
  // controller's one-line call covers custom types without knowing about them.
70
76
  // A plain post never touches the database here.
@@ -11,3 +11,10 @@ export declare function seoFields(body: unknown): {
11
11
  errors: Record<string, string[]>;
12
12
  };
13
13
  export declare const SEO_COLUMNS: string[];
14
+ /**
15
+ * The private flag (migration 043) as stored: 1 or 0.
16
+ *
17
+ * A checkbox arrives as true, "true", "on" or "1" depending on the client, and
18
+ * anything else — including absent-but-present-as-null — is public.
19
+ */
20
+ export declare function privateFlag(value: unknown): 0 | 1;
@@ -50,3 +50,12 @@ export const SEO_COLUMNS = [
50
50
  'og_title', 'og_description', 'og_image', 'twitter_title', 'twitter_description',
51
51
  'twitter_image', 'canonical_url', 'noindex'
52
52
  ];
53
+ /**
54
+ * The private flag (migration 043) as stored: 1 or 0.
55
+ *
56
+ * A checkbox arrives as true, "true", "on" or "1" depending on the client, and
57
+ * anything else — including absent-but-present-as-null — is public.
58
+ */
59
+ export function privateFlag(value) {
60
+ return [true, 1, '1', 'true', 'on'].includes(value) ? 1 : 0;
61
+ }
@@ -25,11 +25,14 @@ export declare const Media: {
25
25
  * @param perPage
26
26
  * @param filters - `search` matches the original filename; `type` is a mime
27
27
  * prefix such as 'image', or 'other' for anything that is not image, video
28
- * or audio.
28
+ * or audio. `servedAt` is the path of a URL the file is served from: it
29
+ * matches the item whose storage key that path ends with, which is how a
30
+ * pasted URL is turned back into the library item it points at.
29
31
  */
30
32
  all(page?: number, perPage?: number, filters?: {
31
33
  search?: string;
32
34
  type?: string;
35
+ servedAt?: string;
33
36
  }): Promise<{
34
37
  items: MediaType[];
35
38
  total: number;
@@ -11,7 +11,9 @@ export const Media = {
11
11
  * @param perPage
12
12
  * @param filters - `search` matches the original filename; `type` is a mime
13
13
  * prefix such as 'image', or 'other' for anything that is not image, video
14
- * or audio.
14
+ * or audio. `servedAt` is the path of a URL the file is served from: it
15
+ * matches the item whose storage key that path ends with, which is how a
16
+ * pasted URL is turned back into the library item it points at.
15
17
  */
16
18
  async all(page = 1, perPage = 20, filters = {}) {
17
19
  const db = await getDb();
@@ -22,6 +24,21 @@ export const Media = {
22
24
  where.push('m.original_name LIKE ?');
23
25
  params.push(`%${filters.search}%`);
24
26
  }
27
+ if (filters.servedAt) {
28
+ // Every storage driver serves a key at a URL ending in that key, after
29
+ // whatever prefix its bucket, CDN or local route adds. So the key is one
30
+ // of the path's whole-segment suffixes: compared exactly, because a
31
+ // stored key used as a LIKE pattern would make `_` and `%` wildcards.
32
+ const segments = filters.servedAt.split('/').filter(Boolean).slice(-20);
33
+ const suffixes = segments.map((_, i) => segments.slice(i).join('/'));
34
+ if (suffixes.length) {
35
+ where.push(`m.path IN (${suffixes.map(() => '?').join(', ')})`);
36
+ params.push(...suffixes);
37
+ }
38
+ else {
39
+ where.push('1 = 0');
40
+ }
41
+ }
25
42
  if (filters.type === 'other') {
26
43
  where.push("COALESCE(m.mime_type, '') NOT LIKE 'image/%'");
27
44
  where.push("COALESCE(m.mime_type, '') NOT LIKE 'video/%'");
@@ -7,7 +7,7 @@
7
7
  * draft, a trashed post, or a page that was deleted out from under it.
8
8
  */
9
9
  import { getDb, query } from '@basicbenframework/core/db';
10
- import { livePost } from "./visibility.js";
10
+ import { livePost, livePage } from "./visibility.js";
11
11
  import { postPath, pagePath, categoryPath, isSafeLinkUrl } from "../helpers/content-paths.js";
12
12
  export const TARGET_TYPES = ['post', 'page', 'category'];
13
13
  /**
@@ -296,11 +296,11 @@ export const Menu = {
296
296
  return map;
297
297
  };
298
298
  // The same visibility rules as the rest of the public API: `livePost` for
299
- // posts (published, not trashed, its time has come), `published = 1` for
300
- // pages. Categories have no visibility of their own.
299
+ // posts (published, not trashed, its time has come, not private), `livePage`
300
+ // for pages. Categories have no visibility of their own.
301
301
  const targets = {
302
302
  post: await lookup('post', list => `SELECT posts.id, posts.slug FROM posts WHERE posts.id IN (${list}) AND ${livePost('posts')}`),
303
- page: await lookup('page', list => `SELECT id, slug FROM pages WHERE id IN (${list}) AND published = 1`),
303
+ page: await lookup('page', list => `SELECT pages.id, pages.slug FROM pages WHERE pages.id IN (${list}) AND ${livePage('pages')}`),
304
304
  category: await lookup('category', list => `SELECT id, slug FROM categories WHERE id IN (${list})`)
305
305
  };
306
306
  const result = {};
@@ -6,6 +6,7 @@ interface CreatePageData {
6
6
  featured_image?: number | null;
7
7
  template?: string;
8
8
  published?: boolean;
9
+ is_private?: number;
9
10
  parent_id?: number;
10
11
  menu_order?: number;
11
12
  meta_title?: string;
@@ -18,6 +19,7 @@ interface UpdatePageData {
18
19
  featured_image?: number | null;
19
20
  template?: string;
20
21
  published?: boolean;
22
+ is_private?: number;
21
23
  parent_id?: number;
22
24
  menu_order?: number;
23
25
  meta_title?: string;
@@ -4,6 +4,7 @@ import { hooks, HOOKS } from '@basicbenframework/core/hooks';
4
4
  import { renderContent } from '@basicbenframework/core/content';
5
5
  import { getStorage } from '@basicbenframework/core/storage';
6
6
  import { uniqueSlug } from "./derive.js";
7
+ import { livePage } from "./visibility.js";
7
8
  /**
8
9
  * Columns `update()` will write.
9
10
  *
@@ -12,7 +13,7 @@ import { uniqueSlug } from "./derive.js";
12
13
  */
13
14
  const UPDATABLE = [
14
15
  'title', 'slug', 'content', 'content_html', 'featured_image', 'template',
15
- 'published', 'parent_id', 'menu_order', 'meta_title', 'meta_description',
16
+ 'published', 'is_private', 'parent_id', 'menu_order', 'meta_title', 'meta_description',
16
17
  'updated_at', ...SEO_COLUMNS
17
18
  ];
18
19
  export const Page = {
@@ -50,13 +51,13 @@ export const Page = {
50
51
  const db = await getDb();
51
52
  return withFeaturedImages(await db.all(`
52
53
  ${SELECT_PAGE}
53
- WHERE pages.published = 1
54
+ WHERE ${livePage('pages')}
54
55
  ORDER BY pages.menu_order ASC, pages.title ASC
55
56
  `));
56
57
  },
57
58
  async findPublishedBySlug(slug) {
58
59
  const db = await getDb();
59
- return first(await db.get(`${SELECT_PAGE} WHERE pages.slug = ? AND pages.published = 1`, [slug]));
60
+ return first(await db.get(`${SELECT_PAGE} WHERE pages.slug = ? AND ${livePage('pages')}`, [slug]));
60
61
  },
61
62
  async tree() {
62
63
  const pages = await this.all();
@@ -87,6 +88,7 @@ export const Page = {
87
88
  featured_image: data.featured_image ?? null,
88
89
  template: data.template || 'default',
89
90
  published: data.published ? 1 : 0,
91
+ is_private: data.is_private ? 1 : 0,
90
92
  parent_id: data.parent_id || null,
91
93
  menu_order: data.menu_order || 0,
92
94
  meta_title: data.meta_title || null,
@@ -105,6 +107,7 @@ export const Page = {
105
107
  featured_image: data.featured_image ?? null,
106
108
  template: data.template || 'default',
107
109
  published: data.published || false,
110
+ is_private: data.is_private ? 1 : 0,
108
111
  parent_id: data.parent_id,
109
112
  menu_order: data.menu_order || 0,
110
113
  meta_title: data.meta_title,
@@ -22,10 +22,13 @@ interface CreatePostData {
22
22
  noindex?: number;
23
23
  visibility?: string;
24
24
  send_newsletter?: number;
25
+ is_private?: number;
25
26
  /** Content type key (migration 038). Absent means `post`. */
26
27
  post_type?: string;
27
28
  /** Custom field values as stored: a JSON string, already validated. */
28
29
  fields?: string | null;
30
+ /** The editor's idempotency key for a first autosave (migration 044). */
31
+ autosave_key?: string;
29
32
  }
30
33
  interface UpdatePostData {
31
34
  user_id?: number;
@@ -51,6 +54,7 @@ interface UpdatePostData {
51
54
  noindex?: number;
52
55
  visibility?: string;
53
56
  send_newsletter?: number;
57
+ is_private?: number;
54
58
  post_type?: string;
55
59
  fields?: string | null;
56
60
  }
@@ -130,6 +134,18 @@ export declare const Post: {
130
134
  findPublishedById(id: number): Promise<PostType | undefined>;
131
135
  create(data: CreatePostData): Promise<PostType>;
132
136
  update(id: number, data: UpdatePostData): Promise<PostType>;
137
+ /**
138
+ * Forget a draft's slug, so the first real save derives one.
139
+ *
140
+ * For the draft an autosave makes from a new post's first words (see
141
+ * `PostController.autosaveNew`): a slug derived then would come from "He",
142
+ * or be `post` for a draft with only a body, and the editor would load it
143
+ * back as if the author had chosen it. Null is what a post with no slug yet
144
+ * already means, and the unique index allows any number of them.
145
+ */
146
+ /** The draft a first autosave with this key already made, if any (migration 044). */
147
+ findByAutosaveKey(userId: number, key: string): Promise<PostType | undefined>;
148
+ forgetSlug(id: number): Promise<void>;
133
149
  /** Gone for good. Only ever called on a post already in the trash. */
134
150
  delete(id: number): Promise<void>;
135
151
  };
@@ -19,7 +19,7 @@ const UPDATABLE = [
19
19
  'status', 'deleted_at', 'live_notified',
20
20
  'og_title', 'og_description', 'og_image', 'twitter_title', 'twitter_description',
21
21
  'twitter_image', 'canonical_url', 'noindex',
22
- 'visibility', 'send_newsletter',
22
+ 'visibility', 'send_newsletter', 'is_private',
23
23
  // Content types (migrations 038–039). Validated by helpers/content-model.ts
24
24
  // before they reach here.
25
25
  'post_type', 'fields'
@@ -262,8 +262,10 @@ export const Post = {
262
262
  live_notified: data.live_notified ?? 1,
263
263
  visibility: data.visibility ?? 'public',
264
264
  send_newsletter: data.send_newsletter ?? 0,
265
+ is_private: data.is_private ? 1 : 0,
265
266
  post_type: data.post_type ?? 'post',
266
267
  fields: data.fields ?? null,
268
+ ...(data.autosave_key ? { autosave_key: data.autosave_key } : {}),
267
269
  ...Object.fromEntries(SEO_FIELDS.filter((key) => data[key] !== undefined).map((key) => [key, data[key]]))
268
270
  });
269
271
  const now = new Date().toISOString();
@@ -309,6 +311,24 @@ export const Post = {
309
311
  await db.run(`UPDATE posts SET ${fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [...writable.map(([, value]) => value), id]);
310
312
  return this.find(id);
311
313
  },
314
+ /**
315
+ * Forget a draft's slug, so the first real save derives one.
316
+ *
317
+ * For the draft an autosave makes from a new post's first words (see
318
+ * `PostController.autosaveNew`): a slug derived then would come from "He",
319
+ * or be `post` for a draft with only a body, and the editor would load it
320
+ * back as if the author had chosen it. Null is what a post with no slug yet
321
+ * already means, and the unique index allows any number of them.
322
+ */
323
+ /** The draft a first autosave with this key already made, if any (migration 044). */
324
+ async findByAutosaveKey(userId, key) {
325
+ const db = await getDb();
326
+ return db.get('SELECT * FROM posts WHERE user_id = ? AND autosave_key = ?', [userId, key]);
327
+ },
328
+ async forgetSlug(id) {
329
+ const db = await getDb();
330
+ await db.run('UPDATE posts SET slug = NULL WHERE id = ?', [id]);
331
+ },
312
332
  /** Gone for good. Only ever called on a post already in the trash. */
313
333
  async delete(id) {
314
334
  const db = await getDb();
@@ -173,7 +173,7 @@ export declare const PublicContent: {
173
173
  *
174
174
  * Only people who have published: an account with no posts is a user, not an
175
175
  * author, and listing one exposes that the account exists to anyone who asks
176
- * for the author index. Counts come from the same `published = 1` filter the
176
+ * for the author index. Counts come from the same `livePost` filter the
177
177
  * post listing uses, so an archive link never leads to an empty page.
178
178
  */
179
179
  authors(): Promise<PublicAuthor[]>;
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import { getDb } from '@basicbenframework/core/db';
15
15
  import { getStorage, absoluteUrl } from '@basicbenframework/core/storage';
16
- import { livePost, parseStoredTimestamp } from "./visibility.js";
16
+ import { livePost, livePage, parseStoredTimestamp } from "./visibility.js";
17
17
  import { responsiveImage } from "../helpers/images.js";
18
18
  import { siteUrl } from "../helpers/site.js";
19
19
  import { publicExcerpt } from "../helpers/gating.js";
@@ -194,9 +194,9 @@ export const PublicContent = {
194
194
  async pages(options = {}) {
195
195
  const db = await getDb();
196
196
  const { perPage = 10, offset = 0, format = 'html' } = options;
197
- const counted = (await db.get('SELECT COUNT(*) AS total FROM pages WHERE published = 1'));
197
+ const counted = (await db.get(`SELECT COUNT(*) AS total FROM pages WHERE ${livePage('pages')}`));
198
198
  const rows = (await db.all(`SELECT ${PAGE_COLUMNS} ${PAGE_JOINS}
199
- WHERE pages.published = 1
199
+ WHERE ${livePage('pages')}
200
200
  ORDER BY pages.created_at DESC
201
201
  LIMIT ? OFFSET ?`, [perPage, offset]));
202
202
  return { pages: await shapePages(rows, format), total: Number(counted?.total) || 0 };
@@ -205,7 +205,7 @@ export const PublicContent = {
205
205
  async page(identifier, format = 'html') {
206
206
  const db = await getDb();
207
207
  const row = (await db.get(`SELECT ${PAGE_COLUMNS} ${PAGE_JOINS}
208
- WHERE pages.published = 1 AND (pages.slug = ? OR pages.id = ?)`, [identifier, Number(identifier) || -1]));
208
+ WHERE ${livePage('pages')} AND (pages.slug = ? OR pages.id = ?)`, [identifier, Number(identifier) || -1]));
209
209
  return row ? (await shapePages([row], format))[0] : null;
210
210
  },
211
211
  /**
@@ -247,7 +247,7 @@ export const PublicContent = {
247
247
  *
248
248
  * Only people who have published: an account with no posts is a user, not an
249
249
  * author, and listing one exposes that the account exists to anyone who asks
250
- * for the author index. Counts come from the same `published = 1` filter the
250
+ * for the author index. Counts come from the same `livePost` filter the
251
251
  * post listing uses, so an archive link never leads to an empty page.
252
252
  */
253
253
  async authors() {
@@ -14,8 +14,17 @@
14
14
  * Scheduling needs no cron: a scheduled post simply starts matching when its
15
15
  * time comes. What does need a tick is telling webhooks — see `publishDue()` in
16
16
  * `src/hooks.ts`.
17
+ *
18
+ * Not private (migration 043): a private post is published for the people who
19
+ * can edit it, in the admin, and for nobody on any public surface. Folding it
20
+ * into this fragment is what makes that true everywhere at once.
17
21
  */
18
22
  export declare function livePost(alias?: string): string;
23
+ /**
24
+ * When a page is on the public site: published and not private. The page
25
+ * counterpart of `livePost`, for the same reason — one copy of the rule.
26
+ */
27
+ export declare function livePage(alias?: string): string;
19
28
  /** Normalise a date to the stored form, or null. Throws on nonsense. */
20
29
  export declare function toStoredTimestamp(value: unknown): string | null;
21
30
  /** The editorial states a post can be in. Scheduled is published-in-the-future. */
@@ -14,10 +14,24 @@
14
14
  * Scheduling needs no cron: a scheduled post simply starts matching when its
15
15
  * time comes. What does need a tick is telling webhooks — see `publishDue()` in
16
16
  * `src/hooks.ts`.
17
+ *
18
+ * Not private (migration 043): a private post is published for the people who
19
+ * can edit it, in the admin, and for nobody on any public surface. Folding it
20
+ * into this fragment is what makes that true everywhere at once.
17
21
  */
18
22
  export function livePost(alias = 'posts') {
19
23
  const now = new Date().toISOString();
20
- return `(${alias}.published = 1 AND ${alias}.deleted_at IS NULL AND (${alias}.publish_at IS NULL OR ${alias}.publish_at <= '${now}'))`;
24
+ return `(${alias}.published = 1 AND ${alias}.deleted_at IS NULL AND (${alias}.publish_at IS NULL OR ${alias}.publish_at <= '${now}') AND ${notPrivate(alias)})`;
25
+ }
26
+ /**
27
+ * When a page is on the public site: published and not private. The page
28
+ * counterpart of `livePost`, for the same reason — one copy of the rule.
29
+ */
30
+ export function livePage(alias = 'pages') {
31
+ return `(${alias}.published = 1 AND ${notPrivate(alias)})`;
32
+ }
33
+ function notPrivate(alias) {
34
+ return `${alias}.is_private = 0`;
21
35
  }
22
36
  /** Normalise a date to the stored form, or null. Throws on nonsense. */
23
37
  export function toStoredTimestamp(value) {
@@ -21,6 +21,9 @@ export default (router) => {
21
21
  router.post('/api/posts', contentWrite, requireCapability('post.create'), PostController.store);
22
22
  // Before the /:id routes, which would otherwise read `bulk` as an id.
23
23
  router.post('/api/posts/bulk', auth, PostController.bulk);
24
+ // The editor's first autosave of a post that has never been saved: a draft,
25
+ // from whatever has been typed so far. A person's, like autosave itself.
26
+ router.post('/api/posts/autosave', auth, requireCapability('post.create'), PostController.autosaveNew);
24
27
  router.get('/api/posts/:id', contentWrite, PostController.show);
25
28
  router.post('/api/posts/:id/restore', auth, PostController.restore);
26
29
  router.put('/api/posts/:id/autosave', auth, PostController.autosave);
@@ -83,6 +83,8 @@ export interface Post {
83
83
  noindex?: number | boolean;
84
84
  /** Who may read the body: `public`, or a level the access policy defines (helpers/access.ts). */
85
85
  visibility?: string;
86
+ /** 1 when private: published, but only for people who can edit it, in the admin (migration 043). */
87
+ is_private?: number | boolean;
86
88
  /** Written by the members feature: the author asked for this post to be emailed when it goes live. */
87
89
  send_newsletter?: number | boolean;
88
90
  /** Content type key (migration 038). `post` for every post that predates types. */
@@ -126,6 +128,8 @@ export interface Page {
126
128
  content_html?: string;
127
129
  template: string;
128
130
  published: boolean;
131
+ /** 1 when private: published, but only for people who can edit it, in the admin (migration 043). */
132
+ is_private?: number | boolean;
129
133
  parent_id?: number;
130
134
  menu_order: number;
131
135
  /** Foreign key into `media`. Not a filename — see `featured_image_url`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basicbenframework/cms",
3
- "version": "0.7.3",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "The BasicBen CMS. Posts, pages, media, an admin UI, and a headless content API.",
6
6
  "license": "MIT",