@joryio/web-sdk 1.4.0-beta.7 → 1.4.0-beta.9

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 (48) 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-context.d.ts +13 -0
  6. package/dist/core/page-context.d.ts.map +1 -1
  7. package/dist/core/page-edits.d.ts +26 -0
  8. package/dist/core/page-edits.d.ts.map +1 -1
  9. package/dist/core/placements.d.ts +34 -0
  10. package/dist/core/placements.d.ts.map +1 -1
  11. package/dist/core/sdk.d.ts +5 -0
  12. package/dist/core/sdk.d.ts.map +1 -1
  13. package/dist/core/show-when.d.ts +42 -0
  14. package/dist/core/show-when.d.ts.map +1 -0
  15. package/dist/editor/editor-strings.d.ts +11 -0
  16. package/dist/editor/editor-strings.d.ts.map +1 -1
  17. package/dist/editor/editor-ui.d.ts +4 -1
  18. package/dist/editor/editor-ui.d.ts.map +1 -1
  19. package/dist/editor/liquid-field.d.ts +1 -0
  20. package/dist/editor/liquid-field.d.ts.map +1 -1
  21. package/dist/editor/visual-editor.d.ts +25 -2
  22. package/dist/editor/visual-editor.d.ts.map +1 -1
  23. package/dist/index.d.mts +25 -3
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/joryio-cards-ui.min.js +1 -1
  27. package/dist/joryio-cards-ui.min.js.map +1 -1
  28. package/dist/joryio-editor.min.js +2 -2
  29. package/dist/joryio-editor.min.js.map +1 -1
  30. package/dist/joryio-sw.js +1 -1
  31. package/dist/joryio.cjs.js +631 -26
  32. package/dist/joryio.min.js +2 -2
  33. package/dist/joryio.min.js.map +1 -1
  34. package/dist/joryio.mjs +631 -27
  35. package/dist/joryio.umd.js +631 -26
  36. package/package.json +1 -1
  37. package/src/core/config.ts +1 -1
  38. package/src/core/editor-gate.ts +21 -0
  39. package/src/core/page-context.ts +84 -1
  40. package/src/core/page-edits.ts +149 -5
  41. package/src/core/placements.ts +373 -6
  42. package/src/core/sdk.ts +79 -1
  43. package/src/core/show-when.ts +159 -0
  44. package/src/editor/editor-strings.ts +11 -0
  45. package/src/editor/editor-ui.ts +15 -1
  46. package/src/editor/liquid-field.ts +17 -2
  47. package/src/editor/visual-editor.ts +350 -75
  48. package/src/index.ts +4 -0
@@ -32,15 +32,37 @@
32
32
  * original nodes come back on undo - nothing is ever parsed as HTML.
33
33
  * - A dock: campaign · variant · page, the hint, "N edits" (a click jumps to
34
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.
35
53
  *
36
54
  * Messages (constants: EDITOR_MESSAGES in the core, EDITOR_SESSION_MESSAGES
37
55
  * here; the dashboard's copy is packages/frontend/src/lib/web-experience.ts):
38
56
  *
39
57
  * editor -> dashboard
40
58
  * joryio:editor-active { url } the editor is up
41
- * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, tag, text }
59
+ * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, device, tag, text }
42
60
  * a saved edit; `id` is the edit's id - an id the
43
- * 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
44
66
  * joryio:editor-remove { id } undo of a new edit
45
67
  * joryio:editor-done {} "Save & return to Joryio"
46
68
  * joryio:editor-open-slot { placementKey, campaignId? }
@@ -52,7 +74,7 @@
52
74
  * joryio:editor-closed {} the editor stopped
53
75
  *
54
76
  * dashboard -> editor
