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

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 ADDED
@@ -0,0 +1,168 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-beta.19 — 2026-11-26
4
+
5
+ - **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"`).
6
+ - **A new list row stores what it shows.** Its defaults and a dropdown's first choice were displayed but not saved, so a row left on "Cancelled" was saved without it. Rows already saved that way are unchanged: mark the field `required` (that writes it on the next save) or give it a default in the schema.
7
+ - `CHANGELOG.md` is in the npm package.
8
+
9
+ ## 0.1.0-beta.18 — 2026-11-24
10
+
11
+ - **Required fields.** `required: true` on any field: the form stars it, and Save says what is missing, opens it and is refused, by the API too. A cleared field the site's Astro schema insists on used to stop the next build. In collections drafts are checked as well, because Astro checks every file, and **Add** asks for what it can't fill in itself (new items could break the build before anyone had opened them). Pages are checked unless they are drafts. Opt-in; hosts should mark the fields their schemas require. `POST /api/editor/collection/<id>` takes an optional `data`.
12
+ - **Saving a page no longer takes the cursor out of the field.** The sidebar was redrawn after every save and an edit on the page was ended, so what you typed next went nowhere, and Backspace deleted the selected block.
13
+ - **Text typed while a save is running is kept as unsaved.** It was shown as saved, and its recovery copy dropped, though only the earlier text had been sent: on pages, collection items and globals. A second save asked for meanwhile waits for the first; it used to be refused as a conflict.
14
+ - ⌘S saves a value still being typed (a number, a date, tags). It used to save what was there before.
15
+ - Clearing a number in a collection item now clears it; the old value used to stay in the file.
16
+ - The image picker opens above a dialog, and Escape closes the picker first.
17
+ - **`examples/bakery`**: a news post's date is required.
18
+ - **The editor stays within the 50 requests a page that Cloudflare's free plan allows, however big the site.** Above about 45 files `/edit` and other screens returned a 500, because each file cost a GitHub request. Now:
19
+ - A folder is read in one request, pages in subfolders included: the Pages screen, collections, the page editor, sample content, and the check for where an image is used.
20
+ - A save of many files makes a fixed handful of requests: hiding or deleting sample content, and updating a synced pattern on every page. Checking that the files haven't changed meanwhile costs one request per 50.
21
+ - The media library lists all folders in a few requests; each folder used to cost two.
22
+ - When GitHub can't return a folder in one answer, its files are read 50 per request, never one by one. If GitHub refuses GraphQL (token, rate limit), the error says so. A stand-in GitHub API (`EDITOR_GITHUB_API`) must now answer `/graphql`.
23
+ - A file over 1 MB can be read at a past revision and in a conditional save (its text came back empty).
24
+ - **Post pages no longer go blank in dev.** Once a list page, the editor or a preview had been opened, `liveEntries` gave stored entries to everything in the process, the site's `getStaticPaths` included. Those entries have no rendered HTML, so post pages that use `liveEntries` showed no body. Stored entries now reach only the requests they are meant for: live pages, the editor and its previews. Other on-demand routes of the site get `null`, as documented, and so can't show unpublished work.
25
+ - Storage adapters: `readDir` and `readDirs` are required, `readDirs` takes a `depth` for subfolders, and `readFiles` and `listTree` are new.
26
+
27
+ ## 0.1.0-beta.17 — 2026-11-24
28
+
29
+ - **Checkboxes for several values: the `multiselect` field.** It shows its `options` as checkboxes and stores an array of the ticked values, in option order (`repeatsOn: [mon, wed]`). Values no longer offered stay ticked, marked "(current)", until someone unticks them.
30
+ - **Conditional fields: `showIf`.** Any field can be shown only when another has a certain value: `showIf: { field: 'repeats', not: '' }`. It takes `is` and `not` (one value or several), or neither for "has a value", and works in every form and within a list's rows. It only changes the form: hidden values are kept.
31
+ - In a list row, choosing a blank option of a `select` that has a default now sticks; the default used to come back.
32
+ - Both are opt-in, and existing schemas need no changes. New in the runtime: the `ShowIf` type.
33
+ - **`examples/bakery`**: a day marked closed hides its hours field.
34
+
35
+ ## 0.1.0-beta.16 — 2026-11-15
36
+
37
+ - **Hide or delete sample content.** A starter or theme can mark its sample pages (`"sample": true` in the page JSON) and posts (`sample: true` in front matter). While any are on the site, admins see a notice on the Pages screen with **Hide sample content** (they become drafts, kept in the editor to copy from; a sample home page moves to a `sample-home` draft and the host's replacement takes its place) and **Delete sample content** (they're removed; the confirmation lists them all). Each is one commit. A host can set the replacement home page and reset globals with them through a new optional `sampleContent` export (type `SampleContent` in the runtime). Images are never touched. Saving a sample from the editor drops its mark, so anything someone has edited is theirs and is left alone. Marked pages show a **Sample** pill in the page list. Sites without marked content see no change.
38
+ - **Add block goes after the selected block, as in WordPress.** With a section that holds blocks selected (a logo strip, a feature grid), the top bar's **Add block** button and the `/` key put the new block *inside* it, at the end. They now put it right after the selected block, beside it, and the panel says where ("Adding to the page"). To add inside a section, use the **Add block** button on that section's toolbar, as before. With nothing selected, new blocks still go at the end of the page.
39
+
40
+ ## 0.1.0-beta.15 — 2026-11-14
41
+
42
+ - **Escape really cancels an in-page edit.** Text typed and then cancelled with Escape disappeared from the page but stayed in the draft, so Save lit up and the cancelled words were saved. Escape now puts the draft back as it was before the edit.
43
+ - README: a section on bold and italic in headings (`marks`), with how to render it and where to strip the tags.
44
+
45
+ ## 0.1.0-beta.14 — 2026-11-14
46
+
47
+ - **Bold and italic in headings.** A `text` field with `marks: true` allows bold and italic, as a WordPress heading does. Clicking it on the page shows a small **B** / **I** bar (⌘B / ⌘I work too), the sidebar shows a one-line field with the same two buttons, and pasting keeps bold and italic and drops everything else. The value is HTML holding only `<strong>` and `<em>`, cleaned to exactly that on save; render it with `set:html`. Fields without `marks` are unchanged, so existing sites see no difference until they opt in.
48
+ - **`examples/bakery`**: section titles use `marks`. The hero's separate *Word in italics* field is gone; its title is now `Bread worth getting up <em>early</em> for`.
49
+
50
+ ## 0.1.0-beta.13 — 2026-11-13
51
+
52
+ - **Only admins can publish.** With `github.live`, **Publish changes** puts staging live for admins only. Editors still see the count and the list of what's waiting, with a note that an admin publishes it; the API refuses them (403).
53
+ - **Withdraw an invite.** The Users screen lists invite links nobody has used yet (who, role, time left, who sent it), each with **Withdraw**: the link stops working at once. Invites made there are recorded in the users file (`invites`); used, withdrawn and expired ones drop off. Links from the `pagestack-invite` CLI aren't listed.
54
+ - **Signing out is a POST.** The Sign out links are now small forms, and the editor menu posts. A GET to `/api/editor/auth/logout` only shows a Sign out button, so a link on another site can't sign anyone out.
55
+ - **No lost changes to the users file.** Enrolling, inviting, changing a role and removing someone now read, change and save the file as one step: if another change landed in between, the file is read again and the change re-applied. Storage adapters gained a conditional commit (`expect`, throwing `StaleWrite`).
56
+ - Astro's dev toolbar no longer shows inside the editor's preview.
57
+ - Hosts: the message for a used invite link is now "This invite link has already been used or was withdrawn."
58
+
59
+ ## 0.1.0-beta.12 — 2026-11-13
60
+
61
+ - **Site pages on a deployed editor need sign-in, and open in Browse.** The editor's build carries a copy of every site page, and Cloudflare served those files before the editor's code ran: anyone could read them (saved work included, for pages rebuilt from a staging branch), and opening one showed no editor bar. On Cloudflare, editor builds now route everything except hashed build assets through the editor's Worker (`assets.run_worker_first` is set in the generated `dist/server/wrangler.json`, unless the host set it) and PageStack wraps the adapter's entry: a page opened directly goes to Browse, a page loaded any other way needs a session. Styles, scripts, images and fonts are served as before. Hosts change nothing.
62
+ - **A deployed editor missing `GITHUB_TOKEN` or `EDITOR_SECRET` says so** on every editor page, instead of a 500.
63
+ - The editor's copies of site pages are sent with `X-Robots-Tag: noindex`.
64
+ - **Saving in dev no longer reloads the editor.** A save writes files the site's routes import, and Vite answered with a full reload of every open page, which threw away the selection and undo history. Reloads caused by the editor's own writes are now dropped.
65
+ - Editor pages have a favicon (the PageStack mark).
66
+ - **`examples/bakery`**: Crumb & Co., an invented bakery site to try the editor on (`npm run dev:editor`).
67
+ - `@astrojs/cloudflare` is now an optional peer dependency.
68
+ - Repo: MIT `LICENSE`, `SECURITY.md`, `CONTRIBUTING.md`, issue templates; tests run only from `test/`.
69
+
70
+ ## 0.1.0-beta.11 — 2026-11-13
71
+
72
+ **Security fixes. Upgrade before inviting people.**
73
+
74
+ - **Rich text could carry a script past the sanitiser.** Its tag reader disagreed with browsers about where an unquoted attribute value ends, so a crafted `<img … onerror=…>` saved by any editor came through unchanged and ran in an admin's editor (and on the public site after a publish). Tags are now read the way the HTML spec's tokenizer reads them, and anything not plainly written is rebuilt from what was read. A new test runs the sanitiser's output through a spec HTML parser (`parse5`, dev only) with known bypasses and 20,000 generated tags. Inline SVG fields had the same problem and get the same fix.
75
+ - **No inline event handlers anywhere on the editor's origin**: `script-src-attr 'none'` on every editor response, preview and live page, and (new) on the site's built pages the editor serves, through a block appended to the editor build's static `_headers` file. Those pages also get the site-scripts-only rule.
76
+ - **Invite links can't be used twice**, even after the person or the passkey made from them is removed: used invite ids are kept in the users file (`usedInvites`).
77
+ - **Removing a passkey ends the sessions it opened.** Sessions now name their passkey and stop working when it is gone (sessions from before this release last until they expire).
78
+ - **Removed `/api/editor/asset/*`**, a debugging route that let any signed-in editor read any file in the repo, `editor-users.json` included.
79
+ - Sign-in reads the users file through the cache, and a lookup that misses re-reads at most every 5 s, so unauthenticated requests can't spend the GitHub token's quota.
80
+ - The uploads route checks that the person still exists, not just the cookie's signature.
81
+ - Commit subjects sent by the client are cut to one line and can't claim "Edited by" someone else.
82
+ - Sign-in errors no longer echo internal error text. The proxy shared secret is compared in constant time.
83
+
84
+ - **Ready to publish switch** replaces the Publish / Switch to draft / Save draft / Update buttons on pages and collection items. Flipping it saves straight away and says what it means; Save is always "Save". Without `github.live` the switch reads **Published**. A page only asks before turning into a draft when that takes it off the site at the next build.
85
+ - **Go live is now labelled "Publish changes"**, so "publish" always means the public site. Element ids are unchanged (`#ps-live`); `#ps-publish`, `#ps-item-publish` and `#ps-item-draft` are gone (use `#ps-ready` / `#ps-item-ready`, or click `#ps-ready-wrap` / `#ps-item-ready-wrap`).
86
+
87
+ ## 0.1.0-beta.10 — 2026-11-12
88
+
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)`.
90
+ - **Browse shows when a page is loading**: a moving strip under the bar and "Loading page…", instead of a blank frame.
91
+
92
+ ## 0.1.0-beta.9 — 2026-11-12
93
+
94
+ - **Browse site** (`/edit/site`): the site as visitors see it, with a bar on top. Click around; **Edit this page** opens the editor for what's showing, and the editor's **View on site** comes back. Pages and items with a `previews` layout show their latest saved version; other pages show the editor's built copy, and the bar warns when something has been saved since that build. Back and Forward work. The View buttons across the editor now open Browse, and the nav's "View site ↗" is now "Browse site".
95
+ - **Live list pages** (`liveRoutes`): in the editor's build only, the named pages render on request, reading collections from storage through the new `@pirateandfox/pagestack/live` export (`liveEntries`). A new or edited item shows in them straight away. The public build is unchanged. Opened directly on a deployed editor, they land in Browse.
96
+ - Storage adapters gain optional `readDir`, `head` and `lastChange`. On GitHub, `readDir` caches file contents by blob hash.
97
+ - `site` is now a reserved page slug (`/edit/site` is Browse).
98
+
99
+ ## 0.1.0-beta.8 — 2026-11-11
100
+
101
+ **Breaking, for host sites:** everything the editor puts on a page now uses the `ps` prefix instead of `ase`, from the editor's old name: `data-ps-node`, `data-ps-field`, `data-ps-field-type`, `data-ps-id`, `.ps-*` classes, `window.__PS_*__`. Hosts that only use `nodeAttrs` / `fieldAttrs` / `itemField` need nothing. Hosts that write the attributes by hand, or tests that select `.ase-*`, replace `ase` with `ps` (`data-ase-` → `data-ps-`, `.ase-` → `.ps-`). Editors are signed out once (the session cookie is now `ps_session`).
102
+
103
+ **Also changed:** the editor is off unless asked for. `astro dev` alone no longer includes it; use `EDITOR=dev astro dev` (or `EDITOR=1`). A host passing `enabled` is unaffected.
104
+
105
+ - **Go live**: with `github.live`, saves wait on the staging branch and a Go live button on every screen puts them on the live branch in one step, with the list of changes and a link to the staging site (`github.stagingUrl`). Fast-forward when possible, a merge commit when someone committed to live directly, and a clear refusal on a conflict. Saving then says "Use Go live to put it on the site."
106
+ - **Collection items**: Change URL (with a redirect), Revisions with Restore, and Delete, from a ⋮ menu.
107
+ - **Adding blocks on the page**: a + beside each block, and `/` in an empty one, add a paragraph, heading, list, quote, image or table. A block added and left untouched goes away again.
108
+ - **Lists and quotes are edited in place**, like paragraphs: flat bulleted and numbered lists, and one-paragraph quotes. Nested lists, task lists and tables still open the Markdown.
109
+ - **Third-party scripts stay out of the block editor's preview**: the site's own scripts run, scripts from other origins are refused (`previewScripts: 'all'` to allow them). The item frame no longer loads the site's scripts at all, which also ends a console error per script.
110
+
111
+ ## 0.1.0-beta.7 — 2026-11-09
112
+
113
+ - **Collection items on their own page**: with `previews: { <collection>: './Layout.astro' }`, an item opens in the site's layout and is edited in place: title and fields, paragraphs and headings (back to Markdown, only that block's lines change), images, with Page / Markdown views and Preview in a tab. New runtime export `itemField` and type `ItemPreviewProps`. The frame is sandboxed, so the site's own scripts (analytics, spam checks) don't run in the editor.
114
+ - **Uploads show in a deployed editor**: images uploaded or committed after the editor was built were 404s on Workers (the static 404 page answered before any editor code ran). They are now served from the repo to signed-in editors by a route at the uploads URL. Storage adapters gain `asset(path)`.
115
+ - Image fields redraw after a pick in the item and global editors (they used to show "No image" until a reload). `altField` on an `asUrl` image field takes the alt text from the picker.
116
+ - Passkeys must verify the user (Touch ID, PIN). The request said "preferred" while the check required it, so an authenticator that skipped it was refused with a confusing error.
117
+ - The item editor's title is the large heading it was meant to be (an invalid `font` shorthand was ignored).
118
+
119
+ ## 0.1.0-beta.6 — 2026-11-06
120
+
121
+ - **`pages: false`** for a site with no block pages: `renderer` becomes optional, and the Pages screen and Add page go away.
122
+ - **New collection items** start from each field's `default`, so required frontmatter is there. `create: false` on a collection hides Add.
123
+ - Prerendered routes skip the middleware, so a build no longer needs `EDITOR_SECRET`.
124
+
125
+ ## 0.1.0-beta.5 — 2026-11-05
126
+
127
+ A WordPress block-editor user should feel at home. Everything is additive: pages, options, routes, `data-ase-*` and `editor-users.json` keep working unchanged, and a site that adopts none of this builds byte-identically.
128
+
129
+ - **Pages screen** at `/edit`: search, status, add, copy, delete. Add page takes a title, an auto slug, and a starting point (blank, a copy of a page, or a host template). Slugs are checked for duplicates, reserved paths and the site's own routes. A new page needs the host's catch-all route (see README).
130
+ - **Draft / Publish**: optional `status: 'draft'` in the page JSON. Absent means published, so existing pages are unaffected. `staticPages()` (new runtime export) leaves drafts out of the build.
131
+ - **Change URL** moves the file and adds a 301 to `public/_redirects` (if that file exists) in one commit. **Revisions** lists the git history of a page; picking one loads it as an undoable draft. **Delete page** removes the file in one commit, so it can be recovered from git.
132
+ - **Block inserter**: searchable panel with categories (`category`, `keywords` on a schema) and a Patterns tab. Save any block as a pattern, kept in the repo. `+` between sections, an empty-page prompt, breadcrumbs, a block ⋮ menu, copy/paste across pages, keyboard shortcuts.
133
+ - **Document Overview**: List View can move blocks between containers; blocks can also be dragged on the canvas.
134
+ - **Rich text**: toolbar and link popover both inline and in the sidebar, with an HTML view. Pasted content is cleaned.
135
+ - **Previews**: real device widths (1280 / 1024 / 390) scaled to fit, plus Preview in a new tab that renders the unsaved draft.
136
+ - **Global content**: `globals` in the sections module describes JSON files (menus, footer links) edited at `/edit/global/<id>`. New `list` field type for repeatable rows, `asUrl` on image fields.
137
+ - **Host hooks**, all optional: `pageFields`, `templates`, `globals` exports; `reservedSlugs`, `redirectsFile`, `patternsFile` options.
138
+ - **Security**: every value is cleaned on save, not only rich text: all field types, keys outside the schema, titles, descriptions, `attrs` and Markdown. Unchanged content stays byte-identical. Select, number, boolean and color values are checked against their type. SVG fields and uploads go through an allowlist. Uploads are judged by their bytes, not their claimed type.
139
+ - **Roles**: `admin` and `editor` (no `role` in `editor-users.json` means admin). Only admins invite, manage people, and write raw HTML in `code` fields; editors can't damage what an admin put there. Users screen at `/edit/users`: change roles, remove people or single passkeys. The last admin is protected. Removing someone ends their sessions within seconds.
140
+ - **Invites** moved from `/edit` to `/edit/users`. Invites from the screen default to Editor; `pagestack-invite` from the CLI creates admins, so you can always get back in.
141
+ - **Hardening**: login rate limit (30 attempts per 5 minutes per IP, per server instance; `clientIpHeader` option behind a proxy), cross-site writes refused, security headers on all editor routes, open redirect after login closed, the Preview tab sandboxed away from the session, `none-behind-proxy` refuses requests with no identity in a build (optional `EDITOR_PROXY_SECRET`).
142
+ - **Media library** at `/edit/media`: browse, search, upload, see where an image is used, delete. Large photos are scaled to 2400px in the browser.
143
+ - **Date fields** with no time stay day-only (`time: false`, or any stored `2026-11-05`).
144
+ - **Posts**: `collections` in the sections module describes Markdown folders, edited at `/edit/collection/<id>`: frontmatter form, Markdown with toolbar and live preview, drafts. New `date` and `tags` field types. Untouched frontmatter keeps its exact formatting.
145
+ - **Synced patterns**: copies stay linked and "Update all copies" rewrites them in one commit. Pages stay plain JSON, so the build needs no lookup.
146
+ - **Block transforms** ("Turn into…", optional `transforms` on a schema) and `/` in an empty block to open the inserter, with the pick replacing that block.
147
+ - **Cloudflare Workers**: runs on workerd with `@astrojs/cloudflare`. Uploads now wait on a `pagestack-uploads` branch instead of in memory, so an upload and the save after it can reach different instances and a restart loses nothing. `pendingAsset` is now async.
148
+ - **Requires** Astro 7.2.1+ and Node 22.23.4+; `@astrojs/node` 11.1.11. This clears Astro's AVIF remote code execution advisory and the others against 6.x.
149
+ - **Storage**: `commit()` accepts `deletes`; adapters add `history()` and `readAt()`.
150
+ - Fixes: toolbar text could be saved into headings (the toolbar is now an overlay); sidebar fields lost focus while typing; a debounced edit could swallow an undo step; `moveNode` used a stale path when moving between lists; "Blank container" no longer assumes a `container` type; the 840px "desktop" preview was not desktop width.
151
+
152
+ ## 0.1.0-beta.4 — 2026-11-04
153
+
154
+ - First npm release as **`@pirateandfox/pagestack`** (`npm install @pirateandfox/pagestack@beta`). The bare `pagestack` is blocked by npm's similarity rule against an unrelated `page-stack`, and the `pagestack` org name was taken; beta.3 was tagged as `@pagestack/astro` but never published. Imports are `@pirateandfox/pagestack` and `@pirateandfox/pagestack/runtime`; the integration is still named `pagestack` and the CLI `pagestack-invite`.
155
+
156
+ ## 0.1.0-beta.2 — 2026-11-03
157
+
158
+ - Renamed to **PageStack**: package `pagestack`, integration `pagestack`, CLI `pagestack-invite`, imports `pagestack/runtime` and `pagestack/core/*`. No behaviour change.
159
+
160
+ ## 0.1.0-beta.1 — 2026-11-03
161
+
162
+ First tagged release, extracted with its history from the site it was first built for.
163
+
164
+ - Integration: `/edit`, `/edit/login`, `/edit/enroll`, `/edit/preview/*`, `/api/editor/*` routes; static build untouched unless `EDITOR=1`.
165
+ - Editor: section tree, schema-driven inspector, inline text editing, image picker + uploads, presets ("Add section"), reorder / duplicate / delete, undo/redo, drafts, page settings.
166
+ - Storage: local working tree (dev) or one GitHub commit per save (optional PR), hash check against concurrent saves.
167
+ - Auth: passkeys with one-time invite links, stateless HMAC challenges, signed cookie sessions.
168
+ - New: `interactiveSelector` option replaces a hard-coded list of host-site class names.
package/README.md CHANGED
@@ -222,6 +222,30 @@ A few things worth knowing while you set up the schema:
222
222
  in a WordPress heading. See [Bold and italic in headings](#bold-and-italic-in-headings).
223
223
  - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
224
224
 
225
+ ### Required fields
226
+
227
+ Mark a field `required: true` and the editor won't save without it: the field is starred, and Save
228
+ says what is missing and goes to it.
229
+
230
+ ```ts
231
+ fields: {
232
+ title: { type: 'text', label: 'Title' }, // always required
233
+ date: { type: 'date', label: 'Date', time: false, required: true },
234
+ year: { type: 'number', label: 'Year', required: true },
235
+ }
236
+ ```
237
+
238
+ - **Collections: mark every field the Astro schema insists on** (no `.optional()`, no `.default()`). One
239
+ file without it stops the whole build, and Astro checks drafts too, so the editor does as well.
240
+ **Add** asks for required fields along with the title, unless a `default` answers them (a collection's
241
+ first date starts as today).
242
+ - **Pages** are checked when they are on the site; a draft may be incomplete. This covers block fields
243
+ and `pageFields`. **Globals** are always checked.
244
+ - A field hidden by `showIf` isn't asked for, so keep it optional in the Astro schema. Fields in a `list`
245
+ can be required in each row. A `boolean` can't be: off is an answer.
246
+ - A required field showing its default (or a select's first option) counts as filled in. In collections
247
+ and globals that value is written to the file.
248
+
225
249
  ### Checkboxes, and fields that depend on others
226
250
 
227
251
  `multiselect` shows its `options` as checkboxes and stores the ticked values as an array, in the
@@ -319,7 +343,7 @@ export const templates = [{ label: 'Standard page', create: ({ title }) => ({ ti
319
343
  export const collections = {
320
344
  blog: {
321
345
  label: 'Posts', singular: 'post', dir: 'src/content/blog', url: (slug) => `/${slug}/`,
322
- fields: { title: { type: 'text', label: 'Title' }, draft: { type: 'boolean', label: 'Draft' }, date: { type: 'date', label: 'Date' }, tags: { type: 'tags', label: 'Tags' } },
346
+ fields: { title: { type: 'text', label: 'Title' }, draft: { type: 'boolean', label: 'Draft' }, date: { type: 'date', label: 'Date', required: true }, tags: { type: 'tags', label: 'Tags' } },
323
347
  },
324
348
  };
325
349
 
@@ -436,8 +460,8 @@ editor's build only, they render on request from storage instead:
436
460
  pagestack({ liveRoutes: ['/', '/blog'], /* … */ })
