@joryio/web-sdk 1.4.0-beta.6 → 1.4.0-beta.8

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/config.d.ts +1 -1
  3. package/dist/core/editor-gate.d.ts +2 -0
  4. package/dist/core/editor-gate.d.ts.map +1 -1
  5. package/dist/core/page-edits.d.ts +13 -0
  6. package/dist/core/page-edits.d.ts.map +1 -1
  7. package/dist/core/sdk.d.ts.map +1 -1
  8. package/dist/editor/editor-model.d.ts +16 -8
  9. package/dist/editor/editor-model.d.ts.map +1 -1
  10. package/dist/editor/editor-strings.d.ts +22 -1
  11. package/dist/editor/editor-strings.d.ts.map +1 -1
  12. package/dist/editor/editor-ui.d.ts +6 -2
  13. package/dist/editor/editor-ui.d.ts.map +1 -1
  14. package/dist/editor/liquid-field.d.ts +23 -0
  15. package/dist/editor/liquid-field.d.ts.map +1 -0
  16. package/dist/editor/visual-editor.d.ts +31 -2
  17. package/dist/editor/visual-editor.d.ts.map +1 -1
  18. package/dist/index.d.mts +1 -1
  19. package/dist/joryio-cards-ui.min.js +1 -1
  20. package/dist/joryio-editor.min.js +2 -2
  21. package/dist/joryio-editor.min.js.map +1 -1
  22. package/dist/joryio-sw.js +1 -1
  23. package/dist/joryio.cjs.js +68 -8
  24. package/dist/joryio.min.js +2 -2
  25. package/dist/joryio.min.js.map +1 -1
  26. package/dist/joryio.mjs +68 -8
  27. package/dist/joryio.umd.js +68 -8
  28. package/package.json +1 -1
  29. package/src/core/config.ts +1 -1
  30. package/src/core/editor-gate.ts +21 -0
  31. package/src/core/page-edits.ts +70 -3
  32. package/src/core/sdk.ts +4 -1
  33. package/src/editor/editor-model.ts +89 -38
  34. package/src/editor/editor-strings.ts +22 -1
  35. package/src/editor/editor-ui.ts +47 -5
  36. package/src/editor/liquid-field.ts +316 -0
  37. package/src/editor/visual-editor.ts +616 -124
@@ -22,33 +22,71 @@
22
22
  * - A light side panel: the element, how many elements its selector matches,
23
23
  * "What do you want to do?" (Change text, Change link, Change image, Hide
24
24
  * it, Add content slot), ONE field set per action, a collapsible CSS
25
- * selector, Cancel / Save.
25
+ * selector, Cancel / Save. The New text field shows variables as the
26
+ * same pills (liquid-field.ts) and stores unchanged Liquid. Selecting an
27
+ * element that already has an edit opens that edit.
26
28
  * - Every edit shows live on the page while editing (the draft too); the
27
29
  * text with the dashboard's sample values for its variables, else their
28
- * fallbacks. Text is set with textContent, addresses must be http(s), the
30
+ * fallbacks, else a placeholder pill with the field name (a custom element
31
+ * with its own shadow root, never page text). Text is set with textContent, addresses must be http(s), the
29
32
  * original nodes come back on undo - nothing is ever parsed as HTML.
30
33
  * - A dock: campaign · variant · page, the hint, "N edits" (a click jumps to
31
34
  * that edit), Undo, "Save & return to Joryio".
