@pirateandfox/pagestack 0.1.0-beta.7 → 0.1.0-beta.9

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.
Files changed (53) hide show
  1. package/README.md +85 -12
  2. package/index.mjs +33 -7
  3. package/live.mjs +30 -0
  4. package/package.json +4 -2
  5. package/src/client/auth.ts +5 -5
  6. package/src/client/browse.ts +123 -0
  7. package/src/client/collection.ts +6 -6
  8. package/src/client/editor.ts +105 -105
  9. package/src/client/form.ts +26 -26
  10. package/src/client/global.ts +4 -4
  11. package/src/client/inline.ts +4 -4
  12. package/src/client/inserter.ts +11 -11
  13. package/src/client/invite.ts +4 -4
  14. package/src/client/item.ts +202 -54
  15. package/src/client/live.ts +92 -0
  16. package/src/client/media.ts +12 -12
  17. package/src/client/pages.ts +14 -14
  18. package/src/client/picker.ts +30 -30
  19. package/src/client/preview.css +58 -58
  20. package/src/client/rich.ts +14 -14
  21. package/src/client/shell.css +304 -272
  22. package/src/client/state.ts +2 -2
  23. package/src/client/tomarkdown.ts +4 -2
  24. package/src/client/tree.ts +11 -11
  25. package/src/client/ui.ts +13 -13
  26. package/src/client/users.ts +6 -6
  27. package/src/core/auth.ts +1 -1
  28. package/src/core/markdown.ts +54 -5
  29. package/src/core/pages.ts +7 -3
  30. package/src/core/storage-github.ts +88 -5
  31. package/src/core/storage-local.ts +9 -0
  32. package/src/core/storage.ts +24 -0
  33. package/src/routes/Nav.astro +6 -4
  34. package/src/routes/api/browse.ts +24 -0
  35. package/src/routes/api/collection.ts +30 -8
  36. package/src/routes/api/live.ts +27 -0
  37. package/src/routes/edit-collection.astro +14 -14
  38. package/src/routes/edit-global.astro +8 -8
  39. package/src/routes/edit-index.astro +18 -18
  40. package/src/routes/edit-item.astro +25 -23
  41. package/src/routes/edit-media.astro +9 -9
  42. package/src/routes/edit-page.astro +32 -30
  43. package/src/routes/edit-site.astro +41 -0
  44. package/src/routes/edit-users.astro +9 -9
  45. package/src/routes/enroll.astro +6 -6
  46. package/src/routes/login.astro +6 -6
  47. package/src/routes/preview-item.astro +2 -1
  48. package/src/routes/preview.astro +4 -2
  49. package/src/runtime.ts +3 -3
  50. package/src/server/browse.ts +80 -0
  51. package/src/server/context.ts +7 -3
  52. package/src/server/live.ts +46 -0
  53. package/src/server/middleware.ts +32 -5
package/README.md CHANGED
@@ -4,8 +4,8 @@ A visual editor for Astro sites where pages are a stack of sections. Git-only: s
4
4
  the public site stays static, and nothing lives outside the repo.
5
5
 
6
6
  - The public site stays **fully static**. `astro build` is unchanged.
7
- - The editor (`/edit/*`, `/api/editor/*`) is on-demand rendered and only exists in `astro dev`
8
- or in a build made with `EDITOR=1` (which adds `@astrojs/node`).
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
9
  - Pages are JSON documents in the repo (`src/content/pages/<slug>.json`). Saving writes a file
10
10
  (dev) or makes **one commit** through the GitHub API (production). Nothing is stored anywhere else.
11
11
  - Login is **passkeys** (WebAuthn). Users' public keys live in a committed `editor-users.json`;