437
461
  ```
438
462
 
439
- The page reads its collections through `liveEntries`, which gives the saved entries on the editor's
440
- server and `null` everywhere else, so the public build is unchanged and stays fully static:
463
+ The page reads its collections through `liveEntries`, which gives the saved entries to these
464
+ pages and to the editor's previews, and `null` everywhere else, so the public build is unchanged and stays fully static:
441
465
 
442
466
  ```ts
443
467
  // src/lib/content.ts
package/live.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // For host sites whose list pages should show what the editor has saved (the `liveRoutes` option).
2
2
  //
3
- // On the editor's server, for those pages, this returns a collection's entries as stored now (the
3
+ // On the editor's server, for those pages and the editor's previews, this returns a collection's entries as stored now (the
4
4
  // staging branch). Everywhere else, including the public build and prerendering, it returns null,
5
5
  // so the caller uses Astro's own getCollection and the public site is unchanged:
6
6
  //
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.17",
3
+ "version": "0.1.0-beta.19",
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",
@@ -17,7 +17,8 @@
17
17
  "index.mjs",
18
18
  "live.mjs",
19
19
  "bin",
20
- "src"
20
+ "src",
21
+ "CHANGELOG.md"
21
22
  ],
22
23
  "scripts": {
23
24
  "test": "vitest run"
@@ -1,20 +1,57 @@
1
1
  // The list of a collection: add, delete, search.
2
2
  import { slugify, uniqueSlug } from '../core/pages';
3
- import { confirmDialog, promptDialog, toast } from './ui';
3
+ import { missingFields } from '../core/required';
4
+ import type { Field } from '../runtime';
5
+ import { renderForm, showMissing } from './form';
6
+ import { pickImage } from './picker';
7
+ import { confirmDialog, dialog, promptDialog, toast } from './ui';
4
8
 
5
- const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[] };
9
+ const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[]; ask: Record<string, Field> };
6
10
  const api = `/api/editor/collection/${boot.id}`;
