@pirateandfox/pagestack 0.1.0-beta.10 → 0.1.0-beta.12

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pirate & Fox LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,41 +1,99 @@
1
- # PageStack
1
+ <p align="center">
2
+ <img src="docs/media/logo.svg" width="72" height="72" alt="">
3
+ </p>
4
+ <h1 align="center">PageStack</h1>
5
+
6
+ <p align="center">
7
+ <strong>A block editor for Astro sites. Your content stays in your repo.</strong><br>
8
+ Click a heading on the real page and type. Drag sections around. Press Save, and it's a git commit.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@pirateandfox/pagestack"><img src="https://img.shields.io/npm/v/@pirateandfox/pagestack/beta?label=npm%20%40beta&color=2563eb" alt="npm beta version"></a>
13
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-1e1e1e" alt="MIT license"></a>
14
+ <img src="https://img.shields.io/badge/status-beta-f59e0b" alt="Beta">
15
+ </p>
16
+
17
+ <p align="center">
18
+ <img src="docs/media/demo.gif" width="860" alt="Editing a bakery's home page in PageStack: clicking a heading to change it, adding a section, and saving">
19
+ </p>
20
+
21
+ ## Why
22
+
23
+ Static Astro sites are fast, cheap and hard to break, and the people who write for them usually
24
+ can't touch them. The usual fix is a headless CMS: another service, another login, content in
25
+ someone else's database, and a site that no longer builds from the repo alone.
26
+
27
+ PageStack takes the other route. It adds an editor **to the site itself**:
28
+
29
+ - **Edit on the real page.** The preview is your site, rendered by your own components. Click text to
30
+ change it, click an image to swap it, press **+** or **/** to add a block. If you've used the
31
+ WordPress block editor, you already know it.
32
+ - **Content is files in your repo.** Pages are JSON, posts are Markdown. Saving writes a file in dev
33
+ and makes **one commit** in production. No database, nothing stored anywhere else. `git log` is
34
+ your revision history.
35
+ - **The public site stays fully static.** `astro build` is unchanged and ships no editor code. The
36
+ editor is a separate small deployment (a Cloudflare Worker or any Node host) that only exists
37
+ when you build it with `EDITOR=1`.
38
+ - **Passkey sign-in.** Touch ID, Face ID, Windows Hello or a security key. No passwords, no user
39
+ database: invite someone with a single-use link.
40
+ - **Draft, stage, publish.** Saves can go to a staging branch, and **Publish changes** puts them live
41
+ in one step, so a dozen edits make one production build.
42
+
43
+ ## How it works
2
44
 
3
- A visual editor for Astro sites where pages are a stack of sections. Git-only: saving is a commit,
4
- the public site stays static, and nothing lives outside the repo.
5
-
6
- - The public site stays **fully static**. `astro build` is unchanged.
7
- - The editor (`/edit/*`, `/api/editor/*`) is on-demand rendered and only exists when asked for:
8
- `EDITOR=dev astro dev`, or a build made with `EDITOR=1` (which adds `@astrojs/node` unless the site has an adapter).
9
- - Pages are JSON documents in the repo (`src/content/pages/<slug>.json`). Saving writes a file
10
- (dev) or makes **one commit** through the GitHub API (production). Nothing is stored anywhere else.
11
- - Login is **passkeys** (WebAuthn). Users' public keys live in a committed `editor-users.json`;
12
- the only server secret is `EDITOR_SECRET`. No database, no session store.
13
- - Live preview renders the real page with the site's own components, in the browser's iframe.
45
+ ```
46
+ your repo on GitHub the editor (edit.example.com)
47
+ ┌──────────────────────────┐ reads ┌───────────────────────────────────┐
48
+ │ src/content/pages/*.json │ ───────────▶ │ your Astro site + PageStack, │
49
+ │ src/content/posts/*.md │ │ built with EDITOR=1 │
50
+ │ public/images/… │ ◀─────────── │ previews use your own components │
51
+ └────────────┬─────────────┘ one commit │ passkey sign-in │
52
+ │ per save └───────────────────────────────────┘
53
+ │ your normal deploy (Pages, Netlify, Vercel…)
54
+ ▼
55
+ ┌──────────────────────────┐
56
+ │ public site: astro build │ static files, no editor code
57
+ └──────────────────────────┘
58
+ ```
14
59
 
15
- Status: **early beta** (`0.1.0-beta.x`). The API will move; pin a version. See [ROADMAP.md](ROADMAP.md)
16
- and [CHANGELOG.md](CHANGELOG.md).
60
+ The editor only needs a GitHub token with *Contents: read and write* on the one repo. It never
61
+ leaves the server.
17
62
 
18
- ## Versions
63
+ ## Try it in two minutes
19
64
 
20
- Published on npm as **`@pirateandfox/pagestack`** (betas under the `beta` dist-tag):
65
+ The repo includes a demo site, an invented bakery called **Crumb & Co.**
21
66
 
22
67
  ```bash
23
- npm install @pirateandfox/pagestack@beta
68
+ git clone https://github.com/pirateandfox/pagestack.git
69
+ cd pagestack/examples/bakery
70
+ npm install
71
+ npm run dev:editor # then open http://localhost:4321/edit
24
72
  ```
25
73
 
26
- Or install from a git tag and bump the tag to upgrade:
74
+ In dev there is no sign-in, and saving writes straight to `examples/bakery/src/content`. Run
75
+ `git diff` afterwards to see exactly what the editor wrote.
27
76
 
28
- ```json
29
- "dependencies": { "@pirateandfox/pagestack": "github:pirateandfox/pagestack#v0.1.0-beta.4" }
30
- ```
77
+ ## Status
78
+
79
+ **Beta** (`0.1.0-beta.x`). It runs real sites today, and the API can still change between betas, so
80
+ pin an exact version. What's solid: block pages, Markdown collections edited in place, media,
81
+ global content, synced patterns, revisions, Browse, passkeys, staging and publish. What's next is
82
+ in the [roadmap](ROADMAP.md); every release is in the [changelog](CHANGELOG.md). Found a security
83
+ problem? See [SECURITY.md](SECURITY.md).
84
+
85
+ ---
86
+
87
+ # Guide
88
+
89
+ ## Install
31
90
 
32
91
  ```bash
33
- npm install # after changing the tag
92
+ npm install @pirateandfox/pagestack@beta --save-exact
34
93
  ```
35
94
 
36
- Releases are tags `vX.Y.Z[-beta.N]` on `main`; each one has a CHANGELOG entry.
95
+ Requires Node 22.23.4+ and Astro 7.2.1+.
37
96
 
38
- ## Install
39
97
 
40
98
  ```js
41
99
  // astro.config.mjs
@@ -152,6 +210,17 @@ const { node, edit } = Astro.props;
152
210
  passes `child(edit, i)` to each child. The `renderer` component takes `{ page, editing }` and
153
211
  renders the page inside the site's normal layout.
154
212
 
213
+ A few things worth knowing while you set up the schema:
214
+
215
+ - **Components can live in the schema or beside it.** The editor strips `component` before sending
216
+ the registry to the browser, so either works. `examples/bakery` keeps them in a separate map
217
+ (`src/sections/components.ts`) so the schema stays plain data.
218
+ - **List View names a block after its first non-empty inline text field**, so put the field people
219
+ recognise (the title) first.
220
+ - **`text` fields are plain text.** Typing in them replaces any markup they held. For a styled word
221
+ in a heading, give the block its own field for it (the bakery's hero has *Word in italics*).
222
+ - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
223
+
155
224
  ## Editing
156
225
 
157
226
  Coming from the WordPress block editor:
@@ -164,7 +233,7 @@ Coming from the WordPress block editor:
164
233
  | Block toolbar, ⋮ menu | Move, parent, add, duplicate, delete, copy, save as pattern |
165
234
  | Settings sidebar, Page / Block tabs | Same, generated from the schema |
166
235
  | Rich text toolbar, links | Same; `⌘B`, `⌘I`, `⌘K`, and an HTML view |
167
- | Save draft, Publish, Preview | Same; Preview opens the unsaved draft in a new tab |
236
+ | Status (Draft / Published), Publish, Preview | A **Ready to publish** switch (**Published** without `github.live`) that saves when flipped; Publish is **Publish changes** in the top bar with `github.live`; Preview opens the unsaved draft in a new tab |
168
237
  | Revisions | The page's git history |
169
238
  | Permalink | Change URL, which also adds a redirect |
170
239
  | Menus, site options | Global content, at `/edit/global/<id>` |
@@ -334,11 +403,12 @@ than setting a hard limit. Passkeys are what actually stops guessing.
334
403
  ### Staging and Go live
335
404
 
336
405
  With `github.live`, saves stay on `github.branch` (staging) and the public site builds from `live`.
337
- Every screen gets a **Go live** button counting the saved changes the live site doesn't have yet;
406
+ Every screen gets a **Publish changes** button (Go live) counting the saved changes the live site doesn't have yet;
338
407
  it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
339
408
  That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
340
409
  commit and moves staging to it; when their change conflicts, it refuses and says so, and a person
341
- merges in GitHub. A burst of saves becomes one production build.
410
+ merges in GitHub. A burst of saves becomes one production build. Drafts (the **Ready to publish**
411
+ switch off) stay in the files but out of the built site, whatever is published.
342
412
 
343
413
  ```js
344
414
  github: { repo: 'acme/site', branch: 'develop', live: 'main', stagingUrl: 'https://develop.acme.pages.dev/' }
@@ -389,13 +459,36 @@ Dev only. A build with `auth: "none"` is refused.
389
459
 
390
460
  ## Deploying the editor
391
461
 
392
- Requires Node 22.23.4+ and Astro 7.2.1+. On Cloudflare, add `@astrojs/cloudflare` as the host's
393
- adapter and set `EDITOR_SECRET`, `EDITOR_ORIGIN` and `GITHUB_TOKEN` as secrets.
462
+ Requires Node 22.23.4+ and Astro 7.2.1+.
463
+
464
+ **On Cloudflare Workers**, add `@astrojs/cloudflare` as the host's adapter in the editor build only,
465
+ and give the Worker three secrets: `EDITOR_SECRET` (32+ random characters), `EDITOR_ORIGIN` (its
466
+ https address) and `GITHUB_TOKEN`. Until `EDITOR_SECRET` and `GITHUB_TOKEN` are set, every editor page says
467
+ which one is missing. PageStack takes care of the rest: in the editor build it wraps the adapter's Worker entry
468
+ and sets `assets.run_worker_first` in the generated `dist/server/wrangler.json`, so the built copies
469
+ of your site pages need a sign-in and, opened directly, land in Browse.
470
+
471
+ ```js
472
+ // astro.config.mjs: the adapter only in the editor's build
473
+ const editorBuild = process.env.EDITOR === '1' && process.argv.includes('build');
474
+ const { default: cloudflare } = editorBuild ? await import('@astrojs/cloudflare') : {};
475
+ export default defineConfig({
476
+ ...(cloudflare ? { adapter: cloudflare({ configPath: 'wrangler.editor.jsonc' }) } : {}),
477
+ // …
478
+ });
479
+ ```
480
+
481
+ ```bash
482
+ EDITOR=1 astro build && wrangler deploy --config dist/server/wrangler.json
483
+ EDITOR_SECRET=… npx pagestack-invite --name "You" --email you@example.com --origin https://edit.example.com
484
+ ```
394
485
 
395
- The editor server is a normal `@astrojs/node` standalone build. Run `node dist/server/entry.mjs`
486
+ **On a Node host**, the editor server is a normal `@astrojs/node` standalone build. Run `node dist/server/entry.mjs`
396
487
  on any small Node host (Fly, Railway, a VPS…) with `EDITOR_SECRET`, `GITHUB_TOKEN` and
397
488
  `EDITOR_ORIGIN` set, behind HTTPS. It serves the editor routes and the static pages it was built
398
- with; the public site is still deployed separately from the same repo as static files. Every
489
+ with; the public site is still deployed separately from the same repo as static files. (Here the
490
+ built site pages are served as plain files, without a sign-in; put the host behind an access proxy
491
+ if staged work must stay private.) Every
399
492
  editor response is `noindex` and `no-store`.
400
493
 
401
494
  ## Options
@@ -428,4 +521,4 @@ editor response is `noindex` and `no-store`.
428
521
  - [@astrojs/node](https://docs.astro.build/en/guides/integrations-guide/node/) (MIT) as the editor's adapter.
429
522
  - [Puck](https://puckeditor.com) was used as a design reference for JSON page editing only; no code.
430
523
 
431
- MIT.
524
+ MIT © Pirate & Fox LLC. See [LICENSE](LICENSE).
package/index.mjs CHANGED
@@ -11,6 +11,39 @@ import { fileURLToPath } from 'node:url';
11
11
  import fs from 'node:fs';
12
12
  import path from 'node:path';
13
13
 
14
+ /**
15
+ * The editor's copy of the site serves its built pages as static files, on the editor's origin,
16
+ * where the editor API and the session cookie live. The platform answers those before any of our
17
+ * code runs, so the rules the middleware puts on everything else go in the static headers file
18
+ * (Cloudflare `_headers`): the site's own scripts only, no inline event handlers, framed only here.
19
+ */
20
+ function writeEditorHeaders(clientDir, previewScripts) {
21
+ if (!fs.existsSync(clientDir)) return;
22
+ const file = path.join(clientDir, '_headers');
23
+ const scripts = previewScripts === 'all' ? "script-src-attr 'none'" : "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; script-src-attr 'none'";
24
+ const block = `\n# pagestack: built pages served by the editor\n/*\n Content-Security-Policy: ${scripts}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n X-Frame-Options: SAMEORIGIN\n X-Robots-Tag: noindex\n`;
25
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
26
+ if (!existing.includes('# pagestack: built pages served by the editor')) fs.writeFileSync(file, existing + block);
27
+ }
28
+
29
+ /**
30
+ * Cloudflare serves files in the assets directory before the Worker runs, which would put every
31
+ * built site page on the editor's domain with no sign-in. Send everything but hashed build assets
32
+ * through the Worker (src/worker.ts decides). Leaves a host's own `run_worker_first` alone.
33
+ */
34
+ function routeThroughWorker(serverDir, logger) {
35
+ const file = path.join(serverDir, 'wrangler.json');
36
+ if (!fs.existsSync(file)) return;
37
+ const conf = JSON.parse(fs.readFileSync(file, 'utf8'));
38
+ if (!conf.assets) return;
39
+ if (conf.assets.run_worker_first === undefined) {
40
+ conf.assets.run_worker_first = ['/*', '!/_astro/*'];
41
+ fs.writeFileSync(file, JSON.stringify(conf));
42
+ } else if (conf.assets.run_worker_first === false) {
43
+ logger?.warn('wrangler assets.run_worker_first is false: built site pages on the editor are served without sign-in.');
44
+ }
45
+ }
46
+
14
47
  const VIRTUAL = 'virtual:pagestack/site';
