@pirateandfox/pagestack 0.1.0-beta.15 → 0.1.0-beta.16

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 CHANGED
@@ -311,8 +311,33 @@ export const globals = {
311
311
  },
312
312
  },
313
313
  };
314
+
315
+ // For a starter or template: what replaces its sample content (see "Sample content" below)
316
+ export const sampleContent = {
317
+ label: 'Crumb, the sample bakery',
318
+ home: { title: 'Home', sections: [/* … */] },
319
+ globals: { menus: { announcement: '' } },
320
+ };
314
321
  ```
315
322
 
323
+ #### Sample content
324
+
325
+ A starter or theme can ship sample pages and posts and let the site's owner clear them with one
326
+ button. Mark each sample with `"sample": true` at the top of a page's JSON, or `sample: true` in
327
+ an item's frontmatter. While any are on the site, admins see a notice on the Pages screen with:
328
+
329
+ - **Hide sample content**: sample pages become drafts and sample items `draft: true`, so they stay
330
+ in the editor to open and copy from and leave the public site. The home page can't be a draft,
331
+ so the sample one moves to a draft page `sample-home` and `sampleContent.home` takes its place
332
+ (default: an empty page titled Home).
333
+ - **Delete sample content**: every sample page and item is removed, and a sample home page is
334
+ replaced the same way. The confirmation lists them all.
335
+
336
+ Either is one commit, and both set the `sampleContent.globals` values (an announcement that
337
+ advertised a sample event, say). Images are never touched. Saving a sample from the editor drops
338
+ its mark: once someone has edited it, it's theirs, and Hide and Delete leave it alone. Pages still
339
+ marked show a **Sample** pill in the page list.
340
+
316
341
  #### Editing a collection item on its own page
317
342
 
318
343
  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.15",
3
+ "version": "0.1.0-beta.16",
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",
@@ -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
- function defaultTarget(): Target {
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);
@@ -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')));
@@ -290,6 +290,13 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
290
290
 
291
291
  /* Markdown items */
292
292
  .ps-pill--synced { background: #e0e7ff; color: #3730a3; }
293
+ .ps-pill--sample { background: #f1f5f9; color: #475569; }
294
+ .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; }
295
+ .ps-samples--hidden { border-left-color: var(--ps-border); }
296
+ .ps-samples p { margin: 4px 0 0; max-width: 62ch; }
297
+ .ps-samples__actions { display: flex; flex-wrap: wrap; gap: 8px; }
298
+ .ps-samplelist { max-height: 40vh; overflow: auto; margin: 8px 0 0; padding-left: 18px; }
299
+ .ps-samplelist li { margin: 2px 0; }
293
300
  .ps-check { display: flex; gap: 6px; align-items: center; margin-top: 8px; font-weight: normal; }
294
301
  .ps-check input { width: auto; }
295
302
  .ps-item__top { display: flex; align-items: center; gap: 16px; padding: 10px 20px; background: #fff; border-bottom: 1px solid var(--ps-border); }
@@ -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
+ }
@@ -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
- const content = writeMarkdown(raw, data, sanitizeMarkdown(body.body));
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) {
@@ -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
- const content = serializePage(clean(page, locals, current.page));
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 }];
@@ -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
- page = copyPage(source.page, title);
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
@@ -66,6 +66,8 @@ export interface BlockSchema {
66
66
  transforms?: string[];
67
67
  }
68
68
 
69
+ export type { SampleContent } from './core/samples';
70
+
69
71
  export interface ImageValue { src: string; alt: string; width?: number; height?: number }
70
72
 
71
73
  export interface Node {
@@ -87,6 +89,8 @@ export interface PageDoc {
87
89
  ogImage?: string;
88
90
  /** Site-specific frame data (layout, CSS files…); the editor never interprets it. */
89
91
  layout?: Record<string, any>;
92
+ /** Sample content a starter ships with. Hide/Delete sample content act on it; saving it from the editor drops the mark. */
93
+ sample?: boolean;
90
94
  sections: Node[];
91
95
  }
92
96
 
@@ -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
  }