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

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,27 @@ 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
+ ### Checkboxes, and fields that depend on others
226
+
227
+ `multiselect` shows its `options` as checkboxes and stores the ticked values as an array, in the
228
+ order the options are declared. `showIf` shows a field only when another one has a certain value:
229
+
230
+ ```ts
231
+ repeats: { type: 'select', label: 'Repeats', options: [{ value: '', label: 'Never' }, { value: 'weekly', label: 'Weekly' }] },
232
+ repeatsOn: { type: 'multiselect', label: 'Repeats on', options: [{ value: 'mon', label: 'Mon' }, { value: 'wed', label: 'Wed' }], showIf: { field: 'repeats', is: 'weekly' } },
233
+ until: { type: 'date', label: 'Until', time: false, showIf: { field: 'repeats', not: '' } },
234
+ ```
235
+
236
+ - `is` and `not` take one value or a list of them (any may match). With neither, the field shows when
237
+ the other one has a value. Missing, `''`, `false` and an empty list all count as no value. A
238
+ `multiselect` matches when any ticked value does.
239
+ - `field` names a field in the same form, or in the same row inside a `list`. A field that depends on
240
+ a hidden field is hidden too.
241
+ - Hiding a field only changes the form. **The stored value stays**, so your component should look at
242
+ the same condition (`repeats && until`) rather than at the dependent field alone.
243
+ - Nothing ticked is stored as `[]`. In a collection, allow for both that and a missing key in the Astro
244
+ schema: `z.array(z.string()).default([])`.
245
+
225
246
  ### Bold and italic in headings
226
247
 
227
248
  Text fields are plain text by default. Add `marks: true` to one and it behaves like a WordPress
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.17",
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,6 +1,6 @@
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
4
  import { marksField, richField } from './rich';
5
5
 
6
6
  export interface FormCallbacks {
@@ -24,12 +24,31 @@ export function renderForm(root: HTMLElement, schema: BlockSchema, settings: Rec
24
24
  root.innerHTML = '';
25
25
  const groups = formModel(schema, settings);
26
26
  if (!groups.length) { root.append(el('p', { class: 'ps-muted' }, 'This block has no settings.')); return; }
27
+ const values = { ...settings };
28
+ const shown = conditions(schema.fields, values);
29
+ const formCb: FormCallbacks = { ...cb, onChange: (name, value, ...o) => { values[name] = value; cb.onChange(name, value, ...o); shown.update(); } };
27
30
  for (const g of groups) {
28
31
  const body = el('div', { class: 'ps-fields' });
29
- for (const f of g.fields) body.append(fieldWidget(f.name, f.field, f.value, cb));
32
+ for (const f of g.fields) body.append(shown.track(f.name, fieldWidget(f.name, f.field, f.value, formCb)));
30
33
  const details = el('details', { class: 'ps-group', open: g.name !== 'advanced' }, el('summary', {}, g.label), body) as HTMLDetailsElement;
34
+ shown.trackGroup(details, g.fields.map((f) => f.name));
31
35
  root.append(details);
32
36
  }
37
+ shown.update();
38
+ }
39
+
40
+ /** Shows and hides a form's widgets by their fields' `showIf`, and a group with nothing left to show. */
41
+ function conditions(fields: Record<string, Field>, values: Record<string, unknown>) {
42
+ const widgets = new Map<string, HTMLElement>();
43
+ const groups: [HTMLElement, string[]][] = [];
44
+ return {
45
+ track: (name: string, widget: HTMLElement) => { widgets.set(name, widget); return widget; },
46
+ trackGroup: (group: HTMLElement, names: string[]) => { groups.push([group, names]); },
47
+ update: () => {
48
+ for (const [name, w] of widgets) w.hidden = !isShown(name, fields, values);
49
+ for (const [g, names] of groups) g.hidden = names.every((n) => widgets.get(n)!.hidden);
50
+ },
51
+ };
33
52
  }
34
53
 
35
54
  function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbacks, idPrefix = 'ps-f-'): HTMLElement {
@@ -107,6 +126,21 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
107
126
  wrap.append(sel);
108
127
  break;
109
128
  }
