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

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 (46) hide show
  1. package/README.md +39 -12
  2. package/index.mjs +18 -6
  3. package/package.json +1 -1
  4. package/src/client/auth.ts +5 -5
  5. package/src/client/collection.ts +6 -6
  6. package/src/client/editor.ts +105 -105
  7. package/src/client/form.ts +26 -26
  8. package/src/client/global.ts +4 -4
  9. package/src/client/inline.ts +4 -4
  10. package/src/client/inserter.ts +11 -11
  11. package/src/client/invite.ts +4 -4
  12. package/src/client/item.ts +202 -54
  13. package/src/client/live.ts +92 -0
  14. package/src/client/media.ts +12 -12
  15. package/src/client/pages.ts +14 -14
  16. package/src/client/picker.ts +30 -30
  17. package/src/client/preview.css +58 -58
  18. package/src/client/rich.ts +14 -14
  19. package/src/client/shell.css +281 -272
  20. package/src/client/state.ts +2 -2
  21. package/src/client/tomarkdown.ts +4 -2
  22. package/src/client/tree.ts +11 -11
  23. package/src/client/ui.ts +13 -13
  24. package/src/client/users.ts +6 -6
  25. package/src/core/auth.ts +1 -1
  26. package/src/core/markdown.ts +54 -5
  27. package/src/core/pages.ts +6 -2
  28. package/src/core/storage-github.ts +51 -5
  29. package/src/core/storage.ts +14 -0
  30. package/src/routes/Nav.astro +5 -3
  31. package/src/routes/api/collection.ts +30 -8
  32. package/src/routes/api/live.ts +27 -0
  33. package/src/routes/edit-collection.astro +14 -14
  34. package/src/routes/edit-global.astro +8 -8
  35. package/src/routes/edit-index.astro +18 -18
  36. package/src/routes/edit-item.astro +25 -23
  37. package/src/routes/edit-media.astro +9 -9
  38. package/src/routes/edit-page.astro +32 -30
  39. package/src/routes/edit-users.astro +9 -9
  40. package/src/routes/enroll.astro +6 -6
  41. package/src/routes/login.astro +6 -6
  42. package/src/routes/preview-item.astro +1 -1
  43. package/src/routes/preview.astro +1 -1
  44. package/src/runtime.ts +3 -3
  45. package/src/server/context.ts +3 -3
  46. package/src/server/middleware.ts +19 -4
@@ -18,7 +18,7 @@ export class EditorState extends EventTarget {
18
18
  this.doc = doc;
19
19
  this.hash = hash;
20
20
  this.savedJson = JSON.stringify(doc);
21
- this.key = `ase:draft:${slug}`;
21
+ this.key = `ps:draft:${slug}`;
22
22
  }
23
23
 
24
24
  get dirty() { return JSON.stringify(this.doc) !== this.savedJson; }
