@pirateandfox/pagestack 0.1.0-beta.15 → 0.1.0-beta.17
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/README.md +47 -1
- package/index.mjs +1 -0
- package/package.json +1 -1
- package/src/client/editor.ts +2 -8
- package/src/client/form.ts +44 -4
- package/src/client/pages.ts +27 -1
- package/src/client/shell.css +10 -1
- package/src/core/insert.ts +12 -0
- package/src/core/samples.ts +120 -0
- package/src/core/sanitize.ts +6 -0
- package/src/core/schema.ts +30 -1
- package/src/core/transform.ts +2 -1
- package/src/routes/api/collection.ts +3 -1
- package/src/routes/api/page.ts +3 -1
- package/src/routes/api/pages.ts +2 -1
- package/src/routes/api/samples.ts +43 -0
- package/src/routes/edit-index.astro +31 -2
- package/src/runtime.ts +17 -0
- package/src/server/context.ts +32 -3
package/README.md
CHANGED
|
@@ -188,7 +188,7 @@ export const presets: Preset[] = [
|
|
|
188
188
|
```
|
|
189
189
|
|
|
190
190
|
Field types: `text`, `richtext`, `image`, `link`, `color`, `select`, `number`, `boolean`,
|
|
191
|
-
`textarea`, `code`, `svg`. `inline: true` on `text` / `richtext` / `image` makes the field
|
|
191
|
+
`textarea`, `code`, `svg`, `date`, `tags`, `list`, `multiselect`. `inline: true` on `text` / `richtext` / `image` makes the field
|
|
192
192
|
editable by clicking it in the preview. `marks: true` on a `text` field allows bold and italic in it
|
|
193
193
|
(see [Bold and italic in headings](#bold-and-italic-in-headings)). The schema drives the sidebar form, validation on save,
|
|
194
194
|
the add-block menus and the tree labels. **Presets are the section library.**
|
|
@@ -222,6 +222,27 @@ A few things worth knowing while you set up the schema:
|
|
|
222
222
|
in a WordPress heading. See [Bold and italic in headings](#bold-and-italic-in-headings).
|
|
223
223
|
- **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
|
|
224
224
|
|
|
225
|
+
### Checkboxes, and fields that depend on others
|
|
226
|
+
|
|
227
|
+
`multiselect` shows its `options` as checkboxes and stores the ticked values as an array, in the
|
|
228
|
+
order the options are declared. `showIf` shows a field only when another one has a certain value:
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
repeats: { type: 'select', label: 'Repeats', options: [{ value: '', label: 'Never' }, { value: 'weekly', label: 'Weekly' }] },
|
|
232
|
+
repeatsOn: { type: 'multiselect', label: 'Repeats on', options: [{ value: 'mon', label: 'Mon' }, { value: 'wed', label: 'Wed' }], showIf: { field: 'repeats', is: 'weekly' } },
|
|
233
|
+
until: { type: 'date', label: 'Until', time: false, showIf: { field: 'repeats', not: '' } },
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
- `is` and `not` take one value or a list of them (any may match). With neither, the field shows when
|
|
237
|
+
the other one has a value. Missing, `''`, `false` and an empty list all count as no value. A
|
|
238
|
+
`multiselect` matches when any ticked value does.
|
|
239
|
+
- `field` names a field in the same form, or in the same row inside a `list`. A field that depends on
|
|
240
|
+
a hidden field is hidden too.
|
|
241
|
+
- Hiding a field only changes the form. **The stored value stays**, so your component should look at
|
|
242
|
+
the same condition (`repeats && until`) rather than at the dependent field alone.
|
|
243
|
+
- Nothing ticked is stored as `[]`. In a collection, allow for both that and a missing key in the Astro
|
|
244
|
+
schema: `z.array(z.string()).default([])`.
|
|
245
|
+
|
|
225
246
|
### Bold and italic in headings
|
|
226
247
|
|
|
227
248
|
Text fields are plain text by default. Add `marks: true` to one and it behaves like a WordPress
|
|
@@ -311,8 +332,33 @@ export const globals = {
|
|
|
311
332
|
},
|
|
312
333
|
},
|
|
313
334
|
};
|
|
335
|
+
|
|
336
|
+
// For a starter or template: what replaces its sample content (see "Sample content" below)
|
|
337
|
+
export const sampleContent = {
|
|
338
|
+
label: 'Crumb, the sample bakery',
|
|
339
|
+
home: { title: 'Home', sections: [/* … */] },
|
|
340
|
+
globals: { menus: { announcement: '' } },
|
|
341
|
+
};
|
|
314
342
|
```
|
|
315
343
|
|
|
344
|
+
#### Sample content
|
|
345
|
+
|
|
346
|
+
A starter or theme can ship sample pages and posts and let the site's owner clear them with one
|
|
347
|
+
button. Mark each sample with `"sample": true` at the top of a page's JSON, or `sample: true` in
|
|
348
|
+
an item's frontmatter. While any are on the site, admins see a notice on the Pages screen with:
|
|
349
|
+
|
|
350
|
+
- **Hide sample content**: sample pages become drafts and sample items `draft: true`, so they stay
|
|
351
|
+
in the editor to open and copy from and leave the public site. The home page can't be a draft,
|
|
352
|
+
so the sample one moves to a draft page `sample-home` and `sampleContent.home` takes its place
|
|
353
|
+
(default: an empty page titled Home).
|
|
354
|
+
- **Delete sample content**: every sample page and item is removed, and a sample home page is
|
|
355
|
+
replaced the same way. The confirmation lists them all.
|
|
356
|
+
|
|
357
|
+
Either is one commit, and both set the `sampleContent.globals` values (an announcement that
|
|
358
|
+
advertised a sample event, say). Images are never touched. Saving a sample from the editor drops
|
|
359
|
+
its mark: once someone has edited it, it's theirs, and Hide and Delete leave it alone. Pages still
|
|
360
|
+
marked show a **Sample** pill in the page list.
|
|
361
|
+
|
|
316
362
|
#### Editing a collection item on its own page
|
|
317
363
|
|
|
318
364
|
Give a collection a layout in `previews` (an option on the integration) and its items open on that
|
package/index.mjs
CHANGED
|
@@ -276,6 +276,7 @@ export default function sectionEditor(userOptions) {
|
|
|
276
276
|
injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
|
|
277
277
|
injectRoute({ pattern: '/api/editor/browse', entrypoint: route('api/browse.ts'), prerender: false });
|
|
278
278
|
injectRoute({ pattern: '/api/editor/live', entrypoint: route('api/live.ts'), prerender: false });
|
|
279
|
+
injectRoute({ pattern: '/api/editor/samples', entrypoint: route('api/samples.ts'), prerender: false });
|
|
279
280
|
injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
|
|
280
281
|
// Uploads saved after this editor was built aren't static files in it; serve them from the repo.
|
|
281
282
|
const uploadsUrl = options.storage === 'github' && uploadsUrlPrefix(options.uploadsDir, options.publicDir);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pirateandfox/pagestack",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.17",
|
|
4
4
|
"description": "A block editor for Astro sites. Content stays in your repo, saves are git commits, the public site stays static, sign-in is passkeys.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/src/client/editor.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { getAt, insertNode, isNodePath, moveNode, nodeAt, nodePathOf, pathOfId,
|
|
|
6
6
|
import { transformNode, transformTargets } from '../core/transform';
|
|
7
7
|
import { accepts, allowedChildTypes, createNode, fieldOf, nodeLabel } from '../core/schema';
|
|
8
8
|
import type { InsertItem, Pattern, SavedPattern } from '../core/insert';
|
|
9
|
-
import { insertItems } from '../core/insert';
|
|
9
|
+
import { insertTarget, insertItems } from '../core/insert';
|
|
10
10
|
import { slugProblem } from '../core/pages';
|
|
11
11
|
import type { Revision } from '../core/storage';
|
|
12
12
|
import { EditorState } from './state';
|
|
@@ -670,13 +670,7 @@ function setLeft(view: typeof leftView) {
|
|
|
670
670
|
fitPreview();
|
|
671
671
|
}
|
|
672
672
|
|
|
673
|
-
|
|
674
|
-
if (!selected) return { listPath: 'sections', index: state.doc.sections.length };
|
|
675
|
-
const node = nodeAt(state.doc, selected)!;
|
|
676
|
-
if (allowedChildTypes(node.type, registry)?.length) return { listPath: `${selected}.blocks`, index: node.blocks?.length ?? 0 };
|
|
677
|
-
const { listPath, index } = splitNodePath(selected);
|
|
678
|
-
return { listPath, index: index + 1 };
|
|
679
|
-
}
|
|
673
|
+
const defaultTarget = (): Target => insertTarget(state.doc, selected);
|
|
680
674
|
|
|
681
675
|
function openInserter(at: Target = defaultTarget()) {
|
|
682
676
|
inline.stop(true);
|
package/src/client/form.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Schema -> sidebar form. One widget per field type; changes are reported through `onChange`.
|
|
2
2
|
import type { BlockSchema, Field, ImageValue } from '../runtime';
|
|
3
|
-
import { formModel } from '../core/schema';
|
|
3
|
+
import { formModel, isShown } from '../core/schema';
|
|
4
4
|
import { marksField, richField } from './rich';
|
|
5
5
|
|
|
6
6
|
export interface FormCallbacks {
|
|
@@ -24,12 +24,31 @@ export function renderForm(root: HTMLElement, schema: BlockSchema, settings: Rec
|
|
|
24
24
|
root.innerHTML = '';
|
|
25
25
|
const groups = formModel(schema, settings);
|
|
26
26
|
if (!groups.length) { root.append(el('p', { class: 'ps-muted' }, 'This block has no settings.')); return; }
|
|
27
|
+
const values = { ...settings };
|
|
28
|
+
const shown = conditions(schema.fields, values);
|
|
29
|
+
const formCb: FormCallbacks = { ...cb, onChange: (name, value, ...o) => { values[name] = value; cb.onChange(name, value, ...o); shown.update(); } };
|
|
27
30
|
for (const g of groups) {
|
|
28
31
|
const body = el('div', { class: 'ps-fields' });
|
|
29
|
-
for (const f of g.fields) body.append(fieldWidget(f.name, f.field, f.value,
|
|
32
|
+
for (const f of g.fields) body.append(shown.track(f.name, fieldWidget(f.name, f.field, f.value, formCb)));
|
|
30
33
|
const details = el('details', { class: 'ps-group', open: g.name !== 'advanced' }, el('summary', {}, g.label), body) as HTMLDetailsElement;
|
|
34
|
+
shown.trackGroup(details, g.fields.map((f) => f.name));
|
|
31
35
|
root.append(details);
|
|
32
36
|
}
|
|
37
|
+
shown.update();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Shows and hides a form's widgets by their fields' `showIf`, and a group with nothing left to show. */
|
|
41
|
+
function conditions(fields: Record<string, Field>, values: Record<string, unknown>) {
|
|
42
|
+
const widgets = new Map<string, HTMLElement>();
|
|
43
|
+
const groups: [HTMLElement, string[]][] = [];
|
|
44
|
+
return {
|
|
45
|
+
track: (name: string, widget: HTMLElement) => { widgets.set(name, widget); return widget; },
|
|
46
|
+
trackGroup: (group: HTMLElement, names: string[]) => { groups.push([group, names]); },
|
|
47
|
+
update: () => {
|
|
48
|
+
for (const [name, w] of widgets) w.hidden = !isShown(name, fields, values);
|
|
49
|
+
for (const [g, names] of groups) g.hidden = names.every((n) => widgets.get(n)!.hidden);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
33
52
|
}
|
|
34
53
|
|
|
35
54
|
function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, idPrefix = 'ps-f-'): HTMLElement {
|
|
@@ -107,6 +126,21 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
|
|
|
107
126
|
wrap.append(sel);
|
|
108
127
|
break;
|
|
109
128
|
}
|
|
129
|
+
case 'multiselect': {
|
|
130
|
+
const current = (Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value]).map(String);
|
|
131
|
+
const known = field.options ?? [];
|
|
132
|
+
// Values no longer offered stay ticked until someone unticks them.
|
|
133
|
+
const extra = [...new Set(current)].filter((v) => !known.some((o) => o.value === v)).map((v) => ({ value: v, label: `${v} (current)` }));
|
|
134
|
+
const boxes = [...known, ...extra].map((o, i) => {
|
|
135
|
+
const box = el('input', { id: `${id}-${i}`, type: 'checkbox', value: o.value, checked: current.includes(o.value) }) as HTMLInputElement;
|
|
136
|
+
box.addEventListener('change', () => cb.onChange(name, boxes.filter((b) => b.box.checked).map((b) => b.box.value)));
|
|
137
|
+
return { box, row: el('label', { for: `${id}-${i}` }, box, o.label) };
|
|
138
|
+
});
|
|
139
|
+
const heading = el('span', { class: 'ps-field__label', id: `${id}-label` }, field.label);
|
|
140
|
+
label.replaceWith(heading);
|
|
141
|
+
wrap.append(el('div', { id, class: 'ps-checks', role: 'group', 'aria-labelledby': `${id}-label` }, ...boxes.map((b) => b.row)));
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
110
144
|
case 'color': {
|
|
111
145
|
const text = el('input', { id, type: 'text', value: (value as string) ?? '', placeholder: 'e.g. #BAA77E or var(--e-global-color-primary)' }) as HTMLInputElement;
|
|
112
146
|
const swatch = el('input', { type: 'color', 'aria-label': `${field.label} picker` }) as HTMLInputElement;
|
|
@@ -196,14 +230,20 @@ function listWidget(name: string, field: Field, value: unknown, cb: FormCallback
|
|
|
196
230
|
rows.forEach((row, i) => {
|
|
197
231
|
const title = el('span', { class: 'ps-ellipsis' }, rowName(row, i));
|
|
198
232
|
const body = el('div', { class: 'ps-fields' });
|
|
233
|
+
const shown = conditions(fields, row);
|
|
199
234
|
for (const [k, sub] of Object.entries(fields)) {
|
|
200
235
|
const rowCb: FormCallbacks = { ...cb, onChange: (key, v, o) => {
|
|
201
|
-
|
|
236
|
+
// "None" over a default has to be stored, or the default comes back.
|
|
237
|
+
const f = fields[key];
|
|
238
|
+
const keep = (f?.type === 'select' || f?.type === 'multiselect') && String(f.default ?? '') !== '';
|
|
239
|
+
if (v === undefined || (!keep && (v === '' || (Array.isArray(v) && !v.length)))) delete row[key]; else row[key] = v;
|
|
202
240
|
if (key === field.itemLabel) { title.textContent = rowName(row, i); remove.setAttribute('aria-label', `Remove ${rowName(row, i)}`); }
|
|
203
241
|
save(o?.live);
|
|
242
|
+
shown.update();
|
|
204
243
|
} };
|
|
205
|
-
body.append(fieldWidget(k, sub, row[k] ?? sub.default, rowCb, `${id}-${i}-`));
|
|
244
|
+
body.append(shown.track(k, fieldWidget(k, sub, row[k] ?? sub.default, rowCb, `${id}-${i}-`)));
|
|
206
245
|
}
|
|
246
|
+
shown.update();
|
|
207
247
|
const remove = el('button', { type: 'button', title: 'Remove', 'aria-label': `Remove ${rowName(row, i)}`, onclick: (e: Event) => { e.preventDefault(); rows.splice(i, 1); open.clear(); save(); draw(); } }, '×');
|
|
208
248
|
const details = el('details', { class: 'ps-list__row', open: open.has(i), ontoggle: () => { if (details.open) open.add(i); else open.delete(i); } }, el('summary', {},
|
|
209
249
|
title,
|
package/src/client/pages.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { publicPath, slugify, slugProblem, uniqueSlug } from '../core/pages';
|
|
3
3
|
import { confirmDialog, dialog, toast } from './ui';
|
|
4
4
|
|
|
5
|
-
interface Boot { pages: { slug: string; title: string }[]; reserved: string[]; templates: { id: number; label: string; description?: string }[] }
|
|
5
|
+
interface Boot { pages: { slug: string; title: string }[]; reserved: string[]; templates: { id: number; label: string; description?: string }[]; samples?: { state: 'shown' | 'hidden' | 'none'; list: { title: string; where: string }[] } }
|
|
6
6
|
const boot = (window as any).__PS_PAGES__ as Boot;
|
|
7
7
|
const existing = boot.pages.map((p) => p.slug);
|
|
8
8
|
const titleOnly = (t: string) => t.split(/\s[-–|]\s/)[0];
|
|
@@ -87,3 +87,29 @@ search.addEventListener('input', () => {
|
|
|
87
87
|
document.querySelectorAll<HTMLElement>('#ps-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
|
|
88
88
|
document.getElementById('ps-no-match')!.hidden = shown > 0;
|
|
89
89
|
});
|
|
90
|
+
|
|
91
|
+
// ---- sample content: hide (drafts) or delete, one commit each ----
|
|
92
|
+
async function samples(action: 'hide' | 'delete') {
|
|
93
|
+
const list = boot.samples?.list ?? [];
|
|
94
|
+
const body = document.createElement('div');
|
|
95
|
+
const intro = document.createElement('p');
|
|
96
|
+
intro.textContent = action === 'hide'
|
|
97
|
+
? 'These become drafts: they stay in the editor to open and copy from, and leave the public site. The sample home page moves to a draft called "Sample: …" and a blank home page takes its place.'
|
|
98
|
+
: 'These are removed from the site. They stay in the site\'s git history, so a developer can recover them. Images are kept.';
|
|
99
|
+
const ul = document.createElement('ul');
|
|
100
|
+
ul.className = 'ps-samplelist';
|
|
101
|
+
for (const s of list) { const li = document.createElement('li'); li.textContent = `${s.title} (${s.where})`; ul.append(li); }
|
|
102
|
+
body.append(intro, ul);
|
|
103
|
+
let ok = false;
|
|
104
|
+
await new Promise<void>((resolve) => dialog(action === 'hide' ? 'Hide sample content' : 'Delete sample content', body, [
|
|
105
|
+
{ label: 'Cancel' },
|
|
106
|
+
{ label: action === 'hide' ? 'Hide sample content' : `Delete ${list.length} ${list.length === 1 ? 'item' : 'items'}`, kind: action === 'hide' ? 'primary' : 'danger', run: () => { ok = true; } },
|
|
107
|
+
], { onClose: resolve }));
|
|
108
|
+
if (!ok) return;
|
|
109
|
+
const res = await fetch('/api/editor/samples', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ action }) });
|
|
110
|
+
const data = await res.json().catch(() => ({}));
|
|
111
|
+
if (!res.ok) { toast(data.error || 'That did not work.', 'error'); return; }
|
|
112
|
+
if (data.result?.pullRequest) { toast('The change is in a pull request.', 'ok', { href: data.result.pullRequest }); return; }
|
|
113
|
+
location.reload();
|
|
114
|
+
}
|
|
115
|
+
document.querySelectorAll<HTMLElement>('[data-samples]').forEach((b) => b.addEventListener('click', () => samples(b.dataset.samples as 'hide' | 'delete')));
|
package/src/client/shell.css
CHANGED
|
@@ -127,7 +127,9 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
|
|
|
127
127
|
.ps-group > summary { padding: 8px 12px; font-weight: 600; cursor: pointer; font-size: 12px; text-transform: uppercase; letter-spacing: .04em; color: var(--ps-muted); }
|
|
128
128
|
.ps-fields { padding: 4px 12px 12px; display: flex; flex-direction: column; gap: 10px; }
|
|
129
129
|
.ps-field { display: flex; flex-direction: column; gap: 4px; }
|
|
130
|
-
.ps-field label { font-size: 12px; font-weight: 600; }
|
|
130
|
+
.ps-field label, .ps-field__label { font-size: 12px; font-weight: 600; }
|
|
131
|
+
.ps-checks { display: flex; flex-wrap: wrap; gap: 6px 14px; }
|
|
132
|
+
.ps-field .ps-checks label { display: inline-flex; align-items: center; gap: 6px; font-weight: 400; cursor: pointer; }
|
|
131
133
|
.ps-field--inline { flex-direction: row; align-items: center; gap: 8px; }
|
|
132
134
|
.ps-field input[type="text"], .ps-field input[type="number"], .ps-field select, .ps-field textarea { width: 100%; padding: 6px 8px; border: 1px solid var(--ps-border); border-radius: 6px; font: inherit; background: #fff; }
|
|
133
135
|
.ps-field textarea { resize: vertical; }
|
|
@@ -290,6 +292,13 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
|
|
|
290
292
|
|
|
291
293
|
/* Markdown items */
|
|
292
294
|
.ps-pill--synced { background: #e0e7ff; color: #3730a3; }
|
|
295
|
+
.ps-pill--sample { background: #f1f5f9; color: #475569; }
|
|
296
|
+
.ps-samples { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px 24px; margin-top: 24px; padding: 14px 16px; background: #fff; border: 1px solid var(--ps-border); border-left: 3px solid var(--ps-accent); border-radius: 8px; }
|
|
297
|
+
.ps-samples--hidden { border-left-color: var(--ps-border); }
|
|
298
|
+
.ps-samples p { margin: 4px 0 0; max-width: 62ch; }
|
|
299
|
+
.ps-samples__actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
|
300
|
+
.ps-samplelist { max-height: 40vh; overflow: auto; margin: 8px 0 0; padding-left: 18px; }
|
|
301
|
+
.ps-samplelist li { margin: 2px 0; }
|
|
293
302
|
.ps-check { display: flex; gap: 6px; align-items: center; margin-top: 8px; font-weight: normal; }
|
|
294
303
|
.ps-check input { width: auto; }
|
|
295
304
|
.ps-item__top { display: flex; align-items: center; gap: 16px; padding: 10px 20px; background: #fff; border-bottom: 1px solid var(--ps-border); }
|
package/src/core/insert.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// What the block inserter offers at a given place in the page. Pure so the rules can be tested.
|
|
2
2
|
import type { Node, SchemaRegistry } from '../runtime';
|
|
3
3
|
import { accepts, allowedChildTypes } from './schema';
|
|
4
|
+
import { splitNodePath } from './patch';
|
|
4
5
|
|
|
5
6
|
export interface Pattern { label: string; description?: string; node: Node }
|
|
6
7
|
export interface SavedPattern extends Pattern { id: string; /** Copies stay linked, and can all be updated at once. */ synced?: boolean }
|
|
@@ -68,3 +69,14 @@ export function groupItems(items: InsertItem[]): { category: string; items: Inse
|
|
|
68
69
|
for (const i of items) groups.set(i.category, [...(groups.get(i.category) ?? []), i]);
|
|
69
70
|
return [...groups].map(([category, items]) => ({ category, items }));
|
|
70
71
|
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Where the toolbar's Add block button (and `/`) puts a new block: right after the selected one,
|
|
75
|
+
* beside it in the same list, as WordPress does. With nothing selected, at the end of the page.
|
|
76
|
+
* A container is no exception; adding inside one is its own Add block button.
|
|
77
|
+
*/
|
|
78
|
+
export function insertTarget(doc: { sections: Node[] }, selected: string | null): { listPath: string; index: number } {
|
|
79
|
+
if (!selected) return { listPath: 'sections', index: doc.sections.length };
|
|
80
|
+
const { listPath, index } = splitNodePath(selected);
|
|
81
|
+
return { listPath, index: index + 1 };
|
|
82
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// Sample content: pages and Markdown items a starter ships with `sample: true` (a page's JSON, an
|
|
2
|
+
// item's frontmatter), so a site can hide them (drafts, kept for reference) or delete them in one
|
|
3
|
+
// step from the editor. Saving a sample from the editor drops the mark: once someone has edited
|
|
4
|
+
// it, it is theirs and Hide and Delete leave it alone. Pure, so the rules can be tested.
|
|
5
|
+
import type { FileChange } from './storage';
|
|
6
|
+
import { parseMarkdown, writeMarkdown } from './frontmatter';
|
|
7
|
+
import type { PageDoc } from '../runtime';
|
|
8
|
+
|
|
9
|
+
/** What a host can add in its `sections` module as `sampleContent`. All optional. */
|
|
10
|
+
export interface SampleContent {
|
|
11
|
+
/** Who the samples belong to, for the notice, e.g. "Crumb, the sample bakery". */
|
|
12
|
+
label?: string;
|
|
13
|
+
/** The home page that takes the sample one's place. Default: an empty page titled "Home". */
|
|
14
|
+
home?: PageDoc;
|
|
15
|
+
/** Values to set in globals when the samples go, e.g. `{ site: { announcement: '' } }`. */
|
|
16
|
+
globals?: Record<string, Record<string, unknown>>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface SamplePage { slug: string; path: string; raw: string; page: PageDoc }
|
|
20
|
+
export interface SampleItem { collection: string; label: string; slug: string; path: string; raw: string; title: string; draft: boolean }
|
|
21
|
+
export interface SampleGlobal { id: string; path: string; raw: string | null }
|
|
22
|
+
|
|
23
|
+
export type SampleState = 'shown' | 'hidden' | 'none';
|
|
24
|
+
|
|
25
|
+
/** The page slug the sample home page moves to when it is hidden. */
|
|
26
|
+
export const SAMPLE_HOME = 'sample-home';
|
|
27
|
+
|
|
28
|
+
export const isSamplePage = (page: unknown) => (page as { sample?: unknown } | null)?.sample === true;
|
|
29
|
+
export const isSampleItem = (raw: string) => parseMarkdown(raw).data.sample === true;
|
|
30
|
+
|
|
31
|
+
/** shown: a sample is on the public site. hidden: samples remain, all drafts. none: no samples. */
|
|
32
|
+
export function sampleState(pages: SamplePage[], items: SampleItem[]): SampleState {
|
|
33
|
+
if (!pages.length && !items.length) return 'none';
|
|
34
|
+
const shown = pages.some((p) => p.slug === 'index' || p.page.status !== 'draft') || items.some((i) => !i.draft);
|
|
35
|
+
return shown ? 'shown' : 'hidden';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface SamplePlan { files: FileChange[]; deletes: string[]; expect: Record<string, string | null>; pages: number; items: number }
|
|
39
|
+
|
|
40
|
+
interface PlanInput {
|
|
41
|
+
pages: SamplePage[];
|
|
42
|
+
items: SampleItem[];
|
|
43
|
+
globals: SampleGlobal[];
|
|
44
|
+
config: SampleContent;
|
|
45
|
+
/** Repo path for a page slug. */
|
|
46
|
+
pagePath: (slug: string) => string;
|
|
47
|
+
/** Slugs taken now, so the moved home page gets a free one. */
|
|
48
|
+
taken: string[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const pageJson = (page: PageDoc) => JSON.stringify(page, null, 2) + '\n';
|
|
52
|
+
const home = (config: SampleContent): PageDoc => {
|
|
53
|
+
const { sample: _, ...page } = (config.home ?? { title: 'Home', sections: [] }) as PageDoc & { sample?: unknown };
|
|
54
|
+
return { ...page, status: undefined } as PageDoc;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** The global files with the host's values applied, where that changes anything. */
|
|
58
|
+
function globalChanges(input: PlanInput): FileChange[] {
|
|
59
|
+
const out: FileChange[] = [];
|
|
60
|
+
for (const g of input.globals) {
|
|
61
|
+
const values = input.config.globals?.[g.id];
|
|
62
|
+
if (!values || g.raw === null) continue;
|
|
63
|
+
const data = JSON.parse(g.raw);
|
|
64
|
+
if (Object.entries(values).every(([k, v]) => JSON.stringify(data[k]) === JSON.stringify(v))) continue;
|
|
65
|
+
out.push({ path: g.path, content: JSON.stringify({ ...data, ...values }, null, 2) + '\n' });
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function freeSlug(base: string, taken: string[]): string {
|
|
71
|
+
if (!taken.includes(base)) return base;
|
|
72
|
+
for (let n = 2; ; n++) if (!taken.includes(`${base}-${n}`)) return `${base}-${n}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Hide: sample pages become drafts, and sample items `draft: true`. The home page can't be a draft
|
|
77
|
+
* (the site needs one), so the sample home moves to `sample-home` as a draft and `config.home`
|
|
78
|
+
* takes its place. Every file it reads must be unchanged when the commit lands.
|
|
79
|
+
*/
|
|
80
|
+
export function planHide(input: PlanInput): SamplePlan {
|
|
81
|
+
const files: FileChange[] = [];
|
|
82
|
+
const deletes: string[] = [];
|
|
83
|
+
const expect: Record<string, string | null> = {};
|
|
84
|
+
let pages = 0, items = 0;
|
|
85
|
+
for (const p of input.pages) {
|
|
86
|
+
if (p.slug === 'index') {
|
|
87
|
+
const to = input.pagePath(freeSlug(SAMPLE_HOME, input.taken));
|
|
88
|
+
files.push({ path: to, content: pageJson({ ...p.page, title: `Sample: ${p.page.title}`, status: 'draft' }) });
|
|
89
|
+
files.push({ path: p.path, content: pageJson(home(input.config)) });
|
|
90
|
+
expect[to] = null;
|
|
91
|
+
} else if (p.page.status !== 'draft') {
|
|
92
|
+
files.push({ path: p.path, content: pageJson({ ...p.page, status: 'draft' }) });
|
|
93
|
+
} else continue;
|
|
94
|
+
expect[p.path] = p.raw;
|
|
95
|
+
pages++;
|
|
96
|
+
}
|
|
97
|
+
for (const i of input.items) {
|
|
98
|
+
if (i.draft) continue;
|
|
99
|
+
files.push({ path: i.path, content: writeMarkdown(i.raw, { draft: true }, parseMarkdown(i.raw).body) });
|
|
100
|
+
expect[i.path] = i.raw;
|
|
101
|
+
items++;
|
|
102
|
+
}
|
|
103
|
+
for (const g of globalChanges(input)) { files.push(g); expect[g.path] = input.globals.find((x) => x.path === g.path)!.raw; }
|
|
104
|
+
return { files, deletes, expect, pages, items };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Delete: every sample page and item goes. A sample home page is replaced by `config.home`. */
|
|
108
|
+
export function planDelete(input: PlanInput): SamplePlan {
|
|
109
|
+
const files: FileChange[] = [];
|
|
110
|
+
const deletes: string[] = [];
|
|
111
|
+
const expect: Record<string, string | null> = {};
|
|
112
|
+
for (const p of input.pages) {
|
|
113
|
+
if (p.slug === 'index') files.push({ path: p.path, content: pageJson(home(input.config)) });
|
|
114
|
+
else deletes.push(p.path);
|
|
115
|
+
expect[p.path] = p.raw;
|
|
116
|
+
}
|
|
117
|
+
for (const i of input.items) { deletes.push(i.path); expect[i.path] = i.raw; }
|
|
118
|
+
for (const g of globalChanges(input)) { files.push(g); expect[g.path] = input.globals.find((x) => x.path === g.path)!.raw; }
|
|
119
|
+
return { files, deletes, expect, pages: input.pages.length, items: input.items.length };
|
|
120
|
+
}
|
package/src/core/sanitize.ts
CHANGED
|
@@ -243,6 +243,12 @@ function cleanField(v: any, field: Field, o: CleanOptions): any {
|
|
|
243
243
|
if (typeof v === 'number' || typeof v === 'boolean') v = String(v);
|
|
244
244
|
// A value outside the options is usually an old one, so plain words stay and markup goes.
|
|
245
245
|
return field.options?.some((x) => x.value === v) || (typeof v === 'string' && TOKEN_OK.test(v)) ? v : undefined;
|
|
246
|
+
case 'multiselect': {
|
|
247
|
+
// One value on its own is how a hand-written file may put it.
|
|
248
|
+
const all = Array.isArray(v) ? v : v === '' ? [] : [v];
|
|
249
|
+
const kept = all.map((x) => cleanField(x, { ...field, type: 'select' }, o)).filter((x) => typeof x === 'string' && x !== '');
|
|
250
|
+
return kept.length || !all.length ? [...new Set(kept)] : undefined;
|
|
251
|
+
}
|
|
246
252
|
case 'number':
|
|
247
253
|
return v === '' || Number.isFinite(typeof v === 'string' ? Number(v) : v) ? v : undefined;
|
|
248
254
|
case 'boolean':
|
package/src/core/schema.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Schema -> form model and node factories. Pure; used on the server (validation) and in the
|
|
2
2
|
// browser (sidebar forms, add menus).
|
|
3
|
-
import type { BlockSchema, Field, Node, PageDoc, SchemaRegistry } from '../runtime';
|
|
3
|
+
import type { BlockSchema, Field, Node, PageDoc, SchemaRegistry, ShowIf } from '../runtime';
|
|
4
4
|
import { newId } from '../runtime';
|
|
5
5
|
|
|
6
6
|
export interface FormField { name: string; field: Field; value: unknown }
|
|
@@ -18,6 +18,35 @@ export function formModel(schema: BlockSchema, settings: Record<string, unknown>
|
|
|
18
18
|
return (Object.keys(groups) as FormGroup['name'][]).filter((g) => groups[g].length).map((g) => ({ name: g, label: GROUP_LABELS[g], fields: groups[g] }));
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/** A value as `showIf` compares it: always a list of strings, with every kind of "nothing" as ''. */
|
|
22
|
+
function comparable(v: unknown): string[] {
|
|
23
|
+
if (Array.isArray(v)) return v.length ? v.flatMap(comparable) : [''];
|
|
24
|
+
if (v && typeof v === 'object') return [String((v as any).src ?? 'set')]; // an image, or a list's row
|
|
25
|
+
return [v === undefined || v === null || v === false ? '' : String(v)];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function conditionMet(when: ShowIf, value: unknown): boolean {
|
|
29
|
+
const now = comparable(value);
|
|
30
|
+
const any = (v: ShowIf['is']) => comparable(v).some((x) => now.includes(x));
|
|
31
|
+
if (when.is === undefined && when.not === undefined) return now.some(Boolean);
|
|
32
|
+
return (when.is === undefined || any(when.is)) && (when.not === undefined || !any(when.not));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Does the form show this field? A field that depends on a hidden field is hidden too. A condition
|
|
37
|
+
* naming a field that isn't there is ignored, so a typo can't put a field out of reach.
|
|
38
|
+
*/
|
|
39
|
+
export function isShown(name: string, fields: Record<string, Field>, settings: Record<string, unknown>, seen: string[] = []): boolean {
|
|
40
|
+
const when = Object.hasOwn(fields, name) ? fields[name].showIf : undefined;
|
|
41
|
+
if (!when || seen.includes(name)) return true;
|
|
42
|
+
const other = Object.hasOwn(fields, when.field) ? fields[when.field] : undefined;
|
|
43
|
+
const stored = Object.hasOwn(settings, when.field) ? settings[when.field] : undefined;
|
|
44
|
+
if (!other && stored === undefined) return true;
|
|
45
|
+
// With nothing stored, go by what the form displays: the default, or a select's first option.
|
|
46
|
+
const value = stored ?? other?.default ?? (other?.type === 'select' ? other.options?.[0]?.value : undefined);
|
|
47
|
+
return conditionMet(when, value) && isShown(when.field, fields, settings, [...seen, name]);
|
|
48
|
+
}
|
|
49
|
+
|
|
21
50
|
export function defaultSettings(schema: BlockSchema): Record<string, unknown> {
|
|
22
51
|
const s: Record<string, unknown> = {};
|
|
23
52
|
for (const [k, f] of Object.entries(schema.fields)) if (f.default !== undefined) s[k] = structuredClone(f.default);
|
package/src/core/transform.ts
CHANGED
|
@@ -56,10 +56,11 @@ export function transformNode(node: Node, type: string, registry: SchemaRegistry
|
|
|
56
56
|
settings[slot] = convert(node.settings[k], f, to.fields[slot]);
|
|
57
57
|
open.delete(slot);
|
|
58
58
|
}
|
|
59
|
+
const fits = (f: Field, v: unknown) => !f.options || (Array.isArray(v) ? v : [v]).every((x) => f.options!.some((o) => o.value === x));
|
|
59
60
|
// Style settings carry over when the new type has the same field and the value still fits.
|
|
60
61
|
for (const [k, f] of Object.entries(from?.fields ?? {})) {
|
|
61
62
|
const t = to.fields[k];
|
|
62
|
-
if (t && t.type === f.type && !isText(f) && f.type !== 'image' && node.settings[k] !== undefined && (
|
|
63
|
+
if (t && t.type === f.type && !isText(f) && f.type !== 'image' && node.settings[k] !== undefined && fits(t, node.settings[k])) settings[k] = node.settings[k];
|
|
63
64
|
}
|
|
64
65
|
const { blocks, ...rest } = node;
|
|
65
66
|
return { ...rest, type, settings, ...(to.blocks ? { blocks: blocks ?? [] } : {}) };
|
|
@@ -79,10 +79,12 @@ export const PUT: APIRoute = async ({ params, request, locals }) => {
|
|
|
79
79
|
if (body.base && body.base !== await sha256(raw)) return json({ error: 'This changed since you opened it. Reload to get the latest version.' }, 409);
|
|
80
80
|
const data = cleanData(c, body.data);
|
|
81
81
|
if ('title' in c.fields && !String(data.title ?? '').trim()) return bad('Give it a title.');
|
|
82
|
-
|
|
82
|
+
let content = writeMarkdown(raw, data, sanitizeMarkdown(body.body));
|
|
83
83
|
const next = typeof body.slug === 'string' ? body.slug.trim() : slug;
|
|
84
84
|
const moving = next !== slug;
|
|
85
85
|
if (!moving && content === raw) return json({ ok: true, unchanged: true, hash: await sha256(raw) });
|
|
86
|
+
// Once someone has saved a sample item, it is theirs: Hide/Delete sample content leave it alone.
|
|
87
|
+
if (parseMarkdown(content).data.sample === true) content = writeMarkdown(content, { sample: null }, parseMarkdown(content).body);
|
|
86
88
|
const files: FileChange[] = [{ path: file(c, next), content }];
|
|
87
89
|
let deletes: string[] | undefined;
|
|
88
90
|
if (moving) {
|
package/src/routes/api/page.ts
CHANGED
|
@@ -40,7 +40,9 @@ export const PUT: APIRoute = async ({ params, request, locals }) => {
|
|
|
40
40
|
const current = await readPage(slug);
|
|
41
41
|
if (!current) return bad('no such page', 404);
|
|
42
42
|
if (base && base !== current.hash) return json({ error: STALE, hash: current.hash }, 409);
|
|
43
|
-
|
|
43
|
+
// Once someone has saved a sample page, it is theirs: Hide/Delete sample content leave it alone.
|
|
44
|
+
const { sample: _sample, ...saved } = clean(page, locals, current.page);
|
|
45
|
+
const content = serializePage(saved);
|
|
44
46
|
|
|
45
47
|
const moving = typeof nextSlug === 'string' && nextSlug !== slug;
|
|
46
48
|
const files: FileChange[] = [{ path: pagePath(moving ? nextSlug : slug), content }];
|
package/src/routes/api/pages.ts
CHANGED
|
@@ -25,7 +25,8 @@ export const POST: APIRoute = async ({ request, locals }) => {
|
|
|
25
25
|
const source = await readPage(String(body.copyOf));
|
|
26
26
|
if (!source) return bad('The page to copy no longer exists.', 404);
|
|
27
27
|
keep = source.page;
|
|
28
|
-
|
|
28
|
+
const { sample: _sample, ...plain } = source.page;
|
|
29
|
+
page = copyPage(plain, title);
|
|
29
30
|
} else if (body.template != null) {
|
|
30
31
|
const template = templates[Number(body.template)];
|
|
31
32
|
if (!template) return bad('Unknown template.');
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Sample content a starter ships with (`sample: true` on pages and Markdown items): hide it or delete it.
|
|
2
|
+
// GET /api/editor/samples -> { state, pages, items }
|
|
3
|
+
// POST /api/editor/samples { action: 'hide' | 'delete' } -> one commit (admins only)
|
|
4
|
+
import type { APIRoute } from 'astro';
|
|
5
|
+
import { bad, clean, commitMessage, isAdmin, json, pagePath, readSamples, sampleContent, storage, validate } from '../../server/context';
|
|
6
|
+
import { planDelete, planHide, sampleState } from '../../core/samples';
|
|
7
|
+
import { StaleWrite } from '../../core/storage';
|
|
8
|
+
import type { PageDoc } from '../../runtime';
|
|
9
|
+
export const prerender = false;
|
|
10
|
+
|
|
11
|
+
export const GET: APIRoute = async () => {
|
|
12
|
+
const s = await readSamples();
|
|
13
|
+
return json({
|
|
14
|
+
state: sampleState(s.pages, s.items),
|
|
15
|
+
pages: s.pages.map((p) => ({ slug: p.slug, title: p.page.title, draft: p.slug !== 'index' && p.page.status === 'draft' })),
|
|
16
|
+
items: s.items.map((i) => ({ collection: i.collection, label: i.label, slug: i.slug, title: i.title, draft: i.draft })),
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const POST: APIRoute = async ({ request, locals }) => {
|
|
21
|
+
if (!isAdmin(locals)) return bad('Only admins can hide or delete the sample content.', 403);
|
|
22
|
+
const body = await request.json().catch(() => null);
|
|
23
|
+
const action = body?.action;
|
|
24
|
+
if (action !== 'hide' && action !== 'delete') return bad('action must be "hide" or "delete"');
|
|
25
|
+
const home = clean(sampleContent.home ?? ({ title: 'Home', sections: [] } as PageDoc), locals);
|
|
26
|
+
const problems = validate(home);
|
|
27
|
+
if (problems.length) return bad(`The site's replacement home page is not valid: ${problems.join('; ')}`, 500);
|
|
28
|
+
const s = await readSamples();
|
|
29
|
+
if (sampleState(s.pages, s.items) === 'none') return json({ ok: true, nothing: true });
|
|
30
|
+
const plan = (action === 'hide' ? planHide : planDelete)({ pages: s.pages, items: s.items, globals: s.globals, config: { ...sampleContent, home }, pagePath, taken: s.slugs });
|
|
31
|
+
if (!plan.files.length && !plan.deletes.length) return json({ ok: true, nothing: true });
|
|
32
|
+
const what = [plan.pages && `${plan.pages} page${plan.pages === 1 ? '' : 's'}`, plan.items && `${plan.items} item${plan.items === 1 ? '' : 's'}`].filter(Boolean).join(' and ');
|
|
33
|
+
try {
|
|
34
|
+
const result = await storage().commit({
|
|
35
|
+
message: commitMessage(`${action === 'hide' ? 'Hide' : 'Delete'} sample content${what ? ` (${what})` : ''}`, locals),
|
|
36
|
+
files: plan.files, deletes: plan.deletes, expect: plan.expect,
|
|
37
|
+
});
|
|
38
|
+
return json({ ok: true, result, pages: plan.pages, items: plan.items });
|
|
39
|
+
} catch (e: any) {
|
|
40
|
+
if (e instanceof StaleWrite) return bad('Someone changed the sample content at the same moment. Reload and try again.', 409);
|
|
41
|
+
return bad(`Could not ${action} the sample content: ${e.message}`, 500);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
// /edit — the Pages screen: every page, with add, duplicate, delete and search.
|
|
3
|
-
import { collections, globals, listPages, opts, publicPath, reservedSlugs, templates } from '../server/context';
|
|
3
|
+
import { collections, globals, isAdmin, listPages, opts, publicPath, readSamples, reservedSlugs, sampleContent, templates } from '../server/context';
|
|
4
|
+
import { sampleState } from '../core/samples';
|
|
4
5
|
import Nav from './Nav.astro';
|
|
5
6
|
import '../client/shell.css';
|
|
6
7
|
export const prerender = false;
|
|
@@ -9,10 +10,19 @@ if (opts.pages === false) {
|
|
|
9
10
|
return Astro.redirect(first ? `/edit/collection/${first}` : '/edit/media');
|
|
10
11
|
}
|
|
11
12
|
const pages = await listPages();
|
|
13
|
+
// Sample content a starter shipped with: admins can hide it or delete it from here.
|
|
14
|
+
const samples = isAdmin(Astro.locals) ? await readSamples() : null;
|
|
15
|
+
const sampleNow = samples ? sampleState(samples.pages, samples.items) : 'none';
|
|
16
|
+
const sampleList = samples ? [
|
|
17
|
+
...samples.pages.map((p) => ({ title: p.page.title, where: p.slug === 'index' ? 'Home page' : 'Page' })),
|
|
18
|
+
...samples.items.map((i) => ({ title: i.title, where: i.label })),
|
|
19
|
+
] : [];
|
|
20
|
+
const sampleCount = sampleList.length;
|
|
12
21
|
const boot = {
|
|
13
22
|
pages: pages.map((p) => ({ slug: p.slug, title: p.title })),
|
|
14
23
|
reserved: reservedSlugs(),
|
|
15
24
|
templates: templates.map((t, i) => ({ id: i, label: t.label, description: t.description })),
|
|
25
|
+
samples: { state: sampleNow, list: sampleList },
|
|
16
26
|
};
|
|
17
27
|
const globalLinks = Object.entries(globals).map(([id, g]) => ({ id, label: g.label, description: g.description }));
|
|
18
28
|
---
|
|
@@ -35,6 +45,25 @@ const globalLinks = Object.entries(globals).map(([id, g]) => ({ id, label: g.lab
|
|
|
35
45
|
</div>
|
|
36
46
|
<button type="button" id="ps-add-page" class="ps-btn ps-btn--primary">Add page</button>
|
|
37
47
|
</header>
|
|
48
|
+
{sampleNow !== 'none' && (
|
|
49
|
+
<section class={`ps-samples ps-samples--${sampleNow}`} aria-label="Sample content">
|
|
50
|
+
{sampleNow === 'shown' ? (
|
|
51
|
+
<div>
|
|
52
|
+
<strong>This site still has its sample content{sampleContent.label ? `: ${sampleContent.label}` : ''}.</strong>
|
|
53
|
+
<p class="ps-muted">{sampleCount} sample {sampleCount === 1 ? 'page or post' : 'pages and posts'}. <b>Hide</b> keeps them as drafts you can open and copy from, off the public site. <b>Delete</b> removes them. Anything you've edited and saved is yours and stays. Images stay either way.</p>
|
|
54
|
+
</div>
|
|
55
|
+
) : (
|
|
56
|
+
<div>
|
|
57
|
+
<strong>Sample content is hidden.</strong>
|
|
58
|
+
<p class="ps-muted">{sampleCount} {sampleCount === 1 ? 'draft is' : 'drafts are'} kept for reference. Delete them once you no longer need them.</p>
|
|
59
|
+
</div>
|
|
60
|
+
)}
|
|
61
|
+
<div class="ps-samples__actions">
|
|
62
|
+
{sampleNow === 'shown' && <button type="button" class="ps-btn ps-btn--primary" data-samples="hide">Hide sample content</button>}
|
|
63
|
+
<button type="button" class="ps-btn ps-btn--ghost ps-btn--danger" data-samples="delete">Delete sample content</button>
|
|
64
|
+
</div>
|
|
65
|
+
</section>
|
|
66
|
+
)}
|
|
38
67
|
{globalLinks.length > 0 && (
|
|
39
68
|
<nav class="ps-globals" aria-label="Site settings">
|
|
40
69
|
{globalLinks.map((g) => <a href={`/edit/global/${g.id}`}><strong>{g.label}</strong>{g.description && <span class="ps-muted">{g.description}</span>}</a>)}
|
|
@@ -47,7 +76,7 @@ const globalLinks = Object.entries(globals).map(([id, g]) => ({ id, label: g.lab
|
|
|
47
76
|
<ul class="ps-pagelist" id="ps-pagelist">
|
|
48
77
|
{pages.map((p) => (
|
|
49
78
|
<li data-slug={p.slug} data-search={`${p.title} ${p.slug}`.toLowerCase()}>
|
|
50
|
-
<a class="ps-pagelist__edit" href={`/edit/${p.slug}`}><strong>{p.title}{p.status === 'draft' && <span class="ps-pill">Draft</span>}</strong><span class="ps-muted">{publicPath(p.slug)} · {p.sections} {p.sections === 1 ? 'section' : 'sections'}</span></a>
|
|
79
|
+
<a class="ps-pagelist__edit" href={`/edit/${p.slug}`}><strong>{p.title}{p.status === 'draft' && <span class="ps-pill">Draft</span>}{p.sample && <span class="ps-pill ps-pill--sample">Sample</span>}</strong><span class="ps-muted">{publicPath(p.slug)} · {p.sections} {p.sections === 1 ? 'section' : 'sections'}</span></a>
|
|
51
80
|
<div class="ps-pagelist__actions">
|
|
52
81
|
{p.status !== 'draft' && <a class="ps-btn ps-btn--small ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(publicPath(p.slug))}`}>View</a>}
|
|
53
82
|
<button type="button" class="ps-btn ps-btn--small ps-btn--ghost" data-duplicate={p.slug}>Duplicate</button>
|
package/src/runtime.ts
CHANGED
|
@@ -8,6 +8,7 @@ export type FieldType =
|
|
|
8
8
|
| 'link' // URL string
|
|
9
9
|
| 'color' // CSS colour (hex, rgb(), var(--x))
|
|
10
10
|
| 'select'
|
|
11
|
+
| 'multiselect' // checkboxes over `options`; value is an array of their values, in option order
|
|
11
12
|
| 'number'
|
|
12
13
|
| 'boolean'
|
|
13
14
|
| 'textarea' // multi-line plain text, sidebar only
|
|
@@ -17,6 +18,15 @@ export type FieldType =
|
|
|
17
18
|
| 'tags' // array of strings
|
|
18
19
|
| 'list'; // repeatable rows of sub-fields (menus, link lists); value is an array of objects
|
|
19
20
|
|
|
21
|
+
/**
|
|
22
|
+
* When the editor shows a field, from the value of another field beside it (same form, or same list row).
|
|
23
|
+
* With neither `is` nor `not`: when that field has a value (not blank, off or empty).
|
|
24
|
+
* A list of values matches any of them; a 'multiselect' matches when any ticked value does.
|
|
25
|
+
* Missing, '', false and an empty list are the same thing here.
|
|
26
|
+
*/
|
|
27
|
+
export interface ShowIf { field: string; is?: ShowIfValue | ShowIfValue[]; not?: ShowIfValue | ShowIfValue[] }
|
|
28
|
+
export type ShowIfValue = string | number | boolean;
|
|
29
|
+
|
|
20
30
|
export interface Field {
|
|
21
31
|
type: FieldType;
|
|
22
32
|
label: string;
|
|
@@ -28,6 +38,7 @@ export interface Field {
|
|
|
28
38
|
* only `<strong>` and `<em>`; render it with `set:html`. Without it, a text field is plain text.
|
|
29
39
|
*/
|
|
30
40
|
marks?: boolean;
|
|
41
|
+
/** For 'select' and 'multiselect'. */
|
|
31
42
|
options?: { value: string; label: string }[];
|
|
32
43
|
/** Sidebar grouping. Defaults to 'content'. */
|
|
33
44
|
group?: 'content' | 'style' | 'advanced';
|
|
@@ -35,6 +46,8 @@ export interface Field {
|
|
|
35
46
|
max?: number;
|
|
36
47
|
step?: number;
|
|
37
48
|
help?: string;
|
|
49
|
+
/** Show this field only when another one has a certain value. Hiding never changes the stored value. */
|
|
50
|
+
showIf?: ShowIf;
|
|
38
51
|
/** For 'svg': named icons offered in a dropdown besides raw SVG. */
|
|
39
52
|
icons?: string[];
|
|
40
53
|
/** For 'list': the fields of one row. */
|
|
@@ -66,6 +79,8 @@ export interface BlockSchema {
|
|
|
66
79
|
transforms?: string[];
|
|
67
80
|
}
|
|
68
81
|
|
|
82
|
+
export type { SampleContent } from './core/samples';
|
|
83
|
+
|
|
69
84
|
export interface ImageValue { src: string; alt: string; width?: number; height?: number }
|
|
70
85
|
|
|
71
86
|
export interface Node {
|
|
@@ -87,6 +102,8 @@ export interface PageDoc {
|
|
|
87
102
|
ogImage?: string;
|
|
88
103
|
/** Site-specific frame data (layout, CSS files…); the editor never interprets it. */
|
|
89
104
|
layout?: Record<string, any>;
|
|
105
|
+
/** Sample content a starter ships with. Hide/Delete sample content act on it; saving it from the editor drops the mark. */
|
|
106
|
+
sample?: boolean;
|
|
90
107
|
sections: Node[];
|
|
91
108
|
}
|
|
92
109
|
|
package/src/server/context.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { parseMarkdown } from '../core/frontmatter';
|
|
|
13
13
|
import type { EditorUser, Role, UsersFile } from '../core/users';
|
|
14
14
|
import { publicPath, RESERVED_SLUGS } from '../core/pages';
|
|
15
15
|
import type { SavedPattern } from '../core/insert';
|
|
16
|
+
import { isSampleItem, isSamplePage, type SampleContent, type SampleGlobal, type SampleItem, type SamplePage } from '../core/samples';
|
|
16
17
|
|
|
17
18
|
export { options, site };
|
|
18
19
|
|
|
@@ -54,11 +55,39 @@ export function presets() {
|
|
|
54
55
|
}
|
|
55
56
|
|
|
56
57
|
/** Host extras from the `sections` module; all optional. */
|
|
57
|
-
const extras = site as unknown as { pageFields?: Record<string, Field>; templates?: PageTemplate[]; globals?: Record<string, GlobalDoc>; collections?: Record<string, CollectionDoc
|
|
58
|
+
const extras = site as unknown as { pageFields?: Record<string, Field>; templates?: PageTemplate[]; globals?: Record<string, GlobalDoc>; collections?: Record<string, CollectionDoc>; sampleContent?: SampleContent };
|
|
58
59
|
export const pageFields = extras.pageFields ?? {};
|
|
59
60
|
export const templates = extras.templates ?? [];
|
|
60
61
|
export const globals = extras.globals ?? {};
|
|
61
62
|
export const collections = extras.collections ?? {};
|
|
63
|
+
export const sampleContent: SampleContent = extras.sampleContent ?? {};
|
|
64
|
+
|
|
65
|
+
/** Every page and Markdown item marked `sample: true`, and the globals the host resets with them. */
|
|
66
|
+
export async function readSamples(): Promise<{ pages: SamplePage[]; items: SampleItem[]; globals: SampleGlobal[]; slugs: string[] }> {
|
|
67
|
+
const slugs = opts.pages === false ? [] : await pageSlugs();
|
|
68
|
+
const pages: SamplePage[] = [];
|
|
69
|
+
for (const slug of slugs) {
|
|
70
|
+
const r = await readPage(slug);
|
|
71
|
+
if (r && isSamplePage(r.page)) pages.push({ slug, path: pagePath(slug), raw: r.raw, page: r.page });
|
|
72
|
+
}
|
|
73
|
+
const items: SampleItem[] = [];
|
|
74
|
+
for (const [id, c] of Object.entries(collections)) {
|
|
75
|
+
// readDir: one request on GitHub, where reading each file would cost one each.
|
|
76
|
+
const files = storage().readDir ? await storage().readDir!(c.dir)
|
|
77
|
+
: await Promise.all((await storage().listDir(c.dir)).filter((e) => e.type === 'file').map(async (e) => ({ name: e.name, content: await storage().readFile(`${c.dir}/${e.name}`) ?? '' })));
|
|
78
|
+
for (const { name, content: raw } of files) {
|
|
79
|
+
if (!name.endsWith('.md') || !isSampleItem(raw)) continue;
|
|
80
|
+
const { data } = parseMarkdown(raw);
|
|
81
|
+
items.push({ collection: id, label: c.label, slug: name.slice(0, -3), path: `${c.dir}/${name}`, raw, title: String(data.title ?? name), draft: data.draft === true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const globalsOut: SampleGlobal[] = [];
|
|
85
|
+
for (const id of Object.keys(sampleContent.globals ?? {})) {
|
|
86
|
+
const g = Object.hasOwn(globals, id) ? globals[id] : null;
|
|
87
|
+
if (g) globalsOut.push({ id, path: g.file, raw: await storage().readFile(g.file) });
|
|
88
|
+
}
|
|
89
|
+
return { pages, items, globals: globalsOut, slugs };
|
|
90
|
+
}
|
|
62
91
|
/** Pages (and their titles) whose stored JSON mentions a URL. Globals and patterns count too. */
|
|
63
92
|
export async function whereUsed(src: string): Promise<{ title: string; href: string }[]> {
|
|
64
93
|
const out: { title: string; href: string }[] = [];
|
|
@@ -97,7 +126,7 @@ export async function readPage(slug: string): Promise<{ page: PageDoc; hash: str
|
|
|
97
126
|
return { page: JSON.parse(raw) as PageDoc, hash: await sha256(raw), raw };
|
|
98
127
|
}
|
|
99
128
|
|
|
100
|
-
export interface PageSummary { slug: string; title: string; sections: number; status: 'draft' | 'published' }
|
|
129
|
+
export interface PageSummary { slug: string; title: string; sections: number; status: 'draft' | 'published'; sample?: boolean }
|
|
101
130
|
|
|
102
131
|
export async function pageSlugs(dir = '', depth = 0): Promise<string[]> {
|
|
103
132
|
const entries = await storage().listDir(dir ? `${opts.pagesDir}/${dir}` : opts.pagesDir);
|
|
@@ -114,7 +143,7 @@ export async function listPages(): Promise<PageSummary[]> {
|
|
|
114
143
|
const out: PageSummary[] = [];
|
|
115
144
|
for (const slug of await pageSlugs()) {
|
|
116
145
|
const r = await readPage(slug);
|
|
117
|
-
if (r) out.push({ slug, title: r.page.title, sections: r.page.sections.length, status: r.page.status === 'draft' ? 'draft' : 'published' });
|
|
146
|
+
if (r) out.push({ slug, title: r.page.title, sections: r.page.sections.length, status: r.page.status === 'draft' ? 'draft' : 'published', ...(isSamplePage(r.page) ? { sample: true } : {}) });
|
|
118
147
|
}
|
|
119
148
|
return out.sort((a, b) => (a.slug === 'index' ? -1 : b.slug === 'index' ? 1 : a.slug.localeCompare(b.slug)));
|
|
120
149
|
}
|