129
+ case 'multiselect': {
130
+ const current = (Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value]).map(String);
131
+ const known = field.options ?? [];
132
+ // Values no longer offered stay ticked until someone unticks them.
133
+ const extra = [...new Set(current)].filter((v) => !known.some((o) => o.value === v)).map((v) => ({ value: v, label: `${v} (current)` }));
134
+ const boxes = [...known, ...extra].map((o, i) => {
135
+ const box = el('input', { id: `${id}-${i}`, type: 'checkbox', value: o.value, checked: current.includes(o.value) }) as HTMLInputElement;
136
+ box.addEventListener('change', () => cb.onChange(name, boxes.filter((b) => b.box.checked).map((b) => b.box.value)));
137
+ return { box, row: el('label', { for: `${id}-${i}` }, box, o.label) };
138
+ });
139
+ const heading = el('span', { class: 'ps-field__label', id: `${id}-label` }, field.label);
140
+ label.replaceWith(heading);
141
+ wrap.append(el('div', { id, class: 'ps-checks', role: 'group', 'aria-labelledby': `${id}-label` }, ...boxes.map((b) => b.row)));
142
+ break;
143
+ }
110
144
  case 'color': {
111
145
  const text = el('input', { id, type: 'text', value: (value as string) ?? '', placeholder: 'e.g. #BAA77E or var(--e-global-color-primary)' }) as HTMLInputElement;
112
146
  const swatch = el('input', { type: 'color', 'aria-label': `${field.label} picker` }) as HTMLInputElement;
@@ -196,14 +230,20 @@ function listWidget(name: string, field: Field, value: unknown, cb: FormCallback
196
230
  rows.forEach((row, i) => {
197
231
  const title = el('span', { class: 'ps-ellipsis' }, rowName(row, i));
198
232
  const body = el('div', { class: 'ps-fields' });
233
+ const shown = conditions(fields, row);
199
234
  for (const [k, sub] of Object.entries(fields)) {
200
235
  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;
236
+ // "None" over a default has to be stored, or the default comes back.
237
+ const f = fields[key];
238
+ const keep = (f?.type === 'select' || f?.type === 'multiselect') && String(f.default ?? '') !== '';
239
+ if (v === undefined || (!keep && (v === '' || (Array.isArray(v) && !v.length)))) delete row[key]; else row[key] = v;
202
240
  if (key === field.itemLabel) { title.textContent = rowName(row, i); remove.setAttribute('aria-label', `Remove ${rowName(row, i)}`); }
203
241
  save(o?.live);
242
+ shown.update();
204
243
  } };
205
- body.append(fieldWidget(k, sub, row[k] ?? sub.default, rowCb, `${id}-${i}-`));
244
+ body.append(shown.track(k, fieldWidget(k, sub, row[k] ?? sub.default, rowCb, `${id}-${i}-`)));
206
245
  }
246
+ shown.update();
207
247
  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
248
  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
249
  title,
@@ -127,7 +127,9 @@ 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-checks { display: flex; flex-wrap: wrap; gap: 6px 14px; }
132
+ .ps-field .ps-checks label { display: inline-flex; align-items: center; gap: 6px; font-weight: 400; cursor: pointer; }
131
133
  .ps-field--inline { flex-direction: row; align-items: center; gap: 8px; }
132
134
  .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
135
  .ps-field textarea { resize: vertical; }
@@ -243,6 +243,12 @@ function cleanField(v: any, field: Field, o: CleanOptions): any {
243
243
  if (typeof v === 'number' || typeof v === 'boolean') v = String(v);
244
244
  // A value outside the options is usually an old one, so plain words stay and markup goes.
245
245
  return field.options?.some((x) => x.value === v) || (typeof v === 'string' && TOKEN_OK.test(v)) ? v : undefined;
246
+ case 'multiselect': {
247
+ // One value on its own is how a hand-written file may put it.
248
+ const all = Array.isArray(v) ? v : v === '' ? [] : [v];
249
+ const kept = all.map((x) => cleanField(x, { ...field, type: 'select' }, o)).filter((x) => typeof x === 'string' && x !== '');
250
+ return kept.length || !all.length ? [...new Set(kept)] : undefined;
251
+ }
246
252
  case 'number':
247
253
  return v === '' || Number.isFinite(typeof v === 'string' ? Number(v) : v) ? v : undefined;
248
254
  case 'boolean':
@@ -1,6 +1,6 @@
1
1
  // Schema -> form model and node factories. Pure; used on the server (validation) and in the
2
2
  // browser (sidebar forms, add menus).
3
- import type { BlockSchema, Field, Node, PageDoc, SchemaRegistry } from '../runtime';
3
+ import type { BlockSchema, Field, Node, PageDoc, SchemaRegistry, ShowIf } from '../runtime';
4
4
  import { newId } from '../runtime';
5
5
 
6
6
  export interface FormField { name: string; field: Field; value: unknown }
@@ -18,6 +18,35 @@ export function formModel(schema: BlockSchema, settings: Record<string, unknown>
18
18
  return (Object.keys(groups) as FormGroup['name'][]).filter((g) => groups[g].length).map((g) => ({ name: g, label: GROUP_LABELS[g], fields: groups[g] }));
19
19
  }
20
20
 
21
+ /** A value as `showIf` compares it: always a list of strings, with every kind of "nothing" as ''. */
22
+ function comparable(v: unknown): string[] {
23
+ if (Array.isArray(v)) return v.length ? v.flatMap(comparable) : [''];
24
+ if (v && typeof v === 'object') return [String((v as any).src ?? 'set')]; // an image, or a list's row
25
+ return [v === undefined || v === null || v === false ? '' : String(v)];
26
+ }
27
+
28
+ function conditionMet(when: ShowIf, value: unknown): boolean {
29
+ const now = comparable(value);
30
+ const any = (v: ShowIf['is']) => comparable(v).some((x) => now.includes(x));
31
+ if (when.is === undefined && when.not === undefined) return now.some(Boolean);
32
+ return (when.is === undefined || any(when.is)) && (when.not === undefined || !any(when.not));
33
+ }
34
+
35
+ /**
36
+ * Does the form show this field? A field that depends on a hidden field is hidden too. A condition
37
+ * naming a field that isn't there is ignored, so a typo can't put a field out of reach.
38
+ */
39
+ export function isShown(name: string, fields: Record<string, Field>, settings: Record<string, unknown>, seen: string[] = []): boolean {
40
+ const when = Object.hasOwn(fields, name) ? fields[name].showIf : undefined;
41
+ if (!when || seen.includes(name)) return true;
42
+ const other = Object.hasOwn(fields, when.field) ? fields[when.field] : undefined;
43
+ const stored = Object.hasOwn(settings, when.field) ? settings[when.field] : undefined;
44
+ if (!other && stored === undefined) return true;
45
+ // With nothing stored, go by what the form displays: the default, or a select's first option.
46
+ const value = stored ?? other?.default ?? (other?.type === 'select' ? other.options?.[0]?.value : undefined);
47
+ return conditionMet(when, value) && isShown(when.field, fields, settings, [...seen, name]);
48
+ }
49
+
21
50
  export function defaultSettings(schema: BlockSchema): Record<string, unknown> {
22
51
  const s: Record<string, unknown> = {};
23
52
  for (const [k, f] of Object.entries(schema.fields)) if (f.default !== undefined) s[k] = structuredClone(f.default);
@@ -56,10 +56,11 @@ export function transformNode(node: Node, type: string, registry: SchemaRegistry
56
56
  settings[slot] = convert(node.settings[k], f, to.fields[slot]);
57
57
  open.delete(slot);
58
58
  }
59
+ const fits = (f: Field, v: unknown) => !f.options || (Array.isArray(v) ? v : [v]).every((x) => f.options!.some((o) => o.value === x));
59
60
  // Style settings carry over when the new type has the same field and the value still fits.
60
61
  for (const [k, f] of Object.entries(from?.fields ?? {})) {
61
62
  const t = to.fields[k];
62
- if (t && t.type === f.type && !isText(f) && f.type !== 'image' && node.settings[k] !== undefined && (!t.options || t.options.some((o) => o.value === node.settings[k]))) settings[k] = node.settings[k];
63
+ if (t && t.type === f.type && !isText(f) && f.type !== 'image' && node.settings[k] !== undefined && fits(t, node.settings[k])) settings[k] = node.settings[k];
63
64
  }
64
65
  const { blocks, ...rest } = node;
65
66
  return { ...rest, type, settings, ...(to.blocks ? { blocks: blocks ?? [] } : {}) };
package/src/runtime.ts CHANGED
@@ -8,6 +8,7 @@ export type FieldType =
8
8
  | 'link' // URL string
9
9
  | 'color' // CSS colour (hex, rgb(), var(--x))
10
10
  | 'select'
11
+ | 'multiselect' // checkboxes over `options`; value is an array of their values, in option order
11
12
  | 'number'
12
13
  | 'boolean'
13
14
  | 'textarea' // multi-line plain text, sidebar only
@@ -17,6 +18,15 @@ export type FieldType =
17
18
  | 'tags' // array of strings
18
19
  | 'list'; // repeatable rows of sub-fields (menus, link lists); value is an array of objects
19
20
 
21
+ /**
22
+ * When the editor shows a field, from the value of another field beside it (same form, or same list row).
23
+ * With neither `is` nor `not`: when that field has a value (not blank, off or empty).
24
+ * A list of values matches any of them; a 'multiselect' matches when any ticked value does.
25
+ * Missing, '', false and an empty list are the same thing here.
26
+ */
27
+ export interface ShowIf { field: string; is?: ShowIfValue | ShowIfValue[]; not?: ShowIfValue | ShowIfValue[] }
28
+ export type ShowIfValue = string | number | boolean;
29
+
20
30
  export interface Field {
21
31
  type: FieldType;
22
32
  label: string;
@@ -28,6 +38,7 @@ export interface Field {
28
38
  * only `<strong>` and `<em>`; render it with `set:html`. Without it, a text field is plain text.
29
39
  */
30
40
  marks?: boolean;
41
+ /** For 'select' and 'multiselect'. */
31
42
  options?: { value: string; label: string }[];
32
43
  /** Sidebar grouping. Defaults to 'content'. */
33
44
  group?: 'content' | 'style' | 'advanced';
@@ -35,6 +46,8 @@ export interface Field {
35
46
  max?: number;
36
47
  step?: number;
37
48
  help?: string;
49
+ /** Show this field only when another one has a certain value. Hiding never changes the stored value. */
50
+ showIf?: ShowIf;
38
51
  /** For 'svg': named icons offered in a dropdown besides raw SVG. */
39
52
  icons?: string[];
40
53
  /** For 'list': the fields of one row. */