7
11
 
8
12
  document.getElementById('ps-add-item')?.addEventListener('click', async () => {
9
- const title = await promptDialog({ title: `Add ${boot.singular}`, label: 'Title', submit: `Add ${boot.singular}` });
10
- if (!title) return;
11
- const slug = uniqueSlug(slugify(title) || boot.singular, [...boot.slugs, ...boot.reserved]);
12
- const res = await fetch(api, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title, slug }) });
13
- const data = await res.json();
14
- if (!res.ok) { toast(data.error || 'That did not work.', 'error'); return; }
15
- location.href = `/edit/collection/${boot.id}/${data.slug}`;
13
+ const add = `Add ${boot.singular}`;
14
+ const asked = Object.keys(boot.ask).length > 0;
15
+ const title = asked ? null : await promptDialog({ title: add, label: 'Title', submit: add });
16
+ if (title) await create(title);
17
+ else if (asked) askAll(add);
16
18
  });
17
19
 
20
+ /** The title, and the required fields nothing else answers: without them the new file would break the site's build. */
21
+ function askAll(add: string) {
22
+ const data: Record<string, unknown> = {};
23
+ const box = document.createElement('div'); box.className = 'ps-newpage';
24
+ const head = document.createElement('div');
25
+ renderForm(head, { label: boot.singular, fields: { title: { type: 'text', label: 'Title', required: true } } }, {}, { pickImage, onChange: () => {} });
26
+ const form = document.createElement('div');
27
+ renderForm(form, { label: boot.singular, fields: boot.ask }, data, { pickImage, onChange: (name, value) => { data[name] = value; } });
28
+ box.append(head, form);
29
+ dialog(add, box, [{ label: 'Cancel' }, {
30
+ label: add, kind: 'primary', run: async () => {
31
+ const title = head.querySelector('input')!.value.trim();
32
+ const missing = missingFields(boot.ask, data);
33
+ showMissing(form, missing);
34
+ showMissing(head, title ? [] : [{ path: ['title'], label: 'Title' }]);
35
+ return missing.length || !title ? false : create(title, data);
36
+ },
37
+ }]);
38
+ }
39
+
40
+ /** This computer's time, with no zone: what a date field shows and stores. */
41
+ function localNow() {
42
+ const d = new Date();
43
+ return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
44
+ }
45
+
46
+ /** False when it failed, which it has said. */
47
+ async function create(title: string, data?: Record<string, unknown>): Promise<false | void> {
48
+ const slug = uniqueSlug(slugify(title) || boot.singular, [...boot.slugs, ...boot.reserved]);
49
+ const res = await fetch(api, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title, slug, data, now: localNow() }) });
50
+ const d = await res.json();
51
+ if (!res.ok) { toast(d.error || 'That did not work.', 'error'); return false; }
52
+ location.href = `/edit/collection/${boot.id}/${d.slug}`;
53
+ }
54
+
18
55
  document.getElementById('ps-pagelist')!.addEventListener('click', async (e) => {
19
56
  const b = (e.target as HTMLElement).closest<HTMLElement>('[data-delete]');
20
57
  if (!b) return;
@@ -10,14 +10,15 @@ 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';
13
- import { renderForm } from './form';
13
+ import { missingInPage, missingMessage } from '../core/required';
14
+ import { commitTyping, renderForm, showMissing } from './form';
14
15
  import { renderTree } from './tree';
15
16
  import { renderInserter } from './inserter';
16
17
  import { InlineEditor } from './inline';
17
18
  import { pickImage } from './picker';
18
19
  import { icons } from './icons';
19
20
  import type { MenuItem } from './ui';
20
- import { confirmDialog, dialog, openMenu, promptDialog, toast } from './ui';
21
+ import { confirmDialog, dialog, openMenu, promptDialog, taskQueue, toast } from './ui';
21
22
  import previewCss from './preview.css?raw';
22
23
 
23
24
  interface Boot {
@@ -489,7 +490,7 @@ function renderPageTab(root: HTMLElement) {
489
490
  root.append(form);
490
491
 
491
492
  if (Object.keys(boot.pageFields).length) {
492
- const layout = document.createElement('div');
493
+ const layout = document.createElement('div'); layout.id = 'ps-layout-form';
493
494
  renderForm(layout, { label: 'Layout', fields: boot.pageFields }, state.doc.layout ?? {}, {
494
495
  ...formCallbacks,
495
496
  onChange: (name, value, o) => { renderFull = !o?.live; applyField(`layout.${name}`, value, o?.live, boot.pageFields[name]); },
@@ -770,7 +771,7 @@ $('#ps-discard').addEventListener('click', async () => {
770
771
  renderFull = true;
771
772
  state.reset(r.page, r.hash);
772
773
  });
773
- $('#ps-save').addEventListener('click', () => save());
774
+ $('#ps-save').addEventListener('click', () => { inline.stop(true); save(); });
774
775
  $<HTMLInputElement>('#ps-ready').addEventListener('change', (e) => publish((e.target as HTMLInputElement).checked));
775
776
  $('#ps-preview-tab').addEventListener('click', previewInTab);
776
777
  document.querySelectorAll<HTMLButtonElement>('.ps-top__devices button').forEach((b) => b.addEventListener('click', () => {
@@ -801,23 +802,40 @@ function previewInTab() {
801
802
  form.remove();
802
803
  }
803
804
 
804
- async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; result?: any } | null> {
805
- if (!state.dirty && !opts.slug) return null;
805
+ /** Says which required fields are empty, opens the first one's block and points at it. */
806
+ function complete(doc: PageDoc): boolean {
807
+ const missing = missingInPage(doc, registry, boot.pageFields);
808
+ if (!missing.length) return true;
806
809
  inline.stop(true);
810
+ toast(missingMessage(missing), 'error');
811
+ const node = missing[0].node ?? null;
812
+ select(node);
813
+ showMissing($(node ? '#ps-inspector' : '#ps-layout-form'), missing.filter((m) => m.node === node));
814
+ return false;
815
+ }
816
+
817
+ const queued = taskQueue();
818
+ const save = (opts: { slug?: string } = {}) => queued(() => saveNow(opts));
819
+
820
+ /** Leaves the field being edited alone, in the sidebar or on the page: its text is in the document already. */
821
+ async function saveNow(opts: { slug?: string }): Promise<{ slug?: string; result?: any } | null> {
822
+ if (!state.dirty && !opts.slug) return null;
823
+ if (!complete(state.doc)) return null;
824
+ const sent = state.doc;
807
825
  saving = true; refreshButtons(); setSaveStatus('Saving…');
808
826
  try {
809
- const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: state.doc, base: state.hash, slug: opts.slug }) });
827
+ const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: sent, base: state.hash, slug: opts.slug }) });
810
828
  const data = await res.json();
811
829
  if (!res.ok) { toast(data.error || 'Save failed', 'error'); setSaveStatus(''); return null; }
812
- state.markSaved(data.hash);
813
- boot.page = state.doc;
830
+ state.markSaved(data.hash, sent);
831
+ boot.page = sent;
814
832
  const r = data.result;
815
833
  if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : `Committed ${String(r.commit).slice(0, 7)} to ${r.branch}. The host will rebuild the site.`, 'ok', { href: r.pullRequest || r.url });
816
834
  else toast(`Saved to the working tree (${r.files.join(', ')}). Commit it with git when you're happy.`, 'ok');
817
- setSaveStatus('Saved');
835
+ setSaveStatus(state.dirty ? '' : 'Saved');
818
836
  return data;
819
837
  } catch (e: any) { toast(`Save failed: ${e.message}`, 'error'); setSaveStatus(''); return null; }
820
- finally { saving = false; refreshChrome(); }
838
+ finally { saving = false; refreshChrome({ inspector: false }); }
821
839
  }
822
840
 
823
841
  /** The Ready to publish switch: a draft or not. Saves straight away, so the switch means what it shows. */
@@ -828,6 +846,7 @@ async function publish(live: boolean) {
828
846
  inline.stop(true);
829
847
  const next = structuredClone(state.doc);
830
848
  if (live) delete next.status; else next.status = 'draft';
849
+ if (!complete(next)) { refreshButtons(); return; }
831
850
  state.apply(next);
832
851
  if (await save()) toast(live ? (staged ? `${next.title} is ready to publish. It goes on the site with the next Publish changes.` : `${next.title} is published.`) : `${next.title} is now a draft: kept off the site.`, 'ok');
833
852
  else { state.undo(); refreshButtons(); }
@@ -841,10 +860,11 @@ async function changeUrl() {
841
860
  check: (v) => (v === boot.slug ? null : slugProblem(v, { existing, reserved: boot.reserved })),
842
861
  });
843
862
  if (!slug || slug === boot.slug) return;
863
+ inline.stop(true);
844
864
  const data = await save({ slug });
845
865
  if (!data) return;
846
866
  if (data.result?.pullRequest) return; // the move is in a pull request; this page stays where it is for now
847
- leaving = true;
867
+ leaving = !state.dirty; // something typed while it moved: the browser asks first
848
868
  location.replace(`/edit/${data.slug}`);
849
869
  }
