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

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 CHANGED
@@ -222,6 +222,30 @@ A few things worth knowing while you set up the schema:
222
222
  in a WordPress heading. See [Bold and italic in headings](#bold-and-italic-in-headings).
223
223
  - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
224
224
 
225
+ ### Required fields
226
+
227
+ Mark a field `required: true` and the editor won't save without it: the field is starred, and Save
228
+ says what is missing and goes to it.
229
+
230
+ ```ts
231
+ fields: {
232
+ title: { type: 'text', label: 'Title' }, // always required
233
+ date: { type: 'date', label: 'Date', time: false, required: true },
234
+ year: { type: 'number', label: 'Year', required: true },
235
+ }
236
+ ```
237
+
238
+ - **Collections: mark every field the Astro schema insists on** (no `.optional()`, no `.default()`). One
239
+ file without it stops the whole build, and Astro checks drafts too, so the editor does as well.
240
+ **Add** asks for required fields along with the title, unless a `default` answers them (a collection's
241
+ first date starts as today).
242
+ - **Pages** are checked when they are on the site; a draft may be incomplete. This covers block fields
243
+ and `pageFields`. **Globals** are always checked.
244
+ - A field hidden by `showIf` isn't asked for, so keep it optional in the Astro schema. Fields in a `list`
245
+ can be required in each row. A `boolean` can't be: off is an answer.
246
+ - A required field showing its default (or a select's first option) counts as filled in. In collections
247
+ and globals that value is written to the file.
248
+
225
249
  ### Checkboxes, and fields that depend on others
226
250
 
227
251
  `multiselect` shows its `options` as checkboxes and stores the ticked values as an array, in the
@@ -319,7 +343,7 @@ export const templates = [{ label: 'Standard page', create: ({ title }) => ({ ti
319
343
  export const collections = {
320
344
  blog: {
321
345
  label: 'Posts', singular: 'post', dir: 'src/content/blog', url: (slug) => `/${slug}/`,
322
- fields: { title: { type: 'text', label: 'Title' }, draft: { type: 'boolean', label: 'Draft' }, date: { type: 'date', label: 'Date' }, tags: { type: 'tags', label: 'Tags' } },
346
+ fields: { title: { type: 'text', label: 'Title' }, draft: { type: 'boolean', label: 'Draft' }, date: { type: 'date', label: 'Date', required: true }, tags: { type: 'tags', label: 'Tags' } },
323
347
  },
324
348
  };
325
349
 
@@ -436,8 +460,8 @@ editor's build only, they render on request from storage instead:
436
460
  pagestack({ liveRoutes: ['/', '/blog'], /* … */ })
437
461
  ```
438
462
 
439
- The page reads its collections through `liveEntries`, which gives the saved entries on the editor's
440
- server and `null` everywhere else, so the public build is unchanged and stays fully static:
463
+ The page reads its collections through `liveEntries`, which gives the saved entries to these
464
+ pages and to the editor's previews, and `null` everywhere else, so the public build is unchanged and stays fully static:
441
465
 
442
466
  ```ts
443
467
  // src/lib/content.ts
package/live.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // For host sites whose list pages should show what the editor has saved (the `liveRoutes` option).
2
2
  //
3
- // On the editor's server, for those pages, this returns a collection's entries as stored now (the
3
+ // On the editor's server, for those pages and the editor's previews, this returns a collection's entries as stored now (the
4
4
  // staging branch). Everywhere else, including the public build and prerendering, it returns null,
5
5
  // so the caller uses Astro's own getCollection and the public site is unchanged:
6
6
  //
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.17",
3
+ "version": "0.1.0-beta.18",
4
4
  "description": "A block editor for Astro sites. Content stays in your repo, saves are git commits, the public site stays static, sign-in is passkeys.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,20 +1,51 @@
1
1
  // The list of a collection: add, delete, search.
2
2
  import { slugify, uniqueSlug } from '../core/pages';
3
- import { confirmDialog, promptDialog, toast } from './ui';
3
+ import { missingFields } from '../core/required';
4
+ import type { Field } from '../runtime';
5
+ import { renderForm, showMissing } from './form';
6
+ import { pickImage } from './picker';
7
+ import { confirmDialog, dialog, promptDialog, toast } from './ui';
4
8
 
5
- const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[] };
9
+ const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[]; ask: Record<string, Field> };
6
10
  const api = `/api/editor/collection/${boot.id}`;
7
11
 
8
12
  document.getElementById('ps-add-item')?.addEventListener('click', async () => {
9
- const title = await promptDialog({ title: `Add ${boot.singular}`, label: 'Title', submit: `Add ${boot.singular}` });
10
- if (!title) return;
11
- const slug = uniqueSlug(slugify(title) || boot.singular, [...boot.slugs, ...boot.reserved]);
12
- const res = await fetch(api, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title, slug }) });
13
- const data = await res.json();
14
- if (!res.ok) { toast(data.error || 'That did not work.', 'error'); return; }
15
- location.href = `/edit/collection/${boot.id}/${data.slug}`;
13
+ const add = `Add ${boot.singular}`;
14
+ const asked = Object.keys(boot.ask).length > 0;
15
+ const title = asked ? null : await promptDialog({ title: add, label: 'Title', submit: add });
16
+ if (title) await create(title);
17
+ else if (asked) askAll(add);
16
18
  });
17
19
 
20
+ /** The title, and the required fields nothing else answers: without them the new file would break the site's build. */
21
+ function askAll(add: string) {
22
+ const data: Record<string, unknown> = {};
23
+ const box = document.createElement('div'); box.className = 'ps-newpage';
24
+ const head = document.createElement('div');
25
+ renderForm(head, { label: boot.singular, fields: { title: { type: 'text', label: 'Title', required: true } } }, {}, { pickImage, onChange: () => {} });
26
+ const form = document.createElement('div');
27
+ renderForm(form, { label: boot.singular, fields: boot.ask }, data, { pickImage, onChange: (name, value) => { data[name] = value; } });
28
+ box.append(head, form);
29
+ dialog(add, box, [{ label: 'Cancel' }, {
30
+ label: add, kind: 'primary', run: async () => {
31
+ const title = head.querySelector('input')!.value.trim();
32
+ const missing = missingFields(boot.ask, data);
33
+ showMissing(form, missing);
34
+ showMissing(head, title ? [] : [{ path: ['title'], label: 'Title' }]);
35
+ return missing.length || !title ? false : create(title, data);
36
+ },
37
+ }]);
38
+ }
39
+
40
+ /** False when it failed, which it has said. */
41
+ async function create(title: string, data?: Record<string, unknown>): Promise<false | void> {
42
+ const slug = uniqueSlug(slugify(title) || boot.singular, [...boot.slugs, ...boot.reserved]);
43
+ const res = await fetch(api, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title, slug, data }) });
44
+ const d = await res.json();
45
+ if (!res.ok) { toast(d.error || 'That did not work.', 'error'); return false; }
46
+ location.href = `/edit/collection/${boot.id}/${d.slug}`;
47
+ }
48
+
18
49
  document.getElementById('ps-pagelist')!.addEventListener('click', async (e) => {
19
50
  const b = (e.target as HTMLElement).closest<HTMLElement>('[data-delete]');
20
51
  if (!b) return;
@@ -10,14 +10,15 @@ import { insertTarget, insertItems } from '../core/insert';
10
10
  import { slugProblem } from '../core/pages';
11
11
  import type { Revision } from '../core/storage';
12
12
  import { EditorState } from './state';
13
- import { renderForm } from './form';
13
+ import { missingInPage, missingMessage } from '../core/required';
14
+ import { commitTyping, renderForm, showMissing } from './form';
14
15
  import { renderTree } from './tree';
15
16
  import { renderInserter } from './inserter';
16
17
  import { InlineEditor } from './inline';
17
18
  import { pickImage } from './picker';
18
19
  import { icons } from './icons';
19
20
  import type { MenuItem } from './ui';
20
- import { confirmDialog, dialog, openMenu, promptDialog, toast } from './ui';
21
+ import { confirmDialog, dialog, openMenu, promptDialog, taskQueue, toast } from './ui';
21
22
  import previewCss from './preview.css?raw';
22
23
 
23
24
  interface Boot {
@@ -489,7 +490,7 @@ function renderPageTab(root: HTMLElement) {
489
490
  root.append(form);
490
491
 
491
492
  if (Object.keys(boot.pageFields).length) {
492
- const layout = document.createElement('div');
493
+ const layout = document.createElement('div'); layout.id = 'ps-layout-form';
493
494
  renderForm(layout, { label: 'Layout', fields: boot.pageFields }, state.doc.layout ?? {}, {
494
495
  ...formCallbacks,
495
496
  onChange: (name, value, o) => { renderFull = !o?.live; applyField(`layout.${name}`, value, o?.live, boot.pageFields[name]); },
@@ -770,7 +771,7 @@ $('#ps-discard').addEventListener('click', async () => {
770
771
  renderFull = true;
771
772
  state.reset(r.page, r.hash);
772
773
  });
773
- $('#ps-save').addEventListener('click', () => save());
774
+ $('#ps-save').addEventListener('click', () => { inline.stop(true); save(); });
774
775
  $<HTMLInputElement>('#ps-ready').addEventListener('change', (e) => publish((e.target as HTMLInputElement).checked));
775
776
  $('#ps-preview-tab').addEventListener('click', previewInTab);
776
777
  document.querySelectorAll<HTMLButtonElement>('.ps-top__devices button').forEach((b) => b.addEventListener('click', () => {
@@ -801,23 +802,40 @@ function previewInTab() {
801
802
  form.remove();
802
803
  }
803
804
 
804
- async function save(opts: { slug?: string } = {}): Promise<{ slug?: string; result?: any } | null> {
805
- if (!state.dirty && !opts.slug) return null;
805
+ /** Says which required fields are empty, opens the first one's block and points at it. */
806
+ function complete(doc: PageDoc): boolean {
807
+ const missing = missingInPage(doc, registry, boot.pageFields);
808
+ if (!missing.length) return true;
806
809
  inline.stop(true);
810
+ toast(missingMessage(missing), 'error');
811
+ const node = missing[0].node ?? null;
812
+ select(node);
813
+ showMissing($(node ? '#ps-inspector' : '#ps-layout-form'), missing.filter((m) => m.node === node));
814
+ return false;
815
+ }
816
+
817
+ const queued = taskQueue();
818
+ const save = (opts: { slug?: string } = {}) => queued(() => saveNow(opts));
819
+
820
+ /** Leaves the field being edited alone, in the sidebar or on the page: its text is in the document already. */
821
+ async function saveNow(opts: { slug?: string }): Promise<{ slug?: string; result?: any } | null> {
822
+ if (!state.dirty && !opts.slug) return null;
823
+ if (!complete(state.doc)) return null;
824
+ const sent = state.doc;
807
825
  saving = true; refreshButtons(); setSaveStatus('Saving…');
808
826
  try {
809
- const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: state.doc, base: state.hash, slug: opts.slug }) });
827
+ const res = await fetch(`/api/editor/page/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ page: sent, base: state.hash, slug: opts.slug }) });
810
828
  const data = await res.json();
811
829
  if (!res.ok) { toast(data.error || 'Save failed', 'error'); setSaveStatus(''); return null; }
812
- state.markSaved(data.hash);
813
- boot.page = state.doc;
830
+ state.markSaved(data.hash, sent);
831
+ boot.page = sent;
814
832
  const r = data.result;
815
833
  if (r.kind === 'github') toast(r.pullRequest ? `Committed and opened a pull request: ${r.pullRequest}` : document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : `Committed ${String(r.commit).slice(0, 7)} to ${r.branch}. The host will rebuild the site.`, 'ok', { href: r.pullRequest || r.url });
816
834
  else toast(`Saved to the working tree (${r.files.join(', ')}). Commit it with git when you're happy.`, 'ok');
817
- setSaveStatus('Saved');
835
+ setSaveStatus(state.dirty ? '' : 'Saved');
818
836
  return data;
819
837
  } catch (e: any) { toast(`Save failed: ${e.message}`, 'error'); setSaveStatus(''); return null; }
820
- finally { saving = false; refreshChrome(); }
838
+ finally { saving = false; refreshChrome({ inspector: false }); }
821
839
  }
822
840
 
823
841
  /** The Ready to publish switch: a draft or not. Saves straight away, so the switch means what it shows. */
@@ -828,6 +846,7 @@ async function publish(live: boolean) {
828
846
  inline.stop(true);
829
847
  const next = structuredClone(state.doc);
830
848
  if (live) delete next.status; else next.status = 'draft';
849
+ if (!complete(next)) { refreshButtons(); return; }
831
850
  state.apply(next);
832
851
  if (await save()) toast(live ? (staged ? `${next.title} is ready to publish. It goes on the site with the next Publish changes.` : `${next.title} is published.`) : `${next.title} is now a draft: kept off the site.`, 'ok');
833
852
  else { state.undo(); refreshButtons(); }
@@ -841,10 +860,11 @@ async function changeUrl() {
841
860
  check: (v) => (v === boot.slug ? null : slugProblem(v, { existing, reserved: boot.reserved })),
842
861
  });
843
862
  if (!slug || slug === boot.slug) return;
863
+ inline.stop(true);
844
864
  const data = await save({ slug });
845
865
  if (!data) return;
846
866
  if (data.result?.pullRequest) return; // the move is in a pull request; this page stays where it is for now
847
- leaving = true;
867
+ leaving = !state.dirty; // something typed while it moved: the browser asks first
848
868
  location.replace(`/edit/${data.slug}`);
849
869
  }
850
870
 
@@ -920,7 +940,7 @@ function onKeydown(e: KeyboardEvent) {
920
940
  const mod = e.metaKey || e.ctrlKey;
921
941
  const key = e.key.toLowerCase();
922
942
  const run = (fn: () => void) => { e.preventDefault(); fn(); };
923
- if (mod && key === 's') return run(() => { save(); });
943
+ if (mod && key === 's') return run(() => { commitTyping(); save(); });
924
944
  if (mod && e.shiftKey && (key === ',' || key === '<')) return run(toggleSettings);
925
945
  if (e.ctrlKey && e.altKey && (key === 'o' || e.code === 'KeyO')) return run(() => setLeft(leftView === 'list' ? 'off' : 'list'));
926
946
  if (typing) return;
@@ -946,7 +966,7 @@ window.addEventListener('beforeunload', (e) => { if (state.dirty && !leaving) e.
946
966
  state.addEventListener('change', (e) => {
947
967
  const source = (e as CustomEvent).detail.source;
948
968
  if (source === 'inline') return; // DOM already matches; chrome refreshes on commit
949
- if (source === 'field') { refreshChrome({ inspector: false }); return; } // the sidebar is the source: leave the focused input alone
969
+ if (source === 'field' || source === 'save') { refreshChrome({ inspector: false }); return; } // leave the focused input alone
950
970
  if (source === 'undo' || source === 'redo' || source === 'restore' || source === 'reset') {
951
971
  inline.stop(false);
952
972
  if (selected && !nodeAt(state.doc, selected)) { selected = null; tab = 'page'; }
@@ -1,6 +1,7 @@
1
1
  // Schema -> sidebar form. One widget per field type; changes are reported through `onChange`.
2
2
  import type { BlockSchema, Field, ImageValue } from '../runtime';
3
3
  import { formModel, isShown } from '../core/schema';
4
+ import type { Missing } from '../core/required';
4
5
  import { marksField, richField } from './rich';
5
6
 
6
7
  export interface FormCallbacks {
@@ -54,7 +55,9 @@ function conditions(fields: Record<string, Field>, values: Record<string, unknow
54
55
  function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, idPrefix = 'ps-f-'): HTMLElement {
55
56
  const id = `${idPrefix}${name}`;
56
57
  const label = el('label', { for: id }, field.label);
57
- const wrap = el('div', { class: `ps-field ps-field--${field.type}` }, label);
58
+ const wrap = el('div', { class: `ps-field ps-field--${field.type}`, 'data-ps-form': id }, label);
59
+ const outer = cb;
60
+ cb = { ...cb, onChange: (...args) => { clearMissing(wrap); outer.onChange(...args); } };
58
61
  const help = field.help ? el('small', { class: 'ps-muted' }, field.help) : null;
59
62
  // `cancel` matters: a live update landing after `change` would reorder the edit and split its undo step.
60
63
  const debounce = (fn: () => void, ms = 250) => { let t: ReturnType<typeof setTimeout>; const run = () => { clearTimeout(t); t = setTimeout(fn, ms); }; run.cancel = () => clearTimeout(t); return run; };
@@ -62,6 +65,7 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
62
65
  if (field.type === 'text' && field.marks) {
63
66
  wrap.append(marksField(id, (value as string) ?? '', (html, live) => cb.onChange(name, html, { live })));
64
67
  if (help) wrap.append(help);
68
+ markRequired(wrap, field);
65
69
  return wrap;
66
70
  }
67
71
  switch (field.type) {
@@ -207,9 +211,48 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
207
211
  break;
208
212
  }
209
213
  if (help) wrap.append(help);
214
+ markRequired(wrap, field);
210
215
  return wrap;
211
216
  }
212
217
 
218
+ function markRequired(wrap: HTMLElement, field: Field) {
219
+ if (!field.required || field.type === 'boolean') return;
220
+ wrap.querySelector('label, .ps-field__label')?.append(el('span', { class: 'ps-req', 'aria-hidden': 'true', title: 'Required' }, ' *'));
221
+ if (field.type !== 'list' && field.type !== 'multiselect' && field.type !== 'image') wrap.querySelector('input, select, textarea, [contenteditable]')?.setAttribute('aria-required', 'true');
222
+ }
223
+
224
+ function clearMissing(wrap: HTMLElement) {
225
+ wrap.classList.remove('is-missing');
226
+ wrap.querySelector(':scope > .ps-error')?.remove();
227
+ }
228
+
229
+ /** Takes what is still being typed: fields report when they are left, and a keyboard save doesn't leave them. */
230
+ export function commitTyping() {
231
+ const at = document.activeElement;
232
+ if (!(at instanceof HTMLElement) || !(at.isContentEditable || at.matches('input, textarea'))) return;
233
+ const selection = getSelection();
234
+ const caret = at.isContentEditable && selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : null;
235
+ at.blur();
236
+ if (!at.isConnected) return;
237
+ at.focus({ preventScroll: true });
238
+ if (caret) { selection!.removeAllRanges(); selection!.addRange(caret); }
239
+ }
240
+
241
+ /** Points at each field that still needs a value, and goes to the first one in this form. */
242
+ export function showMissing(root: HTMLElement, missing: Missing[]) {
243
+ root.querySelectorAll<HTMLElement>('.is-missing').forEach(clearMissing);
244
+ const wraps = missing.flatMap((m) => root.querySelector<HTMLElement>(`[data-ps-form="${CSS.escape(`ps-f-${m.path.join('-')}`)}"]`) ?? []);
245
+ for (const w of wraps) {
246
+ w.classList.add('is-missing');
247
+ w.append(el('p', { class: 'ps-error', role: 'alert' }, 'This is required.'));
248
+ for (let d = w.closest('details'); d; d = d.parentElement?.closest('details') ?? null) d.open = true;
249
+ }
250
+ // The field itself, not a toolbar above it; a button where that is all there is (choose an image, add a row).
251
+ const first = wraps[0];
252
+ (first?.querySelector<HTMLElement>('input:not([type="file"]), select, textarea:not([hidden]), [contenteditable]') ?? first?.querySelector<HTMLElement>('button'))?.focus();
253
+ wraps[0]?.scrollIntoView?.({ block: 'nearest' });
254
+ }
255
+
213
256
  /** Repeatable rows, each its own little form. Rows can nest (a menu item holds links). */
214
257
  function listWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, id: string): HTMLElement {
215
258
  const fields = field.fields ?? {};
@@ -1,6 +1,7 @@
1
1
  // Edit a site-wide document with the same form widgets as the block sidebar.
2
2
  import type { Field } from '../runtime';
3
- import { renderForm } from './form';
3
+ import { missingFields, missingMessage } from '../core/required';
4
+ import { renderForm, showMissing } from './form';
4
5
  import { pickImage } from './picker';
5
6
  import { toast } from './ui';
6
7
 
@@ -12,6 +13,7 @@ const url = `/api/editor/global/${boot.id}`;
12
13
  let doc: Record<string, unknown> = {};
13
14
  let hash: string | null = null;
14
15
  let dirty = false;
16
+ let saving = false;
15
17
 
16
18
  const res = await fetch(url);
17
19
  const data = await res.json();
@@ -19,15 +21,19 @@ doc = data.doc; hash = data.hash;
19
21
  renderForm(root, { label: boot.label, fields: boot.fields }, doc, {
20
22
  pickImage,
21
23
  pageUrls: boot.pages,
22
- onChange: (name, value) => { doc[name] = value; dirty = true; saveBtn.disabled = false; },
24
+ onChange: (name, value) => { doc[name] = value; dirty = true; saveBtn.disabled = saving; },
23
25
  });
24
26
 
25
27
  saveBtn.addEventListener('click', async () => {
26
- saveBtn.disabled = true;
28
+ const missing = missingFields(boot.fields, doc);
29
+ if (missing.length) { toast(missingMessage(missing), 'error'); showMissing(root, missing); return; }
30
+ saveBtn.disabled = saving = true;
31
+ const sent = JSON.stringify(doc);
27
32
  const r = await fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ doc, base: hash }) });
28
33
  const d = await r.json();
34
+ saving = false;
29
35
  if (!r.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; return; }
30
- hash = d.hash; dirty = false;
36
+ hash = d.hash; dirty = JSON.stringify(doc) !== sent; saveBtn.disabled = !dirty; // edits made meanwhile are still to be saved
31
37
  toast(d.result.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : 'Saved. The site will rebuild.') : "Saved to the working tree. Commit it with git when you're happy.", 'ok');
32
38
  });
33
39
  window.addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
@@ -2,9 +2,10 @@
2
2
  import { marked } from 'marked';
3
3
  import type { Field } from '../runtime';
4
4
  import { sanitizeHtml } from '../core/sanitize';
5
- import { renderForm } from './form';
5
+ import { missingFields, missingMessage } from '../core/required';
6
+ import { commitTyping, renderForm, showMissing } from './form';
6
7
  import { pickImage } from './picker';
7
- import { confirmDialog, dialog, openMenu, promptDialog, toast } from './ui';
8
+ import { confirmDialog, dialog, openMenu, promptDialog, taskQueue, toast } from './ui';
8
9
  import { icons } from './icons';
9
10
  import { InlineEditor } from './inline';
10
11
  import { NEW_BLOCKS, blockAt, insertBlock, replaceBlock } from '../core/markdown';
@@ -86,13 +87,26 @@ body.addEventListener('keydown', (e) => {
86
87
  });
87
88
 
88
89
  // ---- saving ----
89
- async function save(done?: string): Promise<boolean> {
90
+ /** Says which required fields are empty, and points at them. The title has its own message from the server. */
91
+ function complete(): boolean {
92
+ const missing = missingFields(side, data);
93
+ if (!missing.length) return true;
94
+ toast(`${missingMessage(missing)} The site needs ${missing.length === 1 ? 'it' : 'them'} to build, drafts included.`, 'error');
95
+ showMissing($('ps-item-form'), missing);
96
+ return false;
97
+ }
98
+ const queued = taskQueue();
99
+ const save = (done?: string) => queued(() => saveNow(done));
100
+ async function saveNow(done?: string): Promise<boolean> {
101
+ if (!dirty && !done) return true; // a save that was waiting, with nothing new since
90
102
  if (frame && inline.isActive) inline.stop(true);
103
+ if (!complete()) return false;
91
104
  saveBtn.disabled = true; status.textContent = 'Saving…';
105
+ const sent = JSON.stringify([data, body.value]);
92
106
  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 }) });
93
107
  const d = await res.json();
94
108
  if (!res.ok) { toast(d.error || 'Save failed', 'error'); saveBtn.disabled = false; status.textContent = 'Not saved'; return false; }
95
- hash = d.hash; dirty = false; chrome();
109
+ hash = d.hash; dirty = JSON.stringify([data, body.value]) !== sent; chrome(); // edits made meanwhile are still to be saved
96
110
  if (done && !d.result?.pullRequest) toast(done, 'ok'); else toast(d.unchanged ? 'No changes to save.' : d.result?.pullRequest ? 'Saved as a pull request.' : d.result?.kind === 'github' ? (document.getElementById('ps-live') ? 'Saved. Use Publish changes to put it on the site.' : 'Saved. The site will rebuild.') : 'Saved.', 'ok');
97
111
  return true;
98
112
  }
@@ -107,7 +121,7 @@ ready.addEventListener('change', async () => {
107
121
  if (!ok) { data.draft = was; chrome(); }
108
122
  ready.disabled = false;
109
123
  });
110
- addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (dirty) save(); } });
124
+ addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); commitTyping(); if (dirty) save(); } });
111
125
  addEventListener('beforeunload', (e) => { if (dirty) e.preventDefault(); });