@@ -80,7 +80,7 @@ export class EditorState extends EventTarget {
80
80
  /** A draft saved earlier for this page, if it was based on the same stored version. */
81
81
  static restore(slug: string, hash: string): { doc: PageDoc; at: number } | null | 'stale' {
82
82
  try {
83
- const raw = localStorage.getItem(`ase:draft:${slug}`);
83
+ const raw = localStorage.getItem(`ps:draft:${slug}`);
84
84
  if (!raw) return null;
85
85
  const d = JSON.parse(raw);
86
86
  if (d.base !== hash) return 'stale';
@@ -29,7 +29,7 @@ function inline(node: Node): string {
29
29
  }
30
30
  }
31
31
 
32
- /** Markdown for an edited paragraph or heading. `depth` makes its own text a heading of that level. */
32
+ /** Markdown for an edited paragraph, heading, flat list or quote. `depth` makes its own text a heading of that level. */
33
33
  export function blockToMarkdown(el: HTMLElement, depth?: number): string {
34
34
  const out: string[] = [];
35
35
  const text = (nodes: Node[]) => nodes.map(inline).join('').replace(/ {2}\n$/, '').trim();
@@ -37,7 +37,9 @@ export function blockToMarkdown(el: HTMLElement, depth?: number): string {
37
37
  let loose: Node[] = [];
38
38
  const flush = () => { const t = text(loose); loose = []; if (t) out.push(depth ? head(depth, t) : t); };
39
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) {
40
+ // A list or quote edited as a whole is its own first block.
41
+ const nodes = /^(UL|OL|BLOCKQUOTE)$/.test(el.tagName) ? [el as Node] : [...el.childNodes];
42
+ for (const n of nodes) {
41
43
  const tag = n.nodeType === 1 ? (n as HTMLElement).tagName : '';
42
44
  if (!BLOCK.has(tag)) { loose.push(n); continue; }
43
45
  flush();
@@ -21,14 +21,14 @@ export function renderTree(root: HTMLElement, doc: PageDoc, registry: SchemaRegi
21
21
 
22
22
  function list(nodes: Node[], listPath: string, depth: number): HTMLElement {
23
23
  const ul = document.createElement('ul');
24
- ul.className = `ase-tree__list ase-tree__list--d${Math.min(depth, 3)}`;
24
+ ul.className = `ps-tree__list ps-tree__list--d${Math.min(depth, 3)}`;
25
25
  ul.dataset.list = listPath;
26
26
  nodes.forEach((n, i) => ul.append(item(n, `${listPath}.${i}`, depth)));
27
27
  Sortable.create(ul, {
28
- group: { name: 'ase-tree', pull: true, put: (to, _from, dragEl) => cb.canDrop((dragEl as HTMLElement).dataset.path!, (to.el as HTMLElement).dataset.list!) },
28
+ group: { name: 'ps-tree', pull: true, put: (to, _from, dragEl) => cb.canDrop((dragEl as HTMLElement).dataset.path!, (to.el as HTMLElement).dataset.list!) },
29
29
  animation: 120,
30
- handle: '.ase-tree__grip',
31
- draggable: '.ase-tree__item',
30
+ handle: '.ps-tree__grip',
31
+ draggable: '.ps-tree__item',
32
32
  fallbackOnBody: true,
33
33
  swapThreshold: 0.65,
34
34
  onEnd: (evt) => {
@@ -44,18 +44,18 @@ export function renderTree(root: HTMLElement, doc: PageDoc, registry: SchemaRegi
44
44
  const canHold = !!allowedChildTypes(n.type, registry)?.length;
45
45
  const open = opened.has(n.id) || !!selected?.startsWith(path + '.');
46
46
  const li = document.createElement('li');
47
- li.className = 'ase-tree__item' + (path === selected ? ' is-selected' : '') + (open ? ' is-open' : '');
47
+ li.className = 'ps-tree__item' + (path === selected ? ' is-selected' : '') + (open ? ' is-open' : '');
48
48
  li.dataset.path = path;
49
49
  const row = document.createElement('div');
50
- row.className = 'ase-tree__row';
51
- row.innerHTML = `<span class="ase-tree__grip" title="Drag to move">${icons.grip}</span>${hasKids || canHold ? `<button type="button" class="ase-tree__toggle" aria-label="Show contents" aria-expanded="${open}">▸</button>` : '<span class="ase-tree__toggle ase-tree__toggle--leaf"></span>'}<span class="ase-tree__label"></span><button type="button" class="ase-tree__menu" aria-label="Block options">${icons.more}</button>`;
52
- row.querySelector('.ase-tree__label')!.textContent = nodeLabel(n, registry);
53
- if (n.synced) { const pill = document.createElement('span'); pill.className = 'ase-pill ase-pill--synced'; pill.textContent = 'Synced'; row.querySelector('.ase-tree__label')!.after(pill); }
50
+ row.className = 'ps-tree__row';
51
+ row.innerHTML = `<span class="ps-tree__grip" title="Drag to move">${icons.grip}</span>${hasKids || canHold ? `<button type="button" class="ps-tree__toggle" aria-label="Show contents" aria-expanded="${open}">▸</button>` : '<span class="ps-tree__toggle ps-tree__toggle--leaf"></span>'}<span class="ps-tree__label"></span><button type="button" class="ps-tree__menu" aria-label="Block options">${icons.more}</button>`;
52
+ row.querySelector('.ps-tree__label')!.textContent = nodeLabel(n, registry);
53
+ if (n.synced) { const pill = document.createElement('span'); pill.className = 'ps-pill ps-pill--synced'; pill.textContent = 'Synced'; row.querySelector('.ps-tree__label')!.after(pill); }
54
54
  row.addEventListener('click', (e) => {
55
55
  const t = e.target as HTMLElement;
56
- const menu = t.closest<HTMLElement>('.ase-tree__menu');
56
+ const menu = t.closest<HTMLElement>('.ps-tree__menu');
57
57
  if (menu) { cb.onMenu(path, menu); return; }
58
- if (t.closest('.ase-tree__toggle')) {
58
+ if (t.closest('.ps-tree__toggle')) {
59
59
  const on = li.classList.toggle('is-open');
60
60
  if (on) opened.add(n.id); else opened.delete(n.id);
61
61
  return;
package/src/client/ui.ts CHANGED
@@ -5,13 +5,13 @@ export interface ToastAction { label: string; run: () => void }
5
5
 
6
6
  export function toast(text: string, kind: 'ok' | 'info' | 'warn' | 'error', opts: { href?: string; action?: ToastAction } = {}) {
7
7
  const t = document.createElement('div');
8
- t.className = `ase-toast ase-toast--${kind}`;
8
+ t.className = `ps-toast ps-toast--${kind}`;
9
9
  t.setAttribute('role', 'status');
10
10
  t.textContent = text;
11
11
  if (opts.href) { const a = document.createElement('a'); a.href = opts.href; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'Open ↗'; t.append(' ', a); }
12
- if (opts.action) { const b = document.createElement('button'); b.type = 'button'; b.className = 'ase-toast__action'; b.textContent = opts.action.label; b.addEventListener('click', () => { t.remove(); opts.action!.run(); }); t.append(b); }
12
+ if (opts.action) { const b = document.createElement('button'); b.type = 'button'; b.className = 'ps-toast__action'; b.textContent = opts.action.label; b.addEventListener('click', () => { t.remove(); opts.action!.run(); }); t.append(b); }
13
13
  const x = document.createElement('button'); x.type = 'button'; x.textContent = '×'; x.setAttribute('aria-label', 'Dismiss'); x.addEventListener('click', () => t.remove()); t.append(x);
14
- document.querySelectorAll('.ase-toast').forEach((o) => o.remove());
14
+ document.querySelectorAll('.ps-toast').forEach((o) => o.remove());
15
15
  document.body.append(t);
16
16
  setTimeout(() => t.remove(), kind === 'error' ? 15000 : 8000);
17
17
  }
@@ -21,14 +21,14 @@ export interface DialogAction { label: string; kind?: 'primary' | 'danger'; run?
21
21
  /** A modal. An action closes it unless `run` returns false. */
22
22
  export function dialog(title: string, body: HTMLElement | string, actions: DialogAction[], opts: { wide?: boolean; onClose?: () => void } = {}) {
23
23
  const wrap = document.createElement('div');
24
- wrap.className = 'ase-modal';
24
+ wrap.className = 'ps-modal';
25
25
  wrap.setAttribute('role', 'dialog');
26
26
  wrap.setAttribute('aria-modal', 'true');
27
27
  wrap.setAttribute('aria-label', title);
28
28
  const box = document.createElement('form');
29
- box.className = `ase-dialog${opts.wide ? ' ase-dialog--wide' : ''}`;
29
+ box.className = `ps-dialog${opts.wide ? ' ps-dialog--wide' : ''}`;
30
30
  const h = document.createElement('h2'); h.textContent = title;
31
- const content = document.createElement('div'); content.className = 'ase-dialog__body';
31
+ const content = document.createElement('div'); content.className = 'ps-dialog__body';
32
32
  if (typeof body === 'string') { const p = document.createElement('p'); p.textContent = body; content.append(p); } else content.append(body);
33
33
  const foot = document.createElement('footer');
34
34
  const close = () => { wrap.remove(); document.removeEventListener('keydown', onKey, true); opts.onClose?.(); };
@@ -38,7 +38,7 @@ export function dialog(title: string, body: HTMLElement | string, actions: Dialo
38
38
  for (const a of actions) {
39
39
  const b = document.createElement('button');
40
40
  b.type = a.kind ? 'submit' : 'button';
41
- b.className = `ase-btn ${a.kind === 'primary' ? 'ase-btn--primary' : a.kind === 'danger' ? 'ase-btn--destructive' : 'ase-btn--ghost'}`;
41
+ b.className = `ps-btn ${a.kind === 'primary' ? 'ps-btn--primary' : a.kind === 'danger' ? 'ps-btn--destructive' : 'ps-btn--ghost'}`;
42
42
  b.textContent = a.label;
43
43
  if (a.kind) primary = b;
44
44
  b.addEventListener('click', async (e) => { e.preventDefault(); b.disabled = true; const keep = (await a.run?.()) === false; b.disabled = false; if (!keep) close(); });
@@ -63,18 +63,18 @@ export const confirmDialog = (title: string, text: string, label: string, kind:
63
63
  export function promptDialog(o: { title: string; label: string; value?: string; help?: string; submit: string; check?: (v: string) => string | null; toggle?: { label: string; on: boolean } }) {
64
64
  return new Promise<string | null>((resolve) => {
65
65
  const wrap = document.createElement('div');
66
- wrap.className = 'ase-field';
66
+ wrap.className = 'ps-field';
67
67
  const label = document.createElement('label'); label.textContent = o.label;
68
68
  const input = document.createElement('input'); input.type = 'text'; input.value = o.value ?? ''; label.append(input);
69
- const error = document.createElement('p'); error.className = 'ase-error'; error.hidden = true;
69
+ const error = document.createElement('p'); error.className = 'ps-error'; error.hidden = true;
70
70
  wrap.append(label, error);
71
71
  if (o.toggle) {
72
- const row = document.createElement('label'); row.className = 'ase-check';
72
+ const row = document.createElement('label'); row.className = 'ps-check';
73
73
  const box = document.createElement('input'); box.type = 'checkbox'; box.checked = o.toggle.on;
74
74
  box.addEventListener('change', () => { o.toggle!.on = box.checked; });
75
75
  row.append(box, ` ${o.toggle.label}`); wrap.append(row);
76
76
  }
77
- if (o.help) { const s = document.createElement('small'); s.className = 'ase-muted'; s.textContent = o.help; wrap.append(s); }
77
+ if (o.help) { const s = document.createElement('small'); s.className = 'ps-muted'; s.textContent = o.help; wrap.append(s); }
78
78
  let result: string | null = null;
79
79
  dialog(o.title, wrap, [{ label: 'Cancel' }, {
80
80
  label: o.submit, kind: 'primary', run: () => {
@@ -93,9 +93,9 @@ export interface MenuItem { label: string; hint?: string; run: () => void; dange
93
93
  export function openMenu(anchor: HTMLElement, items: MenuItem[]) {
94
94
  const doc = anchor.ownerDocument;
95
95
  const win = doc.defaultView!;
96
- doc.querySelector('.ase-popmenu')?.remove();
96
+ doc.querySelector('.ps-popmenu')?.remove();
97
97
  const menu = doc.createElement('div');
98
- menu.className = 'ase-popmenu';
98
+ menu.className = 'ps-popmenu';
99
99
  menu.setAttribute('role', 'menu');
100
100
  for (const it of items) {
101
101
  if (it.separator) menu.append(doc.createElement('hr'));
@@ -3,7 +3,7 @@ import { confirmDialog, toast } from './ui';
3
3
 
4
4
  interface Passkey { id: string; label: string | null; createdAt: string; synced: boolean }
5
5
  interface User { id: string; name: string; email: string; role: 'admin' | 'editor'; passkeys: Passkey[] }
6
- const list = document.getElementById('ase-users')!;
6
+ const list = document.getElementById('ps-users')!;
7
7
 
8
8
  async function call(method: string, body?: unknown) {
9
9
  const res = await fetch('/api/editor/users', { method, headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
@@ -18,11 +18,11 @@ const text = (tag: string, s: string, cls?: string) => { const e = document.crea
18
18
  function draw(users: User[]) {
19
19
  list.replaceChildren(...users.map((u) => {
20
20
  const li = document.createElement('li'); li.dataset.user = u.email;
21
- const who = document.createElement('div'); who.className = 'ase-pagelist__edit';
22
- who.append(text('strong', u.name), text('span', `${u.email} · ${u.passkeys.length} ${u.passkeys.length === 1 ? 'passkey' : 'passkeys'}`, 'ase-muted'));
23
- const keys = document.createElement('div'); keys.className = 'ase-users__keys';
21
+ const who = document.createElement('div'); who.className = 'ps-pagelist__edit';
22
+ who.append(text('strong', u.name), text('span', `${u.email} · ${u.passkeys.length} ${u.passkeys.length === 1 ? 'passkey' : 'passkeys'}`, 'ps-muted'));
23
+ const keys = document.createElement('div'); keys.className = 'ps-users__keys';
24
24
  for (const k of u.passkeys) {
25
- const b = text('button', `${k.label || (k.synced ? 'Synced passkey' : 'Device passkey')}, added ${k.createdAt.slice(0, 10)} ×`, 'ase-btn ase-btn--small ase-btn--ghost') as HTMLButtonElement;
25
+ const b = text('button', `${k.label || (k.synced ? 'Synced passkey' : 'Device passkey')}, added ${k.createdAt.slice(0, 10)} ×`, 'ps-btn ps-btn--small ps-btn--ghost') as HTMLButtonElement;
26
26
  b.type = 'button'; b.title = 'Remove this passkey';
27
27
  b.addEventListener('click', async () => { if (await confirmDialog('Remove passkey', `${u.name} will not be able to sign in with this passkey any more.${u.passkeys.length === 1 ? ' It is their last one, so they will lose access.' : ''}`, 'Remove', 'danger')) call('DELETE', { credential: k.id }); });
28
28
  keys.append(b);
@@ -31,7 +31,7 @@ function draw(users: User[]) {
31
31
  const role = document.createElement('select'); role.setAttribute('aria-label', `Role for ${u.name}`);
32
32
  for (const r of ['editor', 'admin']) role.append(Object.assign(document.createElement('option'), { value: r, textContent: r === 'admin' ? 'Admin' : 'Editor', selected: u.role === r }));
33
33
  role.addEventListener('change', () => call('PATCH', { id: u.id, role: role.value }));
34
- const del = text('button', 'Remove', 'ase-btn ase-btn--small ase-btn--ghost ase-btn--danger') as HTMLButtonElement; del.type = 'button';
34
+ const del = text('button', 'Remove', 'ps-btn ps-btn--small ps-btn--ghost ps-btn--danger') as HTMLButtonElement; del.type = 'button';
35
35
  del.addEventListener('click', async () => { if (await confirmDialog('Remove user', `${u.name} loses access within seconds, including any session they have open now.`, 'Remove user', 'danger')) call('DELETE', { id: u.id }); });
36
36
  li.append(who, role, del);
37
37
  return li;
package/src/core/auth.ts CHANGED
@@ -48,7 +48,7 @@ export function randomChallenge(bytes = 32): string {
48
48
  }
49
49
 
50
50
  // ---- cookies ----
51
- export const SESSION_COOKIE = 'ase_session';
51
+ export const SESSION_COOKIE = 'ps_session';
52
52
  export const SESSION_TTL = 60 * 60 * 12; // 12h
53
53
 
54
54
  export function parseCookies(header: string | null): Record<string, string> {
@@ -7,9 +7,28 @@ import { sanitizeHtml } from './sanitize';
7
7
 
8
8
  export interface Heading { depth: number; slug: string; text: string }
9
9
 
10
- /** Blocks whose text can be edited in place; the rest (lists, tables, code, HTML) open the Markdown. */
10
+ /** Blocks whose text can be edited in place; the rest (tables, code, HTML) open the Markdown. */
11
11
  export const INLINE_BLOCKS = new Set(['paragraph', 'heading']);
12
12
 
13
+ const PLAIN = new Set(['text', 'paragraph', 'space']);
14
+ /**
15
+ * Whether a block can be edited on the page and turned back into Markdown without losing anything:
16
+ * paragraphs and headings; a flat list (no nesting, tasks or numbering that doesn't start at 1); a
17
+ * quote of one paragraph.
18
+ */
19
+ function inlineEditable(tok: Token): boolean {
20
+ if (INLINE_BLOCKS.has(tok.type)) return true;
21
+ if (tok.type === 'list') {
22
+ const l = tok as Tokens.List;
23
+ return (!l.ordered || l.start === 1 || l.start === '') && l.items.every((it) => !it.task && it.tokens.every((t) => PLAIN.has(t.type)));
24
+ }
25
+ if (tok.type === 'blockquote') {
26
+ const q = (tok as Tokens.Blockquote).tokens.filter((t) => t.type !== 'space');
27
+ return q.length === 1 && q[0].type === 'paragraph';
28
+ }
29
+ return false;
30
+ }
31
+
13
32
  /** github-slugger's rules, which Astro uses for heading ids. */
14
33
  export function slugger() {
15
34
  const seen = new Map<string, number>();
@@ -24,7 +43,7 @@ export function slugger() {
24
43
  const lex = (md: string) => new Lexer({ gfm: true }).lex(md);
25
44
  const plain = (html: string) => html.replace(/<[^>]*>/g, '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'");
26
45
 
27
- /** Sanitised HTML for a Markdown body, with heading ids, and with `data-ase-md` block markers when editing. */
46
+ /** Sanitised HTML for a Markdown body, with heading ids, and with `data-ps-md` block markers when editing. */
28
47
  export function renderMarkdown(md: string, { editing = false } = {}): { html: string; headings: Heading[] } {
29
48
  const tokens = lex(md);
30
49
  const slug = slugger();
@@ -43,9 +62,9 @@ export function renderMarkdown(md: string, { editing = false } = {}): { html: st
43
62
  }
44
63
  if (editing) {
45
64
  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>`;
65
+ const kind = tok.type === 'paragraph' && only?.length === 1 && only[0].type === 'image' ? 'image' : inlineEditable(tok) ? 'text' : 'block';
66
+ html = html.replace(/^(\s*<[a-z][a-z0-9]*)/i, `$1 data-ps-md="${i}" data-ps-md-kind="${kind}"`);
67
+ if (!/^\s*</.test(html)) html = `<div data-ps-md="${i}" data-ps-md-kind="block">${html}</div>`;
49
68
  }
50
69
  parts.push(html);
51
70
  });
@@ -76,3 +95,33 @@ export function replaceBlock(md: string, index: number, source: string): string
76
95
  const trailing = b.raw.match(/\s*$/)![0];
77
96
  return md.slice(0, b.start) + source.trim() + trailing + md.slice(b.end);
78
97
  }
98
+
99
+ /**
100
+ * `md` with a new block after block `after` (null: at the top), one blank line either side, and the
101
+ * index the new block has in `renderMarkdown` numbering.
102
+ */
103
+ export function insertBlock(md: string, after: number | null, source: string): { md: string; index: number } {
104
+ const at = after === null ? 0 : (blockAt(md, after)?.end ?? md.length);
105
+ const before = md.slice(0, at).replace(/\s*$/, '');
106
+ const rest = md.slice(at).replace(/^\s*/, '');
107
+ const head = before ? `${before}\n\n` : '';
108
+ const next = `${head}${source.trim()}\n${rest ? `\n${rest}` : ''}`;
109
+ const tokens = lex(next);
110
+ let pos = 0, index = 0;
111
+ for (let i = 0; i < tokens.length; i++) {
112
+ if (pos >= head.length && tokens[i].type !== 'space') { index = i; break; }
113
+ pos += tokens[i].raw.length;
114
+ }
115
+ return { md: next, index };
116
+ }
117
+
118
+ /** Starting Markdown for each kind of block the page can add. */
119
+ export const NEW_BLOCKS = {
120
+ paragraph: 'Type here',
121
+ heading: '## Heading',
122
+ subheading: '### Subheading',
123
+ list: '- List item',
124
+ numbered: '1. List item',
125
+ quote: '> Quote',
126
+ table: '| Column | Column |\n| --- | --- |\n| Cell | Cell |',
127
+ } as const;
package/src/core/pages.ts CHANGED
@@ -47,6 +47,10 @@ export function copyPage(source: PageDoc, title: string): PageDoc {
47
47
 
48
48
  /** Add `from -> to` to a redirects file (Netlify/Cloudflare `_redirects` format). */
49
49
  export function addRedirect(file: string, fromSlug: string, toSlug: string): string {
50
- const line = `${publicPath(fromSlug)} ${publicPath(toSlug)} 301`;
51
- return `${file.replace(/\n*$/, '')}\n${line}\n`;
50
+ return addRedirectLine(file, publicPath(fromSlug), publicPath(toSlug));
51
+ }
52
+
53
+ /** `_redirects` with one more permanent redirect, between two site paths. */
54
+ export function addRedirectLine(file: string, from: string, to: string): string {
55
+ return `${file.replace(/\n*$/, '')}\n${from} ${to} 301\n`;
52
56
  }
@@ -7,7 +7,7 @@
7
7
  // Uploads wait on a side branch until the next save brings them along in its one commit, then the
8
8
  // branch goes away. Keeping them in the repo rather than in memory means an upload and the save
9
9
  // after it can land on different server instances (Workers), and a restart loses nothing.
10
- import type { CommitResult, FileChange, Revision, Storage } from './storage';
10
+ import type { CommitResult, FileChange, PendingChanges, Revision, Storage } from './storage';
11
11
  import { fromBase64, isSha, safeRelPath, toBase64 } from './storage';
12
12
 
13
13
  export interface GitHubOptions {
@@ -17,6 +17,11 @@ export interface GitHubOptions {
17
17
  branch?: string;
18
18
  /** Commit to a new branch and open a PR against `branch` instead of committing directly. */
19
19
  pullRequest?: boolean;
20
+ /**
21
+ * The branch the public site builds from. Saves go to `branch` (staging) and only Go live
22
+ * moves them here. Leave out to have saves go straight to `branch`.
23
+ */
24
+ live?: string;
20
25
  token: string;
21
26
  apiBase?: string;
22
27
  /** Injected for tests. */
@@ -41,14 +46,17 @@ export class GitHubStorage implements Storage {
41
46
  }
42
47
 
43
48
  private async req<T = any>(method: string, url: string, body?: unknown, allow404 = false): Promise<T | null> {
44
- const res = await this.fetchImpl(`${this.api}${url}`, {
49
+ const res = await this.raw(method, url, body);
50
+ if (res.status === 404 && allow404) return null;
51
+ if (!res.ok) throw new Error(`GitHub ${method} ${url} -> ${res.status} ${(await res.text()).slice(0, 300)}`);
52
+ return (res.status === 204 ? null : await res.json()) as T;
53
+ }
54
+ private raw(method: string, url: string, body?: unknown): Promise<Response> {
55
+ return this.fetchImpl(`${this.api}${url}`, {
45
56
  method,
46
57
  headers: { authorization: `Bearer ${this.opts.token}`, accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', 'user-agent': 'pagestack', ...(body ? { 'content-type': 'application/json' } : {}) },
47
58
  body: body ? JSON.stringify(body) : undefined,
48
59
  });
49
- if (res.status === 404 && allow404) return null;
50
- if (!res.ok) throw new Error(`GitHub ${method} ${url} -> ${res.status} ${(await res.text()).slice(0, 300)}`);
51
- return (res.status === 204 ? null : await res.json()) as T;
52
60
  }
53
61
  private get repoUrl() { return `/repos/${this.opts.repo}`; }
54
62
 
@@ -147,6 +155,44 @@ export class GitHubStorage implements Storage {
147
155
  if (uploads.length) await this.req('DELETE', `${this.repoUrl}/git/refs/heads/${UPLOADS}`, undefined, true).catch(() => { /* an empty next commit is harmless */ });
148
156
  return { kind: 'github', files: [...all.map((f) => f.path), ...uploads.map((u) => u.path), ...removed], commit: commit.sha, url: commit.html_url ?? `https://github.com/${this.opts.repo}/commit/${commit.sha}`, branch, pullRequest };
149
157
  }
158
+
159
+ /** Saved but not yet live: commits on `branch` that `live` doesn't have. */
160
+ async pending(): Promise<PendingChanges> {
161
+ const live = this.opts.live;
162
+ if (!live) throw new Error('no live branch configured');
163
+ const cmp = await this.req<any>('GET', `${this.repoUrl}/compare/${encodeURIComponent(live)}...${encodeURIComponent(this.branch)}?per_page=50`);
164
+ const commits: any[] = cmp.commits ?? [];
165
+ const changes = commits.slice(-50).reverse().map((c) => ({ sha: c.sha, message: String(c.commit.message).split('\n')[0], author: editorOf(c.commit.message) ?? c.commit.author?.name ?? '', date: c.commit.author?.date ?? '' }));
166
+ return { branch: this.branch, live, count: cmp.ahead_by ?? commits.length, changes };
167
+ }
168
+
169
+ /**
170
+ * Moves `live` to the staging head. A fast-forward when `live` has nothing of its own; when it
171
+ * does (someone committed to it directly), a merge commit, and staging follows so the next Go
172
+ * live is a fast-forward again. A conflict is refused and left to a person in GitHub.
173
+ */
174
+ async goLive(message: string): Promise<{ commit: string; url: string; merged: boolean } | null> {
175
+ const live = this.opts.live;
176
+ if (!live) throw new Error('no live branch configured');
177
+ const head = await this.req<any>('GET', `${this.repoUrl}/git/ref/heads/${encodeURIComponent(this.branch)}`);
178
+ const sha: string = head.object.sha;
179
+ const url = (c: string) => `https://github.com/${this.opts.repo}/commit/${c}`;
180
+ const ff = await this.raw('PATCH', `${this.repoUrl}/git/refs/heads/${encodeURIComponent(live)}`, { sha, force: false });
181
+ if (ff.ok) return { commit: sha, url: url(sha), merged: false };
182
+ if (ff.status !== 422) throw new Error(`GitHub PATCH ${live} -> ${ff.status} ${(await ff.text()).slice(0, 300)}`);
183
+ const merge = await this.raw('POST', `${this.repoUrl}/merges`, { base: live, head: sha, commit_message: message });
184
+ if (merge.status === 204) return null; // nothing to put live
185
+ if (merge.status === 409) throw new Error(`The live branch (${live}) has changes that conflict with these. Someone needs to merge ${this.branch} into ${live} in GitHub.`);
186
+ if (!merge.ok) throw new Error(`GitHub merge -> ${merge.status} ${(await merge.text()).slice(0, 300)}`);
187
+ const merged = await merge.json() as any;
188
+ await this.raw('PATCH', `${this.repoUrl}/git/refs/heads/${encodeURIComponent(this.branch)}`, { sha: merged.sha, force: false }).catch(() => { /* a save landed meanwhile; the next Go live merges again */ });
189
+ return { commit: merged.sha, url: merged.html_url ?? url(merged.sha), merged: true };
190
+ }
150
191
  }
151
192
 
152
193
  function encodePath(p: string) { return p.split('/').map(encodeURIComponent).join('/'); }
194
+
195
+ /** The person named by `commitMessage` ("Edited by …"), since every commit's author is the token's. */
196
+ function editorOf(message: string): string | undefined {
197
+ return /\n\nEdited by (.+)$/m.exec(String(message))?.[1]?.trim();
198
+ }
@@ -28,6 +28,16 @@ export interface Revision {
28
28
  date: string;
29
29
  }
30
30
 
31
+ /** Saved changes on the staging branch that the live branch doesn't have yet. */
32
+ export interface PendingChanges {
33
+ /** The branch saves go to, and the one Go live updates. */
34
+ branch: string;
35
+ live: string;
36
+ /** Commits waiting, newest first (at most 50 listed; `count` is the real number). */
37
+ count: number;
38
+ changes: Revision[];
39
+ }
40
+
31
41
  export interface Storage {
32
42
  readonly kind: 'local' | 'github';
33
43
  /** Text file content at a repo-relative path, or null when missing. */
@@ -49,6 +59,10 @@ export interface Storage {
49
59
  * built (the editor deployment doesn't rebuild on every save). undefined when neither.
50
60
  */
51
61
  asset(path: string): Promise<Uint8Array | undefined>;
62
+ /** With a live branch configured (`github.live`): what saving has staged. Absent otherwise. */
63
+ pending?(): Promise<PendingChanges>;
64
+ /** Puts everything staged on the live branch (fast-forward, else a merge commit). */
65
+ goLive?(message: string): Promise<{ commit: string; url: string; merged: boolean } | null>;
52
66
  }
53
67
 
54
68
  export async function sha256(text: string): Promise<string> {
@@ -12,11 +12,13 @@ const links = [
12
12
  ...(opts.auth === 'passkey' && user?.role === 'admin' ? [{ id: 'users', label: 'Users', href: '/edit/users' }] : []),
13
13
  ];
14
14
  ---
15
- <nav class="ase-nav" aria-label="Editor">
16
- <a class="ase-nav__site" href="/edit">{opts.siteName}</a>
15
+ <nav class="ps-nav" aria-label="Editor">
16
+ <a class="ps-nav__site" href="/edit">{opts.siteName}</a>
17
17
  {links.map((l) => <a href={l.href} aria-current={l.id === current ? 'page' : undefined}>{l.label}</a>)}
18
- <span class="ase-nav__user">
18
+ <span class="ps-nav__user">
19
19
  <a href="/" target="_blank" rel="noopener">View site ↗</a>
20
+ {opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-btn--primary ps-live" hidden>Go live</button>}
20
21
  {user && opts.auth === 'passkey' && <span>Signed in as <strong>{user.name}</strong> · <a href="/api/editor/auth/logout">Sign out</a></span>}
21
22
  </span>
22
23
  </nav>
24
+ <script>import '../client/live.ts';</script>
@@ -2,13 +2,15 @@
2
2
  // GET /api/editor/collection/<id> -> { items }
3
3
  // POST /api/editor/collection/<id> { title, slug } -> creates one (a draft, if the collection has drafts)
4
4
  // GET /api/editor/collection/<id>/<slug> -> { data, body, hash }
5
- // PUT /api/editor/collection/<id>/<slug> { data, body, base } -> one commit
5
+ // ?revisions=1 -> { revisions } ?rev=<sha> -> { data, body } as of that commit
6
+ // PUT /api/editor/collection/<id>/<slug> { data, body, base, slug? } -> one commit; a new `slug`
7
+ // also moves the file and adds a redirect (when the collection has `url` and the site a redirects file)
6
8
  // DELETE /api/editor/collection/<id>/<slug>
7
9
  import type { APIRoute } from 'astro';
8
- import { bad, collections, commitMessage, json, listItems, listPages, reservedSlugs, storage } from '../../server/context';
9
- import { sha256 } from '../../core/storage';
10
+ import { bad, collections, commitMessage, json, listItems, listPages, opts, reservedSlugs, storage } from '../../server/context';
11
+ import { isSha, sha256, type FileChange } from '../../core/storage';
10
12
  import { parseMarkdown, writeMarkdown } from '../../core/frontmatter';
11
- import { slugProblem } from '../../core/pages';
13
+ import { addRedirectLine, slugProblem } from '../../core/pages';
12
14
  import { plainText, sanitizeFields, sanitizeMarkdown } from '../../core/sanitize';
13
15
  import type { CollectionDoc } from '../../runtime';
14
16
  export const prerender = false;
@@ -26,11 +28,18 @@ function cleanData(c: CollectionDoc, data: Record<string, unknown>) {
26
28
  return out;
27
29
  }
28
30
 
29
- export const GET: APIRoute = async ({ params }) => {
31
+ export const GET: APIRoute = async ({ params, url }) => {
30
32
  const c = find(params.id);
31
33
  if (!c) return bad('no such collection', 404);
32
34
  if (!params.slug) return json({ items: await listItems(c) });
33
35
  if (!SLUG.test(params.slug)) return bad('not found', 404);
36
+ if (url.searchParams.has('revisions')) return json({ revisions: await storage().history(file(c, params.slug)) });
37
+ const rev = url.searchParams.get('rev');
38
+ if (rev) {
39
+ if (!isSha(rev)) return bad('bad revision');
40
+ const old = await storage().readAt(file(c, params.slug), rev);
41
+ return old === null ? bad('no such revision', 404) : json(parseMarkdown(old));
42
+ }
34
43
  const raw = await storage().readFile(file(c, params.slug));
35
44
  if (raw === null) return bad('not found', 404);
36
45
  return json({ ...parseMarkdown(raw), hash: await sha256(raw) });
@@ -71,10 +80,23 @@ export const PUT: APIRoute = async ({ params, request, locals }) => {
71
80
  const data = cleanData(c, body.data);
72
81
  if ('title' in c.fields && !String(data.title ?? '').trim()) return bad('Give it a title.');
73
82
  const content = writeMarkdown(raw, data, sanitizeMarkdown(body.body));
74
- if (content === raw) return json({ ok: true, unchanged: true, hash: await sha256(raw) });
83
+ const next = typeof body.slug === 'string' ? body.slug.trim() : slug;
84
+ const moving = next !== slug;
85
+ if (!moving && content === raw) return json({ ok: true, unchanged: true, hash: await sha256(raw) });
86
+ const files: FileChange[] = [{ path: file(c, next), content }];
87
+ let deletes: string[] | undefined;
88
+ if (moving) {
89
+ const existing = [...(await listItems(c)).map((i) => i.slug), ...(await listPages()).map((p) => p.slug)].filter((s) => s !== slug);
90
+ const problem = SLUG.test(next) ? slugProblem(next, { existing, reserved: reservedSlugs() }) : 'Use letters, numbers and dashes in the URL.';
91
+ if (problem) return bad(problem, 409);
92
+ deletes = [file(c, slug)];
93
+ const redirects = c.url ? await storage().readFile(opts.redirectsFile) : null;
94
+ if (redirects !== null && c.url) files.push({ path: opts.redirectsFile, content: addRedirectLine(redirects, c.url(slug), c.url(next)) });
95
+ }
96
+ const subject = moving ? `Move ${name(c)} ${slug} to ${next} via site editor` : `Edit ${name(c)} ${slug} via site editor`;
75
97
  try {
76
- const result = await storage().commit({ message: commitMessage(`Edit ${name(c)} ${slug} via site editor`, locals), files: [{ path: file(c, slug), content }] });
77
- return json({ ok: true, result, hash: await sha256(content) });
98
+ const result = await storage().commit({ message: commitMessage(subject, locals), files, deletes });
99
+ return json({ ok: true, result, hash: await sha256(content), slug: next, redirected: !!(moving && files.length > 1) });
78
100
  } catch (e: any) { return bad(`Save failed: ${e.message}`, 500); }
79
101
  };
80
102
 
@@ -0,0 +1,27 @@
1
+ // Go live: with `github.live` set, saves wait on the staging branch and this puts them on the
2
+ // branch the public site builds from, in one step.
3
+ // GET /api/editor/live -> { enabled: false } | { enabled: true, branch, live, count, changes, stagingUrl? }
4
+ // POST /api/editor/live -> { ok, commit, url, merged } | { ok, nothing: true }
5
+ import type { APIRoute } from 'astro';
6
+ import { bad, editorOf, json, opts, storage } from '../../server/context';
7
+ export const prerender = false;
8
+
9
+ const enabled = () => !!(opts.github?.live && storage().pending && storage().goLive);
10
+
11
+ export const GET: APIRoute = async () => {
12
+ if (!enabled()) return json({ enabled: false });
13
+ try {
14
+ return json({ enabled: true, ...await storage().pending!(), stagingUrl: opts.github?.stagingUrl ?? null });
15
+ } catch (e: any) { return bad(`Could not check what is waiting: ${e.message}`, 502); }
16
+ };
17
+
18
+ export const POST: APIRoute = async ({ locals }) => {
19
+ if (!enabled()) return bad('Saving goes straight to the site here; there is nothing to put live.', 404);
20
+ const who = editorOf(locals)?.name;
21
+ try {
22
+ const { count } = await storage().pending!();
23
+ if (!count) return json({ ok: true, nothing: true });
24
+ const res = await storage().goLive!(`Go live: ${count} change${count === 1 ? '' : 's'}${who ? `\n\nPut live by ${who}` : ''}`);
25
+ return res ? json({ ok: true, count, ...res }) : json({ ok: true, nothing: true });
26
+ } catch (e: any) { return bad(e.message, 409); }
27
+ };
@@ -19,29 +19,29 @@ const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reserved
19
19
  <meta name="robots" content="noindex" />
20
20
  <title>{c.label} — {opts.siteName}</title>
21
21
  </head>
22
- <body class="ase-index">
22
+ <body class="ps-index">
23
23
  <Nav current={`collection-${id}`} />
24
- <main class="ase-index__main">
25
- <header class="ase-index__head">
26
- <div><h1>{c.label} <span class="ase-muted">{items.length}</span></h1></div>
27
- {c.create !== false && <button type="button" id="ase-add-item" class="ase-btn ase-btn--primary">Add {singular}</button>}
24
+ <main class="ps-index__main">
25
+ <header class="ps-index__head">
26
+ <div><h1>{c.label} <span class="ps-muted">{items.length}</span></h1></div>
27
+ {c.create !== false && <button type="button" id="ps-add-item" class="ps-btn ps-btn--primary">Add {singular}</button>}
28
28
  </header>
29
- <div class="ase-index__tools"><input type="search" id="ase-page-search" placeholder={`Search ${c.label.toLowerCase()}`} aria-label="Search" /></div>
30
- <ul class="ase-pagelist" id="ase-pagelist">
29
+ <div class="ps-index__tools"><input type="search" id="ps-page-search" placeholder={`Search ${c.label.toLowerCase()}`} aria-label="Search" /></div>
30
+ <ul class="ps-pagelist" id="ps-pagelist">
31
31
  {items.map((i) => (
32
32
  <li data-slug={i.slug} data-search={`${i.title} ${i.slug}`.toLowerCase()}>
33
- <a class="ase-pagelist__edit" href={`/edit/collection/${id}/${i.slug}`}><strong>{i.title}{i.draft && <span class="ase-pill">Draft</span>}</strong><span class="ase-muted">{i.date.slice(0, 10)}</span></a>
34
- <div class="ase-pagelist__actions">
35
- {!i.draft && c.url && <a class="ase-btn ase-btn--small ase-btn--ghost" href={c.url(i.slug)} target="_blank" rel="noopener">View ↗</a>}
36
- <button type="button" class="ase-btn ase-btn--small ase-btn--ghost ase-btn--danger" data-delete={i.slug}>Delete</button>
33
+ <a class="ps-pagelist__edit" href={`/edit/collection/${id}/${i.slug}`}><strong>{i.title}{i.draft && <span class="ps-pill">Draft</span>}</strong><span class="ps-muted">{i.date.slice(0, 10)}</span></a>
34
+ <div class="ps-pagelist__actions">
35
+ {!i.draft && c.url && <a class="ps-btn ps-btn--small ps-btn--ghost" href={c.url(i.slug)} target="_blank" rel="noopener">View ↗</a>}
36
+ <button type="button" class="ps-btn ps-btn--small ps-btn--ghost ps-btn--danger" data-delete={i.slug}>Delete</button>
37
37
  </div>
38
38
  </li>
39
39
  ))}
40
40
  </ul>
41
- <p id="ase-no-match" class="ase-muted" hidden>Nothing matches.</p>
41
+ <p id="ps-no-match" class="ps-muted" hidden>Nothing matches.</p>
42
42
  </main>
43
- <div id="ase-modal-root"></div>
44
- <script is:inline set:html={`window.__ASE_COLLECTION__ = ${JSON.stringify(boot).replace(/</g, '\\u003c')};`} />
43
+ <div id="ps-modal-root"></div>
44
+ <script is:inline set:html={`window.__PS_COLLECTION__ = ${JSON.stringify(boot).replace(/</g, '\\u003c')};`} />
45
45
  <script>import '../client/collection.ts';</script>
46
46
  </body>
47
47
  </html>
@@ -20,20 +20,20 @@ const boot = {
20
20
  <meta name="robots" content="noindex" />
21
21
  <title>{def.label} — {opts.siteName}</title>
22
22
  </head>
23
- <body class="ase-index">
23
+ <body class="ps-index">
24
24
  <Nav current="settings" />
25
- <main class="ase-index__main ase-global">
26
- <header class="ase-index__head">
25
+ <main class="ps-index__main ps-global">
26
+ <header class="ps-index__head">
27
27
  <div>
28
28
  <h1>{def.label}</h1>
29
- {def.description && <p class="ase-muted">{def.description}</p>}
29
+ {def.description && <p class="ps-muted">{def.description}</p>}
30
30
  </div>
31
- <button type="button" id="ase-global-save" class="ase-btn ase-btn--primary" disabled>Save</button>
31
+ <button type="button" id="ps-global-save" class="ps-btn ps-btn--primary" disabled>Save</button>
32
32
  </header>
33
- <div id="ase-global-form" class="ase-global__form"><p class="ase-muted">Loading…</p></div>
33
+ <div id="ps-global-form" class="ps-global__form"><p class="ps-muted">Loading…</p></div>
34
34
  </main>
35
- <div id="ase-modal-root"></div>
36
- <script is:inline set:html={`window.__ASE_GLOBAL__ = ${JSON.stringify(boot).replace(/</g, '\\u003c')};`} />
35
+ <div id="ps-modal-root"></div>
36
+ <script is:inline set:html={`window.__PS_GLOBAL__ = ${JSON.stringify(boot).replace(/</g, '\\u003c')};`} />
37
37
  <script>import '../client/global.ts';</script>
38
38
  </body>
39
39
  </html>