850
870
 
@@ -920,7 +940,7 @@ function onKeydown(e: KeyboardEvent) {
920
940
  const mod = e.metaKey || e.ctrlKey;
921
941
  const key = e.key.toLowerCase();
922
942
  const run = (fn: () => void) => { e.preventDefault(); fn(); };
923
- if (mod && key === 's') return run(() => { save(); });
943
+ if (mod && key === 's') return run(() => { commitTyping(); save(); });
924
944
  if (mod && e.shiftKey && (key === ',' || key === '<')) return run(toggleSettings);
925
945
  if (e.ctrlKey && e.altKey && (key === 'o' || e.code === 'KeyO')) return run(() => setLeft(leftView === 'list' ? 'off' : 'list'));
926
946
  if (typing) return;
@@ -946,7 +966,7 @@ window.addEventListener('beforeunload', (e) => { if (state.dirty && !leaving) e.
946
966
  state.addEventListener('change', (e) => {
947
967
  const source = (e as CustomEvent).detail.source;
948
968
  if (source === 'inline') return; // DOM already matches; chrome refreshes on commit
949
- if (source === 'field') { refreshChrome({ inspector: false }); return; } // the sidebar is the source: leave the focused input alone
969
+ if (source === 'field' || source === 'save') { refreshChrome({ inspector: false }); return; } // leave the focused input alone
950
970
  if (source === 'undo' || source === 'redo' || source === 'restore' || source === 'reset') {
951
971
  inline.stop(false);
952
972
  if (selected && !nodeAt(state.doc, selected)) { selected = null; tab = 'page'; }
@@ -1,6 +1,7 @@
1
1
  // Schema -> sidebar form. One widget per field type; changes are reported through `onChange`.
2
2
  import type { BlockSchema, Field, ImageValue } from '../runtime';
3
3
  import { formModel, isShown } from '../core/schema';
4
+ import type { Missing } from '../core/required';
4
5
  import { marksField, richField } from './rich';
5
6
 
6
7
  export interface FormCallbacks {
@@ -54,7 +55,9 @@ function conditions(fields: Record<string, Field>, values: Record<string, unknow
54
55
  function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, idPrefix = 'ps-f-'): HTMLElement {
55
56
  const id = `${idPrefix}${name}`;
56
57
  const label = el('label', { for: id }, field.label);
57
- const wrap = el('div', { class: `ps-field ps-field--${field.type}` }, label);
58
+ const wrap = el('div', { class: `ps-field ps-field--${field.type}`, 'data-ps-form': id }, label);
59
+ const outer = cb;
60
+ cb = { ...cb, onChange: (...args) => { clearMissing(wrap); outer.onChange(...args); } };
58
61
  const help = field.help ? el('small', { class: 'ps-muted' }, field.help) : null;
59
62
  // `cancel` matters: a live update landing after `change` would reorder the edit and split its undo step.
60
63
  const debounce = (fn: () => void, ms = 250) => { let t: ReturnType<typeof setTimeout>; const run = () => { clearTimeout(t); t = setTimeout(fn, ms); }; run.cancel = () => clearTimeout(t); return run; };
@@ -62,6 +65,7 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
62
65
  if (field.type === 'text' && field.marks) {
63
66
  wrap.append(marksField(id, (value as string) ?? '', (html, live) => cb.onChange(name, html, { live })));
64
67
  if (help) wrap.append(help);
68
+ markRequired(wrap, field);
65
69
  return wrap;
66
70
  }
67
71
  switch (field.type) {
@@ -207,9 +211,48 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
207
211
  break;
208
212
  }
209
213
  if (help) wrap.append(help);
214
+ markRequired(wrap, field);
210
215
  return wrap;
211
216
  }
212
217
 
218
+ function markRequired(wrap: HTMLElement, field: Field) {
219
+ if (!field.required || field.type === 'boolean') return;
220
+ wrap.querySelector('label, .ps-field__label')?.append(el('span', { class: 'ps-req', 'aria-hidden': 'true', title: 'Required' }, ' *'));
221
+ if (field.type !== 'list' && field.type !== 'multiselect' && field.type !== 'image') wrap.querySelector('input, select, textarea, [contenteditable]')?.setAttribute('aria-required', 'true');
222
+ }
223
+
224
+ function clearMissing(wrap: HTMLElement) {
225
+ wrap.classList.remove('is-missing');
226
+ wrap.querySelector(':scope > .ps-error')?.remove();
227
+ }
228
+
229
+ /** Takes what is still being typed: fields report when they are left, and a keyboard save doesn't leave them. */
230
+ export function commitTyping() {
231
+ const at = document.activeElement;
232
+ if (!(at instanceof HTMLElement) || !(at.isContentEditable || at.matches('input, textarea'))) return;
233
+ const selection = getSelection();
234
+ const caret = at.isContentEditable && selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : null;
235
+ at.blur();
236
+ if (!at.isConnected) return;
237
+ at.focus({ preventScroll: true });
238
+ if (caret) { selection!.removeAllRanges(); selection!.addRange(caret); }
239
+ }
240
+
241
+ /** Points at each field that still needs a value, and goes to the first one in this form. */
242
+ export function showMissing(root: HTMLElement, missing: Missing[]) {
243
+ root.querySelectorAll<HTMLElement>('.is-missing').forEach(clearMissing);
244
+ const wraps = missing.flatMap((m) => root.querySelector<HTMLElement>(`[data-ps-form="${CSS.escape(`ps-f-${m.path.join('-')}`)}"]`) ?? []);
245
+ for (const w of wraps) {
246
+ w.classList.add('is-missing');
247
+ w.append(el('p', { class: 'ps-error', role: 'alert' }, 'This is required.'));
248
+ for (let d = w.closest('details'); d; d = d.parentElement?.closest('details') ?? null) d.open = true;
249
+ }
250
+ // The field itself, not a toolbar above it; a button where that is all there is (choose an image, add a row).
251
+ const first = wraps[0];
252
+ (first?.querySelector<HTMLElement>('input:not([type="file"]), select, textarea:not([hidden]), [contenteditable]') ?? first?.querySelector<HTMLElement>('button'))?.focus();
253
+ wraps[0]?.scrollIntoView?.({ block: 'nearest' });
254
+ }
255
+
213
256
  /** Repeatable rows, each its own little form. Rows can nest (a menu item holds links). */
214
257
  function listWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, id: string): HTMLElement {
215
258
  const fields = field.fields ?? {};
@@ -254,7 +297,13 @@ function listWidget(name: string, field: Field, value: unknown, cb: FormCallback
254
297
  root.append(details);
255
298
  });
256
299
  root.append(el('button', { type: 'button', class: 'ps-btn ps-btn--small', onclick: () => {
257
- rows.push({});
300
+ // A new row stores what it shows: defaults, and a dropdown's first choice.
301
+ const row: Record<string, any> = {};
302
+ for (const [k, sub] of Object.entries(fields)) {
303
+ const v = sub.default ?? (sub.type === 'select' ? sub.options?.[0]?.value : undefined);
304
+ if (v !== undefined && v !== '') row[k] = structuredClone(v);
305
+ }
306
+ rows.push(row);
258
307
  open.add(rows.length - 1);
259
308
  save(); draw();
260
309
  } }, '+ Add item'));
@@ -1,6 +1,7 @@
1
1
  // Edit a site-wide document with the same form widgets as the block sidebar.
2
2
  import type { Field } from '../runtime';
3
- import { renderForm } from './form';
3
+ import { missingFields, missingMessage } from '../core/required';
4
+ import { renderForm, showMissing } from './form';
4
5
  import { pickImage } from './picker';
5
6
  import { toast } from './ui';
6
7
 
@@ -12,6 +13,7 @@ const url = `/api/editor/global/${boot.id}`;
12
13
  let doc: Record<string, unknown> = {};
13
14
  let hash: string | null = null;
14
15
  let dirty = false;
16
+ let saving = false;
15
17
 
16
18
  const res = await fetch(url);
17
19
  const data = await res.json();
@@ -19,15 +21,19 @@ doc = data.doc; hash = data.hash;
19
21
  renderForm(root, { label: boot.label, fields: boot.fields }, doc, {
20
22
  pickImage,
21
23
  pageUrls: boot.pages,
22
- onChange: (name, value) => { doc[name] = value; dirty = true; saveBtn.disabled = false; },
24
+ onChange: (name, value) => { doc[name] = value; dirty = true; saveBtn.disabled = saving; },
23
25
  });
24
26
 
25
27
  saveBtn.addEventListener('click', async () => {
26
- saveBtn.disabled = true;
28
+ const missing = missingFields(boot.fields, doc);
29
+ if (missing.length) { toast(missingMessage(missing), 'error'); showMissing(root, missing); return; }
30
+ saveBtn.disabled = saving = true;
31
+ const sent = JSON.stringify(doc);
27
32
  const r = await fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ doc, base: hash }) });
28
33
  const d = await r.json();
34
+ saving = false;
29
35
  if (!r.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; return; }
30
- hash = d.hash; dirty = false;
36
+ hash = d.hash; dirty = JSON.stringify(doc) !== sent; saveBtn.disabled = !dirty; // edits made meanwhile are still to be saved
31
37
  toast(d.result.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : 'Saved. The site will rebuild.') : "Saved to the working tree. Commit it with git when you're happy.", 'ok');
32
38
  });
33
39
  window.addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });