@pirateandfox/pagestack 0.1.0-beta.19 → 0.1.0-beta.21

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.21 — 2026-11-28
4
+
5
+ - **An item's title can always be edited.** In the page view the Title box was hidden, and the title could only be edited by clicking it on the page, which needs the site's layout to mark it with `itemField(editing, 'title')`. A layout that didn't left the title uneditable there. Now the Title box shows above the page whenever the page has no editable title. Sites should still mark their heading, so the title is edited in place.
6
+ - **Collection lists in date order, with Upcoming and Past tabs for events.** A list used to sort only by a field named `date`, so a collection dated by another field (events by `start`) came out in file order. It now uses `list.date`, else `date`, else the first date field. Each item shows its date with the weekday and time. A new optional `list` on a collection (type `CollectionList` in the runtime): `order: 'upcoming'` lists soonest first, and moves anything dated before today, by the editor's clock, to a Past tab. `repeats(data, now)` lets the site say an item repeats, how often (shown as a label) and its next date, which it is listed by. See README, "Collection lists". Without `list`, posts are listed as before. `GET /api/editor/collection/<id>` returns items in that order, with `date` taken from the list's field and `repeats` on repeating items.
7
+
8
+ ## 0.1.0-beta.20 — 2026-11-27
9
+
10
+ - **`@pirateandfox/pagestack/live` has TypeScript types.** `live.d.mts` declares `liveEntries()` and a `LiveEntry` type, so `astro check` no longer reports the import as untyped. Hosts that added their own `declare module '@pirateandfox/pagestack/live'` can delete it. No runtime change.
11
+
3
12
  ## 0.1.0-beta.19 — 2026-11-26
4
13
 
5
14
  - **A new item's date is the editor's time, not the server's.** The first date field started as the server's UTC time, hours out, and in the evening tomorrow; when it was required nobody was asked to correct it. `POST /api/editor/collection/<id>` takes an optional `now` (local time, `"2026-11-24T18:49:35"`).
@@ -86,7 +95,7 @@
86
95
 
87
96
  ## 0.1.0-beta.10 — 2026-11-12
88
97
 
89
- - **Faster first load of live pages and previews.** Live collections now load together, pinned to the branch head, in one GitHub GraphQL request instead of a listing plus one request per file (Sentiosonics: 70 requests and about 10 s on a fresh server, now 11 requests and under 5 s locally). Falls back to the REST reads when GraphQL isn't available. New optional storage method `readDirs(paths, ref)`.
98
+ - **Faster first load of live pages and previews.** Live collections now load together, pinned to the branch head, in one GitHub GraphQL request instead of a listing plus one request per file (on one real site: 70 requests and about 10 s on a fresh server, now 11 requests and under 5 s locally). Falls back to the REST reads when GraphQL isn't available. New optional storage method `readDirs(paths, ref)`.
90
99
  - **Browse shows when a page is loading**: a moving strip under the bar and "Loading page…", instead of a blank frame.
91
100
 
92
101
  ## 0.1.0-beta.9 — 2026-11-12
package/README.md CHANGED
@@ -345,6 +345,12 @@ export const collections = {
345
345
  label: 'Posts', singular: 'post', dir: 'src/content/blog', url: (slug) => `/${slug}/`,
346
346
  fields: { title: { type: 'text', label: 'Title' }, draft: { type: 'boolean', label: 'Draft' }, date: { type: 'date', label: 'Date', required: true }, tags: { type: 'tags', label: 'Tags' } },
347
347
  },
348
+ events: {
349
+ label: 'Events', singular: 'event', dir: 'src/content/events',
350
+ fields: { title: { type: 'text', label: 'Title' }, start: { type: 'date', label: 'Starts' }, repeat: { type: 'select', label: 'Repeats', options: [/* … */] } },
351
+ // The list screen: by `start`, soonest first, with Upcoming and Past tabs (see "Collection lists" below)
352
+ list: { date: 'start', order: 'upcoming', repeats: (data, now) => (data.repeat === 'none' ? null : { label: 'Every week', next: nextStart(data, now) }) },
353
+ },
348
354
  };
349
355
 
350
356
  export const globals = {
@@ -365,6 +371,20 @@ export const sampleContent = {
365
371
  };
366
372
  ```
367
373
 
374
+ #### Collection lists
375
+
376
+ A collection's screen lists its items by a date: `list.date`, else a field named `date`, else its first
377
+ date field. By default the newest comes first, which suits posts. `list.order: 'upcoming'` suits events:
378
+ soonest first on an **Upcoming** tab, and anything dated before today on a **Past** tab, most recent
379
+ first. Today is the editor's own date, and an item stays upcoming all day.
380
+
381
+ Only the site knows its repeat rules, so for items that come round again, give `list.repeats(data, now)`.
382
+ `data` is the item's raw frontmatter and `now` is the current moment. Return `null` for a one-off.
383
+ Otherwise return a `label` shown beside the item (e.g. "Every Tuesday") and `next`: the date to list it
384
+ by, the next one, or the last one once it has ended (local time as stored, or a `Date` holding it in
385
+ its UTC fields). The list shows "Next" (or "Last") before that date. If the function throws, the item
386
+ is listed by its stored date.
387
+
368
388
  #### Sample content
369
389
 
370
390
  A starter or theme can ship sample pages and posts and let the site's owner clear them with one
package/live.d.mts ADDED
@@ -0,0 +1,24 @@
1
+ // Types for live.mjs (`@pirateandfox/pagestack/live`). Keep in step with its JSDoc.
2
+
3
+ /** A collection entry as the editor has stored it. */
4
+ export interface LiveEntry {
5
+ id: string;
6
+ collection: string;
7
+ /** The frontmatter, parsed by `schema` when one is given. */
8
+ data: any;
9
+ body: string;
10
+ filePath: string;
11
+ }
12
+
13
+ /**
14
+ * On the editor's server, for `liveRoutes` pages and the editor's previews: the collection's entries
15
+ * as stored now. Everywhere else, including the public build: `null`, so fall back to `getCollection`.
16
+ *
17
+ * @param collection The editor's collection id (normally the Astro collection name).
18
+ * @param schema The collection's zod schema, so dates and defaults come out as they do at build time.
19
+ * Without one, `data` is the raw frontmatter. Entries the schema rejects are left out.
20
+ */
21
+ export function liveEntries(
22
+ collection: string,
23
+ schema?: { parse(data: unknown): any },
24
+ ): Promise<LiveEntry[] | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.19",
3
+ "version": "0.1.0-beta.21",
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",
@@ -11,11 +11,15 @@
11
11
  ".": "./index.mjs",
12
12
  "./runtime": "./src/runtime.ts",
13
13
  "./core/*": "./src/core/*.ts",
14
- "./live": "./live.mjs"
14
+ "./live": {
15
+ "types": "./live.d.mts",
16
+ "default": "./live.mjs"
17
+ }
15
18
  },
16
19
  "files": [
17
20
  "index.mjs",
18
21
  "live.mjs",
22
+ "live.d.mts",
19
23
  "bin",
20
24
  "src",
21
25
  "CHANGELOG.md"
@@ -1,12 +1,13 @@
1
1
  // The list of a collection: add, delete, search.
2
2
  import { slugify, uniqueSlug } from '../core/pages';
3
+ import { isPast } from '../core/listing';
3
4
  import { missingFields } from '../core/required';
4
5
  import type { Field } from '../runtime';
5
6
  import { renderForm, showMissing } from './form';
6
7
  import { pickImage } from './picker';
7
8
  import { confirmDialog, dialog, promptDialog, toast } from './ui';
8
9
 
9
- const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[]; ask: Record<string, Field> };
10
+ const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[]; ask: Record<string, Field>; upcoming: boolean };
10
11
  const api = `/api/editor/collection/${boot.id}`;
11
12
 
12
13
  document.getElementById('ps-add-item')?.addEventListener('click', async () => {
@@ -62,13 +63,48 @@ document.getElementById('ps-pagelist')!.addEventListener('click', async (e) => {
62
63
  const data = await res.json();
63
64
  if (!res.ok) { toast(data.error || 'Delete failed', 'error'); return; }
64
65
  row.remove();
66
+ filter();
65
67
  toast(`Deleted ${name}.`, 'ok');
66
68
  });
67
69
 
70
+ const list = document.getElementById('ps-pagelist')!;
71
+ const rows = () => [...list.querySelectorAll<HTMLElement>(':scope > li')];
68
72
  const search = document.getElementById('ps-page-search') as HTMLInputElement;
69
- search.addEventListener('input', () => {
73
+ let tab: 'upcoming' | 'past' | null = null;
74
+
75
+ // Upcoming / Past, by this computer's date. The server sends rows soonest first; Past shows the most recent first.
76
+ if (boot.upcoming) {
77
+ const today = localNow().slice(0, 10);
78
+ const past = rows().filter((li) => isPast(li.dataset.date!, today));
79
+ for (const li of past) { li.dataset.past = ''; const w = li.querySelector('[data-when]'); if (w) w.textContent = 'Last '; }
80
+ for (const li of past.reverse()) list.append(li);
81
+ const tabs = [...document.querySelectorAll<HTMLButtonElement>('[data-tab]')];
82
+ const show = (t: 'upcoming' | 'past') => {
83
+ tab = t;
84
+ for (const b of tabs) b.setAttribute('aria-selected', String(b.dataset.tab === t));
85
+ history.replaceState(null, '', t === 'past' ? '#past' : location.pathname + location.search);
86
+ filter();
87
+ };
88
+ tabs.forEach((b) => b.addEventListener('click', () => show(b.dataset.tab as 'upcoming' | 'past')));
89
+ show(location.hash === '#past' ? 'past' : 'upcoming');
90
+ }
91
+
92
+ function filter() {
70
93
  const q = search.value.trim().toLowerCase();
71
- let shown = 0;
72
- document.querySelectorAll<HTMLElement>('#ps-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
73
- document.getElementById('ps-no-match')!.hidden = shown > 0;
74
- });
94
+ let shown = 0, inTab = 0;
95
+ const counts = { upcoming: 0, past: 0 };
96
+ for (const li of rows()) {
97
+ const t = li.dataset.past !== undefined ? 'past' : 'upcoming';
98
+ counts[t]++;
99
+ const mine = !tab || t === tab;
100
+ if (mine) inTab++;
101
+ const on = mine && li.dataset.search!.includes(q);
102
+ li.hidden = !on;
103
+ if (on) shown++;
104
+ }
105
+ document.querySelectorAll<HTMLElement>('[data-tab]').forEach((b) => { b.querySelector('[data-count]')!.textContent = String(counts[b.dataset.tab as 'upcoming' | 'past']); });
106
+ const empty = document.getElementById('ps-tab-empty');
107
+ if (empty) { empty.hidden = inTab > 0; empty.textContent = tab === 'past' ? 'Nothing in the past.' : 'Nothing coming up.'; }
108
+ document.getElementById('ps-no-match')!.hidden = shown > 0 || inTab === 0;
109
+ }
110
+ search.addEventListener('input', filter);
@@ -230,6 +230,11 @@ function setMode(m: 'page' | 'markdown') {
230
230
  document.querySelectorAll<HTMLElement>('.ps-seg__btn').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.mode === m)));
231
231
  try { localStorage.setItem('ps-item-mode', m); } catch { /* private mode */ }
232
232
  if (m === 'page') { if (!frame.src) frame.src = previewUrl; else if (frameReady) renderPage(); }
233
+ titleBox();
234
+ }
235
+ /** In the page view the title is edited where the layout shows it, if it marks it (`itemField`); otherwise in the box above. */
236
+ function titleBox() {
237
+ title.hidden = mode === 'page' && (!frameReady || !!fdoc().querySelector('[data-ps-field="title"]'));
233
238
  }
234
239
  function schedulePage(ms = 300) { if (frame && mode === 'page') { clearTimeout(pageTimer); pageTimer = setTimeout(renderPage, ms); } }
235
240
 
@@ -247,6 +252,7 @@ async function renderPage(): Promise<boolean> {
247
252
  fdoc().body.innerHTML = fresh.body.innerHTML;
248
253
  fdoc().body.className = fresh.body.className;
249
254
  win.scrollTo(0, y);
255
+ titleBox();
250
256
  return true;
251
257
  }
252
258
 
@@ -406,6 +412,7 @@ if (frame) {
406
412
  d.defaultView?.addEventListener('scroll', () => { if (plus) plus.hidden = true; });
407
413
  d.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (inline.isActive) inline.stop(true); if (dirty) save(); } });
408
414
  frameReady = true;
415
+ titleBox();
409
416
  if (dirty) renderPage();
410
417
  });
411
418
  document.querySelectorAll<HTMLElement>('.ps-seg__btn').forEach((b) => b.addEventListener('click', () => setMode(b.dataset.mode as 'page' | 'markdown')));
@@ -300,6 +300,11 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
300
300
  /* Markdown items */
301
301
  .ps-pill--synced { background: #e0e7ff; color: #3730a3; }
302
302
  .ps-pill--sample { background: #f1f5f9; color: #475569; }
303
+ .ps-pill--repeats { background: #dcfce7; color: #166534; }
304
+ .ps-listtabs { display: flex; gap: 4px; margin: 4px 0 8px; border-bottom: 1px solid var(--ps-border); }
305
+ .ps-listtabs button { all: unset; cursor: pointer; padding: 8px 12px; font-weight: 500; box-shadow: inset 0 0 0 0 var(--ps-accent); }
306
+ .ps-listtabs button[aria-selected="true"] { box-shadow: inset 0 -2px 0 0 var(--ps-accent); font-weight: 600; }
307
+ .ps-listtabs button:focus-visible { outline: 2px solid var(--ps-accent); outline-offset: -2px; }
303
308
  .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; }
304
309
  .ps-samples--hidden { border-left-color: var(--ps-border); }
305
310
  .ps-samples p { margin: 4px 0 0; max-width: 62ch; }
@@ -0,0 +1,68 @@
1
+ // How a collection's list screen orders and labels its items. Pure: the server builds the rows,
2
+ // the browser splits Upcoming from Past by its own clock.
3
+ import type { CollectionDoc } from '../runtime';
4
+
5
+ export interface ListRow {
6
+ slug: string;
7
+ title: string;
8
+ /** Local time with no zone, `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM[:SS]`; '' when the item has none. */
9
+ date: string;
10
+ draft: boolean;
11
+ /** Set for an item that comes round again: says how often. `date` is then its next date. */
12
+ repeats?: string;
13
+ }
14
+
15
+ /** The field a collection is listed by: `list.date`, else `date` if declared, else its first date field, else `date`. */
16
+ export function listField(c: Pick<CollectionDoc, 'fields' | 'list'>): string {
17
+ if (c.list?.date) return c.list.date;
18
+ if (c.fields.date) return 'date';
19
+ return Object.keys(c.fields).find((k) => c.fields[k].type === 'date') ?? 'date';
20
+ }
21
+
22
+ /** A frontmatter date as stored text. A YAML timestamp (a Date) is read as local time, which is how it was written. */
23
+ export function dateText(v: unknown): string {
24
+ if (v instanceof Date) return isNaN(+v) ? '' : v.toISOString().slice(0, 19).replace(/T00:00:00$/, '');
25
+ if (typeof v !== 'string') return '';
26
+ return /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2})?)?/.test(v) ? v.slice(0, 19).replace(' ', 'T') : '';
27
+ }
28
+
29
+ export function listRow(c: Pick<CollectionDoc, 'fields' | 'list'>, slug: string, data: Record<string, any>, now: Date): ListRow {
30
+ const field = listField(c);
31
+ const row: ListRow = { slug, title: String(data.title ?? slug), date: dateText(data[field]), draft: data.draft === true };
32
+ let r: ReturnType<NonNullable<NonNullable<CollectionDoc['list']>['repeats']>> = null;
33
+ // A broken rule in the site's code must not take the whole list down.
34
+ try { r = c.list?.repeats?.(data, now) ?? null; } catch { r = null; }
35
+ if (r?.label) {
36
+ row.repeats = r.label;
37
+ const next = dateText(r.next);
38
+ if (next) row.date = next;
39
+ }
40
+ return row;
41
+ }
42
+
43
+ /** Newest first; with `upcoming`, soonest first. Items without a date go last, by title. */
44
+ export function sortRows(rows: ListRow[], order: 'newest' | 'upcoming' = 'newest'): ListRow[] {
45
+ const dir = order === 'upcoming' ? 1 : -1;
46
+ const byTitle = (a: ListRow, b: ListRow) => a.title.localeCompare(b.title, undefined, { numeric: true }) || a.slug.localeCompare(b.slug);
47
+ return [...rows].sort((a, b) => {
48
+ if (!a.date || !b.date) return (a.date ? -1 : b.date ? 1 : 0) || byTitle(a, b);
49
+ return dir * a.date.localeCompare(b.date) || byTitle(a, b);
50
+ });
51
+ }
52
+
53
+ /** Over: dated before `today` (`YYYY-MM-DD`, the editor's). Something on today stays upcoming all day. Undated items are upcoming. */
54
+ export const isPast = (date: string, today: string) => !!date && date.slice(0, 10) < today;
55
+
56
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
57
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
58
+
59
+ /** "Sat 29 Nov 2026, 7:00 pm", read as written (no time zone). The year is left out when it is `year`; a midnight time too (all-day items are stored so). */
60
+ export function formatDate(date: string, year?: number): string {
61
+ const m = date.match(/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?/);
62
+ if (!m) return date;
63
+ const [y, mo, d] = [+m[1], +m[2], +m[3]];
64
+ const day = `${DAYS[new Date(Date.UTC(y, mo - 1, d)).getUTCDay()]} ${d} ${MONTHS[mo - 1]}${y === year ? '' : ` ${y}`}`;
65
+ if (m[4] === undefined || (m[4] === '00' && m[5] === '00')) return day;
66
+ const h = +m[4];
67
+ return `${day}, ${h % 12 || 12}:${m[5]} ${h < 12 ? 'am' : 'pm'}`;
68
+ }
@@ -2,6 +2,7 @@
2
2
  // /edit/collection/<id> — the items of a Markdown collection, e.g. blog posts.
3
3
  import { collections, listItems, opts, reservedSlugs } from '../server/context';
4
4
  import { askedOnAdd } from '../core/required';
5
+ import { formatDate } from '../core/listing';
5
6
  import Nav from './Nav.astro';
6
7
  import '../client/shell.css';
7
8
  export const prerender = false;
@@ -10,7 +11,9 @@ if (!Object.hasOwn(collections, id)) return new Response('No such collection', {
10
11
  const c = collections[id];
11
12
  const items = await listItems(c);
12
13
  const singular = c.singular ?? 'item';
13
- const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reservedSlugs(), ask: askedOnAdd(c.fields) };
14
+ const upcoming = c.list?.order === 'upcoming';
15
+ const year = new Date().getFullYear();
16
+ const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reservedSlugs(), ask: askedOnAdd(c.fields), upcoming };
14
17
  ---
15
18
  <!doctype html>
16
19
  <html lang="en">
@@ -28,11 +31,20 @@ const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reserved
28
31
  <div><h1>{c.label} <span class="ps-muted">{items.length}</span></h1></div>
29
32
  {c.create !== false && <button type="button" id="ps-add-item" class="ps-btn ps-btn--primary">Add {singular}</button>}
30
33
  </header>
34
+ {upcoming && (
35
+ <div class="ps-listtabs" role="tablist" aria-label={c.label}>
36
+ <button type="button" role="tab" id="ps-tab-upcoming" aria-selected="true" data-tab="upcoming">Upcoming <span class="ps-muted" data-count></span></button>
37
+ <button type="button" role="tab" id="ps-tab-past" aria-selected="false" data-tab="past">Past <span class="ps-muted" data-count></span></button>
38
+ </div>
39
+ )}
31
40
  <div class="ps-index__tools"><input type="search" id="ps-page-search" placeholder={`Search ${c.label.toLowerCase()}`} aria-label="Search" /></div>
32
41
  <ul class="ps-pagelist" id="ps-pagelist">
33
42
  {items.map((i) => (
34
- <li data-slug={i.slug} data-search={`${i.title} ${i.slug}`.toLowerCase()}>
35
- <a class="ps-pagelist__edit" href={`/edit/collection/${id}/${i.slug}`}><strong>{i.title}{i.draft && <span class="ps-pill">Draft</span>}</strong><span class="ps-muted">{i.date.slice(0, 10)}</span></a>
43
+ <li data-slug={i.slug} data-date={i.date} data-search={`${i.title} ${i.slug}`.toLowerCase()}>
44
+ <a class="ps-pagelist__edit" href={`/edit/collection/${id}/${i.slug}`}>
45
+ <strong>{i.title}{i.draft && <span class="ps-pill">Draft</span>}{i.repeats && <span class="ps-pill ps-pill--repeats" title="Repeats">↻ {i.repeats}</span>}</strong>
46
+ <span class="ps-muted">{i.repeats && i.date && <span data-when>Next </span>}{i.date ? formatDate(i.date, year) : 'No date'}</span>
47
+ </a>
36
48
  <div class="ps-pagelist__actions">
37
49
  {!i.draft && c.url && <a class="ps-btn ps-btn--small ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(c.url(i.slug))}`}>View</a>}
38
50
  <button type="button" class="ps-btn ps-btn--small ps-btn--ghost ps-btn--danger" data-delete={i.slug}>Delete</button>
@@ -41,6 +53,7 @@ const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reserved
41
53
  ))}
42
54
  </ul>
43
55
  <p id="ps-no-match" class="ps-muted" hidden>Nothing matches.</p>
56
+ {upcoming && <p id="ps-tab-empty" class="ps-muted" hidden></p>}
44
57
  </main>
45
58
  <div id="ps-modal-root"></div>
46
59
  <script is:inline set:html={`window.__PS_COLLECTION__ = ${JSON.stringify(boot).replace(/</g, '\\u003c')};`} />
@@ -51,9 +51,10 @@ const boot = {
51
51
  </header>
52
52
  <div class="ps-item__grid">
53
53
  <main>
54
+ {/* In the page view only when the site's layout doesn't mark its title for editing in place. */}
55
+ <input id="ps-item-title" class="ps-item__title" type="text" placeholder="Add title" aria-label="Title" />
54
56
  {boot.preview && <div class="ps-item__page" id="ps-item-page" hidden><iframe id="ps-item-frame" title="Page preview" sandbox="allow-same-origin"></iframe></div>}
55
57
  <div id="ps-item-md">
56
- <input id="ps-item-title" class="ps-item__title" type="text" placeholder="Add title" aria-label="Title" />
57
58
  <div class="ps-mdbar" id="ps-mdbar" role="toolbar" aria-label="Formatting"></div>
58
59
  <div class="ps-mdsplit">
59
60
  <textarea id="ps-item-body" aria-label="Content in Markdown" spellcheck="true"></textarea>
package/src/runtime.ts CHANGED
@@ -133,6 +133,25 @@ export interface CollectionDoc {
133
133
  url?: (slug: string) => string;
134
134
  /** false hides Add, for a fixed set of items. Otherwise new items start from each field's `default`. */
135
135
  create?: boolean;
136
+ /** How the list screen orders and labels items. Without it: newest first, by `date` or else the first date field. */
137
+ list?: CollectionList;
138
+ }
139
+
140
+ /** The list screen of a collection (`CollectionDoc.list`). */
141
+ export interface CollectionList {
142
+ /** The date field items are listed by. Default: `date`, else the first `date` field. */
143
+ date?: string;
144
+ /**
145
+ * `newest` (default): newest first, for posts. `upcoming`: for events. Soonest first on an
146
+ * Upcoming tab, and what was dated before today on a Past tab, most recent first.
147
+ */
148
+ order?: 'newest' | 'upcoming';
149
+ /**
150
+ * For items that come round again. Return null for a one-off. Otherwise return `label`, shown
151
+ * beside the item (e.g. "Every week"), and `next`: the date it is listed by, the next one from
152
+ * `now` or the last one when there are no more (a local date or `Date`, as stored).
153
+ */
154
+ repeats?: (data: Record<string, any>, now: Date) => { label: string; next?: string | Date | null } | null | undefined;
136
155
  }
137
156
 
138
157
  /** A starting point offered by "Add page". */
@@ -10,6 +10,7 @@ import { codeValues, sanitizeDoc, sanitizeNode } from '../core/sanitize';
10
10
  import type { CleanOptions } from '../core/sanitize';
11
11
  import { parseUsers, serializeUsers } from '../core/users';
12
12
  import { parseMarkdown } from '../core/frontmatter';
13
+ import { listRow, sortRows, type ListRow } from '../core/listing';
13
14
  import type { EditorUser, Role, UsersFile } from '../core/users';
14
15
  import { publicPath, RESERVED_SLUGS } from '../core/pages';
15
16
  import type { SavedPattern } from '../core/insert';
@@ -93,15 +94,14 @@ export async function whereUsed(src: string): Promise<{ title: string; href: str
93
94
  }
94
95
 
95
96
  // ---- collections (Markdown folders) ----
96
- export interface ItemSummary { slug: string; title: string; date: string; draft: boolean }
97
+ export type ItemSummary = ListRow;
98
+ /** A collection's items, in the order its list shows them (`list.order`). */
97
99
  export async function listItems(c: CollectionDoc): Promise<ItemSummary[]> {
98
- const out: ItemSummary[] = [];
99
- for (const { name, content } of (await storage().readDirs([c.dir]))[c.dir]) {
100
- if (!name.endsWith('.md')) continue;
101
- const { data } = parseMarkdown(content);
102
- out.push({ slug: name.slice(0, -3), title: String(data.title ?? name), date: String(data.date ?? ''), draft: data.draft === true });
103
- }
104
- return out.sort((a, b) => b.date.localeCompare(a.date));
100
+ const now = new Date();
101
+ const rows = (await storage().readDirs([c.dir]))[c.dir]
102
+ .filter((f) => f.name.endsWith('.md'))
103
+ .map((f) => listRow(c, f.name.slice(0, -3), parseMarkdown(f.content).data, now));
104
+ return sortRows(rows, c.list?.order);
105
105
  }
106
106
 
107
107
  export const reservedSlugs = () => [...RESERVED_SLUGS, ...opts.reservedSlugs];