@pirateandfox/pagestack 0.1.0-beta.20 → 0.1.0-beta.22
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 +11 -1
- package/README.md +46 -0
- package/live.d.mts +10 -0
- package/live.mjs +23 -0
- package/package.json +1 -1
- package/src/client/collection.ts +42 -6
- package/src/client/item.ts +7 -0
- package/src/client/shell.css +5 -0
- package/src/core/listing.ts +68 -0
- package/src/routes/edit-collection.astro +16 -3
- package/src/routes/edit-item.astro +2 -1
- package/src/runtime.ts +19 -0
- package/src/server/context.ts +8 -8
- package/src/server/live.ts +49 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.0-beta.22 — 2026-11-29
|
|
4
|
+
|
|
5
|
+
- **Globals in the editor show what is saved, through `liveGlobal`.** A component that imported a global (`import menus from '../data/menus.json'`) got the copy built into the editor, so on a deployed editor the header, footer and banners in previews, Browse and `liveRoutes` pages showed the global as of the editor's last deploy. A change saved since, in the editor's global screen, by a commit or by an automation, showed on the public site but not in the editor. New in `@pirateandfox/pagestack/live`: `liveGlobal(id, importedFile)` returns the file as stored now inside an editor request, and the imported file everywhere else, so the public build is unchanged. A missing or invalid stored file also gives the imported file. On GitHub storage all globals are read in one request and kept until the branch moves. Hosts opt in by switching their imports; see README, "Globals in the editor". Changes to a site's code still need the editor redeployed.
|
|
6
|
+
- **`examples/bakery`** reads `site` through `liveGlobal`.
|
|
7
|
+
|
|
8
|
+
## 0.1.0-beta.21 — 2026-11-28
|
|
9
|
+
|
|
10
|
+
- **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.
|
|
11
|
+
- **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.
|
|
12
|
+
|
|
3
13
|
## 0.1.0-beta.20 — 2026-11-27
|
|
4
14
|
|
|
5
15
|
- **`@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.
|
|
@@ -90,7 +100,7 @@
|
|
|
90
100
|
|
|
91
101
|
## 0.1.0-beta.10 — 2026-11-12
|
|
92
102
|
|
|
93
|
-
- **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 (
|
|
103
|
+
- **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)`.
|
|
94
104
|
- **Browse shows when a page is loading**: a moving strip under the bar and "Loading page…", instead of a blank frame.
|
|
95
105
|
|
|
96
106
|
## 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
|
|
@@ -479,6 +499,28 @@ able to render where the editor runs (on Workers: no `node:fs`, and nothing from
|
|
|
479
499
|
until the branch moves, so a list costs one request to GitHub once the first one has warmed up.
|
|
480
500
|
These pages show unpublished work, so they need a signed-in editor.
|
|
481
501
|
|
|
502
|
+
### Globals in the editor (`liveGlobal`)
|
|
503
|
+
|
|
504
|
+
A component that imports a global directly (`import menus from '../data/menus.json'`) gets the copy
|
|
505
|
+
Vite built into the editor. On a deployed editor, its header, footer and banners, in previews, Browse
|
|
506
|
+
and `liveRoutes` pages, then show the global as it was when the editor was deployed. A change saved
|
|
507
|
+
since, in the editor's own global screen, by a commit or by an automation, is on the public site but
|
|
508
|
+
not in the editor until it is deployed again. Read globals through `liveGlobal` instead:
|
|
509
|
+
|
|
510
|
+
```astro
|
|
511
|
+
---
|
|
512
|
+
import menusFile from '../data/menus.json';
|
|
513
|
+
import { liveGlobal } from '@pirateandfox/pagestack/live';
|
|
514
|
+
const menus = await liveGlobal('menus', menusFile);
|
|
515
|
+
---
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
The id is the global's key in `globals`. Inside an editor request `liveGlobal` returns the file as
|
|
519
|
+
stored now; everywhere else (the public build, prerendering, `astro dev` without the editor) it
|
|
520
|
+
returns the imported file, so the public site is unchanged. A stored file that is missing or isn't
|
|
521
|
+
valid JSON also gives the imported file. On GitHub storage every global is read in one request and
|
|
522
|
+
kept until the branch moves.
|
|
523
|
+
|
|
482
524
|
## Security
|
|
483
525
|
|
|
484
526
|
Everything an editor sends is treated as untrusted. On save, every field is cleaned by its type,
|
|
@@ -599,6 +641,10 @@ built site pages are served as plain files, without a sign-in; put the host behi
|
|
|
599
641
|
if staged work must stay private.) Every
|
|
600
642
|
editor response is `noindex` and `no-store`.
|
|
601
643
|
|
|
644
|
+
In the editor, globals imported directly show the copy from the editor's last deploy; read them
|
|
645
|
+
through `liveGlobal` (see "Globals in the editor"). Changes to the site's code and sections still need
|
|
646
|
+
a redeploy of the editor.
|
|
647
|
+
|
|
602
648
|
## Options
|
|
603
649
|
|
|
604
650
|
| option | default | |
|
package/live.d.mts
CHANGED
|
@@ -22,3 +22,13 @@ export function liveEntries(
|
|
|
22
22
|
collection: string,
|
|
23
23
|
schema?: { parse(data: unknown): any },
|
|
24
24
|
): Promise<LiveEntry[] | null>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* On the editor's server (its previews, Browse, `liveRoutes` pages): the global's JSON as stored now.
|
|
28
|
+
* Everywhere else, including the public build, and when the stored file is missing or invalid:
|
|
29
|
+
* `fallback`, the statically imported file.
|
|
30
|
+
*
|
|
31
|
+
* @param id The editor's global id (a key of `globals` in the sections module).
|
|
32
|
+
* @param fallback The statically imported file.
|
|
33
|
+
*/
|
|
34
|
+
export function liveGlobal<T>(id: string, fallback: T): Promise<T>;
|
package/live.mjs
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
// import { liveEntries } from '@pirateandfox/pagestack/live';
|
|
9
9
|
// const all = (await liveEntries('articles', articleSchema)) ?? (await getCollection('articles'));
|
|
10
10
|
//
|
|
11
|
+
// Globals (menus, footer, site details) work the same way through `liveGlobal`: the file as stored
|
|
12
|
+
// now on the editor's server, the statically imported copy everywhere else.
|
|
13
|
+
//
|
|
11
14
|
// Plain JavaScript with no imports, so a public build that never loads the editor can import it.
|
|
12
15
|
|
|
13
16
|
/**
|
|
@@ -28,3 +31,23 @@ export async function liveEntries(collection, schema) {
|
|
|
28
31
|
}
|
|
29
32
|
return out;
|
|
30
33
|
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A global's JSON as stored now, on the editor's server (its previews, Browse, `liveRoutes` pages);
|
|
37
|
+
* `fallback` everywhere else: the public build, prerendering, astro dev without the editor. Also
|
|
38
|
+
* `fallback` when the stored file is missing or isn't valid JSON.
|
|
39
|
+
*
|
|
40
|
+
* import menusFile from '../data/menus.json';
|
|
41
|
+
* import { liveGlobal } from '@pirateandfox/pagestack/live';
|
|
42
|
+
* const menus = await liveGlobal('menus', menusFile);
|
|
43
|
+
*
|
|
44
|
+
* @template T
|
|
45
|
+
* @param {string} id The editor's global id (a key of `globals` in the sections module).
|
|
46
|
+
* @param {T} fallback The statically imported file.
|
|
47
|
+
* @returns {Promise<T>}
|
|
48
|
+
*/
|
|
49
|
+
export async function liveGlobal(id, fallback) {
|
|
50
|
+
const live = /** @type {any} */ (globalThis).__PS_LIVE_GLOBAL__;
|
|
51
|
+
if (typeof live !== 'function') return fallback;
|
|
52
|
+
try { return (await live(id)) ?? fallback; } catch { return fallback; }
|
|
53
|
+
}
|
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.22",
|
|
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/collection.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
73
|
-
|
|
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);
|
package/src/client/item.ts
CHANGED
|
@@ -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')));
|
package/src/client/shell.css
CHANGED
|
@@ -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
|
|
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}`}
|
|
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". */
|
package/src/server/context.ts
CHANGED
|
@@ -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
|
|
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
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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];
|
package/src/server/live.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
// Collection entries straight from storage, for host
|
|
2
|
-
// (see live.mjs). The collection name is the editor's collection id.
|
|
1
|
+
// Collection entries and globals straight from storage, for host pages rendered on the editor's
|
|
2
|
+
// server (see live.mjs). The collection name is the editor's collection id, a global's its id.
|
|
3
3
|
//
|
|
4
|
-
// With a store that knows its head commit (GitHub),
|
|
5
|
-
// the head is asked at most once a second, so a page that lists four collections
|
|
4
|
+
// With a store that knows its head commit (GitHub), what was read is kept until the branch moves,
|
|
5
|
+
// and the head is asked at most once a second, so a page that lists four collections and shows two
|
|
6
|
+
// globals costs two requests.
|
|
6
7
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
7
|
-
import { collections, storage } from './context';
|
|
8
|
+
import { collections, globals, storage } from './context';
|
|
8
9
|
import { parseMarkdown } from '../core/frontmatter';
|
|
9
10
|
|
|
10
11
|
export interface LiveEntry { id: string; collection: string; data: Record<string, any>; body: string; filePath: string }
|
|
@@ -63,17 +64,51 @@ export async function liveCollection(name: string, now = Date.now()): Promise<Li
|
|
|
63
64
|
return entries;
|
|
64
65
|
}
|
|
65
66
|
|
|
66
|
-
|
|
67
|
+
let cachedGlobals: { sha: string; files: Promise<Record<string, string | null>> } | null = null;
|
|
67
68
|
|
|
68
69
|
/**
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
70
|
+
* A global's JSON as stored now, or null when the editor doesn't know the id, the file is missing or
|
|
71
|
+
* isn't valid JSON: the host then shows the copy it was built with rather than a broken header.
|
|
72
|
+
* At a head commit every global is read in one request, since a header and a footer render together.
|
|
73
|
+
* Parsed on each call, so a component that changes what it gets can't change it for the next one.
|
|
74
|
+
*/
|
|
75
|
+
export async function liveGlobalFile(id: string, now = Date.now()): Promise<unknown> {
|
|
76
|
+
const g = Object.hasOwn(globals, id) ? globals[id] : null;
|
|
77
|
+
if (!g) return null;
|
|
78
|
+
const sha = await currentHead(now);
|
|
79
|
+
let files: Promise<Record<string, string | null>>;
|
|
80
|
+
if (!sha) files = storage().readFiles([g.file]); // local storage: the working tree, read every time
|
|
81
|
+
else {
|
|
82
|
+
if (cachedGlobals?.sha !== sha) {
|
|
83
|
+
const mine = { sha, files: storage().readFiles([...new Set(Object.values(globals).map((x) => x.file))], sha) };
|
|
84
|
+
// A failed read is not kept: the next request tries again.
|
|
85
|
+
mine.files.catch(() => { if (cachedGlobals === mine) cachedGlobals = null; });
|
|
86
|
+
cachedGlobals = mine;
|
|
87
|
+
}
|
|
88
|
+
files = cachedGlobals.files;
|
|
89
|
+
}
|
|
90
|
+
const raw = (await files)[g.file];
|
|
91
|
+
if (typeof raw !== 'string') return null;
|
|
92
|
+
try { return JSON.parse(raw); } catch { return null; }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
interface Scope { entries(name: string): Promise<LiveEntry[] | null>; global(id: string): Promise<unknown> }
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Runs `run` with live.mjs's `liveEntries` and `liveGlobal` giving what is stored, for that request
|
|
99
|
+
* alone: its whole render, streamed parts included. Anything else in the process must keep getting
|
|
100
|
+
* null. In dev the same process runs the site's getStaticPaths, and a stored entry has no rendered
|
|
101
|
+
* HTML, so a post page built from one came out blank. Kept on globalThis because dev can load this
|
|
102
|
+
* module twice; the readers are set each time, so a reloaded module's shape always matches.
|
|
73
103
|
*/
|
|
74
104
|
export function withLive<T>(run: () => T): T {
|
|
75
|
-
const g = globalThis as {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
105
|
+
const g = globalThis as {
|
|
106
|
+
__PS_LIVE_SCOPE__?: AsyncLocalStorage<Scope>;
|
|
107
|
+
__PS_LIVE__?: (name: string) => Promise<LiveEntry[] | null> | null;
|
|
108
|
+
__PS_LIVE_GLOBAL__?: (id: string) => Promise<unknown> | null;
|
|
109
|
+
};
|
|
110
|
+
const scope = (g.__PS_LIVE_SCOPE__ ??= new AsyncLocalStorage<Scope>());
|
|
111
|
+
g.__PS_LIVE__ = (name) => scope.getStore()?.entries(name) ?? null;
|
|
112
|
+
g.__PS_LIVE_GLOBAL__ = (id) => scope.getStore()?.global(id) ?? null;
|
|
113
|
+
return scope.run({ entries: (name) => liveCollection(name), global: (id) => liveGlobalFile(id) }, run);
|
|
79
114
|
}
|