@@ -58,7 +58,8 @@ export default defineConfig({
58
58
  ```
59
59
 
60
60
  ```bash
61
- npm run dev # editor at http://localhost:4321/edit, saves to the working tree
61
+ EDITOR=dev astro dev # editor at http://localhost:4321/edit, saves to the working tree
62
+ astro dev # the site alone: no editor, nothing can write content
62
63
  EDITOR=1 astro build # dist/server (node) + dist/client — the editor for a host
63
64
  astro build # plain static site, no editor code
64
65
  ```
@@ -216,10 +217,16 @@ export const globals = {
216
217
  #### Editing a collection item on its own page
217
218
 
218
219
  Give a collection a layout in `previews` (an option on the integration) and its items open on that
219
- page in the editor: click the title, a paragraph or a heading and type; click an image to pick
220
- another; lists, tables and code open the Markdown with that block selected. **Page** and **Markdown**
221
- switch views, and Preview ↗ shows the unsaved item in a tab. An edited paragraph is turned back into
222
- Markdown and replaces only its own lines, so the rest of the file stays byte-for-byte as it was.
220
+ page in the editor: click the title, a paragraph, a heading, a list or a quote and type; click an
221
+ image to pick another; tables, code and nested lists open the Markdown with that block selected. The
222
+ **+** beside a block, or `/` in an empty one, adds a paragraph, heading, list, quote, image or table
223
+ there. **Page** and **Markdown** switch views, and Preview ↗ shows the unsaved item in a tab. An
224
+ edited block is turned back into Markdown and replaces only its own lines, so the rest of the file
225
+ stays byte-for-byte as it was.
226
+
227
+ The ⋮ menu has **Change URL** (moves the file; with the collection's `url` and a redirects file, the
228
+ old address redirects in the same commit), **Revisions** (the file's git history; Restore loads one
229
+ as unsaved changes, covering the body and the fields the editor shows) and **Delete**.
223
230
 
224
231
  ```js
225
232
  pagestack({ /* … */ previews: { blog: './src/editor/PostPreview.astro' } })
@@ -229,7 +236,7 @@ The layout gets `{ item: { id, collection, data, body, html, headings }, editing
229
236
  sanitised body (render it with `set:html`), blocks already marked; `data` is the frontmatter as
230
237
  written, so apply the defaults and date parsing your content schema would. Mark the item's own
231
238
  fields with `itemField(editing, 'title')` from the runtime, or write the same two attributes
232
- (`data-ase-field`, `data-ase-field-type`) yourself. Sharing one component between the real page
239
+ (`data-ps-field`, `data-ps-field-type`) yourself. Sharing one component between the real page
233
240
  and the preview keeps them identical:
234
241
 
235
242
  ```astro
@@ -246,7 +253,12 @@ const { item, editing } = Astro.props;
246
253
  The preview renders on the editor's server (a Worker on Cloudflare), so whatever the layout imports
247
254
  must run there: no `node:fs` reads of the project, no native modules (sharp, resvg), and no import of
248
255
  `content.config.ts` (its loaders only run in a build). `getCollection` works. The page's own scripts
249
- don't run in the editor's frame.
256
+ are left out of the editor's frame.
257
+
258
+ In the block editor's preview, Browse and live list pages, the site's own scripts do run (tabs,
259
+ accordions), but scripts from other origins are refused, so analytics, captchas and chat widgets
260
+ stay out of the editor.
261
+ `previewScripts: 'all'` lifts that for a site whose preview needs an outside script.
250
262
 
251
263
  An image field stored as a bare URL can name its alt-text field, `{ type: 'image', asUrl: true,
252
264
  altField: 'imageAlt' }`, and the picker fills it in.
@@ -254,6 +266,50 @@ altField: 'imageAlt' }`, and the picker fills it in.
254
266
  Blocks can set `category` and `keywords` for the inserter. A `list` field is a repeatable group of
255
267
  `fields`, with `itemLabel` naming the field that titles each row.
256
268
 
269
+ ## Browsing the site
270
+
271
+ **Browse site** in the editor's top bar (`/edit/site`) shows the site as visitors see it, with a
272
+ slim bar on top. Click around as you would on the real site; **Edit this page** opens the editor
273
+ for whatever is showing, and **View on site** in the editor comes back to it. On a deployed editor,
274
+ opening a live page directly (below) lands in Browse too.
275
+
276
+ What each page shows:
277
+
278
+ - **Pages** and **collection items with a `previews` layout**: the latest saved version, through
279
+ their previews. A new item shows before the editor has been rebuilt.
280
+ - **List pages named in `liveRoutes`**: rendered on request from what has been saved (see below).
281
+ - **Anything else**: the copy built into this editor deployment. When something has been saved
282
+ since that build, the bar says so ("As of Nov 12, 4:28 PM. May not show changes saved since.").
283
+
284
+ ### Live list pages (`liveRoutes`)
285
+
286
+ On a deployed editor, list pages (the home page, `/blog/`) are frozen when the editor is built, so a
287
+ new post wouldn't appear in them until the next deploy. Name them in `liveRoutes` and, in the
288
+ editor's build only, they render on request from storage instead:
289
+
290
+ ```js
291
+ pagestack({ liveRoutes: ['/', '/blog'], /* … */ })
292
+ ```
293
+
294
+ The page reads its collections through `liveEntries`, which gives the saved entries on the editor's
295
+ server and `null` everywhere else, so the public build is unchanged and stays fully static:
296
+
297
+ ```ts
298
+ // src/lib/content.ts
299
+ import { getCollection } from 'astro:content';
300
+ import { liveEntries } from '@pirateandfox/pagestack/live';
301
+ import { postSchema } from './schemas'; // the same zod schema content.config.ts uses
302
+
303
+ export const posts = async () => (await liveEntries('posts', postSchema)) ?? (await getCollection('posts'));
304
+ ```
305
+
306
+ The collection name is the editor's collection id. Pass the schema so dates and defaults come out as
307
+ they do at build time; an entry the schema rejects is left out of the list. These pages need to be
308
+ able to render where the editor runs (on Workers: no `node:fs`, and nothing from
309
+ `content.config.ts`, whose loaders only run at build time). On GitHub storage, entries are cached
310
+ until the branch moves, so a list costs one request to GitHub once the first one has warmed up.
311
+ These pages show unpublished work, so they need a signed-in editor.
312
+
257
313
  ## Security
258
314
 
259
315
  Everything an editor sends is treated as untrusted. On save, every field is cleaned by its type,
@@ -275,6 +331,21 @@ than setting a hard limit. Passkeys are what actually stops guessing.
275
331
  | `local` (dev default) | working tree | writes the JSON file (you commit) | written to `public/images/uploads/` |
276
332
  | `github` (build default) | Contents API on `github.branch` | one commit via the Git Data API: blobs → tree → commit → ref; with `pullRequest: true` a new `site-editor/<timestamp>-<sha>` branch + PR instead | wait on a `pagestack-uploads` branch until the next save brings them along; the editor serves them, and anything committed since it was built, to signed-in editors |
277
333
 
334
+ ### Staging and Go live
335
+
336
+ 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;
338
+ it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
339
+ That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
340
+ 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.
342
+
343
+ ```js
344
+ github: { repo: 'acme/site', branch: 'develop', live: 'main', stagingUrl: 'https://develop.acme.pages.dev/' }
345
+ ```
346
+
347
+ Point the host's production deploy at `live` and its preview deploys at the staging branch.
348
+
278
349
  The GitHub token (`GITHUB_TOKEN` or `EDITOR_GITHUB_TOKEN`) is read from the environment on the
279
350
  server only. A fine-grained token with *Contents: write* (and *Pull requests: write* for PR mode)
280
351
  on the one repo is enough. The host that runs the editor rebuilds and deploys from the commit
@@ -287,7 +358,7 @@ like any other push.
287
358
  - `editor-users.json` (committed, path configurable with `usersFile`) holds users and the
288
359
  **public keys** of their passkeys. Nothing in it is secret.
289
360
  - `EDITOR_SECRET` (≥ 16 chars, environment only) signs three kinds of short-lived tokens:
290
- WebAuthn challenges (5 min), the session cookie (`ase_session`, HttpOnly, SameSite=Lax, 12 h) and
361
+ WebAuthn challenges (5 min), the session cookie (`ps_session`, HttpOnly, SameSite=Lax, 12 h) and
291
362
  invite links (3 days). Tokens are `base64url(json).base64url(hmac-sha256)` with the expiry inside,
292
363
  so there is no server state.
293
364
  - **Invites** are single-use: the invite id is recorded on the credential it created. Make the first
@@ -340,8 +411,10 @@ editor response is `noindex` and `no-store`.
340
411
  | `usersFile` | `editor-users.json` | |
341
412
  | `auth` | `passkey` | `passkey` \| `none-behind-proxy` \| `none` |
342
413
  | `storage` | `local` in dev, `github` in build | |
343
- | `github` | — | `{ repo, branch, pullRequest }` |
344
- | `enabled` | dev, or `EDITOR=1` | |
414
+ | `github` | — | `{ repo, branch, live?, stagingUrl?, pullRequest? }`: see Staging and Go live |
415
+ | `liveRoutes` | `[]` | site paths rendered on request in the editor's build, from saved content (see Live list pages) |
416
+ | `previewScripts` | `'site'` | block-editor preview runs the site's own scripts only; `'all'` allows other origins too |
417
+ | `enabled` | `EDITOR=dev` (dev) or `EDITOR=1` | Off otherwise, so plain `astro dev` never writes content |
345
418
  | `siteName`, `secretEnv` | `Site editor`, `EDITOR_SECRET` | |
346
419
  | `reservedSlugs` | `[]` | URLs Add page must refuse, on top of the editor's own and `src/pages` |
347
420
  | `redirectsFile` | `public/_redirects` | Change URL appends here, only if the file exists |
package/index.mjs CHANGED
@@ -4,8 +4,8 @@
4
4
  // integrations: [sectionEditor({ renderer: './src/components/SectionPage.astro', sections: './src/sections/index.ts' })]
5
5
  //
6
6
  // The public site stays fully static. The editor (/edit/*, /api/editor/*) is on-demand rendered
7
- // and only exists when the integration is enabled: always in `astro dev`, and in `astro build`
8
- // when EDITOR=1 (which produces a Node server build with @astrojs/node).
7
+ // and only exists when the integration is enabled: `EDITOR=dev astro dev` (or EDITOR=1) locally, and
8
+ // `EDITOR=1 astro build` for a server build. Plain `astro dev` / `astro build` leave it out.
9
9
  import node from '@astrojs/node';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import fs from 'node:fs';
@@ -32,8 +32,12 @@ const route = (file) => new URL(`./src/routes/${file}`, import.meta.url);
32
32
  * @property {string} [usersFile='editor-users.json'] Passkey users (public keys only).
33
33
  * @property {'none'|'passkey'|'none-behind-proxy'} [auth='passkey']
34
34
  * @property {'local'|'github'} [storage] Defaults: local in dev, github in a build.
35
- * @property {{repo: string, branch?: string, pullRequest?: boolean}} [github]
36
- * @property {boolean} [enabled] Default: dev, or EDITOR=1.
35
+ * @property {{repo: string, branch?: string, pullRequest?: boolean, live?: string, stagingUrl?: string}} [github]
36
+ * `branch` is where saves go. With `live` (the branch the public site builds from), saves stay on
37
+ * `branch` as staging and a Go live button puts them on `live` in one step; `stagingUrl` links to
38
+ * a preview of the staging branch. `pullRequest` opens a PR per save instead.
39
+ * @property {'site'|'all'} [previewScripts='site'] Scripts in the block editor's preview: 'site' runs the site's own and blocks other origins (analytics, captchas, widgets); 'all' allows everything.
40
+ * @property {boolean} [enabled] Default: EDITOR=dev or EDITOR=1 (exact values: $EDITOR is also the shell's text editor). Off otherwise, in dev too.
37
41
  * @property {string} [siteName] Shown in the editor chrome.
38
42
  * @property {string} [interactiveSelector='summary'] Elements in the preview that keep their own click
39
43
  * behaviour (accordion summaries, tab titles, load-map buttons…). Everything else is
@@ -77,16 +81,24 @@ export default function sectionEditor(userOptions) {
77
81
  // integration hook to it (an integration added via updateConfig() doesn't get to call
78
82
  // setAdapter() in time, so we proxy its hooks instead).
79
83
  let adapter = null;
84
+ // Set in astro:config:setup when the editor is on: page files to render on request (liveRoutes).
85
+ let liveComponents = null;
80
86
  const forward = (hook) => async (params) => { if (adapter?.hooks?.[hook]) await adapter.hooks[hook](params); };
81
87
  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)]));
82
88
  return {
83
89
  name: 'pagestack',
84
90
  hooks: {
85
91
  ...forwarded,
92
+ // List pages named in `liveRoutes` render on request on the editor's server, reading what
93
+ // has been saved. Only in the editor build: the public build never gets here.
94
+ 'astro:route:setup': ({ route }) => {
95
+ if (liveComponents?.has(route.component.replace(/\\/g, '/'))) route.prerender = false;
96
+ },
86
97
  'astro:config:setup': async (params) => {
87
98
  const { config, command, injectRoute, updateConfig, addMiddleware, logger } = params;
88
- const enabled = userOptions.enabled ?? (command === 'dev' || process.env.EDITOR === '1');
89
- if (!enabled) { logger.info('disabled (static build). Set EDITOR=1 to build the editor.'); return; }
99
+ const flag = process.env.EDITOR;
100
+ const enabled = userOptions.enabled ?? (flag === '1' || (command === 'dev' && flag === 'dev'));
101
+ 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; }
90
102
  const isBuild = command === 'build';
91
103
  const options = {
92
104
  pagesDir: 'src/content/pages',
@@ -110,10 +122,21 @@ export default function sectionEditor(userOptions) {
110
122
  if (options.storage === 'github' && !options.github?.repo) {
111
123
  throw new Error('pagestack: storage "github" needs github.repo ("owner/name")');
112
124
  }
125
+ if (options.github?.live && options.github.live === (options.github.branch ?? 'main')) {
126
+ throw new Error('pagestack: github.live must differ from github.branch (saves go to branch, Go live moves them to live)');
127
+ }
128
+ if (options.github?.live && options.github.pullRequest) {
129
+ throw new Error('pagestack: use github.live or github.pullRequest, not both');
130
+ }
113
131
  const root = fileURLToPath(config.root);
132
+ const pagesRel = path.relative(root, path.join(fileURLToPath(config.srcDir), 'pages')).replace(/\\/g, '/');
133
+ liveComponents = new Set((options.liveRoutes ?? []).flatMap((r) => {
134
+ const base = r.replace(/^\/|\/$/g, '');
135
+ return base ? [`${pagesRel}/${base}.astro`, `${pagesRel}/${base}/index.astro`] : [`${pagesRel}/index.astro`];
136
+ }));
114
137
  const abs = (p) => path.isAbsolute(p) ? p : path.resolve(root, p);
115
138
  const reservedSlugs = [...new Set([...(options.reservedSlugs ?? []), ...staticRoutes(fileURLToPath(config.srcDir))])];
116
- const serial = { ...options, reservedSlugs, root, renderer: options.renderer ? abs(options.renderer) : null, previews: Object.fromEntries(Object.entries(options.previews ?? {}).map(([k, v]) => [k, abs(v)])), sections: abs(options.sections), command };
139
+ const serial = { ...options, builtAt: Date.now(), reservedSlugs, root, renderer: options.renderer ? abs(options.renderer) : null, previews: Object.fromEntries(Object.entries(options.previews ?? {}).map(([k, v]) => [k, abs(v)])), sections: abs(options.sections), command };
117
140
 
118
141
  updateConfig({
119
142
  vite: {
@@ -160,6 +183,7 @@ export default function sectionEditor(userOptions) {
160
183
  injectRoute({ pattern: '/edit/global/[id]', entrypoint: route('edit-global.astro'), prerender: false });
161
184
  injectRoute({ pattern: '/edit/collection/[id]', entrypoint: route('edit-collection.astro'), prerender: false });
162
185
  injectRoute({ pattern: '/edit/collection/[id]/[...slug]', entrypoint: route('edit-item.astro'), prerender: false });
186
+ injectRoute({ pattern: '/edit/site', entrypoint: route('edit-site.astro'), prerender: false });
163
187
  injectRoute({ pattern: '/edit/media', entrypoint: route('edit-media.astro'), prerender: false });
164
188
  injectRoute({ pattern: '/edit/users', entrypoint: route('edit-users.astro'), prerender: false });
165
189
  injectRoute({ pattern: '/edit/[...slug]', entrypoint: route('edit-page.astro'), prerender: false });
@@ -170,6 +194,8 @@ export default function sectionEditor(userOptions) {
170
194
  injectRoute({ pattern: '/api/editor/images', entrypoint: route('api/images.ts'), prerender: false });
171
195
  injectRoute({ pattern: '/api/editor/collection/[id]/[...slug]', entrypoint: route('api/collection.ts'), prerender: false });
172
196
  injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
197
+ injectRoute({ pattern: '/api/editor/browse', entrypoint: route('api/browse.ts'), prerender: false });
198
+ injectRoute({ pattern: '/api/editor/live', entrypoint: route('api/live.ts'), prerender: false });
173
199
  injectRoute({ pattern: '/api/editor/asset/[...path]', entrypoint: route('api/asset.ts'), prerender: false });
174
200
  injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
175
201
  // Uploads saved after this editor was built aren't static files in it; serve them from the repo.
package/live.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // For host sites whose list pages should show what the editor has saved (the `liveRoutes` option).
2
+ //
3
+ // On the editor's server, for those pages, this returns a collection's entries as stored now (the
4
+ // staging branch). Everywhere else, including the public build and prerendering, it returns null,
5
+ // so the caller uses Astro's own getCollection and the public site is unchanged:
6
+ //
7
+ // import { getCollection } from 'astro:content';
8
+ // import { liveEntries } from '@pirateandfox/pagestack/live';
9
+ // const all = (await liveEntries('articles', articleSchema)) ?? (await getCollection('articles'));
10
+ //
11
+ // Plain JavaScript with no imports, so a public build that never loads the editor can import it.
12
+
13
+ /**
14
+ * @param {string} collection The editor's collection id (normally the Astro collection name).
15
+ * @param {{ parse(data: unknown): any }} [schema] The collection's zod schema, so dates and defaults
16
+ * come out as they do at build time. Without one, `data` is the raw frontmatter.
17
+ * @returns {Promise<{ id: string; collection: string; data: any; body: string; filePath: string }[] | null>}
18
+ */
19
+ export async function liveEntries(collection, schema) {
20
+ const live = /** @type {any} */ (globalThis).__PS_LIVE__;
21
+ if (typeof live !== 'function') return null;
22
+ const entries = await live(collection);
23
+ if (!entries) return null;
24
+ const out = [];
25
+ for (const e of entries) {
26
+ // An item the build would reject is left out rather than taking the list page down.
27
+ try { out.push(schema ? { ...e, data: schema.parse(e.data) } : e); } catch { /* skipped */ }
28
+ }
29
+ return out;
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.7",
3
+ "version": "0.1.0-beta.9",
4
4
  "description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -10,10 +10,12 @@
10
10
  "exports": {
11
11
  ".": "./index.mjs",
12
12
  "./runtime": "./src/runtime.ts",
13
- "./core/*": "./src/core/*.ts"
13
+ "./core/*": "./src/core/*.ts",
14
+ "./live": "./live.mjs"
14
15
  },
15
16
  "files": [
16
17
  "index.mjs",
18
+ "live.mjs",
17
19
  "bin",
18
20
  "src"
19
21
  ],
@@ -1,9 +1,9 @@
1
1
  // Browser side of passkey login / enrolment (login.astro, enroll.astro).
2
2
  import { browserSupportsWebAuthn, startAuthentication, startRegistration } from '@simplewebauthn/browser';
3
3
 
4
- const root = document.querySelector<HTMLElement>('[data-ase-auth]')!;
5
- const go = document.getElementById('ase-auth-go') as HTMLButtonElement | null;
6
- const errEl = document.getElementById('ase-auth-error')!;
4
+ const root = document.querySelector<HTMLElement>('[data-ps-auth]')!;
5
+ const go = document.getElementById('ps-auth-go') as HTMLButtonElement | null;
6
+ const errEl = document.getElementById('ps-auth-error')!;
7
7
  const fail = (msg: string) => { errEl.textContent = msg; errEl.hidden = false; if (go) go.disabled = false; };
8
8
  const post = async (action: string, body: unknown) => {
9
9
  const res = await fetch(`/api/editor/auth/${action}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
@@ -16,7 +16,7 @@ if (!browserSupportsWebAuthn()) fail('This browser does not support passkeys.');
16
16
  else if (go) go.addEventListener('click', async () => {
17
17
  go.disabled = true; errEl.hidden = true;
18
18
  try {
19
- if (root.dataset.aseAuth === 'login') {
19
+ if (root.dataset.psAuth === 'login') {
20
20
  const { options, token } = await post('login-options', {});
21
21
  const response = await startAuthentication({ optionsJSON: options });
22
22
  const { next } = await post('login-verify', { token, response, next: root.dataset.next });
@@ -24,7 +24,7 @@ else if (go) go.addEventListener('click', async () => {
24
24
  } else {
25
25
  const { options, token } = await post('register-options', { invite: root.dataset.invite });
26
26
  const response = await startRegistration({ optionsJSON: options });
27
- const label = (document.getElementById('ase-auth-label') as HTMLInputElement | null)?.value;
27
+ const label = (document.getElementById('ps-auth-label') as HTMLInputElement | null)?.value;
28
28
  await post('register-verify', { token, response, label });
29
29
  location.assign('/edit');
30
30
  }
@@ -0,0 +1,123 @@
1
+ // Browse (/edit/site): keeps the bar in step with the page in the frame.
2
+ //
3
+ // Links inside the frame are caught and sent through /api/editor/browse, so an item opens through
4
+ // its preview (its latest saved version) instead of the copy this editor was built with, and the
5
+ // "Edit this page" button always points at whatever is showing. The address bar tracks the site
6
+ // path (/edit/site?path=…), so Back, Forward and reload work.
7
+ interface Resolved {
8
+ path: string;
9
+ kind: 'page' | 'item' | 'live' | 'snapshot';
10
+ frame: string;
11
+ edit: string | null;
12
+ label?: string;
13
+ builtAt?: string;
14
+ savedAt?: string | null;
15
+ }
16
+
17
+ const frame = document.getElementById('ps-browse-frame') as HTMLIFrameElement;
18
+ const pathEl = document.getElementById('ps-browse-path')!;
19
+ const note = document.getElementById('ps-browse-note')!;
20
+ const edit = document.getElementById('ps-browse-edit') as HTMLAnchorElement;
21
+ let current = (window as any).__PS_BROWSE__ as Resolved;
22
+
23
+ const when = (iso: string) => new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
24
+
25
+ function drawBar(r: Resolved) {
26
+ pathEl.textContent = r.path;
27
+ pathEl.title = r.path;
28
+ edit.hidden = !r.edit;
29
+ if (r.edit) edit.href = r.edit;
30
+ note.classList.remove('is-stale');
31
+ note.title = '';
32
+ if (r.kind === 'page' || r.kind === 'item' || r.kind === 'live') {
33
+ note.textContent = 'Latest saved version';
34
+ } else if (r.builtAt && r.savedAt && Date.parse(r.savedAt) > Date.parse(r.builtAt)) {
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.';
37
+ note.classList.add('is-stale');
38
+ } else {
39
+ note.textContent = '';
40
+ }
41
+ }
42
+
43
+ async function lookup(path: string): Promise<Resolved | null> {
44
+ try {
45
+ const r = await fetch(`/api/editor/browse?path=${encodeURIComponent(path)}`, { headers: { accept: 'application/json' } });
46
+ if (r.status === 401) { location.href = `/edit/login?next=${encodeURIComponent(location.pathname + location.search)}`; return null; }
47
+ return r.ok ? await r.json() : null;
48
+ } catch { return null; }
49
+ }
50
+
51
+ /**
52
+ * Point the frame somewhere without adding to the tab's history: Browse keeps its own entries
53
+ * (one per site page, in the address bar), so Back goes back a page, not back inside the frame.
54
+ */
55
+ function show(url: string) {
56
+ try { frame.contentWindow!.location.replace(url); } catch { frame.src = url; }
57
+ }
58
+
59
+ /** Show a site path: resolve it, point the frame at it, and (unless from history) record it. */
60
+ async function go(path: string, hash = '', push = true) {
61
+ const r = await lookup(path);
62
+ if (!r) { show(path + hash); return; }
63
+ current = r;
64
+ drawBar(r);
65
+ if (push) history.pushState({ path: r.path }, '', `/edit/site?path=${encodeURIComponent(r.path)}`);
66
+ show(r.frame + hash);
67
+ }
68
+
69
+ /** The site path the frame is showing, from its own address. */
70
+ function framePath(): string | null {
71
+ try {
72
+ const loc = frame.contentWindow!.location;
73
+ if (loc.pathname.startsWith('/edit/preview')) return null; // a preview: `current` already says which page
74
+ return loc.pathname;
75
+ } catch { return null; }
76
+ }
77
+
78
+ function isModified(e: MouseEvent) { return e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0; }
79
+
80
+ function wire() {
81
+ let doc: Document;
82
+ try { doc = frame.contentDocument!; } catch { return; }
83
+ if (!doc) return;
84
+ if (doc.title) document.title = doc.title;
85
+ doc.addEventListener('click', (e) => {
86
+ if (e.defaultPrevented || isModified(e)) return;
87
+ const a = (e.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;
88
+ if (!a || a.hasAttribute('download')) return;
89
+ const href = a.getAttribute('href') ?? '';
90
+ if (href.startsWith('#') || /^(mailto|tel|javascript):/i.test(href)) return;
91
+ const url = new URL(a.href, doc.baseURI);
92
+ e.preventDefault();
93
+ if (url.origin !== location.origin) { window.open(url.href, '_blank', 'noopener'); return; }
94
+ if (url.pathname === '/edit' || url.pathname.startsWith('/edit/') || url.pathname.startsWith('/api/')) { location.href = url.href; return; }
95
+ if (a.target === '_blank') { window.open(`/edit/site?path=${encodeURIComponent(url.pathname)}`, '_blank'); return; }
96
+ void go(url.pathname, url.hash);
97
+ });
98
+ }
99
+
100
+ frame.addEventListener('load', () => {
101
+ wire();
102
+ // Got here some other way (a form, a script, a redirect): bring the bar and address up to date.
103
+ const p = framePath();
104
+ if (p && p !== current.path && p.replace(/\/$/, '') !== current.path.replace(/\/$/, '')) {
105
+ void lookup(p).then((r) => {
106
+ if (!r) return;
107
+ current = r;
108
+ drawBar(r);
109
+ history.replaceState({ path: r.path }, '', `/edit/site?path=${encodeURIComponent(r.path)}`);
110
+ if (r.frame !== p) show(r.frame); // an item: show its saved version, not the old copy
111
+ });
112
+ }
113
+ });
114
+
115
+ window.addEventListener('popstate', (e) => {
116
+ const path = (e.state as { path?: string } | null)?.path ?? new URLSearchParams(location.search).get('path') ?? '/';
117
+ void go(path, '', false);
118
+ });
119
+
120
+ history.replaceState({ path: current.path }, '', `/edit/site?path=${encodeURIComponent(current.path)}`);
121
+ drawBar(current);
122
+ // The first resolve came with the page; ask again for the snapshot dates the server left out.
123
+ if (current.kind === 'snapshot') void lookup(current.path).then((r) => { if (r && r.path === current.path) { current = r; drawBar(r); } });
@@ -2,10 +2,10 @@
2
2
  import { slugify, uniqueSlug } from '../core/pages';
3
3
  import { confirmDialog, promptDialog, toast } from './ui';
4
4
 
5
- const boot = (window as any).__ASE_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[] };
5
+ const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[] };
6
6
  const api = `/api/editor/collection/${boot.id}`;
7
7
 
8
- document.getElementById('ase-add-item')?.addEventListener('click', async () => {
8
+ document.getElementById('ps-add-item')?.addEventListener('click', async () => {
9
9
  const title = await promptDialog({ title: `Add ${boot.singular}`, label: 'Title', submit: `Add ${boot.singular}` });
10
10
  if (!title) return;
11
11
  const slug = uniqueSlug(slugify(title) || boot.singular, [...boot.slugs, ...boot.reserved]);
@@ -15,7 +15,7 @@ document.getElementById('ase-add-item')?.addEventListener('click', async () => {
15
15
  location.href = `/edit/collection/${boot.id}/${data.slug}`;
16
16
  });
17
17
 
18
- document.getElementById('ase-pagelist')!.addEventListener('click', async (e) => {
18
+ document.getElementById('ps-pagelist')!.addEventListener('click', async (e) => {
19
19
  const b = (e.target as HTMLElement).closest<HTMLElement>('[data-delete]');
20
20
  if (!b) return;
21
21
  const row = b.closest('li')!;
@@ -28,10 +28,10 @@ document.getElementById('ase-pagelist')!.addEventListener('click', async (e) =>
28
28
  toast(`Deleted ${name}.`, 'ok');
29
29
  });
30
30
 
31
- const search = document.getElementById('ase-page-search') as HTMLInputElement;
31
+ const search = document.getElementById('ps-page-search') as HTMLInputElement;
32
32
  search.addEventListener('input', () => {
33
33
  const q = search.value.trim().toLowerCase();
34
34
  let shown = 0;
35
- document.querySelectorAll<HTMLElement>('#ase-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
36
- document.getElementById('ase-no-match')!.hidden = shown > 0;
35
+ document.querySelectorAll<HTMLElement>('#ps-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
36
+ document.getElementById('ps-no-match')!.hidden = shown > 0;
37
37
  });