15
48
  const VIRTUAL_RENDERER = 'virtual:pagestack/renderer';
16
49
  const VIRTUAL_PREVIEWS = 'virtual:pagestack/previews';
@@ -83,12 +116,28 @@ export default function sectionEditor(userOptions) {
83
116
  let adapter = null;
84
117
  // Set in astro:config:setup when the editor is on: page files to render on request (liveRoutes).
85
118
  let liveComponents = null;
119
+ // Set when building the editor: the site's built pages it serves need the editor's script rules.
120
+ let editorBuild = null;
86
121
  const forward = (hook) => async (params) => { if (adapter?.hooks?.[hook]) await adapter.hooks[hook](params); };
87
122
  const forwarded = Object.fromEntries(['astro:config:done', 'astro:server:setup', 'astro:server:start', 'astro:server:done', 'astro:build:start', 'astro:build:setup', 'astro:build:ssr', 'astro:build:generated', 'astro:build:done'].map((h) => [h, forward(h)]));
88
123
  return {
89
124
  name: 'pagestack',
90
125
  hooks: {
91
126
  ...forwarded,
127
+ 'astro:config:done': async (params) => {
128
+ if (editorBuild) {
129
+ editorBuild.dirs = [params.config.build.client, params.config.outDir]; // with an adapter, files go to build.client
130
+ editorBuild.server = params.config.build.server;
131
+ editorBuild.logger = params.logger;
132
+ }
133
+ await forwarded['astro:config:done'](params);
134
+ },
135
+ 'astro:build:done': async (params) => {
136
+ await forwarded['astro:build:done'](params);
137
+ const dir = editorBuild?.dirs?.map((u) => fileURLToPath(u)).find((d) => fs.existsSync(d));
138
+ if (dir) writeEditorHeaders(dir, editorBuild.previewScripts);
139
+ if (editorBuild?.cloudflare && editorBuild.server) routeThroughWorker(fileURLToPath(editorBuild.server), editorBuild.logger);
140
+ },
92
141
  // List pages named in `liveRoutes` render on request on the editor's server, reading what
93
142
  // has been saved. Only in the editor build: the public build never gets here.
94
143
  'astro:route:setup': ({ route }) => {
@@ -100,6 +149,7 @@ export default function sectionEditor(userOptions) {
100
149
  const enabled = userOptions.enabled ?? (flag === '1' || (command === 'dev' && flag === 'dev'));
101
150
  if (!enabled) { logger.info(command === 'dev' ? 'off. Run with EDITOR=dev to edit at /edit.' : 'off (static build). Set EDITOR=1 to build the editor.'); return; }
102
151
  const isBuild = command === 'build';
152
+ if (isBuild) editorBuild = { previewScripts: userOptions.previewScripts };
103
153
  const options = {
104
154
  pagesDir: 'src/content/pages',
105
155
  imagesDir: 'public/images',
@@ -142,7 +192,37 @@ export default function sectionEditor(userOptions) {
142
192
  vite: {
143
193
  plugins: [{
144
194
  name: 'pagestack:virtual',
145
- resolveId(id) { if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id; },
195
+ enforce: 'pre',
196
+ // A save in dev writes files the site's routes import, and Vite answers with a full
197
+ // reload of every open page, the editor included. Drop reloads caused by the editor's
198
+ // own writes (src/core/storage-local.ts); the editor refreshes its preview itself.
199
+ configureServer(server) {
200
+ const recent = () => {
201
+ const writes = globalThis.__PS_WRITES__;
202
+ if (!writes) return false;
203
+ const now = Date.now();
204
+ for (const [f, t] of writes) if (now - t > 3000) writes.delete(f);
205
+ return writes.size > 0;
206
+ };
207
+ const own = (payload) => {
208
+ if (payload?.type !== 'full-reload' || !recent()) return false;
209
+ const by = payload.triggeredBy ? path.resolve(payload.triggeredBy) : null;
210
+ return !by || globalThis.__PS_WRITES__.has(by) || /\.(json|md|mdx)$/.test(by);
211
+ };
212
+ const channels = [server.ws, ...Object.values(server.environments ?? {}).map((e) => e.hot)].filter(Boolean);
213
+ for (const ch of new Set(channels)) {
214
+ const send = ch.send.bind(ch);
215
+ ch.send = (payload, ...rest) => { if (!own(payload)) send(payload, ...rest); };
216
+ }
217
+ },
218
+ resolveId(id) {
219
+ if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id;
220
+ // On Cloudflare the editor's Worker checks site pages before the adapter (src/worker.ts).
221
+ if (isBuild && /^@astrojs\/cloudflare\/entrypoints\/server(\.js)?$/.test(id)) {
222
+ editorBuild.cloudflare = true;
223
+ return fileURLToPath(new URL('./src/worker.ts', import.meta.url));
224
+ }
225
+ },
146
226
  load(id) {
147
227
  // The renderer (and the site layout/CSS behind it) is only imported by the preview
148
228
  // route, so the editor shell doesn't drag the whole site's CSS into its page.
@@ -196,7 +276,6 @@ export default function sectionEditor(userOptions) {
196
276
  injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
197
277
  injectRoute({ pattern: '/api/editor/browse', entrypoint: route('api/browse.ts'), prerender: false });
198
278
  injectRoute({ pattern: '/api/editor/live', entrypoint: route('api/live.ts'), prerender: false });
199
- injectRoute({ pattern: '/api/editor/asset/[...path]', entrypoint: route('api/asset.ts'), prerender: false });
200
279
  injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
201
280
  // Uploads saved after this editor was built aren't static files in it; serve them from the repo.
202
281
  const uploadsUrl = options.storage === 'github' && uploadsUrlPrefix(options.uploadsDir, options.publicDir);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.10",
4
- "description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
3
+ "version": "0.1.0-beta.12",
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",
7
7
  "bin": {
@@ -23,7 +23,8 @@
23
23
  "test": "vitest run"
24
24
  },
25
25
  "peerDependencies": {
26
- "astro": ">=7.2.1"
26
+ "astro": ">=7.2.1",
27
+ "@astrojs/cloudflare": ">=13"
27
28
  },
28
29
  "dependencies": {
29
30
  "@astrojs/node": "11.1.11",
@@ -36,6 +37,7 @@
36
37
  "devDependencies": {
37
38
  "@types/sortablejs": "^1.15.8",
38
39
  "happy-dom": "^21.0.4",
40
+ "parse5": "^7.3.0",
39
41
  "vitest": "^4.0.0"
40
42
  },
41
43
  "keywords": [
@@ -45,7 +47,14 @@
45
47
  "visual-editor",
46
48
  "cms",
47
49
  "git-based-cms",
48
- "sections"
50
+ "sections",
51
+ "astro",
52
+ "block-editor",
53
+ "page-builder",
54
+ "static-site",
55
+ "passkeys",
56
+ "webauthn",
57
+ "cloudflare-workers"
49
58
  ],
50
59
  "repository": {
51
60
  "type": "git",
@@ -57,5 +66,14 @@
57
66
  },
58
67
  "engines": {
59
68
  "node": ">=22.23.4"
60
- }
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "@astrojs/cloudflare": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "bugs": {
76
+ "url": "https://github.com/pirateandfox/pagestack/issues"
77
+ },
78
+ "author": "Pirate & Fox LLC (https://pirateandfox.com)"
61
79
  }
@@ -33,7 +33,7 @@ function drawBar(r: Resolved) {
33
33
  note.textContent = 'Latest saved version';
34
34
  } else if (r.builtAt && r.savedAt && Date.parse(r.savedAt) > Date.parse(r.builtAt)) {
35
35
  note.textContent = `⚠ As of ${when(r.builtAt)}. May not show changes saved since.`;
36
- note.title = 'This page is the copy built into the editor. Changes saved after that show here once the editor is redeployed, and on the public site after Go live.';
36
+ note.title = 'This page is the copy built into the editor. Changes saved after that show here once the editor is redeployed, and on the public site after Publish changes.';
37
37
  note.classList.add('is-stale');
38
38
  } else {
39
39
  note.textContent = '';
@@ -343,12 +343,10 @@ function refreshButtons() {
343
343
  $<HTMLButtonElement>('#ps-redo').disabled = !state.canRedo;
344
344
  const save = $<HTMLButtonElement>('#ps-save');
345
345
  save.disabled = !dirty || saving;
346
- save.textContent = draft ? 'Save draft' : 'Save';
347
- save.classList.toggle('ps-btn--primary', !draft);
348
- save.classList.toggle('ps-btn--ghost', draft);
349
- const publish = $<HTMLButtonElement>('#ps-publish');
350
- publish.hidden = !draft;
351
- publish.disabled = saving;
346
+ const ready = $<HTMLInputElement>('#ps-ready');
347
+ ready.checked = !draft;
348
+ ready.disabled = saving || isHome;
349
+ if (isHome) $('#ps-ready-wrap').title = 'The home page is always published.';
352
350
  $('#ps-discard').hidden = !dirty;
353
351
  $('#ps-view').hidden = draft || boot.page.status === 'draft';
354
352
  $('#ps-draft-pill').hidden = !draft;
@@ -467,7 +465,7 @@ function renderPageTab(root: HTMLElement) {
467
465
  if (button) { const b = document.createElement('button'); b.type = 'button'; b.id = button.id; b.className = 'ps-linkbtn'; b.textContent = button.text; b.disabled = !!button.disabled; b.addEventListener('click', button.run); r.append(b); }
468
466
  summary.append(r);
469
467
  };
470
- row('Status', draft ? 'Draft' : 'Published', draft ? undefined : { text: 'Switch to draft', id: 'ps-unpublish', run: () => publish(false), disabled: isHome });
468
+ row('Status', draft ? 'Draft' : document.getElementById('ps-live') ? 'Ready to publish' : 'Published');
471
469
  row('URL', boot.options.viewUrl, isHome ? undefined : { text: 'Change', id: 'ps-change-url', run: changeUrl });
472
470
  root.append(summary);
473
471
 
@@ -772,7 +770,7 @@ $('#ps-discard').addEventListener('click', async () => {
772
770
  state.reset(r.page, r.hash);
773
771
  });
774
772
  $('#ps-save').addEventListener('click', () => save());
775
- $('#ps-publish').addEventListener('click', () => publish(true));
773
+ $<HTMLInputElement>('#ps-ready').addEventListener('change', (e) => publish((e.target as HTMLInputElement).checked));
776
774
  $('#ps-preview-tab').addEventListener('click', previewInTab);
777
775
  document.querySelectorAll<HTMLButtonElement>('.ps-top__devices button').forEach((b) => b.addEventListener('click', () => {
778
776
  document.querySelectorAll('.ps-top__devices button').forEach((x) => x.classList.remove('is-active'));
@@ -813,7 +811,7 @@ async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; resu
813
811
  state.markSaved(data.hash);
814
812
  boot.page = state.doc;
815
813
  const r = data.result;
816
- if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : document.getElementById('ps-live') ? 'Saved. Use Go live 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 });
814
+ 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 });
817
815
  else toast(`Saved to the working tree (${r.files.join(', ')}). Commit it with git when you're happy.`, 'ok');
818
816
  setSaveStatus('Saved');
819
817
  return data;
@@ -821,14 +819,17 @@ async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; resu
821
819
  finally { saving = false; refreshChrome(); }
822
820
  }
823
821
 
824
- /** Publish a draft, or take a published page back to draft. Saves straight away, like WordPress. */
822
+ /** The Ready to publish switch: a draft or not. Saves straight away, so the switch means what it shows. */
825
823
  async function publish(live: boolean) {
826
- if (!live && !await confirmDialog('Switch to draft', 'This page will be left out of the site the next time it is built.', 'Switch to draft')) return;
824
+ const staged = !!document.getElementById('ps-live');
825
+ // Without a Publish changes step, a draft leaves the site at the next build: ask first.
826
+ if (!live && !staged && !await confirmDialog('Make this a draft?', 'This page will be left out of the site the next time it is built.', 'Make it a draft')) { refreshButtons(); return; }
827
827
  inline.stop(true);
828
828
  const next = structuredClone(state.doc);
829
829
  if (live) delete next.status; else next.status = 'draft';
830
830
  state.apply(next);
831
- if (await save()) toast(live ? `${next.title} is published.` : `${next.title} is now a draft.`, 'ok'); else state.undo();
831
+ 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');
832
+ else { state.undo(); refreshButtons(); }
832
833
  }
833
834
 
834
835
  async function changeUrl() {
@@ -28,6 +28,6 @@ saveBtn.addEventListener('click', async () => {
28
28
  const d = await r.json();
29
29
  if (!r.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; return; }
30
30
  hash = d.hash; dirty = false;
31
- toast(d.result.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Go live 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');
31
+ 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
32
  });
33
33
  window.addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
@@ -18,8 +18,8 @@ const title = $<HTMLInputElement>('ps-item-title');
18
18
  const body = $<HTMLTextAreaElement>('ps-item-body');
19
19
  const preview = $('ps-item-preview');
20
20
  const saveBtn = $<HTMLButtonElement>('ps-item-save');
21
- const publishBtn = $<HTMLButtonElement>('ps-item-publish');
22
- const draftBtn = $<HTMLButtonElement>('ps-item-draft');
21
+ const ready = $<HTMLInputElement>('ps-item-ready');
22
+ const readyWrap = $('ps-item-ready-wrap');
23
23
  const status = $('ps-item-status');
24
24
 
25
25
  const data = structuredClone(boot.data);
@@ -29,12 +29,11 @@ let dirty = false;
29
29
 
30
30
  function chrome() {
31
31
  const draft = hasDraft && data.draft === true;
32
- saveBtn.textContent = !hasDraft ? 'Save' : draft ? 'Save draft' : 'Update';
33
- publishBtn.hidden = !draft;
34
- draftBtn.hidden = !hasDraft || draft;
32
+ readyWrap.hidden = !hasDraft;
33
+ ready.checked = !draft;
35
34
  saveBtn.disabled = !dirty;
36
35
  const view = document.getElementById('ps-item-view'); if (view) view.hidden = draft;
37
- status.textContent = dirty ? 'Unsaved changes' : draft ? 'Draft: not on the site yet' : '';
36
+ status.textContent = dirty ? 'Unsaved changes' : draft ? 'Draft: not on the site' : '';
38
37
  }
39
38
  const touch = () => { dirty = true; chrome(); };
40
39
 
@@ -87,20 +86,27 @@ body.addEventListener('keydown', (e) => {
87
86
  });
88
87
 
89
88
  // ---- saving ----
90
- async function save(): Promise<boolean> {
89
+ async function save(done?: string): Promise<boolean> {
91
90
  if (frame && inline.isActive) inline.stop(true);
92
91
  saveBtn.disabled = true; status.textContent = 'Saving…';
93
92
  const res = await fetch(`/api/editor/collection/${boot.id}/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data, body: body.value, base: hash }) });
94
93
  const d = await res.json();
95
94
  if (!res.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; status.textContent = 'Not saved'; return false; }
96
95
  hash = d.hash; dirty = false; chrome();
97
- toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Go live to put it on the site.' : 'Saved. The site will rebuild.') : 'Saved.', 'ok');
96
+ if (done && !d.result?.pullRequest) toast(done, 'ok'); else toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : 'Saved. The site will rebuild.') : 'Saved.', 'ok');
98
97
  return true;
99
98
  }
100
- saveBtn.addEventListener('click', save);
101
- const setDraft = async (v: boolean) => { const was = data.draft; data.draft = v; if (!await save()) { data.draft = was; chrome(); } };
102
- publishBtn.addEventListener('click', () => setDraft(false));
103
- draftBtn.addEventListener('click', () => setDraft(true));
99
+ saveBtn.addEventListener('click', () => save());
100
+ // The switch saves straight away (with any other unsaved changes), so it means what it shows.
101
+ ready.addEventListener('change', async () => {
102
+ const was = data.draft;
103
+ data.draft = !ready.checked;
104
+ ready.disabled = true;
105
+ const staged = !!document.getElementById('ps-live');
106
+ const ok = await save(ready.checked ? (staged ? 'Ready to publish. It goes on the site with the next Publish changes.' : 'Published. The site will rebuild.') : 'Now a draft: kept off the site.');
107
+ if (!ok) { data.draft = was; chrome(); }
108
+ ready.disabled = false;
109
+ });
104
110
  addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (dirty) save(); } });
105
111
  addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
106
112
 
@@ -1,4 +1,4 @@
1
- // The Go live button, in every screen's top bar. Hidden unless the site has a live branch
1
+ // The Publish changes button (Go live), in every screen's top bar. Hidden unless the site has a live branch
2
2
  // (`github.live`): then saves wait on staging, the button counts them, and one click puts them all
3
3
  // on the public site. It refreshes itself after any save, wherever on the screen that happened.
4
4
  import { dialog, toast } from './ui';
@@ -22,7 +22,7 @@ function draw() {
22
22
  btn.hidden = false;
23
23
  const n = state.count;
24
24
  btn.disabled = n === 0;
25
- btn.textContent = 'Go live';
25
+ btn.textContent = 'Publish changes';
26
26
  if (n) { const b = document.createElement('span'); b.className = 'ps-live__count'; b.textContent = String(n); btn.append(b); }
27
27
  btn.title = n ? `${n} saved change${n === 1 ? '' : 's'} not on the live site yet` : 'Everything saved is on the live site';
28
28
  }
@@ -61,15 +61,15 @@ async function goLive() {
61
61
  a.href = state.stagingUrl; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'See them on the staging site first ↗';
62
62
  p.append(a); body.append(p);
63
63
  }
64
- dialog('Go live?', body, [
64
+ dialog('Publish changes?', body, [
65
65
  { label: 'Cancel' },
66
66
  {
67
- label: 'Go live', kind: 'primary', run: async () => {
67
+ label: 'Publish changes', kind: 'primary', run: async () => {
68
68
  const r = await fetch('/api/editor/live', { method: 'POST', headers: { accept: 'application/json' } });
69
69
  const data = await r.json().catch(() => ({}));
70
- if (!r.ok) { toast(data.error ?? 'Could not go live.', 'error'); return false; }
71
- if (data.nothing) toast('Everything saved was already live.', 'info');
72
- else toast(`Live. ${data.count} change${data.count === 1 ? ' is' : 's are'} on the way to the site; it updates in a few minutes.`, 'ok', { href: data.url });
70
+ if (!r.ok) { toast(data.error ?? 'Could not publish.', 'error'); return false; }
71
+ if (data.nothing) toast('Everything saved was already on the site.', 'info');
72
+ else toast(`Published. ${data.count} change${data.count === 1 ? ' is' : 's are'} on the way to the site; it updates in a few minutes.`, 'ok', { href: data.url });
73
73
  await refresh();
74
74
  },
75
75
  },
@@ -28,7 +28,7 @@ function addPage(copyOf?: string) {
28
28
  <span class="ps-prefixed"><span class="ps-muted">/</span><input type="text" name="slug" autocomplete="off" spellcheck="false" /><span class="ps-muted">/</span></span></label>
29
29
  <p class="ps-error" hidden></p></div>
30
30
  <div class="ps-field"><label>Start from <select name="from"></select></label></div>
31
- <small class="ps-muted">New pages start as drafts. Nothing is public until you press Publish.</small>`;
31
+ <small class="ps-muted">New pages start as drafts. Nothing is public until you turn on ${document.getElementById('ps-live') ? 'Ready to publish' : 'Published'}.</small>`;
32
32
  const title = form.querySelector<HTMLInputElement>('[name=title]')!;
33
33
  const slug = form.querySelector<HTMLInputElement>('[name=slug]')!;
34
34
  const from = form.querySelector<HTMLSelectElement>('[name=from]')!;
@@ -349,3 +349,15 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
349
349
  .ps-browse__where:not(:has(.is-stale)) { display: none; } /* only the warning earns a second line */
350
350
  .ps-browse__path, .ps-browse__out { display: none; }
351
351
  }
352
+
353
+ /* Ready to publish: a switch that saves when flipped */
354
+ .ps-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px; white-space: nowrap; user-select: none; }
355
+ .ps-switch[hidden] { display: none; }
356
+ .ps-switch input { position: absolute; opacity: 0; width: 1px; height: 1px; margin: 0; }
357
+ .ps-switch__track { position: relative; flex: none; width: 34px; height: 20px; border-radius: 10px; background: #9ca3af; transition: background .15s; }
358
+ .ps-switch__track::after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(0 0 0 / .25); transition: transform .15s; }
359
+ .ps-switch input:checked + .ps-switch__track { background: #16a34a; }
360
+ .ps-switch input:checked + .ps-switch__track::after { transform: translateX(14px); }
361
+ .ps-switch input:focus-visible + .ps-switch__track { outline: 2px solid #2563eb; outline-offset: 2px; }
362
+ .ps-switch:has(input:disabled) { cursor: default; opacity: .6; }
363
+ @media (prefers-reduced-motion: reduce) { .ps-switch__track, .ps-switch__track::after { transition: none; } }