@pirateandfox/pagestack 0.1.0-beta.16 → 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
@@ -188,7 +188,7 @@ export const presets: Preset[] = [
188
188
  ```
189
189
 
190
190
  Field types: `text`, `richtext`, `image`, `link`, `color`, `select`, `number`, `boolean`,
191
- `textarea`, `code`, `svg`. `inline: true` on `text` / `richtext` / `image` makes the field
191
+ `textarea`, `code`, `svg`, `date`, `tags`, `list`, `multiselect`. `inline: true` on `text` / `richtext` / `image` makes the field
192
192
  editable by clicking it in the preview. `marks: true` on a `text` field allows bold and italic in it
193
193
  (see [Bold and italic in headings](#bold-and-italic-in-headings)). The schema drives the sidebar form, validation on save,
194
194
  the add-block menus and the tree labels. **Presets are the section library.**
@@ -222,6 +222,51 @@ 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
+
249
+ ### Checkboxes, and fields that depend on others
250
+
251
+ `multiselect` shows its `options` as checkboxes and stores the ticked values as an array, in the
252
+ order the options are declared. `showIf` shows a field only when another one has a certain value:
253
+
254
+ ```ts
255
+ repeats: { type: 'select', label: 'Repeats', options: [{ value: '', label: 'Never' }, { value: 'weekly', label: 'Weekly' }] },
256
+ repeatsOn: { type: 'multiselect', label: 'Repeats on', options: [{ value: 'mon', label: 'Mon' }, { value: 'wed', label: 'Wed' }], showIf: { field: 'repeats', is: 'weekly' } },
257
+ until: { type: 'date', label: 'Until', time: false, showIf: { field: 'repeats', not: '' } },
258
+ ```
259
+
260
+ - `is` and `not` take one value or a list of them (any may match). With neither, the field shows when
261
+ the other one has a value. Missing, `''`, `false` and an empty list all count as no value. A
262
+ `multiselect` matches when any ticked value does.
263
+ - `field` names a field in the same form, or in the same row inside a `list`. A field that depends on
264
+ a hidden field is hidden too.
265
+ - Hiding a field only changes the form. **The stored value stays**, so your component should look at
266
+ the same condition (`repeats && until`) rather than at the dependent field alone.
267
+ - Nothing ticked is stored as `[]`. In a collection, allow for both that and a missing key in the Astro
268
+ schema: `z.array(z.string()).default([])`.
269
+
225
270
  ### Bold and italic in headings
226
271
 
227
272
  Text fields are plain text by default. Add `marks: true` to one and it behaves like a WordPress
@@ -298,7 +343,7 @@ export const templates = [{ label: 'Standard page', create: ({ title }) => ({ ti
298
343
  export const collections = {
299
344
  blog: {
300
345
  label: 'Posts', singular: 'post', dir: 'src/content/blog', url: (slug) => `/${slug}/`,
301
- 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' } },
302
347
  },
303
348
  };
304
349
 
@@ -415,8 +460,8 @@ editor's build only, they render on request from storage instead:
415
460
  pagestack({ liveRoutes: ['/', '/blog'], /* … */ })
416
461
  ```
417
462
 
418
- The page reads its collections through `liveEntries`, which gives the saved entries on the editor's
419
- 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:
420
465
 
421
466
  ```ts
422
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.16",
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
- import { formModel } from '../core/schema';
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 {
@@ -24,18 +25,39 @@ export function renderForm(root: HTMLElement, schema: BlockSchema, settings: Rec
24
25
  root.innerHTML = '';
25
26
  const groups = formModel(schema, settings);
26
27
  if (!groups.length) { root.append(el('p', { class: 'ps-muted' }, 'This block has no settings.')); return; }
28
+ const values = { ...settings };
29
+ const shown = conditions(schema.fields, values);
30
+ const formCb: FormCallbacks = { ...cb, onChange: (name, value, ...o) => { values[name] = value; cb.onChange(name, value, ...o); shown.update(); } };
27
31
  for (const g of groups) {
28
32
  const body = el('div', { class: 'ps-fields' });
29
- for (const f of g.fields) body.append(fieldWidget(f.name, f.field, f.value, cb));
33
+ for (const f of g.fields) body.append(shown.track(f.name, fieldWidget(f.name, f.field, f.value, formCb)));
30
34
  const details = el('details', { class: 'ps-group', open: g.name !== 'advanced' }, el('summary', {}, g.label), body) as HTMLDetailsElement;
35
+ shown.trackGroup(details, g.fields.map((f) => f.name));
31
36
  root.append(details);
32
37
  }
38
+ shown.update();
39
+ }
40
+
41
+ /** Shows and hides a form's widgets by their fields' `showIf`, and a group with nothing left to show. */
42
+ function conditions(fields: Record<string, Field>, values: Record<string, unknown>) {
43
+ const widgets = new Map<string, HTMLElement>();
44
+ const groups: [HTMLElement, string[]][] = [];
45
+ return {
46
+ track: (name: string, widget: HTMLElement) => { widgets.set(name, widget); return widget; },
47
+ trackGroup: (group: HTMLElement, names: string[]) => { groups.push([group, names]); },
48
+ update: () => {
49
+ for (const [name, w] of widgets) w.hidden = !isShown(name, fields, values);
50
+ for (const [g, names] of groups) g.hidden = names.every((n) => widgets.get(n)!.hidden);
51
+ },
52
+ };
33
53
  }
34
54
 
35
55
  function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, idPrefix = 'ps-f-'): HTMLElement {
36
56
  const id = `${idPrefix}${name}`;
37
57
  const label = el('label', { for: id }, field.label);
38
- 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); } };
39
61
  const help = field.help ? el('small', { class: 'ps-muted' }, field.help) : null;
40
62
  // `cancel` matters: a live update landing after `change` would reorder the edit and split its undo step.
41
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; };
@@ -43,6 +65,7 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
43
65
  if (field.type === 'text' && field.marks) {
44
66
  wrap.append(marksField(id, (value as string) ?? '', (html, live) => cb.onChange(name, html, { live })));
45
67
  if (help) wrap.append(help);
68
+ markRequired(wrap, field);
46
69
  return wrap;
47
70
  }
48
71
  switch (field.type) {
@@ -107,6 +130,21 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
107
130
  wrap.append(sel);
108
131
  break;
109
132
  }
133
+ case 'multiselect': {
134
+ const current = (Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value]).map(String);
135
+ const known = field.options ?? [];
136
+ // Values no longer offered stay ticked until someone unticks them.
137
+ const extra = [...new Set(current)].filter((v) => !known.some((o) => o.value === v)).map((v) => ({ value: v, label: `${v} (current)` }));
138
+ const boxes = [...known, ...extra].map((o, i) => {
139
+ const box = el('input', { id: `${id}-${i}`, type: 'checkbox', value: o.value, checked: current.includes(o.value) }) as HTMLInputElement;
140
+ box.addEventListener('change', () => cb.onChange(name, boxes.filter((b) => b.box.checked).map((b) => b.box.value)));
141
+ return { box, row: el('label', { for: `${id}-${i}` }, box, o.label) };
142
+ });
143
+ const heading = el('span', { class: 'ps-field__label', id: `${id}-label` }, field.label);
144
+ label.replaceWith(heading);
145
+ wrap.append(el('div', { id, class: 'ps-checks', role: 'group', 'aria-labelledby': `${id}-label` }, ...boxes.map((b) => b.row)));
146
+ break;
147
+ }
110
148
  case 'color': {
111
149
  const text = el('input', { id, type: 'text', value: (value as string) ?? '', placeholder: 'e.g. #BAA77E or var(--e-global-color-primary)' }) as HTMLInputElement;
112
150
  const swatch = el('input', { type: 'color', 'aria-label': `${field.label} picker` }) as HTMLInputElement;
@@ -173,9 +211,48 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
173
211
  break;
174
212
  }
175
213
  if (help) wrap.append(help);
214
+ markRequired(wrap, field);
176
215
  return wrap;
177
216
  }
178
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
+
179
256
  /** Repeatable rows, each its own little form. Rows can nest (a menu item holds links). */
180
257
  function listWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, id: string): HTMLElement {
181
258
  const fields = field.fields ?? {};
@@ -196,14 +273,20 @@ function listWidget(name: string, field: Field, value: unknown, cb: FormCallback
196
273
  rows.forEach((row, i) => {
197
274
  const title = el('span', { class: 'ps-ellipsis' }, rowName(row, i));
198
275
  const body = el('div', { class: 'ps-fields' });
276
+ const shown = conditions(fields, row);
199
277
  for (const [k, sub] of Object.entries(fields)) {
200
278
  const rowCb: FormCallbacks = { ...cb, onChange: (key, v, o) => {
201
- if (v === undefined || v === '' || (Array.isArray(v) && !v.length)) delete row[key]; else row[key] = v;
279
+ // "None" over a default has to be stored, or the default comes back.
280
+ const f = fields[key];
281
+ const keep = (f?.type === 'select' || f?.type === 'multiselect') && String(f.default ?? '') !== '';
282
+ if (v === undefined || (!keep && (v === '' || (Array.isArray(v) && !v.length)))) delete row[key]; else row[key] = v;
202
283
  if (key === field.itemLabel) { title.textContent = rowName(row, i); remove.setAttribute('aria-label', `Remove ${rowName(row, i)}`); }
203
284
  save(o?.live);
285
+ shown.update();
204
286
  } };
205
- body.append(fieldWidget(k, sub, row[k] ?? sub.default, rowCb, `${id}-${i}-`));
287
+ body.append(shown.track(k, fieldWidget(k, sub, row[k] ?? sub.default, rowCb, `${id}-${i}-`)));
206
288
  }
289
+ shown.update();
207
290
  const remove = el('button', { type: 'button', title: 'Remove', 'aria-label': `Remove ${rowName(row, i)}`, onclick: (e: Event) => { e.preventDefault(); rows.splice(i, 1); open.clear(); save(); draw(); } }, '×');
208
291
  const details = el('details', { class: 'ps-list__row', open: open.has(i), ontoggle: () => { if (details.open) open.add(i); else open.delete(i); } }, el('summary', {},
209
292
  title,
@@ -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">
@@ -127,7 +127,11 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
127
127
  .ps-group > summary { padding: 8px 12px; font-weight: 600; cursor: pointer; font-size: 12px; text-transform: uppercase; letter-spacing: .04em; color: var(--ps-muted); }
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
- .ps-field label { font-size: 12px; font-weight: 600; }
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); }
133
+ .ps-checks { display: flex; flex-wrap: wrap; gap: 6px 14px; }
134
+ .ps-field .ps-checks label { display: inline-flex; align-items: center; gap: 6px; font-weight: 400; cursor: pointer; }
131
135
  .ps-field--inline { flex-direction: row; align-items: center; gap: 8px; }
132
136
  .ps-field input[type="text"], .ps-field input[type="number"], .ps-field select, .ps-field textarea { width: 100%; padding: 6px 8px; border: 1px solid var(--ps-border); border-radius: 6px; font: inherit; background: #fff; }
133
137
  .ps-field textarea { resize: vertical; }
@@ -206,6 +210,11 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
206
210
  .ps-dialog footer { display: flex; justify-content: flex-end; gap: 8px; }
207
211
  .ps-dialog__body, .ps-newpage { display: flex; flex-direction: column; gap: 12px; }
208
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; }
209
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; }
210
219
  .ps-prefixed { display: flex; align-items: center; gap: 4px; font-weight: 400; }
211
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) {