35
+ * - Desktop / Mobile (1.4.0-beta.8): the dock's toggle shows the page at
36
+ * phone width (MOBILE_FRAME_WIDTH, 390 px) - a same-origin frame of the
37
+ * current URL with `?joryio_editor=frame` inside the editor's shadow root.
38
+ * The SDK in that frame is inert (core editorFrame(): no page view, no
39
+ * message, no live page edit); the editor works on the frame's document
40
+ * (hover, selection, previews, selectors), its own UI stays in this tab.
41
+ * The site's own scripts run in the frame, so its responsive layout, its
42
+ * SPA routing and its lazy content are the real ones. Limits: a site that
43
+ * forbids being framed (X-Frame-Options DENY, CSP frame-ancestors 'none')
44
+ * shows a note instead - make the window narrower than 768 px; a page that
45
+ * needs state of the tab (a cart, a form step reached by clicks) shows its
46
+ * fresh load; the frame is a phone-width viewport, not a phone (no touch
47
+ * events, the desktop browser's user agent).
48
+ * - Each edit applies to All devices (the default, as before), Mobile only
49
+ * or Desktop only (the panel's "Applies to"); mobile = viewport below
50
+ * PAGE_EDIT_MOBILE_BREAKPOINT (768 px), the SDK's rule. The live preview
51
+ * shows only the edits of the current view, and the edit list marks the
52
+ * per-device ones.
32
53
  *
33
54
  * Messages (constants: EDITOR_MESSAGES in the core, EDITOR_SESSION_MESSAGES
34
55
  * here; the dashboard's copy is packages/frontend/src/lib/web-experience.ts):
35
56
  *
36
57
  * editor -> dashboard
37
58
  * joryio:editor-active { url } the editor is up
38
- * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, tag, text }
59
+ * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, device, tag, text }
39
60
  * a saved edit; `id` is the edit's id - an id the
40
- * dashboard already has REPLACES that edit
61
+ * dashboard already has REPLACES that edit.
62
+ * `device` (1.4.0-beta.8) is always sent: 'all' |
63
+ * 'mobile' | 'desktop'. A pick WITHOUT it comes from
64
+ * an editor before beta.8, which drops the field:
65
+ * the dashboard keeps the stored device of that id
41
66
  * joryio:editor-remove { id } undo of a new edit
42
67
  * joryio:editor-done {} "Save & return to Joryio"
68
+ * joryio:editor-open-slot { placementKey, campaignId? }
69
+ * "Create content for this slot" (no campaignId) or
70
+ * a campaign of the slot (its id): the dashboard
71
+ * opens that campaign, or a new Placement campaign
72
+ * for the slot; sent only to a dashboard that set
73
+ * `openSlot` in its context
43
74
  * joryio:editor-closed {} the editor stopped
44
75
  *
45
76
  * dashboard -> editor
46
- * joryio:editor-context { campaignName?, variantName?, edits?, focusId?,
47
- * attributes?: [{ name, custom? }], placements?: [{ key, name? }],
77
+ * joryio:editor-context { campaignName?, variantName?, edits? (each may carry device), focusId?,
78
+ * attributes?: [{ key, label?, group? } | { name, custom? }],
79
+ * placements?: [{ key, name?, campaigns?: [{ id, name, status, statusLabel? }] }],
80
+ * openSlot?: true,
48
81
  * sample?: { "user.firstName": "Lior", ... },
49
82
  * strings?: { <EDITOR_STRINGS key>: text }, dir?: 'ltr' | 'rtl' }
50
83
  * the variant's edits (shown live and in "N edits"),
51
- * the words in the marketer's language; enables Undo
84
+ * the words in the marketer's language; enables Undo.
85
+ * `campaigns` per placement (1.4.0-beta.7): the
86
+ * campaigns that fill that slot, shown on a saved
87
+ * slot edit ("In this slot: ..."); `openSlot`: the
88
+ * dashboard handles joryio:editor-open-slot. An
89
+ * editor before beta.7 ignores both.
52
90
  * joryio:editor-focus { id } jump to that edit
53
91
  * joryio:editor-close {} stop
54
92
  *
@@ -57,19 +95,21 @@
57
95
  * off (that dashboard would not hear a remove).
58
96
  */
59
97
  import type { Logger } from '../utils/logger';
60
- import { isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';
61
- import { EDITOR_MESSAGES } from '../core/editor-gate';
98
+ import { editShowsOn, isMobileViewport, isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditDevice, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';
99
+ import { EDITOR_FRAME_FLAG, EDITOR_MESSAGES, EDITOR_QUERY_FLAG } from '../core/editor-gate';
62
100
  import { EDITOR_STRINGS, fill, mergeStrings, type EditorStringKey, type EditorStrings } from './editor-strings';
63
- import { kindKey, liquidOutputs, newEditId, previewText, setTextFallback, slugify, textFallback, variableTag } from './editor-model';
64
- import { EDITOR_CSS, HOST_STYLE, PREVIEW_CSS, PREVIEW_HOST_STYLE, h, icon, type IconName } from './editor-ui';
101
+ import { VAR_PATH, kindKey, newEditId, pathTag, previewParts, slugify } from './editor-model';
102
+ import { EDITOR_CSS, HOST_STYLE, MOBILE_FRAME_WIDTH, PREVIEW_CSS, PREVIEW_HOST_STYLE, PREVIEW_VAR_HOST_STYLE, h, icon, type IconName } from './editor-ui';
103
+ import { liquidField, type LiquidField } from './liquid-field';
65
104
 
66
- export { EDITOR_MESSAGES };
105
+ export { EDITOR_MESSAGES, MOBILE_FRAME_WIDTH };
67
106
 
68
107
  export const EDITOR_SESSION_MESSAGES = {
69
108
  CONTEXT: 'joryio:editor-context',
70
109
  FOCUS: 'joryio:editor-focus',
71
110
  REMOVE: 'joryio:editor-remove',
72
111
  DONE: 'joryio:editor-done',
112
+ OPEN_SLOT: 'joryio:editor-open-slot',
73
113
  } as const;
74
114
 
75
115
  /** Attributes that name an element on purpose, most stable first. */
@@ -79,8 +119,29 @@ const ATTRIBUTE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
79
119
  const MAX_TEXT = 2000;
80
120
  const MAX_EDITS = 100;
81
121
  const PREVIEW_TAG = 'joryio-editor-preview';
122
+ /** The open overlays of the panel and what opens them: a press on anything else closes them. */
123
+ const OVERLAY_PARTS = '[data-j="var-picker"],[data-j="more"],[data-j="fallback-pop"],[data-liquid]';
124
+
125
+ /**
126
+ * Scroll the picker's list so the highlighted option shows whole - with its
127
+ * group heading when it is the group's first - inside the list only (never the
128
+ * panel or the page, as scrollIntoView would).
129
+ */
130
+ export function revealOption(list: HTMLElement, o: HTMLElement | null): void {
131
+ if (!o) return;
132
+ const prev = o.previousElementSibling as HTMLElement | null;
133
+ const top = prev && prev.getAttribute('role') === 'presentation' ? prev : o;
134
+ if (top.offsetTop < list.scrollTop) list.scrollTop = top.offsetTop;
135
+ else if (o.offsetTop + o.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = o.offsetTop + o.offsetHeight - list.clientHeight;
136
+ }
82
137
  const OURS = '[data-joryio-editor]';
83
138
  const HELP_DISMISSED_KEY = 'jry_editor_help_dismissed';
139
+ export type EditorView = 'desktop' | 'mobile';
140
+ const DEVICES: Array<[PageEditDevice, EditorStringKey]> = [
141
+ ['all', 'devAll'],
142
+ ['mobile', 'devMobile'],
143
+ ['desktop', 'devDesktop'],
144
+ ];
84
145
 
85
146
  /** CSS.escape, for browsers (and test DOMs) without it. */
86
147
  export function cssEscape(value: string): string {
@@ -99,12 +160,20 @@ export function cssEscape(value: string): string {
99
160
  }
100
161
 
101
162
  const isOurs = (el: Element | null): boolean => !!el && !!el.closest(OURS);
163
+ const VAR_PILL = 'var';
102
164
 
103
- /** The page's elements a selector finds - never the editor's own. */
104
- function pageMatches(selector: string): Element[] {
165
+ /** The page element an event on the page is about: a variable pill in the preview stands for the element it is in. */
166
+ function pageTarget(t: EventTarget | null): Element | null {
167
+ let el = t instanceof Element ? t : null;
168
+ if (el && el.getAttribute('data-joryio-editor') === VAR_PILL) el = el.parentElement;
169
+ return el && !isOurs(el) && el !== el.ownerDocument.body && el !== el.ownerDocument.documentElement ? el : null;
170
+ }
171
+
172
+ /** The page's elements a selector finds - never the editor's own. `doc`: the tab's page, or the Mobile view's frame. */
173
+ function pageMatches(selector: string, doc: Document): Element[] {
105
174
  if (!isSafeSelector(selector)) return [];
106
175
  try {
107
- return Array.from(document.querySelectorAll(selector)).filter((e) => !isOurs(e));
176
+ return Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));
108
177
  } catch {
109
178
  return [];
110
179
  }
@@ -183,6 +252,8 @@ export interface EditorPick {
183
252
  value?: string;
184
253
  placementKey?: string;
185
254
  position?: PageEditPosition;
255
+ /** Always sent by 1.4.0-beta.8 ('all' included), so the dashboard can tell it from an older editor's pick. */
256
+ device: PageEditDevice;
186
257
  tag: string;
187
258
  text: string;
188
259
  }
@@ -207,6 +278,7 @@ interface Draft {
207
278
  url: string;
208
279
  slotName: string;
209
280
  position: PageEditPosition;
281
+ device: PageEditDevice;
210
282
  selector: string;
211
283
  /** The edit being changed (opened from the list or the dashboard), null for a new one. */
212
284
  editingId: string | null;
@@ -214,16 +286,52 @@ interface Draft {
214
286
  touched: boolean;
215
287
  }
216
288
 
289
+ interface Var {
290
+ path: string;
291
+ label: string;
292
+ group: string;
293
+ }
294
+
295
+ /** The chips shown before "More…": these when the catalog has them, else its first ones. */
296
+ const COMMON_VARS = ['user.firstName', 'user.lastName', 'user.email', 'user.custom.city'];
297
+ const CHIPS = 4;
298
+
217
299
  interface EditorContext {
218
300
  campaignName: string;
219
301
  variantName: string;
220
- attributes: Array<{ name: string; custom: boolean }>;
221
- placements: Array<{ key: string; name: string }>;
302
+ /** The personalization catalog: Liquid path, label, group ('' for the old `{ name, custom }` shape). */
303
+ attributes: Var[];
304
+ placements: Array<{ key: string; name: string; campaigns: SlotCampaign[] }>;
222
305
  sample: Record<string, string>;
306
+ /** The dashboard handles joryio:editor-open-slot: the slot's campaigns and "Create content for this slot" show. */
307
+ openSlot: boolean;
308
+ }
309
+
310
+ /** A campaign that fills a slot, as the dashboard sent it. */
311
+ interface SlotCampaign {
312
+ id: string;
313
+ name: string;
314
+ /** The wire status (`draft`, `active`, ...), and the dashboard's word for it. */
315
+ status: string;
316
+ statusLabel: string;
223
317
  }
318
+ const CAMPAIGN_ID = /^[A-Za-z0-9_-]{1,64}$/;
224
319
 
225
320
  const clip = (v: unknown, n: number): string => (typeof v === 'string' ? v.trim().slice(0, n) : '');
226
- const shortText = (el: Element | null): string => ((el && el.textContent) || '').replace(/\s+/g, ' ').trim();
321
+ /**
322
+ * An element's own text, read from the page: never the editor's previews in it
323
+ * (a placeholder pill, a slot or "hidden" note) - a pill's text lives in its
324
+ * shadow root, so reading textContent over it would silently drop the variable.
325
+ */
326
+ export const shortText = (el: Element | null): string => {
327
+ if (!el) return '';
328
+ let src: Element = el;
329
+ if (el.querySelector(OURS)) {
330
+ src = el.cloneNode(true) as Element;
331
+ for (const n of Array.from(src.querySelectorAll(OURS))) n.remove();
332
+ }
333
+ return (src.textContent || '').replace(/\s+/g, ' ').trim();
334
+ };
227
335
 
228
336
  export class VisualEditor {
229
337
  private listeners: Array<() => void> = [];
@@ -241,6 +349,11 @@ export class VisualEditor {
241
349
  private selected: Element | null = null;
242
350
  private draft: Draft | null = null;
243
351
  private showCss = false;
352
+ private showLiquid = false;
353
+ /** Closes an open overlay of the panel (the variable picker) on Esc; true when it closed one. */
354
+ private closeOverlay: (() => boolean) | null = null;
355
+ /** The New text field on screen (a page pill's click opens its fallback here). */
356
+ private field: LiquidField | null = null;
244
357
  private popOpen = false;
245
358
  private edits: PageEditWire[] = [];
246
359
  private history: Array<{ id: string; before: PageEditWire | null }> = [];
@@ -248,10 +361,19 @@ export class VisualEditor {
248
361
  private synced = false;
249
362
  private t: EditorStrings = { ...EDITOR_STRINGS };
250
363
  private dir: 'ltr' | 'rtl' = 'ltr';
251
- private ctx: EditorContext = { campaignName: '', variantName: '', attributes: [], placements: [], sample: {} };
364
+ private ctx: EditorContext = { campaignName: '', variantName: '', attributes: [], placements: [], sample: {}, openSlot: false };
252
365
  private previewUndo: Array<() => void> = [];
253
366
  /** The page's own text / address of an element before any preview, for "Was:". */
254
367
  private originals = new WeakMap<Element, { text: string; href: string | null; src: string | null }>();
368
+ /** The page being edited: this tab's document, or the Mobile view's frame document. */
369
+ private doc: Document = document;
370
+ private view: EditorView = 'desktop';
371
+ private stage: HTMLElement | null = null;
372
+ private frame: HTMLIFrameElement | null = null;
373
+ /** Unbinds the listeners on the page being edited (this tab's, or the frame's). */
374
+ private offPage: (() => void) | null = null;
375
+ /** The viewport the preview was drawn for (a resize across 768 px redraws it). */
376
+ private mobileShown = false;
255
377
 
256
378
  constructor(
257
379
  private dashboardOrigin: string,
@@ -293,7 +415,9 @@ export class VisualEditor {
293
415
  for (const off of this.listeners.splice(0)) off();
294
416
  this.clearPreview();
295
417
  this.host?.remove();
296
- this.host = this.root = this.wrap = this.hoverBox = this.selBox = this.dock = this.panel = this.help = null;
418
+ this.host = this.root = this.wrap = this.hoverBox = this.selBox = this.dock = this.panel = this.help = this.stage = this.frame = null;
419
+ this.doc = document;
420
+ this.view = 'desktop';
297
421
  this.selected = this.hovered = null;
298
422
  this.draft = null;
299
423
  try {
@@ -330,54 +454,199 @@ export class VisualEditor {
330
454
  this.host = host;
331
455
  this.root = root;
332
456
  this.wrap = wrap;
457
+ // A press anywhere in the editor's UI outside the open picker / fallback popover (and the
458
+ // button or pill that opens it) closes it.
459
+ const outside = (e: Event) => {
460
+ const path = typeof e.composedPath === 'function' ? e.composedPath() : [e.target];
461
+ if (path.some((n) => n instanceof Element && n.matches(OVERLAY_PARTS))) return;
462
+ this.closeOverlay?.();
463
+ };
464
+ wrap.addEventListener('pointerdown', outside);
465
+ wrap.addEventListener('mousedown', outside);
466
+
467
+ // Esc and the arrows also while the focus is in this tab (the panel, or the Mobile view's surroundings).
468
+ const onKey = (e: KeyboardEvent) => this.onKey(e);
469
+ doc.addEventListener('keydown', onKey, true);
470
+ const onResize = () => {
471
+ this.placeBoxes();
472
+ // The tab crossed the 768 px breakpoint: the preview shows the other device's edits.
473
+ if (this.view === 'desktop' && isMobileViewport(window) !== this.mobileShown) {
474
+ this.renderPreview();
475
+ if (this.draft) this.renderPanel();
476
+ }
477
+ };
478
+ window.addEventListener('resize', onResize);
479
+ this.listeners.push(
480
+ () => doc.removeEventListener('keydown', onKey, true),
481
+ () => window.removeEventListener('resize', onResize),
482
+ () => this.unbindPage(),
483
+ );
484
+ this.bindPage(doc, window);
485
+ this.renderDock();
486
+ this.renderHelp();
487
+ this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });
488
+ }
333
489
 
490
+ private onKey(e: KeyboardEvent): void {
491
+ if (e.key === 'Escape') {
492
+ if (this.closeOverlay && this.closeOverlay()) return;
493
+ if (this.popOpen) this.togglePop(false);
494
+ else if (this.panel) this.cancel();
495
+ else this.stop();
496
+ return;
497
+ }
498
+ if (isOurs(e.target instanceof Element ? e.target : null)) return; // typing in the panel
499
+ if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
500
+ const from = this.selected || this.hovered;
501
+ if (!from) return;
502
+ e.preventDefault();
503
+ e.stopPropagation();
504
+ this.move(e.key === 'ArrowUp' ? 'up' : 'down', from);
505
+ }
506
+ }
507
+
508
+ /** Hover, click (and keys, in a frame) on the page being edited; scroll moves the outlines. */
509
+ private bindPage(doc: Document, win: Window): void {
510
+ this.unbindPage();
511
+ this.doc = doc;
334
512
  const onMove = (e: MouseEvent) => {
335
513
  const t = e.target instanceof Element ? e.target : null;
336
- if (isOurs(t)) return;
337
- this.hovered = t && t !== doc.body && t !== doc.documentElement ? t : null;
514
+ if (isOurs(t) && t!.getAttribute('data-joryio-editor') !== VAR_PILL) return;
515
+ this.hovered = pageTarget(t);
338
516
  this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
339
517
  };
340
518
  const onClick = (e: MouseEvent) => {
341
- if (isOurs(e.target instanceof Element ? e.target : null)) return;
519
+ if (e.target instanceof Element && e.target.closest('[data-joryio-editor="root"]')) return;
520
+ // A click on the page - a preview of ours included - never reaches the site.
342
521
  e.preventDefault();
343
522
  e.stopPropagation();
344
- if (e.target instanceof Element && e.target !== doc.body && e.target !== doc.documentElement) this.select(e.target);
523
+ // An open picker or fallback popover: a click outside it only closes it, it selects nothing.
524
+ if (this.closeOverlay && this.closeOverlay()) return;
525
+ const el = pageTarget(e.target);
526
+ if (!el) return;
527
+ // A placeholder pill in the preview: its element's edit, and that variable's fallback - never a new draft.
528
+ const pill = e.target instanceof Element && e.target.getAttribute('data-joryio-editor') === VAR_PILL ? e.target.getAttribute('data-path') : null;
529
+ this.select(el);
530
+ if (pill) this.field?.openPill(pill);
345
531
  };
346
- const onKey = (e: KeyboardEvent) => {
347
- if (e.key === 'Escape') {
348
- if (this.popOpen) this.togglePop(false);
349
- else if (this.panel) this.cancel();
350
- else this.stop();
532
+ const onKey = (e: KeyboardEvent) => this.onKey(e);
533
+ const onScroll = () => this.placeBoxes();
534
+ const inFrame = doc !== document;
535
+ doc.addEventListener('mousemove', onMove, true);
536
+ doc.addEventListener('click', onClick, true);
537
+ if (inFrame) doc.addEventListener('keydown', onKey, true);
538
+ win.addEventListener('scroll', onScroll, true);
539
+ if (inFrame) win.addEventListener('resize', onScroll);
540
+ this.offPage = () => {
541
+ doc.removeEventListener('mousemove', onMove, true);
542
+ doc.removeEventListener('click', onClick, true);
543
+ doc.removeEventListener('keydown', onKey, true);
544
+ win.removeEventListener('scroll', onScroll, true);
545
+ win.removeEventListener('resize', onScroll);
546
+ };
547
+ }
548
+
549
+ private unbindPage(): void {
550
+ const off = this.offPage;
551
+ this.offPage = null;
552
+ try {
553
+ off?.();
554
+ } catch {
555
+ /* the frame went away */
556
+ }
557
+ }
558
+
559
+ private placeBoxes(): void {
560
+ this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
561
+ this.place(this.selBox, this.selected);
562
+ }
563
+
564
+ /** The Desktop / Mobile view (the dock's toggle). */
565
+ currentView(): EditorView {
566
+ return this.view;
567
+ }
568
+
569
+ /** Switch the view. Mobile = the page at phone width, in a same-origin frame; `focusId` opens that edit there. */
570
+ setView(view: EditorView, focusId?: string): void {
571
+ if (!this.active || !this.wrap) return;
572
+ if (view === this.view) {
573
+ if (focusId) this.focusEdit(focusId);
574
+ return;
575
+ }
576
+ // Leave the page being edited as it was: no preview, no selection, no panel.
577
+ this.clearPreview();
578
+ this.unbindPage();
579
+ this.draft = null;
580
+ this.selected = this.hovered = null;
581
+ this.panel?.remove();
582
+ this.panel = null;
583
+ this.wrap.classList.remove('open');
584
+ this.popOpen = false;
585
+ this.stage?.remove();
586
+ this.stage = this.frame = null;
587
+ this.view = view;
588
+ // Until the frame has loaded, an empty page: nothing to match, nothing previewed in this tab.
589
+ this.doc = document.implementation.createHTMLDocument('');
590
+ if (view === 'desktop') {
591
+ this.bindPage(document, window);
592
+ this.renderAll();
593
+ if (focusId) this.focusEdit(focusId);
594
+ return;
595
+ }
596
+ const frame = h('iframe', { title: this.t.viewMobile, 'data-j': 'frame' }) as HTMLIFrameElement;
597
+ const url = new URL(location.href);
598
+ url.searchParams.set(EDITOR_QUERY_FLAG, EDITOR_FRAME_FLAG);
599
+ const stage = h('div', { class: 'stage', 'data-j': 'stage' }, frame);
600
+ frame.addEventListener('load', () => {
601
+ if (this.frame !== frame) return;
602
+ // Every load of the frame (its first, a redirect, a reload) is a new document to bind.
603
+ let doc: Document | null = null;
604
+ try {
605
+ doc = frame.contentDocument;
606
+ if (doc && (doc.URL === 'about:blank' || !doc.documentElement)) doc = null;
607
+ } catch {
608
+ doc = null; // another origin (a redirect), or the browser's own error page
609
+ }
610
+ if (!doc || !frame.contentWindow) {
611
+ // The site does not allow itself in a frame (X-Frame-Options, CSP frame-ancestors).
612
+ this.unbindPage();
613
+ this.doc = document.implementation.createHTMLDocument('');
614
+ frame.hidden = true;
615
+ stage.appendChild(h('div', { class: 'note fnote', role: 'status', 'data-j': 'frame-blocked' }, this.t.frameBlocked));
351
616
  return;
352
617
  }
353
- if (isOurs(e.target instanceof Element ? e.target : null)) return; // typing in the panel
354
- if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
355
- const from = this.selected || this.hovered;
356
- if (!from) return;
357
- e.preventDefault();
358
- e.stopPropagation();
359
- this.move(e.key === 'ArrowUp' ? 'up' : 'down', from);
618
+ this.clearPreview();
619
+ this.selected = this.hovered = null;
620
+ this.bindPage(doc, frame.contentWindow);
621
+ this.renderPreview();
622
+ this.placeBoxes();
623
+ if (focusId) {
624
+ this.focusEdit(focusId);
625
+ focusId = undefined;
360
626
  }
361
- };
362
- const onScroll = () => {
363
- this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
364
- this.place(this.selBox, this.selected);
365
- };
366
- doc.addEventListener('mousemove', onMove, true);
367
- doc.addEventListener('click', onClick, true);
368
- doc.addEventListener('keydown', onKey, true);
369
- window.addEventListener('scroll', onScroll, true);
370
- window.addEventListener('resize', onScroll);
371
- this.listeners.push(
372
- () => doc.removeEventListener('mousemove', onMove, true),
373
- () => doc.removeEventListener('click', onClick, true),
374
- () => doc.removeEventListener('keydown', onKey, true),
375
- () => window.removeEventListener('scroll', onScroll, true),
376
- () => window.removeEventListener('resize', onScroll),
377
- );
627
+ });
628
+ frame.setAttribute('src', url.toString());
629
+ this.stage = stage;
630
+ this.frame = frame;
631
+ this.wrap.insertBefore(stage, this.wrap.firstChild);
632
+ this.renderAll();
633
+ }
634
+
635
+ private renderAll(): void {
636
+ this.renderPreview();
378
637
  this.renderDock();
379
638
  this.renderHelp();
380
- this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });
639
+ this.placeBoxes();
640
+ }
641
+
642
+ /** True when the page being edited is a mobile viewport: the Mobile view, or a narrow tab. */
643
+ private mobileNow(): boolean {
644
+ return this.view === 'mobile' || isMobileViewport(window);
645
+ }
646
+
647
+ /** The edit shows in the current view (its device is All, or this view's). */
648
+ private inView(e: { device?: string }): boolean {
649
+ return editShowsOn(e, this.mobileNow());
381
650
  }
382
651
 
383
652
  /** The dashboard's context: words, campaign, the variant's edits (validated like the runtime does). */
@@ -394,9 +663,39 @@ export class VisualEditor {
394
663
  this.ctx = {
395
664
  campaignName: clip(data.campaignName, 120),
396
665
  variantName: clip(data.variantName, 60),
397
- attributes: list(data.attributes, (a) => (a && typeof a.name === 'string' && ATTRIBUTE_NAME.test(a.name) ? { name: a.name, custom: a.custom === true } : null), 40),
398
- placements: list(data.placements, (p) => (p && typeof p.key === 'string' && PLACEMENT_KEY_PATTERN.test(p.key) ? { key: p.key, name: clip(p.name, 80) } : null), 40),
666
+ // Both shapes: the catalog's { key, label, group } and the older { name, custom }.
667
+ attributes: list(
668
+ data.attributes,
669
+ (a): Var | null =>
670
+ !a
671
+ ? null
672
+ : typeof a.key === 'string' && VAR_PATH.test(a.key)
673
+ ? { path: a.key, label: clip(a.label, 60) || a.key.split('.').pop()!, group: clip(a.group, 40) }
674
+ : typeof a.name === 'string' && ATTRIBUTE_NAME.test(a.name)
675
+ ? // The older shape has no group: under "Profile" / "Custom fields", never after another group's heading.
676
+ { path: `user.${a.custom === true ? 'custom.' : ''}${a.name}`, label: a.name, group: a.custom === true ? this.t.groupCustom : this.t.groupProfile }
677
+ : null,
678
+ 400,
679
+ ),
680
+ placements: list(
681
+ data.placements,
682
+ (p) =>
683
+ p && typeof p.key === 'string' && PLACEMENT_KEY_PATTERN.test(p.key)
684
+ ? {
685
+ key: p.key,
686
+ name: clip(p.name, 80),
687
+ campaigns: list(
688
+ p.campaigns,
689
+ (c): SlotCampaign | null =>
690
+ c && typeof c.id === 'string' && CAMPAIGN_ID.test(c.id) ? { id: c.id, name: clip(c.name, 120) || c.id, status: clip(c.status, 30), statusLabel: clip(c.statusLabel, 40) } : null,
691
+ 10,
692
+ ),
693
+ }
694
+ : null,
695
+ 200,
696
+ ),
399
697
  sample: {},
698
+ openSlot: data.openSlot === true,
400
699
  };
401
700
  if (data.sample && typeof data.sample === 'object') {
402
701
  for (const [k, v] of Object.entries(data.sample as Record<string, unknown>).slice(0, 100)) {
@@ -427,7 +726,9 @@ export class VisualEditor {
427
726
  return;
428
727
  }
429
728
  const r = el.getBoundingClientRect();
430
- Object.assign(box.style, { display: 'block', top: `${r.top - 2}px`, left: `${r.left - 2}px`, width: `${r.width + 4}px`, height: `${r.height + 4}px` });
729
+ // An element of the Mobile view's frame: its frame-viewport box, moved to where the frame sits in this tab.
730
+ const f = this.frame && el.ownerDocument !== document ? this.frame.getBoundingClientRect() : { top: 0, left: 0 };
731
+ Object.assign(box.style, { display: 'block', top: `${r.top + f.top - 2}px`, left: `${r.left + f.left - 2}px`, width: `${r.width + 4}px`, height: `${r.height + 4}px` });
431
732
  box.textContent = '';
432
733
  const label = `${this.t[kindKey(el.tagName)]} · ${el.tagName.toLowerCase()}`;
433
734
  box.appendChild(h('span', { class: 'chip', 'data-j': 'label' }, withLabel ? `${label} - ${this.t.clickToEdit}` : label));
@@ -435,13 +736,32 @@ export class VisualEditor {
435
736
 
436
737
  private move(dir: 'up' | 'down', from: Element): void {
437
738
  const next = dir === 'up' ? from.parentElement : Array.from(from.children).filter((c) => !isOurs(c))[0] || null;
438
- if (!next || next === document.body || next === document.documentElement) return;
739
+ if (!next || next === from.ownerDocument.body || next === from.ownerDocument.documentElement) return;
439
740
  this.select(next);
440
741
  }
441
742
 
442
- /** The element is chosen: open the panel on it (or on one of its edits). */
743
+ /**
744
+ * The edits on an element (its selector finds it, or is the selector the
745
+ * editor would make for it), oldest first - only those of the current view:
746
+ * in Mobile view a Desktop-only edit is not what the marketer is looking at.
747
+ */
748
+ private editsOn(el: Element | null): PageEditWire[] {
749
+ if (!el) return [];
750
+ const own = robustSelector(el);
751
+ return this.edits.filter((e) => this.inView(e) && (e.selector === own || pageMatches(e.selector, el.ownerDocument).indexOf(el) >= 0));
752
+ }
753
+
754
+ /**
755
+ * The element is chosen: open the panel on it. An element that already
756
+ * has an edit (this session's or the dashboard's) opens that edit - the
757
+ * most recent one - like jumping to it from the list: its value, its
758
+ * fallback, and Save updates the same edit.
759
+ */
443
760
  select(el: Element, edit?: PageEditWire): void {
444
761
  if (!this.active) return;
762
+ // The element already open: keep the draft as typed (re-reading the page would lose it).
763
+ if (!edit && this.draft && el === this.selected) return;
764
+ edit = edit || this.editsOn(el).pop();
445
765
  this.selected = el;
446
766
  this.hovered = null;
447
767
  this.place(this.hoverBox, null);
@@ -467,7 +787,7 @@ export class VisualEditor {
467
787
  private newDraft(el: Element, selector: string): Draft {
468
788
  const o = this.orig(el);
469
789
  const action: Action = el.tagName === 'IMG' ? 'image' : this.enabled('text', el) ? 'text' : el.tagName === 'A' ? 'link' : 'hide';
470
- return { action, text: o.text.slice(0, MAX_TEXT), url: (action === 'image' ? o.src : o.href) || '', slotName: '', position: 'after', selector, editingId: null, touched: false };
790
+ return { action, text: o.text.slice(0, MAX_TEXT), url: (action === 'image' ? o.src : o.href) || '', slotName: '', position: 'after', device: 'all', selector, editingId: null, touched: false };
471
791
  }
472
792
 
473
793
  private draftOf(e: PageEditWire): Draft {
@@ -478,6 +798,7 @@ export class VisualEditor {
478
798
  url: action === 'link' || action === 'image' ? e.value || '' : '',
479
799
  slotName: e.placementKey || '',
480
800
  position: e.position || 'after',
801
+ device: e.device || 'all',
481
802
  selector: e.selector,
482
803
  editingId: e.id,
483
804
  touched: true,
@@ -493,7 +814,15 @@ export class VisualEditor {
493
814
  focusEdit(id: unknown): boolean {
494
815
  const edit = this.edits.filter((e) => e.id === id)[0];
495
816
  if (!edit || !this.active) return false;
496
- const el = pageMatches(edit.selector)[0] || null;
817
+ // Another device's edit: switch to its view first (Mobile opens the frame and focuses it once loaded).
818
+ if (!this.inView(edit)) {
819
+ const want: EditorView = edit.device === 'mobile' ? 'mobile' : 'desktop';
820
+ if (want !== this.view) {
821
+ this.setView(want, edit.id);
822
+ if (want === 'mobile') return true;
823
+ }
824
+ }
825
+ const el = (this.inView(edit) && pageMatches(edit.selector, this.doc)[0]) || null;
497
826
  if (el) {
498
827
  try {
499
828
  el.scrollIntoView({ block: 'center' });
@@ -518,7 +847,7 @@ export class VisualEditor {
518
847
 
519
848
  /** The draft as an edit, or null while a field is not valid yet. */
520
849
  private draftEdit(d: Draft): PageEditWire | null {
521
- const base = { id: d.editingId || '', selector: d.selector.trim() };
850
+ const base = { id: d.editingId || '', selector: d.selector.trim(), ...(d.device !== 'all' ? { device: d.device } : {}) };
522
851
  if (!isSafeSelector(base.selector)) return null;
523
852
  const operation = OPERATION_OF[d.action];
524
853
  if (d.action === 'hide') return { ...base, operation };
@@ -532,8 +861,23 @@ export class VisualEditor {
532
861
  const d = this.draft;
533
862
  const edit = d && this.draftEdit(d);
534
863
  if (!d || !edit) return;
535
- const el = this.selected || pageMatches(edit.selector)[0] || null;
536
- this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id: d.editingId || undefined, position: edit.position });
864
+ const el = this.selected || pageMatches(edit.selector, this.doc)[0] || null;
865
+ const id = d.editingId || newEditId();
866
+ if (!this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id, position: edit.position, device: d.device })) return;
867
+ // A saved slot stays open on its edit, with its campaigns or "Create content for this slot".
868
+ if (edit.operation === 'insert_placement' && this.ctx.openSlot) this.focusEdit(id);
869
+ }
870
+
871
+ /** "Create content for this slot" or one of its campaigns: the dashboard opens it, in its own tab. */
872
+ openSlot(placementKey: string, campaignId?: string): boolean {
873
+ if (!this.ctx.openSlot || !PLACEMENT_KEY_PATTERN.test(placementKey)) return false;
874
+ this.send({ type: EDITOR_SESSION_MESSAGES.OPEN_SLOT, placementKey, ...(campaignId ? { campaignId } : {}) });
875
+ try {
876
+ this.opener.focus();
877
+ } catch {
878
+ /* not allowed */
879
+ }
880
+ return true;
537
881
  }
538
882
 
539
883
  /**
@@ -541,7 +885,7 @@ export class VisualEditor {
541
885
  * in the list (and on the page). `value` is the text, the address or the
542
886
  * slot name (made a placement key).
543
887
  */
544
- pick(el: Element | null, selector: string, operation: PageEditOperation, value: string, opts: { id?: string; position?: PageEditPosition } = {}): boolean {
888
+ pick(el: Element | null, selector: string, operation: PageEditOperation, value: string, opts: { id?: string; position?: PageEditPosition; device?: PageEditDevice } = {}): boolean {
545
889
  const id = opts.id || newEditId();
546
890
  const tag = el ? el.tagName.toLowerCase() : '';
547
891
  const text = el ? this.orig(el).text.slice(0, 200) : '';
@@ -557,7 +901,8 @@ export class VisualEditor {
557
901
  }
558
902
  }
559
903
  if (!edit) return false;
560
- const msg: EditorPick = { type: EDITOR_MESSAGES.PICK, ...edit, tag, text } as EditorPick;
904
+ if (opts.device === 'mobile' || opts.device === 'desktop') edit.device = opts.device;
905
+ const msg: EditorPick = { type: EDITOR_MESSAGES.PICK, ...edit, device: edit.device || 'all', tag, text } as EditorPick;
561
906
  this.send(msg as unknown as Record<string, unknown>);
562
907
  const at = this.edits.map((e) => e.id).indexOf(id);
563
908
  this.history.push({ id, before: at >= 0 ? this.edits[at] : null });
@@ -592,7 +937,7 @@ export class VisualEditor {
592
937
  if (last.before) {
593
938
  if (at >= 0) this.edits[at] = last.before;
594
939
  const b = last.before;
595
- this.send({ type: EDITOR_MESSAGES.PICK, ...b, tag: '', text: '' });
940
+ this.send({ type: EDITOR_MESSAGES.PICK, ...b, device: b.device || 'all', tag: '', text: '' });
596
941
  } else {
597
942
  if (at >= 0) this.edits.splice(at, 1);
598
943
  this.send({ type: EDITOR_SESSION_MESSAGES.REMOVE, id: last.id });
@@ -642,21 +987,31 @@ export class VisualEditor {
642
987
  const shown: PageEditWire[] = [];
643
988
  for (const e of this.edits) shown.push(d && d.editingId === e.id ? draft || e : e);
644
989
  if (d && !d.editingId && draft && d.touched) shown.push(draft);
645
- for (const e of shown) for (const el of pageMatches(e.selector).slice(0, 50)) this.applyPreview(e, el);
990
+ // Only the current view's edits: a Mobile-only edit shows in Mobile view, not in Desktop.
991
+ this.mobileShown = this.mobileNow();
992
+ for (const e of shown) if (this.inView(e)) for (const el of pageMatches(e.selector, this.doc).slice(0, 50)) this.applyPreview(e, el);
646
993
  if (this.selected) this.place(this.selBox, this.selected);
647
994
  }
648
995
 
649
- private previewNode(build: (root: ShadowRoot) => void): HTMLElement {
650
- const n = document.createElement(PREVIEW_TAG);
651
- n.setAttribute('data-joryio-editor', 'preview');
652
- n.setAttribute('style', PREVIEW_HOST_STYLE);
996
+ private previewNode(doc: Document, build: (root: ShadowRoot) => void, style = PREVIEW_HOST_STYLE, kind = 'preview'): HTMLElement {
997
+ const n = doc.createElement(PREVIEW_TAG);
998
+ n.setAttribute('data-joryio-editor', kind);
999
+ n.setAttribute('style', style);
653
1000
  const root = n.attachShadow({ mode: 'open' });
654
1001
  root.appendChild(h('style', null, PREVIEW_CSS));
655
1002
  build(root);
656
1003
  return n;
657
1004
  }
658
1005
 
1006
+ /** A variable's placeholder pill in the page preview; `data-path` names the variable (a click opens its fallback). */
1007
+ private previewPill(doc: Document, path: string, label: string): HTMLElement {
1008
+ const n = this.previewNode(doc, (r) => r.appendChild(h('span', { class: 'v', dir: 'auto' }, label)), PREVIEW_VAR_HOST_STYLE, VAR_PILL);
1009
+ n.setAttribute('data-path', path);
1010
+ return n;
1011
+ }
1012
+
659
1013
  private applyPreview(e: PageEditWire, el: Element): void {
1014
+ const doc = el.ownerDocument;
660
1015
  if (!this.originals.has(el)) this.originals.set(el, { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') });
661
1016
  const undo = this.previewUndo;
662
1017
  const attr = (name: string, value: string | null) => {
@@ -684,7 +1039,9 @@ export class VisualEditor {
684
1039
  switch (e.operation) {
685
1040
  case 'replace_text': {
686
1041
  const kids = Array.from(el.childNodes);
687
- el.textContent = previewText(e.value || '', this.ctx.sample);
1042
+ el.textContent = '';
1043
+ // A variable with neither a sample value nor a fallback is a pill, in its own shadow root.
1044
+ for (const p of previewParts(e.value || '', this.ctx.sample)) el.appendChild(typeof p === 'string' ? doc.createTextNode(p) : this.previewPill(doc, p.path, this.labelOf(p.path) || p.name));
688
1045
  undo.push(() => {
689
1046
  el.textContent = '';
690
1047
  for (const k of kids) el.appendChild(k);
@@ -700,14 +1057,14 @@ export class VisualEditor {
700
1057
  break;
701
1058
  case 'hide': {
702
1059
  const what = `${this.t[kindKey(el.tagName)]} "${this.orig(el).text.slice(0, 40)}"`;
703
- insert(this.previewNode((r) => r.appendChild(h('div', { class: 'x' }, `${this.t.hiddenFor}: ${what}`))), 'after');
1060
+ insert(this.previewNode(doc, (r) => r.appendChild(h('div', { class: 'x' }, `${this.t.hiddenFor}: ${what}`))), 'after');
704
1061
  hide();
705
1062
  break;
706
1063
  }
707
1064
  case 'insert_placement': {
708
1065
  const where = e.position || 'after';
709
1066
  insert(
710
- this.previewNode((r) => r.appendChild(h('div', { class: 's' }, h('b', null, `${this.t.slotPreview} · `), h('code', null, e.placementKey || ''), h('div', null, this.t.slotHelp)))),
1067
+ this.previewNode(doc, (r) => r.appendChild(h('div', { class: 's' }, h('b', null, `${this.t.slotPreview} · `), h('code', null, e.placementKey || ''), h('div', null, this.t.slotHelp)))),
711
1068
  where,
712
1069
  );
713
1070
  if (where === 'replace') hide();
@@ -745,8 +1102,14 @@ export class VisualEditor {
745
1102
  this.wrap.appendChild(this.help);
746
1103
  }
747
1104
 
1105
+ /** A variable's label from the catalog. */
1106
+ private labelOf(path: string): string | undefined {
1107
+ const v = this.ctx.attributes.filter((a) => a.path === path)[0];
1108
+ return v && v.label;
1109
+ }
1110
+
748
1111
  private editTitle(e: PageEditWire): string {
749
- const el = pageMatches(e.selector)[0];
1112
+ const el = pageMatches(e.selector, this.doc)[0];
750
1113
  const kind = this.t[el ? kindKey(el.tagName) : kindKey(e.selector, true)];
751
1114
  return `${this.t[ACTION_LABEL[ACTION_OF[e.operation]]]} · ${kind}`;
752
1115
  }
@@ -769,6 +1132,13 @@ export class VisualEditor {
769
1132
  undoBtn.addEventListener('click', () => this.undo());
770
1133
  const doneBtn = h('button', { class: 'go', type: 'button', 'data-j': 'done' }, t.saveReturn);
771
1134
  doneBtn.addEventListener('click', () => this.done());
1135
+ // Desktop / Mobile: the page as it is in this tab, or at phone width.
1136
+ const views = h('span', { class: 'vw', role: 'radiogroup', 'aria-label': t.view, 'data-j': 'views' });
1137
+ for (const [v, label] of [['desktop', t.viewDesktop], ['mobile', t.viewMobile]] as Array<[EditorView, string]>) {
1138
+ const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(this.view === v), 'aria-label': label, title: label, 'data-j': `view-${v}` }, icon(v, 15));
1139
+ b.addEventListener('click', () => this.setView(v));
1140
+ views.appendChild(b);
1141
+ }
772
1142
  const dock = h(
773
1143
  'div',
774
1144
  { class: 'dock', 'data-j': 'dock', role: 'toolbar', 'aria-label': t.title },
@@ -778,6 +1148,7 @@ export class VisualEditor {
778
1148
  h('span', { class: 'sep' }),
779
1149
  h('span', { class: 'hint', 'data-j': 'hint' }, icon('cursor', 13), this.draft ? t.hintEditing : t.hintPoint),
780
1150
  h('span', { class: 'sep' }),
1151
+ views,
781
1152
  countBtn,
782
1153
  undoBtn,
783
1154
  doneBtn,
@@ -786,7 +1157,8 @@ export class VisualEditor {
786
1157
  const pop = h('div', { class: 'pop', 'data-j': 'edit-list', role: 'menu' });
787
1158
  if (!n) pop.appendChild(h('div', { class: 'empty' }, t.noEdits));
788
1159
  this.edits.forEach((e, i) => {
789
- const b = h('button', { class: 'e', type: 'button', role: 'menuitem', 'data-j': 'edit-item', 'data-edit-id': e.id }, h('span', { class: 'num' }, String(i + 1)), this.editTitle(e));
1160
+ const badge = e.device ? h('span', { class: 'bdg', 'data-j': 'device-badge' }, e.device === 'mobile' ? t.devMobile : t.devDesktop) : null;
1161
+ const b = h('button', { class: 'e', type: 'button', role: 'menuitem', 'data-j': 'edit-item', 'data-edit-id': e.id }, h('span', { class: 'num' }, String(i + 1)), this.editTitle(e), badge);
790
1162
  b.addEventListener('click', () => this.focusEdit(e.id));
791
1163
  pop.appendChild(b);
792
1164
  });
@@ -808,7 +1180,8 @@ export class VisualEditor {
808
1180
  const crumbs = h('div', { class: 'crumbs', 'data-j': 'crumbs' });
809
1181
  if (el) {
810
1182
  const chain: Element[] = [];
811
- for (let n: Element | null = el; n && n !== document.body && n !== document.documentElement; n = n.parentElement) chain.unshift(n);
1183
+ const doc = el.ownerDocument;
1184
+ for (let n: Element | null = el; n && n !== doc.body && n !== doc.documentElement; n = n.parentElement) chain.unshift(n);
812
1185
  const shown = chain.slice(-3);
813
1186
  const crumb = (label: string, target: Element | null, cur: boolean) => {
814
1187
  const b = h('button', { class: cur ? 'crumb cur' : 'crumb', type: 'button', 'data-j': 'crumb', 'aria-current': cur ? 'true' : undefined, disabled: !target }, label);
@@ -817,7 +1190,7 @@ export class VisualEditor {
817
1190
  };
818
1191
  crumbs.appendChild(crumb(t.page, null, false));
819
1192
  for (const n of shown) crumbs.append(icon('chevron', 9), crumb(t[kindKey(n.tagName)], n, n === el));
820
- const up = h('button', { type: 'button', 'aria-label': t.up, title: t.up, 'data-j': 'up', disabled: !el.parentElement || el.parentElement === document.body }, icon('up', 12));
1193
+ const up = h('button', { type: 'button', 'aria-label': t.up, title: t.up, 'data-j': 'up', disabled: !el.parentElement || el.parentElement === doc.body }, icon('up', 12));
821
1194
  up.addEventListener('click', () => this.move('up', el));
822
1195
  const down = h('button', { type: 'button', 'aria-label': t.down, title: t.down, 'data-j': 'down', disabled: !Array.from(el.children).some((c) => !isOurs(c)) }, icon('down', 12));
823
1196
  down.addEventListener('click', () => this.move('down', el));
@@ -831,16 +1204,24 @@ export class VisualEditor {
831
1204
 
832
1205
  // Body: action tiles, the action's fields, the CSS selector.
833
1206
  const tiles = h('div', { class: 'tiles', role: 'radiogroup', 'aria-label': t.whatToDo });
1207
+ const mine = this.editsOn(el);
834
1208
  for (const a of ACTIONS) {
835
1209
  const on = d.action === a;
836
1210
  const enabled = on || this.enabled(a, el);
837
1211
  const off = !enabled ? (a === 'link' ? t.notLink : a === 'image' ? t.notImage : t.noText) : '';
838
- const b = h('button', { class: a === 'slot' ? 'tile slot' : 'tile', type: 'button', role: 'radio', 'aria-checked': String(on), disabled: !enabled, 'data-j': `action-${a}` }, icon(ACTION_ICON[a]), h('span', null, h('b', null, t[ACTION_LABEL[a]]), off ? h('small', null, off) : null));
1212
+ // The element's own edit of this kind, if it has one: the tile opens it (an element can carry several edits).
1213
+ const own = mine.filter((e) => ACTION_OF[e.operation] === a).pop();
1214
+ const b = h('button', { class: a === 'slot' ? 'tile slot' : 'tile', type: 'button', role: 'radio', 'aria-checked': String(on), disabled: !enabled, 'data-e': !!own, 'data-j': `action-${a}` }, icon(ACTION_ICON[a]), h('span', null, h('b', null, t[ACTION_LABEL[a]]), off ? h('small', null, off) : null));
839
1215
  b.addEventListener('click', () => {
840
1216
  if (!this.draft || this.draft.action === a) return;
841
- this.draft.action = a;
842
- this.draft.touched = true;
843
- if ((a === 'link' || a === 'image') && el) this.draft.url = (a === 'image' ? this.orig(el).src : this.orig(el).href) || '';
1217
+ if (own) this.draft = this.draftOf(own);
1218
+ else {
1219
+ // Another kind of change: a new edit next to the one open (that one stays as it is).
1220
+ if (el && this.draft.editingId) this.draft = this.newDraft(el, this.draft.selector);
1221
+ this.draft.action = a;
1222
+ this.draft.touched = true;
1223
+ if ((a === 'link' || a === 'image') && el) this.draft.url = (a === 'image' ? this.orig(el).src : this.orig(el).href) || '';
1224
+ }
844
1225
  this.renderPanel();
845
1226
  this.renderPreview();
846
1227
  });
@@ -852,7 +1233,7 @@ export class VisualEditor {
852
1233
  const valid = !!this.draftEdit(d);
853
1234
  saveBtn.disabled = !valid;
854
1235
  saveBtn.textContent = fill(t.save, { action: t[ACTION_LABEL[d.action]] });
855
- const n = pageMatches(d.selector).length;
1236
+ const n = pageMatches(d.selector, this.doc).length;
856
1237
  pill.className = `pill ${n === 1 ? 'ok' : n > 1 ? 'many' : 'none'}`;
857
1238
  pill.textContent = n === 1 ? t.matchOne : n > 1 ? fill(t.matchMany, { n }) : t.matchNone;
858
1239
  };
@@ -868,7 +1249,21 @@ export class VisualEditor {
868
1249
  this.showCss = !this.showCss;
869
1250
  this.renderPanel();
870
1251
  });
871
- const body = h('div', { class: 'bd' }, h('span', { class: 'lbl' }, t.whatToDo), tiles, fields, cssToggle);
1252
+ // "Applies to": All devices (default) / Mobile only / Desktop only - first in Mobile view, where it matters most.
1253
+ const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-label': t.appliesTo, 'data-j': 'devices' });
1254
+ for (const [dev, label] of DEVICES) {
1255
+ const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(d.device === dev), 'data-j': `device-${dev}` }, t[label]);
1256
+ b.addEventListener('click', () => {
1257
+ if (d.device === dev) return;
1258
+ d.device = dev;
1259
+ d.touched = true;
1260
+ this.renderPanel();
1261
+ this.renderPreview();
1262
+ });
1263
+ seg.appendChild(b);
1264
+ }
1265
+ const devices = h('div', { class: this.view === 'mobile' ? 'dv top' : 'dv mt', 'data-j': 'applies-to' }, h('span', { class: 'lbl' }, t.appliesTo), seg, this.inView({ device: d.device }) ? null : h('div', { class: 'help2', 'data-j': 'device-hidden' }, t.deviceHidden));
1266
+ const body = h('div', { class: 'bd' }, this.view === 'mobile' ? devices : null, h('span', { class: 'lbl' }, t.whatToDo), tiles, fields, this.view === 'mobile' ? null : devices, cssToggle);
872
1267
  if (this.showCss) {
873
1268
  const input = h('input', { class: 'mono', dir: 'ltr', 'aria-label': t.css, spellcheck: 'false', 'data-j': 'selector' });
874
1269
  input.value = d.selector;
@@ -876,7 +1271,7 @@ export class VisualEditor {
876
1271
  const sync = () => {
877
1272
  const ok = isSafeSelector(d.selector);
878
1273
  note.className = ok ? 'help2' : 'err';
879
- note.textContent = !d.selector.trim() ? t.noSelector : ok ? fill(t.cssHelp, { n: pageMatches(d.selector).length }) : t.cssBad;
1274
+ note.textContent = !d.selector.trim() ? t.noSelector : ok ? fill(t.cssHelp, { n: pageMatches(d.selector, this.doc).length }) : t.cssBad;
880
1275
  };
881
1276
  input.addEventListener('input', () => {
882
1277
  d.selector = input.value;
@@ -900,52 +1295,130 @@ export class VisualEditor {
900
1295
  private renderFields(box: HTMLElement, d: Draft, el: Element | null, changed: () => void): void {
901
1296
  const t = this.t;
902
1297
  box.textContent = '';
1298
+ this.closeOverlay = null;
1299
+ this.field = null;
903
1300
  const was = (v: string | null) => (v ? h('span', { class: 'was', title: v }, fill(t.was, { value: v.slice(0, 60) })) : null);
904
1301
  if (d.action === 'text') {
905
- const area = h('textarea', { rows: '3', dir: 'auto', 'data-j': 'text', 'aria-label': t.newText });
906
- area.value = d.text;
907
- const fb = h('div', { 'data-j': 'fallback-box' });
908
- const renderFallback = () => {
909
- fb.textContent = '';
910
- const current = textFallback(d.text);
911
- if (current === null) return;
912
- const input = h('input', { dir: 'auto', 'data-j': 'fallback', 'aria-label': t.fallback });
913
- input.value = current;
914
- input.addEventListener('input', () => {
915
- d.text = setTextFallback(d.text, input.value);
916
- area.value = d.text;
917
- changed();
918
- });
919
- fb.append(h('div', { class: 'mt' }, h('label', { class: 'lbl' }, t.fallback), input, h('div', { class: 'help2' }, t.fallbackHelp)));
920
- };
921
- let hadVars = liquidOutputs(d.text).length > 0;
922
- area.addEventListener('input', () => {
923
- d.text = area.value;
924
- const hasVars = liquidOutputs(d.text).length > 0;
925
- if (hasVars !== hadVars) {
926
- hadVars = hasVars;
927
- renderFallback();
928
- }
1302
+ let code: HTMLTextAreaElement | null = null;
1303
+ const textChanged = (v: string) => {
1304
+ d.text = v;
1305
+ if (code && code !== this.root?.activeElement) code.value = v;
929
1306
  changed();
1307
+ };
1308
+ // Each pill has its own "If <field> is missing" (a click on it): the `| default:` of that variable only.
1309
+ const field = liquidField({
1310
+ label: t.newText,
1311
+ rawNote: t.rawNote,
1312
+ root: this.root,
1313
+ onChange: textChanged,
1314
+ labelOf: (p) => this.labelOf(p),
1315
+ fallback: { title: t.fallbackFor, help: t.fallbackHelp, bad: t.fallbackBad, done: t.fallbackDone },
930
1316
  });
1317
+ field.set(d.text);
1318
+ this.field = field;
1319
+ const add = (v: Var) => field.insert(pathTag(v.path));
1320
+ const vars: Var[] = this.ctx.attributes.length ? this.ctx.attributes : ['firstName', 'lastName'].map((n) => ({ path: `user.${n}`, label: n, group: '' }));
1321
+ const common = COMMON_VARS.map((p) => vars.filter((v) => v.path === p)[0]).filter(Boolean);
1322
+ const shown = common.concat(vars.filter((v) => common.indexOf(v) < 0)).slice(0, CHIPS);
931
1323
  const chips = h('div', { class: 'chips', 'data-j': 'chips' }, h('span', null, t.insert));
932
- const vars = this.ctx.attributes.length ? this.ctx.attributes : [{ name: 'firstName', custom: false }, { name: 'lastName', custom: false }];
933
- for (const v of vars.slice(0, 12)) {
934
- const c = h('button', { class: 'vc', type: 'button', 'data-j': 'chip' }, v.name);
935
- c.addEventListener('click', () => {
936
- const tag = variableTag(v.name, v.custom, textFallback(d.text) || null);
937
- d.text = d.text ? `${d.text.replace(/\s+$/, '')} ${tag}` : tag;
938
- area.value = d.text;
939
- if (!hadVars) {
940
- hadVars = true;
941
- renderFallback();
1324
+ const picker = h('div', { class: 'pk', 'data-j': 'var-picker', hidden: true });
1325
+ for (const v of shown) {
1326
+ const c = h('button', { class: 'vc', type: 'button', title: v.path, 'data-j': 'chip' }, v.label);
1327
+ c.addEventListener('mousedown', (e) => e.preventDefault()); // the caret stays in the text
1328
+ c.addEventListener('click', () => add(v));
1329
+ chips.appendChild(c);
1330
+ }
1331
+ if (vars.length > shown.length) {
1332
+ // "More…": the whole catalog, searchable, by group; ↑ ↓ Enter in the search box, Esc closes.
1333
+ const more = h('button', { class: 'vc ui', type: 'button', 'aria-expanded': 'false', 'data-j': 'more' }, t.more);
1334
+ const search = h('input', { dir: 'auto', 'aria-label': t.search, placeholder: t.search, 'data-j': 'var-search', role: 'combobox', 'aria-expanded': 'true' });
1335
+ const listEl = h('div', { role: 'listbox', 'aria-label': t.insert, 'data-j': 'var-list' });
1336
+ picker.append(search, listEl);
1337
+ let hits: Var[] = [];
1338
+ let at = 0;
1339
+ const close = () => {
1340
+ if (picker.hidden) return false;
1341
+ picker.hidden = true;
1342
+ more.setAttribute('aria-expanded', 'false');
1343
+ return true;
1344
+ };
1345
+ const pick = (v: Var | undefined) => {
1346
+ if (!v) return;
1347
+ close();
1348
+ add(v);
1349
+ };
1350
+ const draw = () => {
1351
+ const q = search.value.trim().toLowerCase();
1352
+ hits = vars.filter((v) => !q || `${v.label} ${v.path} ${v.group}`.toLowerCase().indexOf(q) >= 0).slice(0, 200);
1353
+ at = Math.min(at, Math.max(hits.length - 1, 0));
1354
+ listEl.textContent = '';
1355
+ if (!hits.length) listEl.appendChild(h('div', { class: 'g' }, t.noMatch));
1356
+ let group: string | null = null;
1357
+ hits.forEach((v, i) => {
1358
+ if (v.group !== group) {
1359
+ group = v.group;
1360
+ if (group) listEl.appendChild(h('div', { class: 'g', role: 'presentation' }, group));
1361
+ }
1362
+ const o = h('div', { class: 'o', role: 'option', id: `jv${i}`, 'aria-selected': String(i === at), 'data-j': 'var-option' }, h('span', { dir: 'auto' }, v.label), h('code', { dir: 'ltr' }, v.path));
1363
+ o.addEventListener('mousedown', (e) => e.preventDefault());
1364
+ o.addEventListener('click', () => pick(v));
1365
+ listEl.appendChild(o);
1366
+ });
1367
+ search.setAttribute('aria-activedescendant', hits.length ? `jv${at}` : '');
1368
+ const o = listEl.querySelector('[aria-selected="true"]') as HTMLElement | null;
1369
+ revealOption(listEl, o);
1370
+ };
1371
+ search.addEventListener('input', () => {
1372
+ at = 0;
1373
+ draw();
1374
+ });
1375
+ search.addEventListener('keydown', (e) => {
1376
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
1377
+ e.preventDefault();
1378
+ at = (at + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % Math.max(hits.length, 1);
1379
+ draw();
1380
+ } else if (e.key === 'Enter') {
1381
+ e.preventDefault();
1382
+ pick(hits[at]);
942
1383
  }
943
- changed();
944
1384
  });
945
- chips.appendChild(c);
1385
+ more.addEventListener('mousedown', (e) => e.preventDefault());
1386
+ // Focus leaving the picker (Tab, a click elsewhere) closes it; the More button toggles it itself.
1387
+ picker.addEventListener('focusout', (e) => {
1388
+ const to = e.relatedTarget as Node | null;
1389
+ if (!to || (!picker.contains(to) && to !== more)) close();
1390
+ });
1391
+ more.addEventListener('click', () => {
1392
+ if (close()) return;
1393
+ picker.hidden = false;
1394
+ more.setAttribute('aria-expanded', 'true');
1395
+ search.value = '';
1396
+ at = 0;
1397
+ listEl.scrollTop = 0;
1398
+ draw();
1399
+ search.focus();
1400
+ });
1401
+ this.closeOverlay = () => field.closePop() || close();
1402
+ chips.appendChild(more);
1403
+ }
1404
+ // "Liquid code": the stored text itself, for developers; editing it redraws the pills.
1405
+ const toggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showLiquid), 'data-j': 'liquid-toggle' }, icon('code', 13), t.liquid, icon(this.showLiquid ? 'up' : 'down', 10));
1406
+ toggle.addEventListener('click', () => {
1407
+ this.showLiquid = !this.showLiquid;
1408
+ this.renderPanel();
1409
+ });
1410
+ if (!this.closeOverlay) this.closeOverlay = () => field.closePop();
1411
+ box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, t.newText), was(el ? this.orig(el).text : null)), field.el, chips, picker, toggle);
1412
+ if (this.showLiquid) {
1413
+ const ta = h('textarea', { class: 'mono', rows: '3', dir: 'ltr', spellcheck: 'false', 'aria-label': t.liquid, 'data-j': 'liquid' });
1414
+ ta.value = d.text;
1415
+ ta.addEventListener('input', () => {
1416
+ field.set(ta.value);
1417
+ textChanged(ta.value);
1418
+ });
1419
+ code = ta;
1420
+ box.appendChild(h('div', { class: 'mt' }, ta));
946
1421
  }
947
- box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, t.newText), was(el ? this.orig(el).text : null)), area, chips, fb);
948
- renderFallback();
949
1422
  } else if (d.action === 'link' || d.action === 'image') {
950
1423
  const input = h('input', { type: 'url', dir: 'ltr', inputmode: 'url', placeholder: 'https://', 'data-j': 'url', 'aria-label': d.action === 'link' ? t.newLink : t.newImage });
951
1424
  input.value = d.url;
@@ -1006,6 +1479,25 @@ export class VisualEditor {
1006
1479
  seg.appendChild(b);
1007
1480
  }
1008
1481
  box.append(h('div', { class: 'mt' }, h('span', { class: 'lbl' }, t.where), seg));
1482
+ // A saved slot: what fills it, from the dashboard (the key as saved, not as being typed).
1483
+ const savedEdit = this.ctx.openSlot && d.editingId ? this.edits.filter((e) => e.id === d.editingId)[0] : undefined;
1484
+ const key = savedEdit && savedEdit.placementKey;
1485
+ if (key) {
1486
+ const camps = (this.ctx.placements.filter((p) => p.key === key)[0] || { campaigns: [] as SlotCampaign[] }).campaigns;
1487
+ const sec = h('div', { class: 'mt slotc', 'data-j': 'slot-content' });
1488
+ const link = (label: string, j: string, id?: string) => {
1489
+ const b = h('button', { class: 'lnk', type: 'button', 'data-j': j }, label);
1490
+ b.addEventListener('click', () => this.openSlot(key, id));
1491
+ return b;
1492
+ };
1493
+ if (!camps.length) sec.appendChild(link(t.slotCreate, 'slot-create'));
1494
+ else {
1495
+ sec.appendChild(h('span', { class: 'lbl' }, t.slotIn));
1496
+ for (const c of camps) sec.appendChild(link(c.statusLabel || c.status ? `${c.name} (${c.statusLabel || c.status})` : c.name, 'slot-campaign', c.id));
1497
+ sec.appendChild(link(t.slotAddAnother, 'slot-add'));
1498
+ }
1499
+ box.appendChild(sec);
1500
+ }
1009
1501
  }
1010
1502
  }
1011
1503
  }