@pirateandfox/pagestack 0.1.0-beta.6 → 0.1.0-beta.7
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/README.md +40 -1
- package/index.mjs +23 -2
- package/package.json +1 -1
- package/src/client/form.ts +29 -9
- package/src/client/item.ts +147 -4
- package/src/client/shell.css +8 -1
- package/src/client/tomarkdown.ts +54 -0
- package/src/core/markdown.ts +78 -0
- package/src/core/storage-github.ts +9 -1
- package/src/core/storage-local.ts +1 -0
- package/src/core/storage.ts +5 -0
- package/src/routes/api/asset.ts +2 -2
- package/src/routes/edit-item.astro +11 -0
- package/src/routes/preview-item.astro +33 -0
- package/src/routes/uploaded.ts +26 -0
- package/src/runtime.ts +14 -0
- package/src/server/context.ts +1 -1
- package/src/server/middleware.ts +1 -9
- package/src/server/webauthn.ts +2 -2
- package/src/virtual.d.ts +1 -0
package/README.md
CHANGED
|
@@ -213,6 +213,44 @@ export const globals = {
|
|
|
213
213
|
};
|
|
214
214
|
```
|
|
215
215
|
|
|
216
|
+
#### Editing a collection item on its own page
|
|
217
|
+
|
|
218
|
+
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.
|
|
223
|
+
|
|
224
|
+
```js
|
|
225
|
+
pagestack({ /* … */ previews: { blog: './src/editor/PostPreview.astro' } })
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
The layout gets `{ item: { id, collection, data, body, html, headings }, editing }`. `html` is the
|
|
229
|
+
sanitised body (render it with `set:html`), blocks already marked; `data` is the frontmatter as
|
|
230
|
+
written, so apply the defaults and date parsing your content schema would. Mark the item's own
|
|
231
|
+
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
|
|
233
|
+
and the preview keeps them identical:
|
|
234
|
+
|
|
235
|
+
```astro
|
|
236
|
+
---
|
|
237
|
+
// src/editor/PostPreview.astro
|
|
238
|
+
import PostPage from '../components/PostPage.astro';
|
|
239
|
+
const { item, editing } = Astro.props;
|
|
240
|
+
---
|
|
241
|
+
<PostPage data={{ ...item.data, date: new Date(item.data.date) }} headings={item.headings} editing={editing}>
|
|
242
|
+
<Fragment set:html={item.html} />
|
|
243
|
+
</PostPage>
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
The preview renders on the editor's server (a Worker on Cloudflare), so whatever the layout imports
|
|
247
|
+
must run there: no `node:fs` reads of the project, no native modules (sharp, resvg), and no import of
|
|
248
|
+
`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.
|
|
250
|
+
|
|
251
|
+
An image field stored as a bare URL can name its alt-text field, `{ type: 'image', asUrl: true,
|
|
252
|
+
altField: 'imageAlt' }`, and the picker fills it in.
|
|
253
|
+
|
|
216
254
|
Blocks can set `category` and `keywords` for the inserter. A `list` field is a repeatable group of
|
|
217
255
|
`fields`, with `itemLabel` naming the field that titles each row.
|
|
218
256
|
|
|
@@ -235,7 +273,7 @@ than setting a hard limit. Passkeys are what actually stops guessing.
|
|
|
235
273
|
| `storage` | Reads | Saves | Uploads |
|
|
236
274
|
|---|---|---|---|
|
|
237
275
|
| `local` (dev default) | working tree | writes the JSON file (you commit) | written to `public/images/uploads/` |
|
|
238
|
-
| `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
|
|
276
|
+
| `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 |
|
|
239
277
|
|
|
240
278
|
The GitHub token (`GITHUB_TOKEN` or `EDITOR_GITHUB_TOKEN`) is read from the environment on the
|
|
241
279
|
server only. A fine-grained token with *Contents: write* (and *Pull requests: write* for PR mode)
|
|
@@ -295,6 +333,7 @@ editor response is `noindex` and `no-store`.
|
|
|
295
333
|
|---|---|---|
|
|
296
334
|
| `renderer` | required, unless `pages: false` | Astro component rendering `{ page, editing }` |
|
|
297
335
|
| `pages` | `true` | `false` for a site with no block pages: only collections, globals and media |
|
|
336
|
+
| `previews` | `{}` | per collection id, an Astro layout for editing items on their page (see above) |
|
|
298
337
|
| `sections` | required | module exporting `{ schemas, presets }` |
|
|
299
338
|
| `pagesDir` | `src/content/pages` | |
|
|
300
339
|
| `imagesDir` / `uploadsDir` / `publicDir` | `public/images` / `public/images/uploads` / `public` | |
|
package/index.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import path from 'node:path';
|
|
|
13
13
|
|
|
14
14
|
const VIRTUAL = 'virtual:pagestack/site';
|
|
15
15
|
const VIRTUAL_RENDERER = 'virtual:pagestack/renderer';
|
|
16
|
+
const VIRTUAL_PREVIEWS = 'virtual:pagestack/previews';
|
|
16
17
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
17
18
|
const route = (file) => new URL(`./src/routes/${file}`, import.meta.url);
|
|
18
19
|
|
|
@@ -20,6 +21,9 @@ const route = (file) => new URL(`./src/routes/${file}`, import.meta.url);
|
|
|
20
21
|
* @typedef {object} SectionEditorOptions
|
|
21
22
|
* @property {string} [renderer] Astro component rendering a page: props { page, editing }. Required unless `pages: false`.
|
|
22
23
|
* @property {boolean} [pages] false for a site with no block pages: only collections, globals and media.
|
|
24
|
+
* @property {Record<string, string>} [previews] Per collection id, an Astro component that lays out one item
|
|
25
|
+
* the way the site does: props { item: { id, collection, data, body, html, headings }, editing }.
|
|
26
|
+
* With one, the item opens on its page and its text is edited in place.
|
|
23
27
|
* @property {string} sections Module exporting { schemas, presets } (see runtime.ts types).
|
|
24
28
|
* @property {string} [pagesDir='src/content/pages'] Directory of <slug>.json pages.
|
|
25
29
|
* @property {string} [imagesDir='public/images'] Browsable image library root.
|
|
@@ -49,6 +53,14 @@ const route = (file) => new URL(`./src/routes/${file}`, import.meta.url);
|
|
|
49
53
|
*/
|
|
50
54
|
|
|
51
55
|
/** Top-level URLs taken by the host's own route files (dynamic ones can't be known here). */
|
|
56
|
+
/** URL prefix of the uploads folder ('/images/uploads'), or null when uploads aren't public files or would be a site-wide catch-all. */
|
|
57
|
+
export function uploadsUrlPrefix(uploadsDir, publicDir) {
|
|
58
|
+
const up = uploadsDir.replace(/\\/g, '/').replace(/\/+$/, ''), pub = publicDir.replace(/\\/g, '/').replace(/\/+$/, '');
|
|
59
|
+
if (!up.startsWith(pub + '/')) return null;
|
|
60
|
+
const rest = up.slice(pub.length + 1);
|
|
61
|
+
return rest && !rest.split('/').some((s) => s === '..' || s === '.' || /[[\]]/.test(s)) ? '/' + rest : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
52
64
|
function staticRoutes(srcDir) {
|
|
53
65
|
try {
|
|
54
66
|
return fs.readdirSync(path.join(srcDir, 'pages'), { withFileTypes: true })
|
|
@@ -101,17 +113,22 @@ export default function sectionEditor(userOptions) {
|
|
|
101
113
|
const root = fileURLToPath(config.root);
|
|
102
114
|
const abs = (p) => path.isAbsolute(p) ? p : path.resolve(root, p);
|
|
103
115
|
const reservedSlugs = [...new Set([...(options.reservedSlugs ?? []), ...staticRoutes(fileURLToPath(config.srcDir))])];
|
|
104
|
-
const serial = { ...options, reservedSlugs, root, renderer: options.renderer ? abs(options.renderer) : null, sections: abs(options.sections), command };
|
|
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 };
|
|
105
117
|
|
|
106
118
|
updateConfig({
|
|
107
119
|
vite: {
|
|
108
120
|
plugins: [{
|
|
109
121
|
name: 'pagestack:virtual',
|
|
110
|
-
resolveId(id) { if (id === VIRTUAL || id === VIRTUAL_RENDERER) return '\0' + id; },
|
|
122
|
+
resolveId(id) { if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id; },
|
|
111
123
|
load(id) {
|
|
112
124
|
// The renderer (and the site layout/CSS behind it) is only imported by the preview
|
|
113
125
|
// route, so the editor shell doesn't drag the whole site's CSS into its page.
|
|
114
126
|
if (id === '\0' + VIRTUAL_RENDERER) return serial.renderer ? `export { default as Renderer } from ${JSON.stringify(serial.renderer)};` : 'export const Renderer = null;';
|
|
127
|
+
// Item layouts, like the renderer, load only on the route that shows them.
|
|
128
|
+
if (id === '\0' + VIRTUAL_PREVIEWS) {
|
|
129
|
+
const entries = Object.entries(serial.previews);
|
|
130
|
+
return [...entries.map(([, file], i) => `import P${i} from ${JSON.stringify(file)};`), `export const previews = { ${entries.map(([k], i) => `${JSON.stringify(k)}: P${i}`).join(', ')} };`].join('\n');
|
|
131
|
+
}
|
|
115
132
|
if (id !== '\0' + VIRTUAL) return;
|
|
116
133
|
return [
|
|
117
134
|
`export * as site from ${JSON.stringify(serial.sections)};`,
|
|
@@ -139,6 +156,7 @@ export default function sectionEditor(userOptions) {
|
|
|
139
156
|
injectRoute({ pattern: '/edit/login', entrypoint: route('login.astro'), prerender: false });
|
|
140
157
|
injectRoute({ pattern: '/edit/enroll', entrypoint: route('enroll.astro'), prerender: false });
|
|
141
158
|
injectRoute({ pattern: '/edit/preview/[...slug]', entrypoint: route('preview.astro'), prerender: false });
|
|
159
|
+
injectRoute({ pattern: '/edit/preview-item/[id]/[...slug]', entrypoint: route('preview-item.astro'), prerender: false });
|
|
142
160
|
injectRoute({ pattern: '/edit/global/[id]', entrypoint: route('edit-global.astro'), prerender: false });
|
|
143
161
|
injectRoute({ pattern: '/edit/collection/[id]', entrypoint: route('edit-collection.astro'), prerender: false });
|
|
144
162
|
injectRoute({ pattern: '/edit/collection/[id]/[...slug]', entrypoint: route('edit-item.astro'), prerender: false });
|
|
@@ -154,6 +172,9 @@ export default function sectionEditor(userOptions) {
|
|
|
154
172
|
injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
|
|
155
173
|
injectRoute({ pattern: '/api/editor/asset/[...path]', entrypoint: route('api/asset.ts'), prerender: false });
|
|
156
174
|
injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
|
|
175
|
+
// Uploads saved after this editor was built aren't static files in it; serve them from the repo.
|
|
176
|
+
const uploadsUrl = options.storage === 'github' && uploadsUrlPrefix(options.uploadsDir, options.publicDir);
|
|
177
|
+
if (uploadsUrl) injectRoute({ pattern: `${uploadsUrl}/[...path]`, entrypoint: route('uploaded.ts'), prerender: false });
|
|
157
178
|
logger.info(`enabled — storage: ${options.storage}, auth: ${options.auth}. Open /edit`);
|
|
158
179
|
},
|
|
159
180
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pirateandfox/pagestack",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.7",
|
|
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",
|
package/src/client/form.ts
CHANGED
|
@@ -118,15 +118,35 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
|
|
|
118
118
|
}
|
|
119
119
|
case 'image': {
|
|
120
120
|
// `asUrl` fields hold a bare URL (social images, menu pictures); the widget is the same.
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
121
|
+
// It redraws itself: not every caller re-renders the form after a change.
|
|
122
|
+
const box = el('div', { class: 'ase-field__image' });
|
|
123
|
+
const sibling = () => { if (!field.asUrl || !field.altField) return null; let top: HTMLElement = box; while (top.parentElement) top = top.parentElement; return top.querySelector<HTMLInputElement>(`#${CSS.escape(idPrefix + field.altField)}`); };
|
|
124
|
+
const draw = (img: ImageValue) => {
|
|
125
|
+
const put = (v: ImageValue) => {
|
|
126
|
+
cb.onChange(name, field.asUrl ? v.src : v);
|
|
127
|
+
// The picker always asks for alt text; with a bare URL it belongs in the sibling field.
|
|
128
|
+
if (field.asUrl && field.altField && v.src) {
|
|
129
|
+
cb.onChange(field.altField, v.alt);
|
|
130
|
+
const sib = sibling();
|
|
131
|
+
if (sib) sib.value = v.alt;
|
|
132
|
+
}
|
|
133
|
+
draw(v);
|
|
134
|
+
};
|
|
135
|
+
const thumb = el('div', { class: 'ase-thumb' }, img.src ? el('img', { src: img.src, alt: '' }) : el('span', { class: 'ase-muted' }, 'No image'));
|
|
136
|
+
const alt = el('input', { type: 'text', value: img.alt ?? '', placeholder: 'Alt text (describe the image)', 'aria-label': 'Alt text' }) as HTMLInputElement;
|
|
137
|
+
alt.addEventListener('change', () => { img = { ...img, alt: alt.value }; cb.onChange(name, img); });
|
|
138
|
+
const current = (): ImageValue | undefined => {
|
|
139
|
+
if (!img.src) return undefined;
|
|
140
|
+
const sib = sibling();
|
|
141
|
+
return sib ? { ...img, alt: sib.value } : img;
|
|
142
|
+
};
|
|
143
|
+
const choose = el('button', { type: 'button', class: 'ase-btn ase-btn--small', onclick: () => cb.pickImage(current(), put) }, img.src ? 'Replace…' : 'Choose…');
|
|
144
|
+
const clear = el('button', { type: 'button', class: 'ase-btn ase-btn--small ase-btn--ghost', onclick: () => put({ src: '', alt: '' }) }, 'Remove');
|
|
145
|
+
box.replaceChildren(thumb, el('div', { class: 'ase-row' }, choose, img.src ? clear : null));
|
|
146
|
+
if (img.src) box.append(...(field.asUrl ? [] : [alt]), el('small', { class: 'ase-muted ase-ellipsis', title: img.src }, img.src));
|
|
147
|
+
};
|
|
148
|
+
draw(field.asUrl ? { src: (value as string) ?? '', alt: '' } : ((value as ImageValue) ?? { src: '', alt: '' }));
|
|
149
|
+
wrap.append(box);
|
|
130
150
|
break;
|
|
131
151
|
}
|
|
132
152
|
case 'svg': {
|
package/src/client/item.ts
CHANGED
|
@@ -5,8 +5,12 @@ import { sanitizeHtml } from '../core/sanitize';
|
|
|
5
5
|
import { renderForm } from './form';
|
|
6
6
|
import { pickImage } from './picker';
|
|
7
7
|
import { promptDialog, toast } from './ui';
|
|
8
|
+
import { InlineEditor } from './inline';
|
|
9
|
+
import { blockAt, replaceBlock } from '../core/markdown';
|
|
10
|
+
import { blockToMarkdown } from './tomarkdown';
|
|
11
|
+
import previewCss from './preview.css?raw';
|
|
8
12
|
|
|
9
|
-
interface Boot { id: string; slug: string; singular: string; fields: Record<string, Field>; data: Record<string, any>; body: string; hash: string; viewUrl: string | null; pages: { title: string; url: string }[] }
|
|
13
|
+
interface Boot { id: string; slug: string; singular: string; fields: Record<string, Field>; data: Record<string, any>; body: string; hash: string; viewUrl: string | null; preview: boolean; pages: { title: string; url: string }[] }
|
|
10
14
|
const boot = (window as any).__ASE_ITEM__ as Boot;
|
|
11
15
|
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
|
|
12
16
|
const title = $<HTMLInputElement>('ase-item-title');
|
|
@@ -73,7 +77,7 @@ for (const [label, text, run] of tools) {
|
|
|
73
77
|
b.addEventListener('click', run);
|
|
74
78
|
$('ase-mdbar').append(b);
|
|
75
79
|
}
|
|
76
|
-
function changed() { draw(); touch(); }
|
|
80
|
+
function changed() { draw(); touch(); schedulePage(); }
|
|
77
81
|
body.addEventListener('input', changed);
|
|
78
82
|
body.addEventListener('keydown', (e) => {
|
|
79
83
|
if (!(e.metaKey || e.ctrlKey)) return;
|
|
@@ -83,6 +87,7 @@ body.addEventListener('keydown', (e) => {
|
|
|
83
87
|
|
|
84
88
|
// ---- saving ----
|
|
85
89
|
async function save(): Promise<boolean> {
|
|
90
|
+
if (frame && inline.isActive) inline.stop(true);
|
|
86
91
|
saveBtn.disabled = true; status.textContent = 'Saving…';
|
|
87
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 }) });
|
|
88
93
|
const d = await res.json();
|
|
@@ -100,8 +105,146 @@ addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
|
|
|
100
105
|
|
|
101
106
|
// ---- start ----
|
|
102
107
|
title.value = data.title ?? '';
|
|
103
|
-
title.addEventListener('input', () => { data.title = title.value; touch(); });
|
|
108
|
+
title.addEventListener('input', () => { data.title = title.value; touch(); schedulePage(); });
|
|
104
109
|
body.value = boot.body;
|
|
105
110
|
const { title: _, draft: __, ...side } = boot.fields;
|
|
106
|
-
renderForm($('ase-item-form'), { label: boot.singular, fields: side }, data, { pickImage, pageUrls: boot.pages, onChange: (name, value) => { data[name] = value; touch(); } });
|
|
111
|
+
const drawForm = () => renderForm($('ase-item-form'), { label: boot.singular, fields: side }, data, { pickImage, pageUrls: boot.pages, onChange: (name, value) => { data[name] = value; touch(); schedulePage(); } });
|
|
112
|
+
drawForm();
|
|
107
113
|
draw(); chrome();
|
|
114
|
+
|
|
115
|
+
// ---- page mode: the item on its own layout, edited in place ----
|
|
116
|
+
// The site's `previews` component renders it; body blocks carry data-ase-md="<index>", and an
|
|
117
|
+
// edited paragraph or heading is turned back into Markdown and replaces only its own source.
|
|
118
|
+
const frame = document.getElementById('ase-item-frame') as HTMLIFrameElement | null;
|
|
119
|
+
const pageBox = document.getElementById('ase-item-page');
|
|
120
|
+
const previewUrl = `/edit/preview-item/${boot.id}/${boot.slug}`;
|
|
121
|
+
let mode: 'page' | 'markdown' = 'markdown';
|
|
122
|
+
let frameReady = false;
|
|
123
|
+
let pageTimer: ReturnType<typeof setTimeout> | undefined;
|
|
124
|
+
let pageSeq = 0;
|
|
125
|
+
let pageQueued = false;
|
|
126
|
+
let editingBlock: { el: HTMLElement; index: number; depth?: number } | null = null;
|
|
127
|
+
const fdoc = () => frame!.contentDocument!;
|
|
128
|
+
|
|
129
|
+
function setMode(m: 'page' | 'markdown') {
|
|
130
|
+
if (!frame) return;
|
|
131
|
+
if (inline.isActive) inline.stop(true);
|
|
132
|
+
mode = m;
|
|
133
|
+
pageBox!.hidden = m !== 'page';
|
|
134
|
+
$('ase-item-md').hidden = m === 'page';
|
|
135
|
+
document.querySelectorAll<HTMLElement>('.ase-seg__btn').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.mode === m)));
|
|
136
|
+
try { localStorage.setItem('ase-item-mode', m); } catch { /* private mode */ }
|
|
137
|
+
if (m === 'page') { if (!frame.src) frame.src = previewUrl; else if (frameReady) renderPage(); }
|
|
138
|
+
}
|
|
139
|
+
function schedulePage(ms = 300) { if (frame && mode === 'page') { clearTimeout(pageTimer); pageTimer = setTimeout(renderPage, ms); } }
|
|
140
|
+
|
|
141
|
+
async function renderPage() {
|
|
142
|
+
if (!frameReady) return;
|
|
143
|
+
if (inline.isActive) { pageQueued = true; return; } // never swap the text under the cursor
|
|
144
|
+
const seq = ++pageSeq;
|
|
145
|
+
const res = await fetch(previewUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data, body: body.value }) }).catch(() => null);
|
|
146
|
+
if (!res || seq !== pageSeq) return;
|
|
147
|
+
const html = await res.text();
|
|
148
|
+
if (!res.ok) { toast(`Preview failed: ${html.slice(0, 160)}`, 'error'); return; }
|
|
149
|
+
if (inline.isActive) { pageQueued = true; return; }
|
|
150
|
+
const fresh = new DOMParser().parseFromString(html, 'text/html');
|
|
151
|
+
const win = frame!.contentWindow!; const y = win.scrollY;
|
|
152
|
+
fdoc().body.innerHTML = fresh.body.innerHTML;
|
|
153
|
+
fdoc().body.className = fresh.body.className;
|
|
154
|
+
win.scrollTo(0, y);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const inline = new InlineEditor({
|
|
158
|
+
pages: boot.pages,
|
|
159
|
+
onStart: () => {},
|
|
160
|
+
onInput: () => {},
|
|
161
|
+
onCommit: (path, value, didChange) => {
|
|
162
|
+
const blk = editingBlock; editingBlock = null;
|
|
163
|
+
if (didChange) {
|
|
164
|
+
if (blk) {
|
|
165
|
+
const md = blockToMarkdown(blk.el, blk.depth);
|
|
166
|
+
body.value = md ? replaceBlock(body.value, blk.index, md) : removeBlock(body.value, blk.index);
|
|
167
|
+
} else {
|
|
168
|
+
data[path] = value;
|
|
169
|
+
if (path === 'title') title.value = value;
|
|
170
|
+
else drawForm();
|
|
171
|
+
}
|
|
172
|
+
draw(); touch();
|
|
173
|
+
}
|
|
174
|
+
if (didChange || pageQueued) { pageQueued = false; schedulePage(0); }
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
const removeBlock = (md: string, i: number) => { const b = blockAt(md, i); return b ? md.slice(0, b.start) + md.slice(b.end) : md; };
|
|
178
|
+
|
|
179
|
+
function onFrameClick(e: MouseEvent) {
|
|
180
|
+
const t = e.target as HTMLElement;
|
|
181
|
+
if (t.closest('.ase-rt, .ase-link, [data-ase-ui]')) return;
|
|
182
|
+
if (!t.closest('summary')) e.preventDefault(); // links don't navigate while editing
|
|
183
|
+
const field = t.closest<HTMLElement>('[data-ase-field]');
|
|
184
|
+
const blockEl = t.closest<HTMLElement>('[data-ase-md]');
|
|
185
|
+
if (field && !field.dataset.aseField!.startsWith('md:')) {
|
|
186
|
+
const name = field.dataset.aseField!;
|
|
187
|
+
if (field.dataset.aseFieldType === 'image') {
|
|
188
|
+
const f = boot.fields[name];
|
|
189
|
+
const cur = data[name];
|
|
190
|
+
pickImage(cur ? (typeof cur === 'string' ? { src: cur, alt: f?.altField ? data[f.altField] ?? '' : '' } : cur) : undefined, (img) => {
|
|
191
|
+
data[name] = f?.asUrl ? img.src : img;
|
|
192
|
+
if (f?.asUrl && f.altField) data[f.altField] = img.alt;
|
|
193
|
+
drawForm(); touch(); schedulePage(0);
|
|
194
|
+
});
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (inline.activePath !== name) inline.start(field);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (blockEl) {
|
|
201
|
+
const index = Number(blockEl.dataset.aseMd);
|
|
202
|
+
const kind = blockEl.dataset.aseMdKind;
|
|
203
|
+
if (kind === 'text') {
|
|
204
|
+
if (editingBlock?.el === blockEl) return;
|
|
205
|
+
if (inline.isActive) inline.stop(true);
|
|
206
|
+
const src = blockAt(body.value, index);
|
|
207
|
+
editingBlock = { el: blockEl, index, depth: src?.type === 'heading' ? src.depth : undefined };
|
|
208
|
+
blockEl.dataset.aseField = `md:${index}`; blockEl.dataset.aseFieldType = 'richtext';
|
|
209
|
+
inline.start(blockEl);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (inline.isActive) inline.stop(true);
|
|
213
|
+
if (kind === 'image') {
|
|
214
|
+
const m = blockAt(body.value, index)?.raw.match(/!\[([^\]]*)\]\(([^)\s]+)/);
|
|
215
|
+
pickImage(m ? { src: m[2], alt: m[1] } : undefined, (img) => { body.value = replaceBlock(body.value, index, `![${img.alt.replace(/[[\]]/g, '')}](${img.src})`); changed(); });
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
// Lists, tables, code: edit their Markdown, with the block selected.
|
|
219
|
+
const b = blockAt(body.value, index);
|
|
220
|
+
setMode('markdown');
|
|
221
|
+
if (b) { body.focus(); body.setSelectionRange(b.start, b.start + b.raw.trimEnd().length); }
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (inline.isActive) inline.stop(true);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (frame) {
|
|
228
|
+
frame.addEventListener('load', () => {
|
|
229
|
+
const d = fdoc();
|
|
230
|
+
const style = d.createElement('style'); style.textContent = previewCss + '[data-ase-md]{cursor:text}[data-ase-md]:hover{outline:1px dotted #2563eb;outline-offset:2px}[data-ase-md-kind="block"],[data-ase-md-kind="image"]{cursor:pointer}';
|
|
231
|
+
d.head.append(style);
|
|
232
|
+
d.addEventListener('click', onFrameClick, true);
|
|
233
|
+
d.addEventListener('submit', (e) => e.preventDefault(), true);
|
|
234
|
+
d.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (inline.isActive) inline.stop(true); if (dirty) save(); } });
|
|
235
|
+
frameReady = true;
|
|
236
|
+
if (dirty) renderPage();
|
|
237
|
+
});
|
|
238
|
+
document.querySelectorAll<HTMLElement>('.ase-seg__btn').forEach((b) => b.addEventListener('click', () => setMode(b.dataset.mode as 'page' | 'markdown')));
|
|
239
|
+
let saved: string | null = null;
|
|
240
|
+
try { saved = localStorage.getItem('ase-item-mode'); } catch { /* private mode */ }
|
|
241
|
+
setMode(saved === 'markdown' ? 'markdown' : 'page');
|
|
242
|
+
// A look at the unsaved item as visitors will see it, in its own tab.
|
|
243
|
+
document.getElementById('ase-item-tab')?.addEventListener('click', () => {
|
|
244
|
+
if (inline.isActive) inline.stop(true);
|
|
245
|
+
const form = document.createElement('form');
|
|
246
|
+
form.method = 'POST'; form.action = previewUrl; form.target = '_blank'; form.hidden = true;
|
|
247
|
+
const input = document.createElement('input'); input.type = 'hidden'; input.name = 'item'; input.value = JSON.stringify({ data, body: body.value });
|
|
248
|
+
form.append(input); document.body.append(form); form.submit(); form.remove();
|
|
249
|
+
});
|
|
250
|
+
}
|
package/src/client/shell.css
CHANGED
|
@@ -296,7 +296,14 @@ body.ase[data-left="add"] .ase-listview, body:not([data-left="add"]) .ase-insert
|
|
|
296
296
|
.ase-item__grid { display: grid; grid-template-columns: minmax(0, 1fr) 300px; }
|
|
297
297
|
.ase-item__grid > main { padding: 20px; min-width: 0; }
|
|
298
298
|
.ase-item__side { padding: 16px; background: #fff; border-left: 1px solid var(--ase-border); min-height: calc(100vh - 100px); }
|
|
299
|
-
.ase-item__title { width: 100%; box-sizing: border-box; border: 0; background: none; font: 600 28px
|
|
299
|
+
.ase-item__title { width: 100%; box-sizing: border-box; border: 0; background: none; font-family: inherit; font-weight: 600; font-size: 28px; line-height: 1.25; color: inherit; padding: 4px 0 12px; outline: none; }
|
|
300
|
+
.ase-item__page { height: calc(100vh - 140px); min-height: 420px; border: 1px solid var(--ase-border); border-radius: 6px; overflow: hidden; background: #fff; }
|
|
301
|
+
.ase-item__page iframe { width: 100%; height: 100%; border: 0; display: block; }
|
|
302
|
+
.ase-item__grid > main:has(> .ase-item__page:not([hidden])) { padding: 12px; }
|
|
303
|
+
.ase-seg { display: inline-flex; border: 1px solid var(--ase-border); border-radius: 6px; overflow: hidden; }
|
|
304
|
+
.ase-seg__btn { all: unset; cursor: pointer; padding: 5px 12px; font-size: 13px; color: inherit; }
|
|
305
|
+
.ase-seg__btn[aria-pressed="true"] { background: #1f2937; color: #fff; }
|
|
306
|
+
.ase-seg__btn:focus-visible { outline: 2px solid #2563eb; outline-offset: -2px; }
|
|
300
307
|
.ase-mdbar { display: flex; flex-wrap: wrap; gap: 2px; padding: 4px; background: #fff; border: 1px solid var(--ase-border); border-bottom: 0; border-radius: 6px 6px 0 0; }
|
|
301
308
|
.ase-mdsplit { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); height: calc(100vh - 240px); min-height: 360px; border: 1px solid var(--ase-border); border-radius: 0 0 6px 6px; background: #fff; }
|
|
302
309
|
.ase-mdsplit textarea { border: 0; border-right: 1px solid var(--ase-border); padding: 14px; font: 14px/1.6 ui-monospace, Menlo, monospace; resize: none; outline: none; background: none; }
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The HTML of one edited block back to Markdown. Only what the inline toolbar can produce has a
|
|
2
|
+
// Markdown form (bold, italic, links, code, strike, line breaks); anything else keeps its HTML,
|
|
3
|
+
// which Markdown allows inline. Paragraphs a browser made on Enter become separate paragraphs.
|
|
4
|
+
const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/([*_`[\]<])/g, '\\$1');
|
|
5
|
+
const BLOCK = new Set(['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'BLOCKQUOTE', 'UL', 'OL', 'LI']);
|
|
6
|
+
|
|
7
|
+
function inline(node: Node): string {
|
|
8
|
+
if (node.nodeType === 3) return esc((node.textContent ?? '').replace(/ /g, ' '));
|
|
9
|
+
if (node.nodeType !== 1) return '';
|
|
10
|
+
const el = node as HTMLElement;
|
|
11
|
+
const kids = () => [...el.childNodes].map(inline).join('');
|
|
12
|
+
const wrapIn = (mark: string) => { const inner = kids(); const m = inner.match(/^(\s*)([\s\S]*?)(\s*)$/)!; return m[2] ? `${m[1]}${mark}${m[2]}${mark}${m[3]}` : inner; };
|
|
13
|
+
switch (el.tagName) {
|
|
14
|
+
case 'STRONG': case 'B': return wrapIn('**');
|
|
15
|
+
case 'EM': case 'I': return wrapIn('*');
|
|
16
|
+
case 'S': case 'DEL': case 'STRIKE': return wrapIn('~~');
|
|
17
|
+
case 'CODE': return '`' + (el.textContent ?? '').replace(/`/g, '\\`') + '`';
|
|
18
|
+
case 'BR': return ' \n';
|
|
19
|
+
case 'A': {
|
|
20
|
+
const href = el.getAttribute('href') ?? '';
|
|
21
|
+
const title = el.getAttribute('title');
|
|
22
|
+
const target = el.getAttribute('target');
|
|
23
|
+
if (target) return el.outerHTML; // Markdown links can't say "new tab"
|
|
24
|
+
return `[${kids()}](${href.replace(/[ )]/g, (c) => encodeURIComponent(c))}${title ? ` "${title.replace(/"/g, '\\"')}"` : ''})`;
|
|
25
|
+
}
|
|
26
|
+
case 'IMG': return ` ?? ''})`;
|
|
27
|
+
case 'SPAN': case 'FONT': return kids();
|
|
28
|
+
default: return BLOCK.has(el.tagName) ? kids() : `<${el.tagName.toLowerCase()}>${kids()}</${el.tagName.toLowerCase()}>`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Markdown for an edited paragraph or heading. `depth` makes its own text a heading of that level. */
|
|
33
|
+
export function blockToMarkdown(el: HTMLElement, depth?: number): string {
|
|
34
|
+
const out: string[] = [];
|
|
35
|
+
const text = (nodes: Node[]) => nodes.map(inline).join('').replace(/ {2}\n$/, '').trim();
|
|
36
|
+
const head = (n: number, t: string) => `${'#'.repeat(n)} ${t.replace(/ {2}\n/g, ' ')}`;
|
|
37
|
+
let loose: Node[] = [];
|
|
38
|
+
const flush = () => { const t = text(loose); loose = []; if (t) out.push(depth ? head(depth, t) : t); };
|
|
39
|
+
// The toolbar's heading, quote and list buttons, and Enter, leave block elements inside the edited one.
|
|
40
|
+
for (const n of el.childNodes) {
|
|
41
|
+
const tag = n.nodeType === 1 ? (n as HTMLElement).tagName : '';
|
|
42
|
+
if (!BLOCK.has(tag)) { loose.push(n); continue; }
|
|
43
|
+
flush();
|
|
44
|
+
const kids = [...n.childNodes];
|
|
45
|
+
if (/^H[1-6]$/.test(tag)) { const t = text(kids); if (t) out.push(head(Number(tag[1]), t)); }
|
|
46
|
+
else if (tag === 'BLOCKQUOTE') { const t = text(kids); if (t) out.push(t.split('\n').map((l) => `> ${l}`).join('\n')); }
|
|
47
|
+
else if (tag === 'UL' || tag === 'OL') {
|
|
48
|
+
const items = kids.filter((k) => (k as HTMLElement).tagName === 'LI').map((li, i) => `${tag === 'OL' ? `${i + 1}.` : '-'} ${text([...li.childNodes])}`);
|
|
49
|
+
if (items.length) out.push(items.join('\n'));
|
|
50
|
+
} else { const t = text(kids); if (t) out.push(depth && tag !== 'P' ? head(depth, t) : t); }
|
|
51
|
+
}
|
|
52
|
+
flush();
|
|
53
|
+
return out.join('\n\n');
|
|
54
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Markdown bodies on the page. The editor renders a body block by block so each top-level block
|
|
2
|
+
// (paragraph, heading, list…) can carry its index; editing one on the page rewrites only that
|
|
3
|
+
// block's source, and every other byte of the file stays as it was. Runs in the browser and on
|
|
4
|
+
// the server (no DOM here; the HTML -> Markdown side takes an element and lives in the client).
|
|
5
|
+
import { Lexer, Parser, type Token, type Tokens } from 'marked';
|
|
6
|
+
import { sanitizeHtml } from './sanitize';
|
|
7
|
+
|
|
8
|
+
export interface Heading { depth: number; slug: string; text: string }
|
|
9
|
+
|
|
10
|
+
/** Blocks whose text can be edited in place; the rest (lists, tables, code, HTML) open the Markdown. */
|
|
11
|
+
export const INLINE_BLOCKS = new Set(['paragraph', 'heading']);
|
|
12
|
+
|
|
13
|
+
/** github-slugger's rules, which Astro uses for heading ids. */
|
|
14
|
+
export function slugger() {
|
|
15
|
+
const seen = new Map<string, number>();
|
|
16
|
+
return (text: string) => {
|
|
17
|
+
const base = text.toLowerCase().trim().replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '').replace(/ /g, '-');
|
|
18
|
+
const n = seen.get(base);
|
|
19
|
+
seen.set(base, (n ?? -1) + 1);
|
|
20
|
+
return n === undefined ? base : `${base}-${n + 1}`;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const lex = (md: string) => new Lexer({ gfm: true }).lex(md);
|
|
25
|
+
const plain = (html: string) => html.replace(/<[^>]*>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'");
|
|
26
|
+
|
|
27
|
+
/** Sanitised HTML for a Markdown body, with heading ids, and with `data-ase-md` block markers when editing. */
|
|
28
|
+
export function renderMarkdown(md: string, { editing = false } = {}): { html: string; headings: Heading[] } {
|
|
29
|
+
const tokens = lex(md);
|
|
30
|
+
const slug = slugger();
|
|
31
|
+
const headings: Heading[] = [];
|
|
32
|
+
const parts: string[] = [];
|
|
33
|
+
tokens.forEach((tok, i) => {
|
|
34
|
+
if (tok.type === 'space') return;
|
|
35
|
+
const list = Object.assign([tok], { links: tokens.links }) as unknown as Token[] & { links: typeof tokens.links };
|
|
36
|
+
let html = sanitizeHtml(new Parser({ gfm: true }).parse(list));
|
|
37
|
+
if (tok.type === 'heading') {
|
|
38
|
+
const h = tok as Tokens.Heading;
|
|
39
|
+
const text = plain(new Parser().parseInline(h.tokens));
|
|
40
|
+
const id = slug(text);
|
|
41
|
+
headings.push({ depth: h.depth, slug: id, text });
|
|
42
|
+
html = html.replace(/^<h([1-6])(?![^>]*\sid=)/, `<h$1 id="${id}"`);
|
|
43
|
+
}
|
|
44
|
+
if (editing) {
|
|
45
|
+
const only = (tok as Tokens.Paragraph).tokens?.filter((t) => !(t.type === 'text' && !t.raw.trim()));
|
|
46
|
+
const kind = tok.type === 'paragraph' && only?.length === 1 && only[0].type === 'image' ? 'image' : INLINE_BLOCKS.has(tok.type) ? 'text' : 'block';
|
|
47
|
+
html = html.replace(/^(\s*<[a-z][a-z0-9]*)/i, `$1 data-ase-md="${i}" data-ase-md-kind="${kind}"`);
|
|
48
|
+
if (!/^\s*</.test(html)) html = `<div data-ase-md="${i}" data-ase-md-kind="block">${html}</div>`;
|
|
49
|
+
}
|
|
50
|
+
parts.push(html);
|
|
51
|
+
});
|
|
52
|
+
return { html: parts.join('\n'), headings };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The source of block `index`, as `renderMarkdown` numbered it, with where it sits in `md`. */
|
|
56
|
+
export function blockAt(md: string, index: number): { raw: string; start: number; end: number; type: string; depth?: number } | null {
|
|
57
|
+
const tokens = lex(md);
|
|
58
|
+
let at = 0;
|
|
59
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
60
|
+
const raw = tokens[i].raw;
|
|
61
|
+
if (i === index) {
|
|
62
|
+
const pos = md.indexOf(raw, at);
|
|
63
|
+
const start = pos === -1 ? at : pos;
|
|
64
|
+
return { raw, start, end: start + raw.length, type: tokens[i].type, depth: (tokens[i] as Tokens.Heading).depth };
|
|
65
|
+
}
|
|
66
|
+
const pos = md.indexOf(raw, at);
|
|
67
|
+
at = pos === -1 ? at + raw.length : pos + raw.length;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `md` with block `index` replaced by `source`, keeping the blank lines around it. */
|
|
73
|
+
export function replaceBlock(md: string, index: number, source: string): string {
|
|
74
|
+
const b = blockAt(md, index);
|
|
75
|
+
if (!b) return md;
|
|
76
|
+
const trailing = b.raw.match(/\s*$/)![0];
|
|
77
|
+
return md.slice(0, b.start) + source.trim() + trailing + md.slice(b.end);
|
|
78
|
+
}
|
|
@@ -84,7 +84,15 @@ export class GitHubStorage implements Storage {
|
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
async pendingAsset(p: string): Promise<Uint8Array | undefined> {
|
|
87
|
-
|
|
87
|
+
return this.bytesAt(p, UPLOADS);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async asset(p: string): Promise<Uint8Array | undefined> {
|
|
91
|
+
return (await this.pendingAsset(p)) ?? this.bytesAt(p, this.branch);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private async bytesAt(p: string, ref: string): Promise<Uint8Array | undefined> {
|
|
95
|
+
const data = await this.req<any>('GET', `${this.repoUrl}/contents/${encodePath(safeRelPath(p))}?ref=${encodeURIComponent(ref)}`, undefined, true);
|
|
88
96
|
if (!data || data.type !== 'file') return undefined;
|
|
89
97
|
const content = data.encoding === 'base64' ? data.content : (await this.req<any>('GET', `${this.repoUrl}/git/blobs/${data.sha}`)).content;
|
|
90
98
|
return fromBase64(String(content).replace(/\n/g, ''));
|
|
@@ -58,4 +58,5 @@ export class LocalStorage implements Storage {
|
|
|
58
58
|
try { return (await run('git', ['show', `${sha}:${safeRelPath(p)}`], { cwd: this.root, maxBuffer: 16 * 1024 * 1024 })).stdout; } catch { return null; }
|
|
59
59
|
}
|
|
60
60
|
async pendingAsset(): Promise<undefined> { return undefined; }
|
|
61
|
+
async asset(): Promise<undefined> { return undefined; } // the dev server serves the working tree
|
|
61
62
|
}
|
package/src/core/storage.ts
CHANGED
|
@@ -44,6 +44,11 @@ export interface Storage {
|
|
|
44
44
|
readAt(path: string, sha: string): Promise<string | null>;
|
|
45
45
|
/** A staged (uncommitted) asset, so the server can serve it in github mode. */
|
|
46
46
|
pendingAsset(path: string): Promise<Uint8Array | undefined>;
|
|
47
|
+
/**
|
|
48
|
+
* An image the deployed build may not have yet: staged, else committed since the editor was
|
|
49
|
+
* built (the editor deployment doesn't rebuild on every save). undefined when neither.
|
|
50
|
+
*/
|
|
51
|
+
asset(path: string): Promise<Uint8Array | undefined>;
|
|
47
52
|
}
|
|
48
53
|
|
|
49
54
|
export async function sha256(text: string): Promise<string> {
|
package/src/routes/api/asset.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Serves a staged (uncommitted) upload in github mode by repo path; the middleware handles the
|
|
2
|
-
// public URL form. Kept as an explicit endpoint for debugging.
|
|
2
|
+
// public URL form (routes/uploaded.ts). Kept as an explicit endpoint for debugging.
|
|
3
3
|
import type { APIRoute } from 'astro';
|
|
4
4
|
import { bad, storage } from '../../server/context';
|
|
5
5
|
export const prerender = false;
|
|
6
6
|
export const GET: APIRoute = async ({ params }) => {
|
|
7
|
-
const bytes = await storage().
|
|
7
|
+
const bytes = await storage().asset(params.path ?? '');
|
|
8
8
|
if (!bytes) return bad('not staged', 404);
|
|
9
9
|
return new Response(bytes, { headers: { 'cache-control': 'no-store' } });
|
|
10
10
|
};
|
|
@@ -16,6 +16,7 @@ const { data, body } = parseMarkdown(raw);
|
|
|
16
16
|
const boot = {
|
|
17
17
|
id, slug, singular: c.singular ?? 'item', fields: c.fields, data, body, hash: await sha256(raw),
|
|
18
18
|
viewUrl: c.url?.(slug) ?? null,
|
|
19
|
+
preview: Object.hasOwn(opts.previews ?? {}, id),
|
|
19
20
|
pages: (await listPages()).filter((p) => p.status !== 'draft').map((p) => ({ title: p.title.split(/\s[-–|]\s/)[0], url: publicPath(p.slug) })),
|
|
20
21
|
};
|
|
21
22
|
---
|
|
@@ -31,9 +32,16 @@ const boot = {
|
|
|
31
32
|
<Nav current={`collection-${id}`} />
|
|
32
33
|
<header class="ase-item__top">
|
|
33
34
|
<a href={`/edit/collection/${id}`}>← {c.label}</a>
|
|
35
|
+
{boot.preview && (
|
|
36
|
+
<span class="ase-seg" role="group" aria-label="Edit as">
|
|
37
|
+
<button type="button" class="ase-seg__btn" data-mode="page" aria-pressed="true">Page</button>
|
|
38
|
+
<button type="button" class="ase-seg__btn" data-mode="markdown" aria-pressed="false">Markdown</button>
|
|
39
|
+
</span>
|
|
40
|
+
)}
|
|
34
41
|
<span id="ase-item-status" class="ase-muted"></span>
|
|
35
42
|
<span class="ase-item__actions">
|
|
36
43
|
{boot.viewUrl && <a id="ase-item-view" class="ase-btn ase-btn--ghost" href={boot.viewUrl} target="_blank" rel="noopener">View ↗</a>}
|
|
44
|
+
{boot.preview && <button type="button" id="ase-item-tab" class="ase-btn ase-btn--ghost">Preview ↗</button>}
|
|
37
45
|
<button type="button" id="ase-item-draft" class="ase-btn ase-btn--ghost" hidden>Switch to draft</button>
|
|
38
46
|
<button type="button" id="ase-item-save" class="ase-btn" disabled>Save</button>
|
|
39
47
|
<button type="button" id="ase-item-publish" class="ase-btn ase-btn--primary" hidden>Publish</button>
|
|
@@ -41,12 +49,15 @@ const boot = {
|
|
|
41
49
|
</header>
|
|
42
50
|
<div class="ase-item__grid">
|
|
43
51
|
<main>
|
|
52
|
+
{boot.preview && <div class="ase-item__page" id="ase-item-page" hidden><iframe id="ase-item-frame" title="Page preview" sandbox="allow-same-origin"></iframe></div>}
|
|
53
|
+
<div id="ase-item-md">
|
|
44
54
|
<input id="ase-item-title" class="ase-item__title" type="text" placeholder="Add title" aria-label="Title" />
|
|
45
55
|
<div class="ase-mdbar" id="ase-mdbar" role="toolbar" aria-label="Formatting"></div>
|
|
46
56
|
<div class="ase-mdsplit">
|
|
47
57
|
<textarea id="ase-item-body" aria-label="Content in Markdown" spellcheck="true"></textarea>
|
|
48
58
|
<article id="ase-item-preview" class="ase-mdpreview" aria-label="Preview"></article>
|
|
49
59
|
</div>
|
|
60
|
+
</div>
|
|
50
61
|
</main>
|
|
51
62
|
<aside id="ase-item-form" class="ase-item__side" aria-label="Details"></aside>
|
|
52
63
|
</div>
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
---
|
|
2
|
+
// A collection item on its own page layout: the component the site names in `previews`, fed the
|
|
3
|
+
// item's frontmatter and its body rendered to HTML. GET renders what is stored; a JSON POST renders
|
|
4
|
+
// the unsaved item in edit mode (data-ase-* markers); a form POST (Preview button) renders it
|
|
5
|
+
// plainly for a look in a tab, sandboxed by the middleware.
|
|
6
|
+
import { previews } from 'virtual:pagestack/previews';
|
|
7
|
+
import { collections, storage } from '../server/context';
|
|
8
|
+
import { parseMarkdown } from '../core/frontmatter';
|
|
9
|
+
import { renderMarkdown } from '../core/markdown';
|
|
10
|
+
export const prerender = false;
|
|
11
|
+
const id = Astro.params.id ?? '';
|
|
12
|
+
const slug = Astro.params.slug ?? '';
|
|
13
|
+
const Preview = Object.hasOwn(previews, id) ? (previews as Record<string, any>)[id] : null;
|
|
14
|
+
if (!Preview || !Object.hasOwn(collections, id) || !/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) return new Response('Not found', { status: 404 });
|
|
15
|
+
let data: Record<string, any> = {};
|
|
16
|
+
let body = '';
|
|
17
|
+
let editing = true;
|
|
18
|
+
try {
|
|
19
|
+
if (Astro.request.method === 'POST') {
|
|
20
|
+
const json = (Astro.request.headers.get('content-type') ?? '').includes('json');
|
|
21
|
+
const item = json ? await Astro.request.json() : JSON.parse(String((await Astro.request.formData()).get('item')));
|
|
22
|
+
editing = json;
|
|
23
|
+
data = item?.data && typeof item.data === 'object' && !Array.isArray(item.data) ? item.data : {};
|
|
24
|
+
body = typeof item?.body === 'string' ? item.body : '';
|
|
25
|
+
} else {
|
|
26
|
+
const raw = await storage().readFile(`${collections[id].dir}/${slug}.md`);
|
|
27
|
+
if (raw === null) return new Response('Not found', { status: 404 });
|
|
28
|
+
({ data, body } = parseMarkdown(raw));
|
|
29
|
+
}
|
|
30
|
+
} catch { return new Response('Bad preview request', { status: 400 }); }
|
|
31
|
+
const { html, headings } = renderMarkdown(body, { editing });
|
|
32
|
+
---
|
|
33
|
+
<Preview item={{ id: slug, collection: id, data, body, html, headings }} editing={editing} />
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Uploads the deployed editor doesn't have as files: staged on the uploads branch, or committed
|
|
2
|
+
// since this editor build (it doesn't rebuild on every save). Existing files are served as static
|
|
3
|
+
// assets before a request gets here; on a miss the platform would otherwise answer with the
|
|
4
|
+
// site's static 404 page without running any of our code (Workers does), so this is a real route.
|
|
5
|
+
// Signed-in editors only: drafts show these images, and visitors shouldn't spend the API quota.
|
|
6
|
+
import type { APIRoute } from 'astro';
|
|
7
|
+
import { opts, secret, storage } from '../server/context';
|
|
8
|
+
import { readSession } from '../core/auth';
|
|
9
|
+
import { EXT_MIME, IMAGE_RE } from '../core/media';
|
|
10
|
+
export const prerender = false;
|
|
11
|
+
|
|
12
|
+
const notFound = () => new Response('Not found', { status: 404, headers: { 'content-type': 'text/plain', 'cache-control': 'no-store', 'x-robots-tag': 'noindex' } });
|
|
13
|
+
|
|
14
|
+
export const GET: APIRoute = async ({ params, request }) => {
|
|
15
|
+
const rel = params.path ?? '';
|
|
16
|
+
if (!IMAGE_RE.test(rel) || rel.split('/').some((s) => s === '..' || s === '')) return notFound();
|
|
17
|
+
if (opts.auth === 'passkey' && !(request.headers.get('cookie') && await readSession(request.headers.get('cookie'), secret()))) return notFound();
|
|
18
|
+
const bytes = await storage().asset(`${opts.uploadsDir.replace(/\/$/, '')}/${rel}`).catch(() => undefined);
|
|
19
|
+
if (!bytes) return notFound();
|
|
20
|
+
return new Response(bytes as BodyInit, { headers: {
|
|
21
|
+
'content-type': EXT_MIME[rel.slice(rel.lastIndexOf('.') + 1).toLowerCase()] ?? 'application/octet-stream',
|
|
22
|
+
'cache-control': 'private, no-store', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex',
|
|
23
|
+
// SVG is an image here, never a document that runs script.
|
|
24
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
|
25
|
+
} });
|
|
26
|
+
};
|
package/src/runtime.ts
CHANGED
|
@@ -40,6 +40,8 @@ export interface Field {
|
|
|
40
40
|
time?: boolean;
|
|
41
41
|
/** For 'image': store just the URL string instead of { src, alt }. */
|
|
42
42
|
asUrl?: boolean;
|
|
43
|
+
/** With `asUrl`: the text field that holds the image's alt text; the picker fills it. */
|
|
44
|
+
altField?: string;
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
export interface BlockSchema {
|
|
@@ -133,6 +135,18 @@ export function nodeAttrs(edit: EditCtx | undefined, node: Node): Record<string,
|
|
|
133
135
|
export function fieldAttrs(edit: EditCtx | undefined, name: string, type: FieldType): Record<string, string> {
|
|
134
136
|
return edit ? { 'data-ase-field': `${edit.path}.settings.${name}`, 'data-ase-field-type': type } : {};
|
|
135
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Click-to-edit markers for a collection item's own fields in its `previews` layout, e.g.
|
|
140
|
+
* `<h1 {...itemField(editing, 'title')}>`. Empty outside the editor.
|
|
141
|
+
*/
|
|
142
|
+
export function itemField(editing: boolean | undefined, name: string, type: 'text' | 'image' = 'text'): Record<string, string> {
|
|
143
|
+
return editing ? { 'data-ase-field': name, 'data-ase-field-type': type } : {};
|
|
144
|
+
}
|
|
145
|
+
/** What a `previews` layout receives. `html` is the sanitised body; render it with set:html. */
|
|
146
|
+
export interface ItemPreviewProps {
|
|
147
|
+
item: { id: string; collection: string; data: Record<string, any>; body: string; html: string; headings: { depth: number; slug: string; text: string }[] };
|
|
148
|
+
editing: boolean;
|
|
149
|
+
}
|
|
136
150
|
/** Edit context for the i-th child block. */
|
|
137
151
|
export function child(edit: EditCtx | undefined, i: number): EditCtx | undefined {
|
|
138
152
|
return edit ? { path: `${edit.path}.blocks.${i}` } : undefined;
|
package/src/server/context.ts
CHANGED
|
@@ -17,7 +17,7 @@ import type { SavedPattern } from '../core/insert';
|
|
|
17
17
|
export { options, site };
|
|
18
18
|
|
|
19
19
|
export interface EditorOptions {
|
|
20
|
-
root: string; renderer: string | null; pages?: boolean; sections: string; pagesDir: string; imagesDir: string; uploadsDir: string; publicDir: string; usersFile: string;
|
|
20
|
+
root: string; renderer: string | null; previews?: Record<string, string>; pages?: boolean; sections: string; pagesDir: string; imagesDir: string; uploadsDir: string; publicDir: string; usersFile: string;
|
|
21
21
|
auth: 'none' | 'passkey' | 'none-behind-proxy'; storage: 'local' | 'github'; github: { repo: string; branch?: string; pullRequest?: boolean } | null;
|
|
22
22
|
siteName: string; secretEnv: string; command: string; interactiveSelector: string;
|
|
23
23
|
reservedSlugs: string[]; redirectsFile: string; patternsFile: string;
|
package/src/server/middleware.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
// Guards /edit/* and /api/editor/*. Public pages are untouched (and don't exist in SSR anyway:
|
|
2
|
-
// they're prerendered).
|
|
2
|
+
// they're prerendered). Uploads the build doesn't have are served by routes/uploaded.ts.
|
|
3
3
|
import { defineMiddleware } from 'astro:middleware';
|
|
4
4
|
import { activeUser, opts, secret, storage, publicUrl } from './context';
|
|
5
5
|
import { SESSION_COOKIE, clearCookieHeader, readSession } from '../core/auth';
|
|
6
6
|
import { roleOf } from '../core/users';
|
|
7
|
-
import { EXT_MIME, IMAGE_RE } from '../core/media';
|
|
8
7
|
import { rateLimiter } from '../core/ratelimit';
|
|
9
8
|
|
|
10
9
|
const PUBLIC = [/^\/edit\/login\/?$/, /^\/edit\/enroll\/?$/, /^\/api\/editor\/auth\//];
|
|
@@ -52,13 +51,6 @@ export const onRequest = defineMiddleware(async (ctx, next) => {
|
|
|
52
51
|
const { request } = ctx;
|
|
53
52
|
const isEditor = pathname === '/edit' || pathname.startsWith('/edit/') || pathname.startsWith('/api/editor/');
|
|
54
53
|
|
|
55
|
-
// Staged uploads (github storage) — served until the next save commits them.
|
|
56
|
-
// Only for a signed-in editor: drafts preview them, and visitors shouldn't spend the API quota.
|
|
57
|
-
if (!isEditor && opts.storage === 'github' && (opts.publicDir + pathname).startsWith(`${opts.uploadsDir}/`) && IMAGE_RE.test(pathname)
|
|
58
|
-
&& (opts.auth !== 'passkey' || await readSession(request.headers.get('cookie'), secret()))) {
|
|
59
|
-
const pending = await storage().pendingAsset(opts.publicDir + pathname).catch(() => undefined);
|
|
60
|
-
if (pending) return new Response(pending as BodyInit, { headers: { 'content-type': EXT_MIME[pathname.slice(pathname.lastIndexOf('.') + 1).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox" } });
|
|
61
|
-
}
|
|
62
54
|
if (!isEditor) return next();
|
|
63
55
|
|
|
64
56
|
// A form POST here is the Preview button: an unsaved draft shown in its own tab, walled off from the session.
|
package/src/server/webauthn.ts
CHANGED
|
@@ -22,7 +22,7 @@ export async function loginOptions(url: URL) {
|
|
|
22
22
|
const { rpID } = relyingParty(url);
|
|
23
23
|
// No allowCredentials: the browser offers every passkey it has for this site (discoverable
|
|
24
24
|
// credentials), so there's no username step.
|
|
25
|
-
const options = await generateAuthenticationOptions({ rpID, userVerification: '
|
|
25
|
+
const options = await generateAuthenticationOptions({ rpID, userVerification: 'required' });
|
|
26
26
|
const token = await createChallengeToken(options.challenge, 'login', secret());
|
|
27
27
|
return { options, token };
|
|
28
28
|
}
|
|
@@ -57,7 +57,7 @@ export async function registerOptions(url: URL, inviteToken: string) {
|
|
|
57
57
|
userID: new TextEncoder().encode(existing?.id ?? `pending:${invite.id}`),
|
|
58
58
|
attestationType: 'none',
|
|
59
59
|
excludeCredentials: existing?.credentials.map((c) => ({ id: c.id, transports: c.transports as any })) ?? [],
|
|
60
|
-
authenticatorSelection: { residentKey: 'preferred', userVerification: '
|
|
60
|
+
authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
|
|
61
61
|
});
|
|
62
62
|
const token = await createChallengeToken(options.challenge, 'register', secret(), invite);
|
|
63
63
|
return { options, token, invite: { name: invite.name, email: invite.email } };
|
package/src/virtual.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
declare module 'virtual:pagestack/renderer' { export const Renderer: any; }
|
|
2
|
+
declare module 'virtual:pagestack/previews' { export const previews: Record<string, any>; }
|
|
2
3
|
declare module 'virtual:pagestack/site' {
|
|
3
4
|
export const site: { schemas: Record<string, any>; presets: { label: string; description?: string; create: () => any }[] };
|
|
4
5
|
export const options: Record<string, any>;
|