@aphexcms/visual-editing 0.2.0 → 0.3.1

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 ADDED
@@ -0,0 +1,71 @@
1
+ # @aphexcms/visual-editing
2
+
3
+ Click-to-edit visual editing for [AphexCMS](https://github.com/IcelandicIcecream/aphex).
4
+
5
+ Renders your real site in the studio's preview pane and makes the content in it clickable: an author clicks a heading on the page and lands on that field in the editor, with edits streaming back live.
6
+
7
+ 📚 **Documentation: [docs.getaphex.com/visual-editing](https://docs.getaphex.com/visual-editing)**
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add @aphexcms/visual-editing
13
+ ```
14
+
15
+ ## Setup is two things
16
+
17
+ **1. Wrap your public layout.** The overlay is a no-op unless the URL carries the `?aphex-preview` marker the editor's iframe adds, so it costs real visitors nothing:
18
+
19
+ ```svelte title="src/routes/(site)/+layout.svelte"
20
+ <script lang="ts">
21
+ import { AphexVisualOverlay } from '@aphexcms/visual-editing';
22
+ let { children } = $props();
23
+ </script>
24
+
25
+ <AphexVisualOverlay>
26
+ {@render children()}
27
+ </AphexVisualOverlay>
28
+ ```
29
+
30
+ **2. Give the schema a `previewUrl`** so the CMS knows which route renders a document:
31
+
32
+ ```ts
33
+ previewUrl: (doc) => (doc.slug ? `/blog/${doc.slug}?aphex-preview=1` : null);
34
+ ```
35
+
36
+ That's the whole setup. Plain text fields become click-to-edit automatically — the CMS encodes them with invisible [stega](https://github.com/vercel/stega) markers, so the string carries its own field address.
37
+
38
+ ## `usePreview()` — the one helper
39
+
40
+ Everything else is one call, once per component:
41
+
42
+ ```svelte
43
+ <script lang="ts">
44
+ import { usePreview } from '@aphexcms/visual-editing';
45
+ const ve = usePreview();
46
+ let { data } = $props();
47
+ const page = $derived(ve.live(data.page));
48
+ </script>
49
+ ```
50
+
51
+ | Method | For |
52
+ | ---------- | ---------------------------------------------------------------------- |
53
+ | `live()` | Merge the editor's in-flight document over your `load` data |
54
+ | `edit()` | Mark an element as the target for a field — required for arrays/images |
55
+ | `image()` | The same, for an image that has no string to carry a marker |
56
+ | `encode()` | Add markers to a string you derived yourself |
57
+
58
+ ## Four things that are easy to get wrong
59
+
60
+ Each produces breakage that only appears in preview, which is why they're worth reading before you debug one:
61
+
62
+ - **A repeated block must reveal its own row.** Spread `{...ve.edit({ field: 'layout', arrayIndex: index })}` onto its root element. Text is clickable on its own, but the surrounding chrome, buttons and empty states are inert without an explicit target — and a block that ignores its index sends the author to the top of the array instead of to their block.
63
+ - **Images always need `edit()`/`image()`.** A string can carry stega inside itself; an image has no string to carry.
64
+ - **`live()` merges, it doesn't replace.** It preserves underscore-prefixed keys (`_posts`, `_form`) that your `load` derived and the editor's document can't know about.
65
+ - **Clean any value you branch on.** A stega-marked `'center'` matches no `===`, and the branch silently takes the wrong arm. `stegaClean(value)` before comparing; leave display strings marked, because that's what makes them clickable.
66
+
67
+ A block that renders a _different_ document needs its own `live()`, gated on type and id — otherwise editing that document does nothing until a reload.
68
+
69
+ ## License
70
+
71
+ MIT
@@ -1 +1 @@
1
- {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/lib/core.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,8EAA8E;IAC9E,MAAM,CAAC,EAAE,CACR,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,IAAI,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,KACjD,IAAI,CAAC;IACV;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB;AAuDD,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,MAAM,IAAI,CA+OhF"}
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/lib/core.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,8EAA8E;IAC9E,MAAM,CAAC,EAAE,CACR,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,IAAI,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,KACjD,IAAI,CAAC;IACV;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB;AAuDD,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,MAAM,IAAI,CAkPhF"}
package/dist/core.js CHANGED
@@ -161,7 +161,10 @@ export function enableAphexPreview(options = {}) {
161
161
  }
162
162
  function showOn(el) {
163
163
  activeEl = el;
164
- label.textContent = el.dataset.aphexField ?? '';
164
+ // Show the row number for a list entry — several rows of one list otherwise all
165
+ // hover as the same bare field name, with nothing to say which slot is which.
166
+ const idx = el.dataset.aphexArrayIndex;
167
+ label.textContent = (el.dataset.aphexField ?? '') + (idx != null ? `[${idx}]` : '');
165
168
  positionOn(el);
166
169
  overlay.style.display = 'block';
167
170
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Carrying server-derived data across the live-preview swap.
3
+ *
4
+ * ## The problem
5
+ *
6
+ * `usePreview().live(fallback)` hands the page the document the studio is
7
+ * holding, so an editor sees their keystrokes immediately. That document comes
8
+ * straight from the editor's form state: it has never been through a page load,
9
+ * and so it carries only what the schema declares.
10
+ *
11
+ * Real pages need more than that. Server-side loads routinely *derive* data and
12
+ * attach it to the document — the posts an archive block queries for, the form a
13
+ * form block embeds, a resolved reference, a computed URL. By convention those
14
+ * are underscore-prefixed (`_posts`, `_form`) precisely because they exist in no
15
+ * schema and are never written back.
16
+ *
17
+ * Swapping the whole document therefore drops all of it, and the block renders
18
+ * empty. That is the worst possible failure to show an author: an archive that
19
+ * says "no posts" in preview while the published page lists twelve, with nothing
20
+ * on screen to suggest the difference is preview itself.
21
+ *
22
+ * ## The rule
23
+ *
24
+ * Keep the live document, and restore only keys that are **underscore-prefixed**,
25
+ * **not structural**, and **absent from the live document**.
26
+ *
27
+ * Each condition is load-bearing:
28
+ *
29
+ * - *Underscore-prefixed* is what separates derived data from authored content.
30
+ * An authored field is never underscore-prefixed, so clearing one in the editor
31
+ * still clears it in preview — a naive "fill in whatever's missing" merge would
32
+ * resurrect every value the author just deleted, which is a far worse bug than
33
+ * the one being fixed.
34
+ * - *Not structural* excludes `_type`, `_key` and `_ref`, which describe the
35
+ * document rather than decorate it. They're always present on the live document
36
+ * anyway; excluding them explicitly means this can't quietly rewrite a block's
37
+ * identity if that ever stops being true.
38
+ * - *Absent* means this only fills gaps. Once preview and load agree on a key,
39
+ * the live value wins.
40
+ *
41
+ * Arrays are matched by `_key`, the stable per-item identity, so reordering,
42
+ * inserting and deleting rows all behave.
43
+ *
44
+ * Derived values are necessarily one load stale — change an archive's category
45
+ * filter and it keeps showing the previous query's posts until the page reloads.
46
+ * That is the right trade: stale-but-real content beats an empty grid, and every
47
+ * authored field around it still updates live.
48
+ */
49
+ /**
50
+ * Merge server-derived data from `fallback` into the live document.
51
+ *
52
+ * Returns `live` unchanged (same identity) when there is nothing to restore.
53
+ */
54
+ export declare function mergeDerived<T>(live: T, fallback: T): T;
55
+ //# sourceMappingURL=merge-derived.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge-derived.d.ts","sourceRoot":"","sources":["../src/lib/merge-derived.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AA4EH;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CAGvD"}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Carrying server-derived data across the live-preview swap.
3
+ *
4
+ * ## The problem
5
+ *
6
+ * `usePreview().live(fallback)` hands the page the document the studio is
7
+ * holding, so an editor sees their keystrokes immediately. That document comes
8
+ * straight from the editor's form state: it has never been through a page load,
9
+ * and so it carries only what the schema declares.
10
+ *
11
+ * Real pages need more than that. Server-side loads routinely *derive* data and
12
+ * attach it to the document — the posts an archive block queries for, the form a
13
+ * form block embeds, a resolved reference, a computed URL. By convention those
14
+ * are underscore-prefixed (`_posts`, `_form`) precisely because they exist in no
15
+ * schema and are never written back.
16
+ *
17
+ * Swapping the whole document therefore drops all of it, and the block renders
18
+ * empty. That is the worst possible failure to show an author: an archive that
19
+ * says "no posts" in preview while the published page lists twelve, with nothing
20
+ * on screen to suggest the difference is preview itself.
21
+ *
22
+ * ## The rule
23
+ *
24
+ * Keep the live document, and restore only keys that are **underscore-prefixed**,
25
+ * **not structural**, and **absent from the live document**.
26
+ *
27
+ * Each condition is load-bearing:
28
+ *
29
+ * - *Underscore-prefixed* is what separates derived data from authored content.
30
+ * An authored field is never underscore-prefixed, so clearing one in the editor
31
+ * still clears it in preview — a naive "fill in whatever's missing" merge would
32
+ * resurrect every value the author just deleted, which is a far worse bug than
33
+ * the one being fixed.
34
+ * - *Not structural* excludes `_type`, `_key` and `_ref`, which describe the
35
+ * document rather than decorate it. They're always present on the live document
36
+ * anyway; excluding them explicitly means this can't quietly rewrite a block's
37
+ * identity if that ever stops being true.
38
+ * - *Absent* means this only fills gaps. Once preview and load agree on a key,
39
+ * the live value wins.
40
+ *
41
+ * Arrays are matched by `_key`, the stable per-item identity, so reordering,
42
+ * inserting and deleting rows all behave.
43
+ *
44
+ * Derived values are necessarily one load stale — change an archive's category
45
+ * filter and it keeps showing the previous query's posts until the page reloads.
46
+ * That is the right trade: stale-but-real content beats an empty grid, and every
47
+ * authored field around it still updates live.
48
+ */
49
+ /** Structural keys: identity, not decoration. Never copied. */
50
+ const STRUCTURAL = new Set(['_type', '_key', '_ref', '_id', '_rev']);
51
+ function isPlainObject(value) {
52
+ return !!value && typeof value === 'object' && !Array.isArray(value);
53
+ }
54
+ function isDerivedKey(key) {
55
+ return key.startsWith('_') && !STRUCTURAL.has(key);
56
+ }
57
+ function mergeArrays(live, fallback) {
58
+ const byKey = new Map();
59
+ for (const item of fallback) {
60
+ if (isPlainObject(item) && typeof item._key === 'string')
61
+ byKey.set(item._key, item);
62
+ }
63
+ return live.map((item, index) => {
64
+ if (!isPlainObject(item))
65
+ return item;
66
+ // Key first; fall back to position for arrays whose items carry no `_key`
67
+ // (an app may build one by hand). Position is only trustworthy when the two
68
+ // arrays are the same length — otherwise a single insertion would shift
69
+ // every derived value onto the wrong row.
70
+ const match = (typeof item._key === 'string' ? byKey.get(item._key) : undefined) ??
71
+ (live.length === fallback.length && isPlainObject(fallback[index])
72
+ ? fallback[index]
73
+ : undefined);
74
+ return match ? mergeNode(item, match) : item;
75
+ });
76
+ }
77
+ function mergeNode(live, fallback) {
78
+ let next = null;
79
+ // Restore derived keys this node is missing.
80
+ for (const key of Object.keys(fallback)) {
81
+ if (!isDerivedKey(key))
82
+ continue;
83
+ if (live[key] !== undefined)
84
+ continue;
85
+ next ??= { ...live };
86
+ next[key] = fallback[key];
87
+ }
88
+ // Then recurse, so a derived key nested inside an authored object or array is
89
+ // restored too.
90
+ for (const key of Object.keys(live)) {
91
+ const liveValue = live[key];
92
+ const fallbackValue = fallback[key];
93
+ if (Array.isArray(liveValue) && Array.isArray(fallbackValue)) {
94
+ const merged = mergeArrays(liveValue, fallbackValue);
95
+ if (merged.some((item, i) => item !== liveValue[i])) {
96
+ next ??= { ...live };
97
+ next[key] = merged;
98
+ }
99
+ }
100
+ else if (isPlainObject(liveValue) && isPlainObject(fallbackValue)) {
101
+ const merged = mergeNode(liveValue, fallbackValue);
102
+ if (merged !== liveValue) {
103
+ next ??= { ...live };
104
+ next[key] = merged;
105
+ }
106
+ }
107
+ }
108
+ // Returning the original when nothing changed keeps `$derived` from seeing a
109
+ // new object identity on every keystroke.
110
+ return next ?? live;
111
+ }
112
+ /**
113
+ * Merge server-derived data from `fallback` into the live document.
114
+ *
115
+ * Returns `live` unchanged (same identity) when there is nothing to restore.
116
+ */
117
+ export function mergeDerived(live, fallback) {
118
+ if (!isPlainObject(live) || !isPlainObject(fallback))
119
+ return live;
120
+ return mergeNode(live, fallback);
121
+ }
@@ -29,7 +29,21 @@ export interface PreviewApi {
29
29
  readonly inPreview: boolean;
30
30
  /** The live document pushed by the editor, or `null` outside preview. */
31
31
  readonly document: Record<string, unknown> | null;
32
- /** The live document merged over your server fallback: `const post = $derived(ve.live(data.post))`. */
32
+ /**
33
+ * Schema type of the document currently open in the editor, or `null` outside preview.
34
+ * Use it when one page is reachable from several document types and an element should
35
+ * behave differently depending on which one is being edited — e.g. a menu row that
36
+ * reveals its slot in the open menu's list, but opens the dish when a dish is open.
37
+ */
38
+ readonly documentType: string | null;
39
+ /**
40
+ * The live document merged over your server fallback:
41
+ * `const post = $derived(ve.live(data.post))`.
42
+ *
43
+ * The editor's values win. Underscore-prefixed keys the editor doesn't carry —
44
+ * data your `load` derived, like an archive block's resolved posts — are kept
45
+ * from the fallback, so server-enriched content doesn't vanish in preview.
46
+ */
33
47
  live<T>(fallback: T, options?: {
34
48
  type?: string;
35
49
  id?: string;
@@ -41,19 +55,27 @@ export interface PreviewApi {
41
55
  */
42
56
  encode(value: string | null | undefined, payload?: EncodePayload): string;
43
57
  /**
44
- * Make any element click-to-edit a *specific* document — for app-level references
45
- * that aren't stored in the current document (e.g. an app-queried "list of posts"
46
- * block). Spread the returned attributes onto the element; clicking it in preview
47
- * opens that document in the studio. Returns `{}` outside preview.
58
+ * Make any element click-to-edit, for content the current document's own stega can't
59
+ * mark up. Spread the returned attributes onto the element; returns `{}` outside preview.
60
+ *
61
+ * Two targets, chosen by whether `id`/`type` are given:
62
+ * - **Another document** (`{ id, type }`) — an app-level reference not stored in the
63
+ * document being edited (e.g. an app-queried "list of posts" block). Clicking opens
64
+ * that document in the studio.
65
+ * - **A field of the open document** (`{ field, arrayIndex }`) — clicking reveals that
66
+ * field, and with `arrayIndex` the specific row, in the form pane. Use this for a
67
+ * list whose entries are references: revealing the row is what lets the author
68
+ * reorder or remove it, which opening the referenced document does not.
48
69
  *
49
70
  * @example
50
- * // {#each posts as post}
51
- * // <a href="/blog/{post.slug}" {...ve.edit({ id: post.id, type: 'blog_post' })}>…</a>
71
+ * // {...ve.edit({ id: post.id, type: 'blog_post' })} → opens that post
72
+ * // {...ve.edit({ field: 'items', arrayIndex: i })} → reveals row i of `items`
52
73
  */
53
74
  edit(target: {
54
- id: string;
55
- type: string;
75
+ id?: string;
76
+ type?: string;
56
77
  field?: string;
78
+ arrayIndex?: number;
57
79
  }): Record<string, string>;
58
80
  /**
59
81
  * Resolve an image field to `{ src, alt }` in one call — destructure it:
@@ -1 +1 @@
1
- {"version":3,"file":"use-preview.svelte.d.ts","sourceRoot":"","sources":["../src/lib/use-preview.svelte.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAI5D;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAEzE;AAED;gEACgE;AAChE,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;AAElD,KAAK,SAAS,GACX;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GACvE,IAAI,GACJ,SAAS,CAAC;AAEb,6CAA6C;AAC7C,MAAM,WAAW,aAAa;IAC7B,yDAAyD;IACzD,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,yEAAyE;IACzE,GAAG,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,UAAU;IAC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I,UAAU,CAyDvC"}
@@ -1,6 +1,7 @@
1
1
  import { getContext, setContext } from 'svelte';
2
2
  import { getLivePreviewDocument } from './live-preview.svelte.js';
3
3
  import { stegaEncode } from './stega.js';
4
+ import { mergeDerived } from './merge-derived.js';
4
5
  const PT_FIELD_KEY = Symbol('aphex:pt-field');
5
6
  /**
6
7
  * Declare which document field a Portable Text body belongs to (e.g. `'content'`), so inline
@@ -32,12 +33,22 @@ export function usePreview() {
32
33
  get document() {
33
34
  return ctx.current;
34
35
  },
36
+ get documentType() {
37
+ return ctx.currentType;
38
+ },
35
39
  live(fallback, options = {}) {
36
40
  if (options.type && ctx.currentType !== options.type)
37
41
  return fallback;
38
42
  if (options.id && ctx.currentId !== options.id)
39
43
  return fallback;
40
- return ctx.current ?? fallback;
44
+ if (ctx.current == null)
45
+ return fallback;
46
+ // The editor's document wins on everything it carries; server-derived
47
+ // keys it can't know about are restored from the fallback. See
48
+ // `merge-derived.ts` — without this an archive block, a resolved
49
+ // reference, anything an app attaches during its load, renders empty in
50
+ // preview only.
51
+ return mergeDerived(ctx.current, fallback);
41
52
  },
42
53
  encode(value, payload = {}) {
43
54
  const raw = value ?? '';
@@ -52,11 +63,19 @@ export function usePreview() {
52
63
  const attrs = {};
53
64
  if (ctx.current == null)
54
65
  return attrs; // not in preview — no attributes
55
- // `data-aphex-field` is what the overlay keys on to make an element clickable;
56
- // the id/type route the click to that document (the studio opens it).
66
+ // `data-aphex-field` is what the overlay keys on to make an element clickable,
67
+ // so it is always set. Adding id/type routes the click to *that* document (the
68
+ // studio opens it); leaving them off keeps the click on the open document, where
69
+ // `arrayIndex` picks out a single row. Both are only emitted together — the
70
+ // studio treats a cross-document click as such only when it has each half.
57
71
  attrs['data-aphex-field'] = target.field ?? 'title';
58
- attrs['data-aphex-document-id'] = target.id;
59
- attrs['data-aphex-document-type'] = target.type;
72
+ if (target.id && target.type) {
73
+ attrs['data-aphex-document-id'] = target.id;
74
+ attrs['data-aphex-document-type'] = target.type;
75
+ }
76
+ if (target.arrayIndex != null) {
77
+ attrs['data-aphex-array-index'] = String(target.arrayIndex);
78
+ }
60
79
  return attrs;
61
80
  },
62
81
  image(img) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aphexcms/visual-editing",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Visual editing overlay for AphexCMS — add click-to-edit overlays to your frontend",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -27,7 +27,7 @@
27
27
  "dist"
28
28
  ],
29
29
  "devDependencies": {
30
- "@sveltejs/kit": "^2.59.1",
30
+ "@sveltejs/kit": "^2.70.2",
31
31
  "@sveltejs/package": "^2.5.6",
32
32
  "svelte": "^5.0.0",
33
33
  "svelte-check": "^4.0.0",