112
126
 
113
127
  // ---- URL, revisions, delete ----
@@ -127,11 +141,16 @@ async function changeUrl() {
127
141
  });
128
142
  if (!next || next === boot.slug) return;
129
143
  if (frame && inline.isActive) inline.stop(true);
130
- 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, slug: next }) });
144
+ if (!complete()) return;
145
+ let sent = '';
146
+ const res = await queued(() => {
147
+ sent = JSON.stringify([data, body.value]);
148
+ return fetch(`/api/editor/collection/${boot.id}/${boot.slug}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ data, body: body.value, base: hash, slug: next }) });
149
+ });
131
150
  const d = await res.json();
132
151
  if (!res.ok) { toast(d.error || 'Could not change the URL.', 'error'); return; }
133
152
  if (d.result?.pullRequest) { toast('The move is in a pull request; this stays where it is until that is merged.', 'info', { href: d.result.pullRequest }); return; }
134
- dirty = false;
153
+ dirty = JSON.stringify([data, body.value]) !== sent;
135
154
  location.replace(`/edit/collection/${boot.id}/${d.slug}`);
136
155
  }
137
156
 
@@ -184,7 +203,7 @@ title.value = data.title ?? '';
184
203
  title.addEventListener('input', () => { data.title = title.value; touch(); schedulePage(); });
185
204
  body.value = boot.body;
186
205
  const { title: _, draft: __, ...side } = boot.fields;
187
- const drawForm = () => renderForm($('ps-item-form'), { label: boot.singular, fields: side }, data, { pickImage, pageUrls: boot.pages, onChange: (name, value) => { data[name] = value; touch(); schedulePage(); } });
206
+ const drawForm = () => renderForm($('ps-item-form'), { label: boot.singular, fields: side }, data, { pickImage, pageUrls: boot.pages, onChange: (name, value) => { data[name] = value ?? ''; touch(); /* a cleared number: undefined would be left out of the save, and the old one kept */ schedulePage(); } });
188
207
  drawForm();
189
208
  draw(); chrome();
190
209
 
@@ -5,6 +5,7 @@ import { uploadImage } from './upload';
5
5
 
6
6
  export function pickImage(current: ImageValue | undefined, done: (img: ImageValue) => void) {
7
7
  const root = document.getElementById('ps-modal-root')!;
8
+ document.body.append(root); // above a dialog it was opened from
8
9
  root.innerHTML = `
9
10
  <div class="ps-modal" role="dialog" aria-modal="true" aria-label="Choose an image">
10
11
  <div class="ps-modal__box">
@@ -128,6 +128,8 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
128
128
  .ps-fields { padding: 4px 12px 12px; display: flex; flex-direction: column; gap: 10px; }
129
129
  .ps-field { display: flex; flex-direction: column; gap: 4px; }
130
130
  .ps-field label, .ps-field__label { font-size: 12px; font-weight: 600; }
131
+ .ps-req { color: var(--ps-danger); }
132
+ .ps-field.is-missing > input, .ps-field.is-missing > select, .ps-field.is-missing > textarea, .ps-field.is-missing > [contenteditable] { border-color: var(--ps-danger); }
131
133
  .ps-checks { display: flex; flex-wrap: wrap; gap: 6px 14px; }
132
134
  .ps-field .ps-checks label { display: inline-flex; align-items: center; gap: 6px; font-weight: 400; cursor: pointer; }
133
135
  .ps-field--inline { flex-direction: row; align-items: center; gap: 8px; }
@@ -208,6 +210,11 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
208
210
  .ps-dialog footer { display: flex; justify-content: flex-end; gap: 8px; }
209
211
  .ps-dialog__body, .ps-newpage { display: flex; flex-direction: column; gap: 12px; }
210
212
  .ps-dialog .ps-field label { display: flex; flex-direction: column; gap: 4px; }
213
+ .ps-dialog .ps-field .ps-checks label { flex-direction: row; }
214
+ .ps-dialog .ps-fields { padding: 0; }
215
+ .ps-dialog .ps-fields .ps-field > label { display: block; }
216
+ .ps-dialog .ps-group { border: 0; }
217
+ .ps-dialog .ps-group > summary { display: none; }
211
218
  .ps-dialog .ps-field input[type="text"], .ps-dialog .ps-field select { width: 100%; padding: 7px 10px; border: 1px solid var(--ps-border); border-radius: 6px; font: inherit; background: #fff; }
212
219
  .ps-prefixed { display: flex; align-items: center; gap: 4px; font-weight: 400; }
213
220
  .ps-error { color: var(--ps-danger); font-size: 12px; margin: 2px 0 0; }
@@ -65,10 +65,11 @@ export class EditorState extends EventTarget {
65
65
  this.persist();
66
66
  this.emit('redo');
67
67
  }
68
- markSaved(hash: string) {
68
+ /** `saved` is the document that was sent: edits made while the save ran are still to be saved. */
69
+ markSaved(hash: string, saved: PageDoc) {
69
70
  this.hash = hash;
70
- this.savedJson = JSON.stringify(this.doc);
71
- this.clearDraft();
71
+ this.savedJson = JSON.stringify(saved);
72
+ this.persist();
72
73
  this.emit('save');
73
74
  }
74
75
  /** Throw away the draft and go back to the stored page. */
package/src/client/ui.ts CHANGED
@@ -16,6 +16,16 @@ export function toast(text: string, kind: 'ok' | 'info' | 'warn' | 'error', opts
16
16
  setTimeout(() => t.remove(), kind === 'error' ? 15000 : 8000);
17
17
  }
18
18
 
19
+ /** Runs tasks one after another: a save asked for during a save waits, and then builds on its result. */
20
+ export function taskQueue() {
21
+ let last: Promise<unknown> = Promise.resolve();
22
+ return <T>(task: () => Promise<T>): Promise<T> => {
23
+ const run = last.then(task);
24
+ last = run.catch(() => {});
25
+ return run;
26
+ };
27
+ }
28
+
19
29
  export interface DialogAction { label: string; kind?: 'primary' | 'danger'; run?: () => void | boolean | Promise<void | boolean> }
20
30
 
21
31
  /** A modal. An action closes it unless `run` returns false. */
@@ -32,7 +42,10 @@ export function dialog(title: string, body: HTMLElement | string, actions: Dialo
32
42
  if (typeof body === 'string') { const p = document.createElement('p'); p.textContent = body; content.append(p); } else content.append(body);
33
43
  const foot = document.createElement('footer');
34
44
  const close = () => { wrap.remove(); document.removeEventListener('keydown', onKey, true); opts.onClose?.(); };
35
- const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); close(); } };
45
+ const onKey = (e: KeyboardEvent) => {
46
+ if (e.key !== 'Escape' || [...document.querySelectorAll('.ps-modal')].at(-1) !== wrap) return; // the image picker is open over it
47
+ e.stopPropagation(); close();
48
+ };
36
49
  document.addEventListener('keydown', onKey, true);
37
50
  let primary: HTMLButtonElement | undefined;
38
51
  for (const a of actions) {
package/src/core/media.ts CHANGED
@@ -35,3 +35,13 @@ export function imagePath(src: string, publicDir: string, roots: string[]): stri
35
35
  const path = publicDir + decodeURI(src);
36
36
  return roots.some((r) => path.startsWith(`${r}/`)) ? path : null;
37
37
  }
38
+
39
+ /** Newest upload folders first: folders before files, folders descending (2026 before 2020), files alphabetically. */
40
+ export function libraryOrder(a: string, b: string): number {
41
+ const x = a.split('/'), y = b.split('/');
42
+ let i = 0;
43
+ while (i < x.length - 1 && i < y.length - 1 && x[i] === y[i]) i++;
44
+ const xDir = i < x.length - 1, yDir = i < y.length - 1;
45
+ if (xDir !== yDir) return xDir ? -1 : 1;
46
+ return xDir ? y[i].localeCompare(x[i]) : x[i].localeCompare(y[i]);
47
+ }