55
- * joryio:editor-context { campaignName?, variantName?, edits?, focusId?,
77
+ * joryio:editor-context { campaignName?, variantName?, edits? (each may carry device), focusId?,
56
78
  * attributes?: [{ key, label?, group? } | { name, custom? }],
57
79
  * placements?: [{ key, name?, campaigns?: [{ id, name, status, statusLabel? }] }],
58
80
  * openSlot?: true,
@@ -73,14 +95,14 @@
73
95
  * off (that dashboard would not hear a remove).
74
96
  */
75
97
  import type { Logger } from '../utils/logger';
76
- import { isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';
77
- 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';
78
100
  import { EDITOR_STRINGS, fill, mergeStrings, type EditorStringKey, type EditorStrings } from './editor-strings';
79
101
  import { VAR_PATH, kindKey, newEditId, pathTag, previewParts, slugify } from './editor-model';
80
- import { EDITOR_CSS, HOST_STYLE, PREVIEW_CSS, PREVIEW_HOST_STYLE, PREVIEW_VAR_HOST_STYLE, h, icon, type IconName } from './editor-ui';
81
- import { liquidField } from './liquid-field';
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';
82
104
 
83
- export { EDITOR_MESSAGES };
105
+ export { EDITOR_MESSAGES, MOBILE_FRAME_WIDTH };
84
106
 
85
107
  export const EDITOR_SESSION_MESSAGES = {
86
108
  CONTEXT: 'joryio:editor-context',
@@ -97,8 +119,29 @@ const ATTRIBUTE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
97
119
  const MAX_TEXT = 2000;
98
120
  const MAX_EDITS = 100;
99
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
+ }
100
137
  const OURS = '[data-joryio-editor]';
101
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
+ ];
102
145
 
103
146
  /** CSS.escape, for browsers (and test DOMs) without it. */
104
147
  export function cssEscape(value: string): string {
@@ -123,14 +166,14 @@ const VAR_PILL = 'var';
123
166
  function pageTarget(t: EventTarget | null): Element | null {
124
167
  let el = t instanceof Element ? t : null;
125
168
  if (el && el.getAttribute('data-joryio-editor') === VAR_PILL) el = el.parentElement;
126
- return el && !isOurs(el) && el !== document.body && el !== document.documentElement ? el : null;
169
+ return el && !isOurs(el) && el !== el.ownerDocument.body && el !== el.ownerDocument.documentElement ? el : null;
127
170
  }
128
171
 
129
- /** The page's elements a selector finds - never the editor's own. */
130
- function pageMatches(selector: string): Element[] {
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[] {
131
174
  if (!isSafeSelector(selector)) return [];
132
175
  try {
133
- return Array.from(document.querySelectorAll(selector)).filter((e) => !isOurs(e));
176
+ return Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));
134
177
  } catch {
135
178
  return [];
136
179
  }
@@ -209,6 +252,8 @@ export interface EditorPick {
209
252
  value?: string;
210
253
  placementKey?: string;
211
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;
212
257
  tag: string;
213
258
  text: string;
214
259
  }
@@ -233,6 +278,7 @@ interface Draft {
233
278
  url: string;
234
279
  slotName: string;
235
280
  position: PageEditPosition;
281
+ device: PageEditDevice;
236
282
  selector: string;
237
283
  /** The edit being changed (opened from the list or the dashboard), null for a new one. */
238
284
  editingId: string | null;
@@ -272,7 +318,20 @@ interface SlotCampaign {
272
318
  const CAMPAIGN_ID = /^[A-Za-z0-9_-]{1,64}$/;
273
319
 
274
320
  const clip = (v: unknown, n: number): string => (typeof v === 'string' ? v.trim().slice(0, n) : '');
275
- 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
+ };
276
335
 
277
336
  export class VisualEditor {
278
337
  private listeners: Array<() => void> = [];
@@ -293,6 +352,8 @@ export class VisualEditor {
293
352
  private showLiquid = false;
294
353
  /** Closes an open overlay of the panel (the variable picker) on Esc; true when it closed one. */
295
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;
296
357
  private popOpen = false;
297
358
  private edits: PageEditWire[] = [];
298
359
  private history: Array<{ id: string; before: PageEditWire | null }> = [];
@@ -304,6 +365,15 @@ export class VisualEditor {
304
365
  private previewUndo: Array<() => void> = [];
305
366
  /** The page's own text / address of an element before any preview, for "Was:". */
306
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;
307
377
 
308
378
  constructor(
309
379
  private dashboardOrigin: string,
@@ -345,7 +415,9 @@ export class VisualEditor {
345
415
  for (const off of this.listeners.splice(0)) off();
346
416
  this.clearPreview();
347
417
  this.host?.remove();
348
- 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';
349
421
  this.selected = this.hovered = null;
350
422
  this.draft = null;
351
423
  try {
@@ -382,7 +454,61 @@ export class VisualEditor {
382
454
  this.host = host;
383
455
  this.root = root;
384
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);
385
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
+ }
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;
386
512
  const onMove = (e: MouseEvent) => {
387
513
  const t = e.target instanceof Element ? e.target : null;
388
514
  if (isOurs(t) && t!.getAttribute('data-joryio-editor') !== VAR_PILL) return;
@@ -394,45 +520,133 @@ export class VisualEditor {
394
520
  // A click on the page - a preview of ours included - never reaches the site.
395
521
  e.preventDefault();
396
522
  e.stopPropagation();
523
+ // An open picker or fallback popover: a click outside it only closes it, it selects nothing.
524
+ if (this.closeOverlay && this.closeOverlay()) return;
397
525
  const el = pageTarget(e.target);
398
- if (el) this.select(el);
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);
399
531
  };
400
- const onKey = (e: KeyboardEvent) => {
401
- if (e.key === 'Escape') {
402
- if (this.closeOverlay && this.closeOverlay()) return;
403
- if (this.popOpen) this.togglePop(false);
404
- else if (this.panel) this.cancel();
405
- 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));
406
616
  return;
407
617
  }
408
- if (isOurs(e.target instanceof Element ? e.target : null)) return; // typing in the panel
409
- if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
410
- const from = this.selected || this.hovered;
411
- if (!from) return;
412
- e.preventDefault();
413
- e.stopPropagation();
414
- 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;
415
626
  }
416
- };
417
- const onScroll = () => {
418
- this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
419
- this.place(this.selBox, this.selected);
420
- };
421
- doc.addEventListener('mousemove', onMove, true);
422
- doc.addEventListener('click', onClick, true);
423
- doc.addEventListener('keydown', onKey, true);
424
- window.addEventListener('scroll', onScroll, true);
425
- window.addEventListener('resize', onScroll);
426
- this.listeners.push(
427
- () => doc.removeEventListener('mousemove', onMove, true),
428
- () => doc.removeEventListener('click', onClick, true),
429
- () => doc.removeEventListener('keydown', onKey, true),
430
- () => window.removeEventListener('scroll', onScroll, true),
431
- () => window.removeEventListener('resize', onScroll),
432
- );
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();
433
637
  this.renderDock();
434
638
  this.renderHelp();
435
- 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());
436
650
  }
437
651
 
438
652
  /** The dashboard's context: words, campaign, the variant's edits (validated like the runtime does). */
@@ -458,7 +672,8 @@ export class VisualEditor {
458
672
  : typeof a.key === 'string' && VAR_PATH.test(a.key)
459
673
  ? { path: a.key, label: clip(a.label, 60) || a.key.split('.').pop()!, group: clip(a.group, 40) }
460
674
  : typeof a.name === 'string' && ATTRIBUTE_NAME.test(a.name)
461
- ? { path: `user.${a.custom === true ? 'custom.' : ''}${a.name}`, label: a.name, group: '' }
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 }
462
677
  : null,
463
678
  400,
464
679
  ),
@@ -511,7 +726,9 @@ export class VisualEditor {
511
726
  return;
512
727
  }
513
728
  const r = el.getBoundingClientRect();
514
- 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` });
515
732
  box.textContent = '';
516
733
  const label = `${this.t[kindKey(el.tagName)]} · ${el.tagName.toLowerCase()}`;
517
734
  box.appendChild(h('span', { class: 'chip', 'data-j': 'label' }, withLabel ? `${label} - ${this.t.clickToEdit}` : label));
@@ -519,15 +736,19 @@ export class VisualEditor {
519
736
 
520
737
  private move(dir: 'up' | 'down', from: Element): void {
521
738
  const next = dir === 'up' ? from.parentElement : Array.from(from.children).filter((c) => !isOurs(c))[0] || null;
522
- if (!next || next === document.body || next === document.documentElement) return;
739
+ if (!next || next === from.ownerDocument.body || next === from.ownerDocument.documentElement) return;
523
740
  this.select(next);
524
741
  }
525
742
 
526
- /** The edits on an element (its selector finds it, or is the selector the editor would make for it), oldest first. */
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
+ */
527
748
  private editsOn(el: Element | null): PageEditWire[] {
528
749
  if (!el) return [];
529
750
  const own = robustSelector(el);
530
- return this.edits.filter((e) => e.selector === own || pageMatches(e.selector).indexOf(el) >= 0);
751
+ return this.edits.filter((e) => this.inView(e) && (e.selector === own || pageMatches(e.selector, el.ownerDocument).indexOf(el) >= 0));
531
752
  }
532
753
 
533
754
  /**
@@ -538,6 +759,8 @@ export class VisualEditor {
538
759
  */
539
760
  select(el: Element, edit?: PageEditWire): void {
540
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;
541
764
  edit = edit || this.editsOn(el).pop();
542
765
  this.selected = el;
543
766
  this.hovered = null;
@@ -564,7 +787,7 @@ export class VisualEditor {
564
787
  private newDraft(el: Element, selector: string): Draft {
565
788
  const o = this.orig(el);
566
789
  const action: Action = el.tagName === 'IMG' ? 'image' : this.enabled('text', el) ? 'text' : el.tagName === 'A' ? 'link' : 'hide';
567
- 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 };
568
791
  }
569
792
 
570
793
  private draftOf(e: PageEditWire): Draft {
@@ -575,6 +798,7 @@ export class VisualEditor {
575
798
  url: action === 'link' || action === 'image' ? e.value || '' : '',
576
799
  slotName: e.placementKey || '',
577
800
  position: e.position || 'after',
801
+ device: e.device || 'all',
578
802
  selector: e.selector,
579
803
  editingId: e.id,
580
804
  touched: true,
@@ -590,7 +814,15 @@ export class VisualEditor {
590
814
  focusEdit(id: unknown): boolean {
591
815
  const edit = this.edits.filter((e) => e.id === id)[0];
592
816
  if (!edit || !this.active) return false;
593
- 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;
594
826
  if (el) {
595
827
  try {
596
828
  el.scrollIntoView({ block: 'center' });
@@ -615,7 +847,7 @@ export class VisualEditor {
615
847
 
616
848
  /** The draft as an edit, or null while a field is not valid yet. */
617
849
  private draftEdit(d: Draft): PageEditWire | null {
618
- 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 } : {}) };
619
851
  if (!isSafeSelector(base.selector)) return null;
620
852
  const operation = OPERATION_OF[d.action];
621
853
  if (d.action === 'hide') return { ...base, operation };
@@ -629,9 +861,9 @@ export class VisualEditor {
629
861
  const d = this.draft;
630
862
  const edit = d && this.draftEdit(d);
631
863
  if (!d || !edit) return;
632
- const el = this.selected || pageMatches(edit.selector)[0] || null;
864
+ const el = this.selected || pageMatches(edit.selector, this.doc)[0] || null;
633
865
  const id = d.editingId || newEditId();
634
- if (!this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id, position: edit.position })) return;
866
+ if (!this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id, position: edit.position, device: d.device })) return;
635
867
  // A saved slot stays open on its edit, with its campaigns or "Create content for this slot".
636
868
  if (edit.operation === 'insert_placement' && this.ctx.openSlot) this.focusEdit(id);
637
869
  }
@@ -653,7 +885,7 @@ export class VisualEditor {
653
885
  * in the list (and on the page). `value` is the text, the address or the
654
886
  * slot name (made a placement key).
655
887
  */
656
- 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 {
657
889
  const id = opts.id || newEditId();
658
890
  const tag = el ? el.tagName.toLowerCase() : '';
659
891
  const text = el ? this.orig(el).text.slice(0, 200) : '';
@@ -669,7 +901,8 @@ export class VisualEditor {
669
901
  }
670
902
  }
671
903
  if (!edit) return false;
672
- 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;
673
906
  this.send(msg as unknown as Record<string, unknown>);
674
907
  const at = this.edits.map((e) => e.id).indexOf(id);
675
908
  this.history.push({ id, before: at >= 0 ? this.edits[at] : null });
@@ -704,7 +937,7 @@ export class VisualEditor {
704
937
  if (last.before) {
705
938
  if (at >= 0) this.edits[at] = last.before;
706
939
  const b = last.before;
707
- this.send({ type: EDITOR_MESSAGES.PICK, ...b, tag: '', text: '' });
940
+ this.send({ type: EDITOR_MESSAGES.PICK, ...b, device: b.device || 'all', tag: '', text: '' });
708
941
  } else {
709
942
  if (at >= 0) this.edits.splice(at, 1);
710
943
  this.send({ type: EDITOR_SESSION_MESSAGES.REMOVE, id: last.id });
@@ -754,12 +987,14 @@ export class VisualEditor {
754
987
  const shown: PageEditWire[] = [];
755
988
  for (const e of this.edits) shown.push(d && d.editingId === e.id ? draft || e : e);
756
989
  if (d && !d.editingId && draft && d.touched) shown.push(draft);
757
- 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);
758
993
  if (this.selected) this.place(this.selBox, this.selected);
759
994
  }
760
995
 
761
- private previewNode(build: (root: ShadowRoot) => void, style = PREVIEW_HOST_STYLE, kind = 'preview'): HTMLElement {
762
- const n = document.createElement(PREVIEW_TAG);
996
+ private previewNode(doc: Document, build: (root: ShadowRoot) => void, style = PREVIEW_HOST_STYLE, kind = 'preview'): HTMLElement {
997
+ const n = doc.createElement(PREVIEW_TAG);
763
998
  n.setAttribute('data-joryio-editor', kind);
764
999
  n.setAttribute('style', style);
765
1000
  const root = n.attachShadow({ mode: 'open' });
@@ -768,7 +1003,15 @@ export class VisualEditor {
768
1003
  return n;
769
1004
  }
770
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
+
771
1013
  private applyPreview(e: PageEditWire, el: Element): void {
1014
+ const doc = el.ownerDocument;
772
1015
  if (!this.originals.has(el)) this.originals.set(el, { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') });
773
1016
  const undo = this.previewUndo;
774
1017
  const attr = (name: string, value: string | null) => {
@@ -798,7 +1041,7 @@ export class VisualEditor {
798
1041
  const kids = Array.from(el.childNodes);
799
1042
  el.textContent = '';
800
1043
  // A variable with neither a sample value nor a fallback is a pill, in its own shadow root.
801
- for (const p of previewParts(e.value || '', this.ctx.sample)) el.appendChild(typeof p === 'string' ? document.createTextNode(p) : this.previewNode((r) => r.appendChild(h('span', { class: 'v', dir: 'auto' }, this.labelOf(p.path) || p.name)), PREVIEW_VAR_HOST_STYLE, VAR_PILL));
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));
802
1045
  undo.push(() => {
803
1046
  el.textContent = '';
804
1047
  for (const k of kids) el.appendChild(k);
@@ -814,14 +1057,14 @@ export class VisualEditor {
814
1057
  break;
815
1058
  case 'hide': {
816
1059
  const what = `${this.t[kindKey(el.tagName)]} "${this.orig(el).text.slice(0, 40)}"`;
817
- 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');
818
1061
  hide();
819
1062
  break;
820
1063
  }
821
1064
  case 'insert_placement': {
822
1065
  const where = e.position || 'after';
823
1066
  insert(
824
- 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)))),
825
1068
  where,
826
1069
  );
827
1070
  if (where === 'replace') hide();
@@ -866,7 +1109,7 @@ export class VisualEditor {
866
1109
  }
867
1110
 
868
1111
  private editTitle(e: PageEditWire): string {
869
- const el = pageMatches(e.selector)[0];
1112
+ const el = pageMatches(e.selector, this.doc)[0];
870
1113
  const kind = this.t[el ? kindKey(el.tagName) : kindKey(e.selector, true)];
871
1114
  return `${this.t[ACTION_LABEL[ACTION_OF[e.operation]]]} · ${kind}`;
872
1115
  }
@@ -889,6 +1132,13 @@ export class VisualEditor {
889
1132
  undoBtn.addEventListener('click', () => this.undo());
890
1133
  const doneBtn = h('button', { class: 'go', type: 'button', 'data-j': 'done' }, t.saveReturn);
891
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
+ }
892
1142
  const dock = h(
893
1143
  'div',
894
1144
  { class: 'dock', 'data-j': 'dock', role: 'toolbar', 'aria-label': t.title },
@@ -898,6 +1148,7 @@ export class VisualEditor {
898
1148
  h('span', { class: 'sep' }),
899
1149
  h('span', { class: 'hint', 'data-j': 'hint' }, icon('cursor', 13), this.draft ? t.hintEditing : t.hintPoint),
900
1150
  h('span', { class: 'sep' }),
1151
+ views,
901
1152
  countBtn,
902
1153
  undoBtn,
903
1154
  doneBtn,
@@ -906,7 +1157,8 @@ export class VisualEditor {
906
1157
  const pop = h('div', { class: 'pop', 'data-j': 'edit-list', role: 'menu' });
907
1158
  if (!n) pop.appendChild(h('div', { class: 'empty' }, t.noEdits));
908
1159
  this.edits.forEach((e, i) => {
909
- 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);
910
1162
  b.addEventListener('click', () => this.focusEdit(e.id));
911
1163
  pop.appendChild(b);
912
1164
  });
@@ -928,7 +1180,8 @@ export class VisualEditor {
928
1180
  const crumbs = h('div', { class: 'crumbs', 'data-j': 'crumbs' });
929
1181
  if (el) {
930
1182
  const chain: Element[] = [];
931
- 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);
932
1185
  const shown = chain.slice(-3);
933
1186
  const crumb = (label: string, target: Element | null, cur: boolean) => {
934
1187
  const b = h('button', { class: cur ? 'crumb cur' : 'crumb', type: 'button', 'data-j': 'crumb', 'aria-current': cur ? 'true' : undefined, disabled: !target }, label);
@@ -937,7 +1190,7 @@ export class VisualEditor {
937
1190
  };
938
1191
  crumbs.appendChild(crumb(t.page, null, false));
939
1192
  for (const n of shown) crumbs.append(icon('chevron', 9), crumb(t[kindKey(n.tagName)], n, n === el));
940
- 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));
941
1194
  up.addEventListener('click', () => this.move('up', el));
942
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));
943
1196
  down.addEventListener('click', () => this.move('down', el));
@@ -980,7 +1233,7 @@ export class VisualEditor {
980
1233
  const valid = !!this.draftEdit(d);
981
1234
  saveBtn.disabled = !valid;
982
1235
  saveBtn.textContent = fill(t.save, { action: t[ACTION_LABEL[d.action]] });
983
- const n = pageMatches(d.selector).length;
1236
+ const n = pageMatches(d.selector, this.doc).length;
984
1237
  pill.className = `pill ${n === 1 ? 'ok' : n > 1 ? 'many' : 'none'}`;
985
1238
  pill.textContent = n === 1 ? t.matchOne : n > 1 ? fill(t.matchMany, { n }) : t.matchNone;
986
1239
  };
@@ -996,7 +1249,21 @@ export class VisualEditor {
996
1249
  this.showCss = !this.showCss;
997
1250
  this.renderPanel();
998
1251
  });
999
- 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);
1000
1267
  if (this.showCss) {
1001
1268
  const input = h('input', { class: 'mono', dir: 'ltr', 'aria-label': t.css, spellcheck: 'false', 'data-j': 'selector' });
1002
1269
  input.value = d.selector;
@@ -1004,7 +1271,7 @@ export class VisualEditor {
1004
1271
  const sync = () => {
1005
1272
  const ok = isSafeSelector(d.selector);
1006
1273
  note.className = ok ? 'help2' : 'err';
1007
- 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;
1008
1275
  };
1009
1276
  input.addEventListener('input', () => {
1010
1277
  d.selector = input.value;
@@ -1029,6 +1296,7 @@ export class VisualEditor {
1029
1296
  const t = this.t;
1030
1297
  box.textContent = '';
1031
1298
  this.closeOverlay = null;
1299
+ this.field = null;
1032
1300
  const was = (v: string | null) => (v ? h('span', { class: 'was', title: v }, fill(t.was, { value: v.slice(0, 60) })) : null);
1033
1301
  if (d.action === 'text') {
1034
1302
  let code: HTMLTextAreaElement | null = null;
@@ -1047,6 +1315,7 @@ export class VisualEditor {
1047
1315
  fallback: { title: t.fallbackFor, help: t.fallbackHelp, bad: t.fallbackBad, done: t.fallbackDone },
1048
1316
  });
1049
1317
  field.set(d.text);
1318
+ this.field = field;
1050
1319
  const add = (v: Var) => field.insert(pathTag(v.path));
1051
1320
  const vars: Var[] = this.ctx.attributes.length ? this.ctx.attributes : ['firstName', 'lastName'].map((n) => ({ path: `user.${n}`, label: n, group: '' }));
1052
1321
  const common = COMMON_VARS.map((p) => vars.filter((v) => v.path === p)[0]).filter(Boolean);
@@ -1061,7 +1330,7 @@ export class VisualEditor {
1061
1330
  }
1062
1331
  if (vars.length > shown.length) {
1063
1332
  // "More…": the whole catalog, searchable, by group; ↑ ↓ Enter in the search box, Esc closes.
1064
- const more = h('button', { class: 'vc', type: 'button', 'aria-expanded': 'false', 'data-j': 'more' }, t.more);
1333
+ const more = h('button', { class: 'vc ui', type: 'button', 'aria-expanded': 'false', 'data-j': 'more' }, t.more);
1065
1334
  const search = h('input', { dir: 'auto', 'aria-label': t.search, placeholder: t.search, 'data-j': 'var-search', role: 'combobox', 'aria-expanded': 'true' });
1066
1335
  const listEl = h('div', { role: 'listbox', 'aria-label': t.insert, 'data-j': 'var-list' });
1067
1336
  picker.append(search, listEl);
@@ -1096,6 +1365,8 @@ export class VisualEditor {
1096
1365
  listEl.appendChild(o);
1097
1366
  });
1098
1367
  search.setAttribute('aria-activedescendant', hits.length ? `jv${at}` : '');
1368
+ const o = listEl.querySelector('[aria-selected="true"]') as HTMLElement | null;
1369
+ revealOption(listEl, o);
1099
1370
  };
1100
1371
  search.addEventListener('input', () => {
1101
1372
  at = 0;
@@ -1106,20 +1377,24 @@ export class VisualEditor {
1106
1377
  e.preventDefault();
1107
1378
  at = (at + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % Math.max(hits.length, 1);
1108
1379
  draw();
1109
- const o = listEl.querySelector('[aria-selected="true"]') as HTMLElement | null;
1110
- if (o && o.scrollIntoView) o.scrollIntoView({ block: 'nearest' });
1111
1380
  } else if (e.key === 'Enter') {
1112
1381
  e.preventDefault();
1113
1382
  pick(hits[at]);
1114
1383
  }
1115
1384
  });
1116
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
+ });
1117
1391
  more.addEventListener('click', () => {
1118
1392
  if (close()) return;
1119
1393
  picker.hidden = false;
1120
1394
  more.setAttribute('aria-expanded', 'true');
1121
1395
  search.value = '';
1122
1396
  at = 0;
1397
+ listEl.scrollTop = 0;
1123
1398
  draw();
1124
1399
  search.focus();
1125
1400
  });