@pirateandfox/pagestack 0.1.0-beta.13 → 0.1.0-beta.14

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
@@ -217,8 +217,10 @@ A few things worth knowing while you set up the schema:
217
217
  (`src/sections/components.ts`) so the schema stays plain data.
218
218
  - **List View names a block after its first non-empty inline text field**, so put the field people
219
219
  recognise (the title) first.
220
- - **`text` fields are plain text.** Typing in them replaces any markup they held. For a styled word
221
- in a heading, give the block its own field for it (the bakery's hero has *Word in italics*).
220
+ - **`text` fields are plain text, unless you add `marks: true`.** With it, the field allows bold
221
+ and italic, as a WordPress heading does: select words and press **B** / **I** (or ⌘B / ⌘I) on the
222
+ page or in the sidebar. The value is then HTML holding only `<strong>` and `<em>` (everything else
223
+ is removed on save), so render it with `set:html`. The bakery's section titles use it.
222
224
  - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
223
225
 
224
226
  ## Editing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.13",
3
+ "version": "0.1.0-beta.14",
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",
@@ -4,7 +4,7 @@ import type { Field, Node, PageDoc, SchemaRegistry } from '../runtime';
4
4
  import { cloneWithNewIds } from '../runtime';
5
5
  import { getAt, insertNode, isNodePath, moveNode, nodeAt, nodePathOf, pathOfId, removeNode, replaceNode, setAt, splitNodePath } from '../core/patch';
6
6
  import { transformNode, transformTargets } from '../core/transform';
7
- import { accepts, allowedChildTypes, createNode, nodeLabel } from '../core/schema';
7
+ import { accepts, allowedChildTypes, createNode, fieldOf, nodeLabel } from '../core/schema';
8
8
  import type { InsertItem, Pattern, SavedPattern } from '../core/insert';
9
9
  import { insertItems } from '../core/insert';
10
10
  import { slugProblem } from '../core/pages';
@@ -118,6 +118,11 @@ function onPreviewClick(e: MouseEvent) {
118
118
 
119
119
  const inline = new InlineEditor({
120
120
  onSlash: (fieldPath) => slash(fieldPath),
121
+ marks: (fieldPath) => {
122
+ const nodePath = nodePathOf(fieldPath);
123
+ const node: Node | undefined = getAt(state.doc, nodePath);
124
+ return !!(node && fieldOf(registry[node.type], fieldPath.slice(nodePath.length + '.settings.'.length))?.marks);
125
+ },
121
126
  pages: pageLinks,
122
127
  onStart: () => { state.snapshot(); idoc().body.setAttribute('data-ps-typing', ''); },
123
128
  onInput: (path, value) => { state.apply(setAt(state.doc, path, value), 'inline', false); refreshButtons(); },
@@ -1,7 +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 } from '../core/schema';
4
- import { richField } from './rich';
4
+ import { marksField, richField } from './rich';
5
5
 
6
6
  export interface FormCallbacks {
7
7
  onChange: (name: string, value: unknown, opts?: { live?: boolean }) => void;
@@ -40,6 +40,11 @@ function fieldWidget(name: string, field: Field, value: unknown, cb: FormCallbac
40
40
  // `cancel` matters: a live update landing after `change` would reorder the edit and split its undo step.
41
41
  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; };
42
42
 
43
+ if (field.type === 'text' && field.marks) {
44
+ wrap.append(marksField(id, (value as string) ?? '', (html, live) => cb.onChange(name, html, { live })));
45
+ if (help) wrap.append(help);
46
+ return wrap;
47
+ }
43
48
  switch (field.type) {
44
49
  case 'text':
45
50
  case 'link': {
@@ -1,9 +1,11 @@
1
1
  // In-page editing of text / richtext fields inside the preview iframe.
2
2
  // - text: contenteditable="plaintext-only", Enter commits, Escape reverts.
3
+ // - text with `marks`: one line too, with just bold and italic (headings).
3
4
  // - richtext: contenteditable with the floating formatting toolbar.
4
5
  // Edits stream to `onInput` (silent draft updates); `onCommit` fires on blur.
5
6
  import type { PageLink } from './rich';
6
- import { cleanPaste, exec, linkPopover, richToolbar } from './rich';
7
+ import { sanitizeMarks } from '../core/sanitize';
8
+ import { cleanPaste, exec, linkPopover, markKey, marksPaste, marksToolbar, richToolbar } from './rich';
7
9
 
8
10
  export interface InlineCallbacks {
9
11
  onStart: (fieldPath: string) => void;
@@ -11,6 +13,8 @@ export interface InlineCallbacks {
11
13
  onCommit: (fieldPath: string, value: string, changed: boolean) => void;
12
14
  /** `/` typed in an empty field: the block inserter takes over. */
13
15
  onSlash?: (fieldPath: string) => void;
16
+ /** Is this text field allowed bold and italic (`marks` in its schema)? */
17
+ marks?: (fieldPath: string) => boolean;
14
18
  pages?: PageLink[];
15
19
  }
16
20
 
@@ -25,8 +29,9 @@ export class InlineEditor {
25
29
  if (this.active?.el === el) return;
26
30
  this.stop();
27
31
  const path = el.dataset.psField!;
28
- const type = el.dataset.psFieldType!;
32
+ let type = el.dataset.psFieldType!;
29
33
  if (type !== 'text' && type !== 'richtext') return;
34
+ if (type === 'text' && this.cb.marks?.(path)) type = 'marks';
30
35
  const original = el.innerHTML;
31
36
  this.active = { el, path, type, original };
32
37
  el.setAttribute('contenteditable', type === 'text' ? 'plaintext-only' : 'true');
@@ -34,13 +39,13 @@ export class InlineEditor {
34
39
  el.addEventListener('input', this.onInput);
35
40
  el.addEventListener('keydown', this.onKey);
36
41
  el.addEventListener('blur', this.onBlur);
37
- if (type === 'richtext') el.addEventListener('paste', this.onPaste);
42
+ if (type !== 'text') el.addEventListener('paste', this.onPaste);
38
43
  el.focus();
39
44
  const doc = el.ownerDocument;
40
45
  // caret at end
41
46
  const range = doc.createRange(); range.selectNodeContents(el); range.collapse(false);
42
47
  const sel = doc.getSelection(); sel?.removeAllRanges(); sel?.addRange(range);
43
- if (type === 'richtext') this.mountToolbar(el);
48
+ if (type !== 'text') this.mountToolbar(el);
44
49
  this.cb.onStart(path);
45
50
  }
46
51
 
@@ -64,16 +69,18 @@ export class InlineEditor {
64
69
  private parse(html: string, like: HTMLElement) { const t = like.ownerDocument.createElement(like.tagName); t.innerHTML = html; return t; }
65
70
  private read(el: HTMLElement, type: string): string {
66
71
  if (type === 'text') return el.textContent?.replace(/ /g, ' ') ?? '';
72
+ if (type === 'marks') return sanitizeMarks(el.innerHTML);
67
73
  return el.innerHTML.trim();
68
74
  }
69
75
 
70
76
  private onInput = () => { const a = this.active; if (a) this.cb.onInput(a.path, this.read(a.el, a.type)); };
71
- private onPaste = (e: ClipboardEvent) => { const a = this.active; if (a) cleanPaste(e, a.el, this.onInput); };
77
+ private onPaste = (e: ClipboardEvent) => { const a = this.active; if (a) (a.type === 'marks' ? marksPaste : cleanPaste)(e, a.el, this.onInput); };
72
78
  private onKey = (e: KeyboardEvent) => {
73
79
  const a = this.active; if (!a) return;
74
80
  if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.stop(false); return; }
75
- if (e.key === 'Enter' && a.type === 'text') { e.preventDefault(); a.el.blur(); return; }
81
+ if (e.key === 'Enter' && a.type !== 'richtext') { e.preventDefault(); a.el.blur(); return; }
76
82
  if (e.key === '/' && !a.el.textContent?.trim() && this.cb.onSlash) { e.preventDefault(); this.cb.onSlash(a.path); return; }
83
+ if (a.type === 'marks') { markKey(e, a.el, this.onInput); return; }
77
84
  if ((e.metaKey || e.ctrlKey) && a.type === 'richtext') {
78
85
  const k = e.key.toLowerCase();
79
86
  const cmd = ({ b: 'bold', i: 'italic', u: 'underline' } as Record<string, string>)[k];
@@ -89,7 +96,7 @@ export class InlineEditor {
89
96
 
90
97
  private mountToolbar(el: HTMLElement) {
91
98
  const doc = el.ownerDocument;
92
- const tb = richToolbar(el, this.richOptions());
99
+ const tb = this.active!.type === 'marks' ? marksToolbar(el, this.onInput, 'Esc cancels') : richToolbar(el, this.richOptions());
93
100
  doc.body.append(tb);
94
101
  this.active!.toolbar = tb;
95
102
  this.place();
@@ -1,6 +1,6 @@
1
1
  // Rich text formatting, shared by in-page editing and the sidebar: the toolbar, the link popover
2
2
  // and clean paste. Everything acts on one contenteditable element, in whichever document it lives.
3
- import { safeUrl, sanitizeHtml } from '../core/sanitize';
3
+ import { safeUrl, sanitizeHtml, sanitizeMarks } from '../core/sanitize';
4
4
 
5
5
  export interface PageLink { url: string; title: string }
6
6
  export interface RichOptions { pages?: PageLink[]; onChange: () => void; hint?: string }
@@ -230,3 +230,115 @@ export function richField(id: string, value: string, onChange: (html: string, li
230
230
  box.append(bar, body, source);
231
231
  return box;
232
232
  }
233
+
234
+ // ---- Bold and italic in one line (text fields with `marks`) ----
235
+ // Headings are usually bold already, and the browser's own bold command "unbolds" them with inline
236
+ // styles we strip, so these two marks are applied by hand: wrap the selection, or unwrap the mark it's in.
237
+
238
+ const MARK_TAGS = { bold: ['STRONG', 'B'], italic: ['EM', 'I'] } as const;
239
+ type Mark = keyof typeof MARK_TAGS;
240
+
241
+ function markAt(target: HTMLElement, mark: Mark, node: Node | null | undefined): HTMLElement | null {
242
+ for (let n = node; n && n !== target; n = n.parentNode) if (n.nodeType === 1 && (MARK_TAGS[mark] as readonly string[]).includes((n as Element).tagName)) return n as HTMLElement;
243
+ return null;
244
+ }
245
+
246
+ /** Wraps the selection in <strong>/<em>, or takes the mark off when the selection is already inside one. */
247
+ export function toggleMark(target: HTMLElement, mark: Mark): boolean {
248
+ const doc = target.ownerDocument;
249
+ const sel = doc.getSelection();
250
+ if (!sel?.rangeCount) return false;
251
+ const range = sel.getRangeAt(0);
252
+ if (!target.contains(range.commonAncestorContainer)) return false;
253
+ const inside = markAt(target, mark, range.commonAncestorContainer);
254
+ if (inside) {
255
+ const first = inside.firstChild, last = inside.lastChild;
256
+ inside.replaceWith(...inside.childNodes);
257
+ if (first && last) { const r = doc.createRange(); r.setStartBefore(first); r.setEndAfter(last); sel.removeAllRanges(); sel.addRange(r); }
258
+ target.normalize();
259
+ return true;
260
+ }
261
+ if (range.collapsed) return false;
262
+ const frag = range.extractContents();
263
+ frag.querySelectorAll(MARK_TAGS[mark].join(',')).forEach((el) => el.replaceWith(...el.childNodes));
264
+ const wrap = doc.createElement(mark === 'bold' ? 'strong' : 'em');
265
+ wrap.append(frag);
266
+ range.insertNode(wrap);
267
+ const r = doc.createRange(); r.selectNodeContents(wrap); sel.removeAllRanges(); sel.addRange(r);
268
+ return true;
269
+ }
270
+
271
+ /** Just B and I, for one line. */
272
+ export function marksToolbar(target: HTMLElement, onChange: () => void, hint?: string): HTMLElement {
273
+ const doc = target.ownerDocument;
274
+ const bar = doc.createElement('div');
275
+ bar.setAttribute('data-ps-toolbar', '');
276
+ bar.className = 'ps-rt ps-rt--marks';
277
+ for (const b of BUTTONS.filter((x) => x.cmd === 'bold' || x.cmd === 'italic')) {
278
+ const el = doc.createElement('button');
279
+ el.type = 'button'; el.title = b.title; el.setAttribute('aria-label', b.title); el.dataset.cmd = b.cmd;
280
+ el.innerHTML = b.html;
281
+ bar.append(el);
282
+ }
283
+ if (hint) { const h = doc.createElement('span'); h.className = 'ps-rt__hint'; h.textContent = hint; bar.append(h); }
284
+ const sync = () => {
285
+ if (!bar.isConnected) { doc.removeEventListener('selectionchange', sync); return; }
286
+ const n = doc.getSelection()?.anchorNode;
287
+ if (!n || !target.contains(n)) return;
288
+ bar.querySelectorAll<HTMLButtonElement>('button[data-cmd]').forEach((b) => b.classList.toggle('is-on', !!markAt(target, b.dataset.cmd as Mark, n)));
289
+ };
290
+ bar.addEventListener('mousedown', (e) => e.preventDefault());
291
+ bar.addEventListener('click', (e) => {
292
+ const b = (e.target as HTMLElement).closest<HTMLButtonElement>('button[data-cmd]');
293
+ if (!b) return;
294
+ e.preventDefault();
295
+ target.focus();
296
+ if (toggleMark(target, b.dataset.cmd as Mark)) onChange();
297
+ sync();
298
+ });
299
+ doc.addEventListener('selectionchange', sync);
300
+ return bar;
301
+ }
302
+
303
+ /** ⌘B / ⌘I in a one-line field. True when the key was handled. */
304
+ export function markKey(e: KeyboardEvent, target: HTMLElement, onChange: () => void): boolean {
305
+ if (!(e.metaKey || e.ctrlKey)) return false;
306
+ const mark = ({ b: 'bold', i: 'italic' } as Record<string, Mark>)[e.key.toLowerCase()];
307
+ if (!mark) return false;
308
+ e.preventDefault();
309
+ if (toggleMark(target, mark)) onChange();
310
+ return true;
311
+ }
312
+
313
+ /** Paste into one line: bold and italic survive, everything else becomes plain words. */
314
+ export function marksPaste(e: ClipboardEvent, target: HTMLElement, onChange: () => void) {
315
+ const data = e.clipboardData;
316
+ if (!data) return;
317
+ e.preventDefault();
318
+ const html = data.getData('text/html');
319
+ const esc = (t: string) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
320
+ const clean = html ? sanitizeMarks(html.replace(/<b[^>]*docs-internal-guid[^>]*>/i, '')) : esc(data.getData('text/plain').replace(/\s+/g, ' ').trim());
321
+ target.ownerDocument.execCommand('insertHTML', false, clean || ' ');
322
+ onChange();
323
+ }
324
+
325
+ /** The sidebar's version of a text field with `marks`: one line you can make bold or italic. */
326
+ export function marksField(id: string, value: string, onChange: (html: string, live: boolean) => void): HTMLElement {
327
+ const box = document.createElement('div');
328
+ box.className = 'ps-rich ps-rich--line';
329
+ const body = document.createElement('div');
330
+ body.id = id; body.className = 'ps-rich__body'; body.contentEditable = 'true'; body.setAttribute('role', 'textbox');
331
+ body.innerHTML = sanitizeMarks(value);
332
+ let last = body.innerHTML, timer: ReturnType<typeof setTimeout> | undefined;
333
+ const emit = (live: boolean) => { clearTimeout(timer); const html = sanitizeMarks(body.innerHTML); if (html !== last) { last = html; onChange(html, live); } };
334
+ const changed = () => { clearTimeout(timer); timer = setTimeout(() => emit(true), 250); };
335
+ body.addEventListener('input', changed);
336
+ body.addEventListener('blur', () => emit(false));
337
+ body.addEventListener('paste', (e) => marksPaste(e, body, changed));
338
+ body.addEventListener('keydown', (e) => {
339
+ if (e.key === 'Enter') { e.preventDefault(); emit(false); return; }
340
+ markKey(e, body, () => emit(true));
341
+ });
342
+ box.append(marksToolbar(body, () => emit(true)), body);
343
+ return box;
344
+ }
@@ -226,6 +226,7 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
226
226
  .ps-rich .ps-rt button:hover { background: #e8ebf0; }
227
227
  .ps-rich .ps-rt button.is-on { background: #e8efff; color: var(--ps-accent); }
228
228
  .ps-rich__body { min-height: 96px; max-height: 320px; overflow: auto; padding: 6px 8px; outline: none; font-size: 13px; }
229
+ .ps-rich--line .ps-rich__body { min-height: 0; white-space: nowrap; overflow-x: auto; }
229
230
  .ps-rich__body:focus { box-shadow: inset 0 0 0 1px var(--ps-accent); }
230
231
  .ps-rich__body > :first-child { margin-top: 0; } .ps-rich__body > :last-child { margin-bottom: 0; }
231
232
  .ps-rich textarea { border: 0 !important; border-radius: 0 0 6px 6px !important; }
@@ -202,6 +202,17 @@ export function sanitizeHtml(html: string, { paste = false }: { paste?: boolean
202
202
  return paste ? out.replace(/<p>(\s|&nbsp;|<br>)*<\/p>/g, '').trim() : out;
203
203
  }
204
204
 
205
+ const MARK = { b: 'strong', strong: 'strong', i: 'em', em: 'em' } as Record<string, string>;
206
+ /** One line with bold and italic only (a text field with `marks`): every other tag goes, its text stays. */
207
+ export function sanitizeMarks(html: string): string {
208
+ return sanitizeHtml(html)
209
+ .replace(/<(\/?)([a-zA-Z][\w-]*)[^>]*>/g, (_, close, tag) => { const t = MARK[tag.toLowerCase()]; return t ? `<${close}${t}>` : tag.toLowerCase() === 'br' ? ' ' : ''; })
210
+ .replace(/<(strong|em)>(\s*)<\/\1>/g, '$2')
211
+ .replace(/&nbsp;/g, ' ')
212
+ .replace(/\s+/g, ' ')
213
+ .trim();
214
+ }
215
+
205
216
  /** Text with no markup at all, for values that end up in `<title>` and `<meta>`. */
206
217
  export const plainText = (s: string) => s.replace(/<!--[\s\S]*?(-->|$)/g, '').replace(/<\/?[a-zA-Z][^>]*>?/g, '').replace(/</g, '');
207
218
 
@@ -248,7 +259,9 @@ function cleanField(v: any, field: Field, o: CleanOptions): any {
248
259
  return typeof v === 'string' ? sanitizeSvg(v) : undefined;
249
260
  case 'code':
250
261
  return typeof v !== 'string' || o.rawOk?.(v) ? v : sanitizeHtml(v);
251
- default: // text, textarea, richtext
262
+ case 'text':
263
+ return cleanDeep(v, field.marks ? sanitizeMarks : sanitizeHtml);
264
+ default: // textarea, richtext
252
265
  return cleanDeep(v, sanitizeHtml);
253
266
  }
254
267
  }
@@ -45,6 +45,22 @@ export function inlineFields(schema: BlockSchema): string[] {
45
45
  return Object.entries(schema.fields).filter(([, f]) => f.inline).map(([k]) => k);
46
46
  }
47
47
 
48
+ /**
49
+ * The field a path inside a node's settings names: `title`, or `items.2.label` through a list's rows.
50
+ * Undefined for anything the schema doesn't describe.
51
+ */
52
+ export function fieldOf(schema: BlockSchema | undefined, settingsPath: string): Field | undefined {
53
+ let fields = schema?.fields;
54
+ let f: Field | undefined;
55
+ for (const key of settingsPath.split('.')) {
56
+ if (/^\d+$/.test(key)) { if (f?.type !== 'list') return undefined; continue; }
57
+ f = fields && Object.hasOwn(fields, key) ? fields[key] : undefined;
58
+ if (!f) return undefined;
59
+ fields = f.fields;
60
+ }
61
+ return f;
62
+ }
63
+
48
64
  /** Validate a document against the registry. Returns human-readable problems (empty = ok). */
49
65
  export function validateDoc(doc: unknown, registry: SchemaRegistry): string[] {
50
66
  const errors: string[] = [];
package/src/runtime.ts CHANGED
@@ -23,6 +23,11 @@ export interface Field {
23
23
  default?: unknown;
24
24
  /** Field can be edited by clicking it in the page (text, richtext, image). */
25
25
  inline?: boolean;
26
+ /**
27
+ * For 'text': allow bold and italic in the line (headings, titles). The value is then HTML holding
28
+ * only `<strong>` and `<em>`; render it with `set:html`. Without it, a text field is plain text.
29
+ */
30
+ marks?: boolean;
26
31
  options?: { value: string; label: string }[];
27
32
  /** Sidebar grouping. Defaults to 'content'. */
28
33
  group?: 'content' | 'style' | 'advanced';