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

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.
@@ -1,28 +1,86 @@
1
1
  /**
2
- * The point-and-click picker (BACKLOG D444 Phase 4,
2
+ * The on-site Web personalization editor (BACKLOG D444 Phase 4,
3
3
  * docs/PLACEMENTS_WEBSITE_LAYER.md 3) - the body of `joryio-editor.min.js`.
4
+ * Design: design_handoff_web_personalization, screens 1-3 (1.4.0-beta.6).
4
5
  *
5
6
  * The handshake lives in the core bundle (src/core/editor-gate.ts): this
6
7
  * file is loaded, and this class constructed, only once the server vouched
7
8
  * for the editor token, with the dashboard origin the token names. From then
8
9
  * on it accepts messages only from that origin and that opener window, and
9
- * posts only to them. It lets the person point at an element, computes a
10
- * robust selector, offers the operations that fit, and posts
11
- * `joryio:editor-pick` back.
10
+ * posts only to them.
12
11
  *
13
- * It reads the page the person already sees and writes nothing to it but its
14
- * own highlight and panel (built from text nodes, never HTML). No free-form
15
- * DOM editing: a pick is a selector + one of the five page-edit operations.
12
+ * What it does on the page:
13
+ * - All of its UI is in ONE shadow root (a closed one, on a host with
14
+ * `all: initial`): the site's CSS cannot restyle it, its CSS cannot reach
15
+ * the site. The previews it puts in the page (a content slot, a "hidden for
16
+ * this audience" note) are custom elements with their own shadow roots,
17
+ * never a `div`, so they do not shift the site's `:nth-of-type` selectors.
18
+ * - Hover shows a dashed outline with a label ("Heading · h1"); a click
19
+ * selects (the click never reaches the site); arrow up / down or the
20
+ * buttons and the breadcrumb ("Page › Main › Heading") move to the element
21
+ * around it or the first one inside it.
22
+ * - A light side panel: the element, how many elements its selector matches,
23
+ * "What do you want to do?" (Change text, Change link, Change image, Hide
24
+ * it, Add content slot), ONE field set per action, a collapsible CSS
25
+ * selector, Cancel / Save.
26
+ * - Every edit shows live on the page while editing (the draft too); the
27
+ * 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
29
+ * original nodes come back on undo - nothing is ever parsed as HTML.
30
+ * - A dock: campaign · variant · page, the hint, "N edits" (a click jumps to
31
+ * that edit), Undo, "Save & return to Joryio".
32
+ *
33
+ * Messages (constants: EDITOR_MESSAGES in the core, EDITOR_SESSION_MESSAGES
34
+ * here; the dashboard's copy is packages/frontend/src/lib/web-experience.ts):
35
+ *
36
+ * editor -> dashboard
37
+ * joryio:editor-active { url } the editor is up
38
+ * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, tag, text }
39
+ * a saved edit; `id` is the edit's id - an id the
40
+ * dashboard already has REPLACES that edit
41
+ * joryio:editor-remove { id } undo of a new edit
42
+ * joryio:editor-done {} "Save & return to Joryio"
43
+ * joryio:editor-closed {} the editor stopped
44
+ *
45
+ * dashboard -> editor
46
+ * joryio:editor-context { campaignName?, variantName?, edits?, focusId?,
47
+ * attributes?: [{ name, custom? }], placements?: [{ key, name? }],
48
+ * sample?: { "user.firstName": "Lior", ... },
49
+ * strings?: { <EDITOR_STRINGS key>: text }, dir?: 'ltr' | 'rtl' }
50
+ * the variant's edits (shown live and in "N edits"),
51
+ * the words in the marketer's language; enables Undo
52
+ * joryio:editor-focus { id } jump to that edit
53
+ * joryio:editor-close {} stop
54
+ *
55
+ * A dashboard that sends no context still works as before this redesign:
56
+ * every save is a pick, the dock counts this session's edits, and Undo stays
57
+ * off (that dashboard would not hear a remove).
16
58
  */
17
59
  import type { Logger } from '../utils/logger';
18
- import { isSafeSelector, isSafeEditUrl, type PageEditOperation } from '../core/page-edits';
60
+ import { isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';
19
61
  import { EDITOR_MESSAGES } from '../core/editor-gate';
62
+ 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';
20
65
 
21
66
  export { EDITOR_MESSAGES };
22
67
 
68
+ export const EDITOR_SESSION_MESSAGES = {
69
+ CONTEXT: 'joryio:editor-context',
70
+ FOCUS: 'joryio:editor-focus',
71
+ REMOVE: 'joryio:editor-remove',
72
+ DONE: 'joryio:editor-done',
73
+ } as const;
74
+
23
75
  /** Attributes that name an element on purpose, most stable first. */
24
76
  const NAMING_ATTRIBUTES = ['data-joryio-id', 'data-testid', 'data-test', 'data-qa', 'data-cy', 'data-id', 'name'];
25
77
  const PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;
78
+ const ATTRIBUTE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
79
+ const MAX_TEXT = 2000;
80
+ const MAX_EDITS = 100;
81
+ const PREVIEW_TAG = 'joryio-editor-preview';
82
+ const OURS = '[data-joryio-editor]';
83
+ const HELP_DISMISSED_KEY = 'jry_editor_help_dismissed';
26
84
 
27
85
  /** CSS.escape, for browsers (and test DOMs) without it. */
28
86
  export function cssEscape(value: string): string {
@@ -40,9 +98,21 @@ export function cssEscape(value: string): string {
40
98
  return out;
41
99
  }
42
100
 
101
+ const isOurs = (el: Element | null): boolean => !!el && !!el.closest(OURS);
102
+
103
+ /** The page's elements a selector finds - never the editor's own. */
104
+ function pageMatches(selector: string): Element[] {
105
+ if (!isSafeSelector(selector)) return [];
106
+ try {
107
+ return Array.from(document.querySelectorAll(selector)).filter((e) => !isOurs(e));
108
+ } catch {
109
+ return [];
110
+ }
111
+ }
112
+
43
113
  const unique = (doc: Document, selector: string, el: Element): boolean => {
44
114
  try {
45
- const hits = doc.querySelectorAll(selector);
115
+ const hits = Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));
46
116
  return hits.length === 1 && hits[0] === el;
47
117
  } catch {
48
118
  return false;
@@ -106,21 +176,82 @@ export function operationsFor(el: Element): PageEditOperation[] {
106
176
 
107
177
  export interface EditorPick {
108
178
  type: typeof EDITOR_MESSAGES.PICK;
179
+ /** The edit's id: new edits get a fresh one, an edit opened from the list keeps its own. */
180
+ id: string;
109
181
  selector: string;
110
182
  operation: PageEditOperation;
111
183
  value?: string;
112
184
  placementKey?: string;
113
- position?: 'before' | 'after' | 'prepend' | 'append';
185
+ position?: PageEditPosition;
114
186
  tag: string;
115
187
  text: string;
116
188
  }
117
189
 
190
+ type Action = 'text' | 'link' | 'image' | 'hide' | 'slot';
191
+ const ACTIONS: Action[] = ['text', 'link', 'image', 'hide', 'slot'];
192
+ const OPERATION_OF: Record<Action, PageEditOperation> = { text: 'replace_text', link: 'replace_link', image: 'replace_image', hide: 'hide', slot: 'insert_placement' };
193
+ const ACTION_OF: Record<PageEditOperation, Action> = { replace_text: 'text', replace_link: 'link', replace_image: 'image', hide: 'hide', insert_placement: 'slot' };
194
+ const ACTION_LABEL: Record<Action, EditorStringKey> = { text: 'actText', link: 'actLink', image: 'actImage', hide: 'actHide', slot: 'actSlot' };
195
+ const ACTION_ICON: Record<Action, IconName> = { text: 'text', link: 'link', image: 'image', hide: 'hide', slot: 'slot' };
196
+ const POSITIONS: Array<[PageEditPosition, EditorStringKey]> = [
197
+ ['before', 'posBefore'],
198
+ ['after', 'posAfter'],
199
+ ['replace', 'posReplace'],
200
+ ['prepend', 'posPrepend'],
201
+ ['append', 'posAppend'],
202
+ ];
203
+
204
+ interface Draft {
205
+ action: Action;
206
+ text: string;
207
+ url: string;
208
+ slotName: string;
209
+ position: PageEditPosition;
210
+ selector: string;
211
+ /** The edit being changed (opened from the list or the dashboard), null for a new one. */
212
+ editingId: string | null;
213
+ /** A new draft shows on the page only once something was changed (its untouched text would flatten the element's markup). */
214
+ touched: boolean;
215
+ }
216
+
217
+ interface EditorContext {
218
+ campaignName: string;
219
+ variantName: string;
220
+ attributes: Array<{ name: string; custom: boolean }>;
221
+ placements: Array<{ key: string; name: string }>;
222
+ sample: Record<string, string>;
223
+ }
224
+
225
+ 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();
227
+
118
228
  export class VisualEditor {
119
229
  private listeners: Array<() => void> = [];
120
- private highlight: HTMLElement | null = null;
230
+ private active = false;
231
+ private host: HTMLElement | null = null;
232
+ /** Kept for tests: the shadow root is closed to the page. */
233
+ root: ShadowRoot | null = null;
234
+ private wrap: HTMLElement | null = null;
235
+ private hoverBox: HTMLElement | null = null;
236
+ private selBox: HTMLElement | null = null;
237
+ private dock: HTMLElement | null = null;
121
238
  private panel: HTMLElement | null = null;
239
+ private help: HTMLElement | null = null;
240
+ private hovered: Element | null = null;
122
241
  private selected: Element | null = null;
123
- private active = false;
242
+ private draft: Draft | null = null;
243
+ private showCss = false;
244
+ private popOpen = false;
245
+ private edits: PageEditWire[] = [];
246
+ private history: Array<{ id: string; before: PageEditWire | null }> = [];
247
+ /** The dashboard sent a context: it understands remove (Undo) and replace-by-id. */
248
+ private synced = false;
249
+ private t: EditorStrings = { ...EDITOR_STRINGS };
250
+ private dir: 'ltr' | 'rtl' = 'ltr';
251
+ private ctx: EditorContext = { campaignName: '', variantName: '', attributes: [], placements: [], sample: {} };
252
+ private previewUndo: Array<() => void> = [];
253
+ /** The page's own text / address of an element before any preview, for "Was:". */
254
+ private originals = new WeakMap<Element, { text: string; href: string | null; src: string | null }>();
124
255
 
125
256
  constructor(
126
257
  private dashboardOrigin: string,
@@ -129,7 +260,7 @@ export class VisualEditor {
129
260
  private onStop: () => void = () => undefined,
130
261
  ) {}
131
262
 
132
- /** The token was vouched for by the server: show the picker. */
263
+ /** The token was vouched for by the server: show the editor. */
133
264
  start(): void {
134
265
  if (this.active) return;
135
266
  this.active = true;
@@ -138,6 +269,8 @@ export class VisualEditor {
138
269
  if (!data || typeof data.type !== 'string') return;
139
270
  if (e.origin !== this.dashboardOrigin || e.source !== this.opener) return;
140
271
  if (data.type === EDITOR_MESSAGES.CLOSE) this.stop();
272
+ else if (data.type === EDITOR_SESSION_MESSAGES.CONTEXT) this.applyContext(data as Record<string, unknown>);
273
+ else if (data.type === EDITOR_SESSION_MESSAGES.FOCUS) this.focusEdit((data as { id?: unknown }).id);
141
274
  };
142
275
  window.addEventListener('message', onMessage);
143
276
  this.listeners.push(() => window.removeEventListener('message', onMessage));
@@ -148,15 +281,21 @@ export class VisualEditor {
148
281
  return this.active;
149
282
  }
150
283
 
284
+ /** The edits this editor knows of (the dashboard's, then this session's), in order. */
285
+ editList(): PageEditWire[] {
286
+ return this.edits.slice();
287
+ }
288
+
151
289
  stop(): void {
152
290
  if (!this.active) return;
153
291
  this.send({ type: EDITOR_MESSAGES.CLOSED });
154
292
  this.active = false;
155
293
  for (const off of this.listeners.splice(0)) off();
156
- this.highlight?.remove();
157
- this.panel?.remove();
158
- this.highlight = this.panel = null;
159
- this.selected = null;
294
+ this.clearPreview();
295
+ this.host?.remove();
296
+ this.host = this.root = this.wrap = this.hoverBox = this.selBox = this.dock = this.panel = this.help = null;
297
+ this.selected = this.hovered = null;
298
+ this.draft = null;
160
299
  try {
161
300
  this.onStop();
162
301
  } catch (error) {
@@ -173,129 +312,700 @@ export class VisualEditor {
173
312
  }
174
313
  }
175
314
 
315
+ // ── setup ────────────────────────────────────────────────────────────────
316
+
176
317
  private activate(): void {
177
318
  const doc = document;
178
- const highlight = doc.createElement('div');
179
- highlight.setAttribute('data-joryio-editor', 'highlight');
180
- highlight.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483646;border:2px solid #14b8a6;background:rgba(20,184,166,.12);border-radius:3px;display:none';
181
- const panel = doc.createElement('div');
182
- panel.setAttribute('data-joryio-editor', 'panel');
183
- panel.style.cssText = 'position:fixed;left:16px;right:16px;bottom:16px;z-index:2147483647;max-width:560px;margin:0 auto;background:#0f172a;color:#fff;font:14px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:10px;box-shadow:0 8px 30px rgba(0,0,0,.3)';
184
- panel.textContent = 'Joryio editor - click an element on the page. Esc to finish.';
185
- doc.body.appendChild(highlight);
186
- doc.body.appendChild(panel);
187
- this.highlight = highlight;
188
- this.panel = panel;
189
- const inEditor = (t: EventTarget | null) => t instanceof Element && !!t.closest('[data-joryio-editor]');
319
+ const host = doc.createElement('joryio-editor');
320
+ host.setAttribute('data-joryio-editor', 'root');
321
+ host.setAttribute('style', HOST_STYLE);
322
+ const root = host.attachShadow({ mode: 'closed' });
323
+ root.appendChild(h('style', null, EDITOR_CSS));
324
+ const wrap = h('div', { class: 'r', dir: this.dir });
325
+ this.hoverBox = h('div', { class: 'box', 'data-j': 'hover' });
326
+ this.selBox = h('div', { class: 'box sel', 'data-j': 'selected' });
327
+ wrap.append(this.hoverBox, this.selBox);
328
+ root.appendChild(wrap);
329
+ doc.documentElement.appendChild(host);
330
+ this.host = host;
331
+ this.root = root;
332
+ this.wrap = wrap;
333
+
190
334
  const onMove = (e: MouseEvent) => {
191
- if (this.selected || inEditor(e.target)) return;
192
- this.outline(e.target instanceof Element ? e.target : null);
335
+ 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;
338
+ this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
193
339
  };
194
340
  const onClick = (e: MouseEvent) => {
195
- if (inEditor(e.target)) return;
341
+ if (isOurs(e.target instanceof Element ? e.target : null)) return;
196
342
  e.preventDefault();
197
343
  e.stopPropagation();
198
- if (e.target instanceof Element) this.select(e.target);
344
+ if (e.target instanceof Element && e.target !== doc.body && e.target !== doc.documentElement) this.select(e.target);
199
345
  };
200
346
  const onKey = (e: KeyboardEvent) => {
201
- if (e.key === 'Escape') this.selected ? this.unselect() : this.stop();
347
+ if (e.key === 'Escape') {
348
+ if (this.popOpen) this.togglePop(false);
349
+ else if (this.panel) this.cancel();
350
+ else this.stop();
351
+ return;
352
+ }
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);
360
+ }
361
+ };
362
+ const onScroll = () => {
363
+ this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
364
+ this.place(this.selBox, this.selected);
202
365
  };
203
366
  doc.addEventListener('mousemove', onMove, true);
204
367
  doc.addEventListener('click', onClick, true);
205
368
  doc.addEventListener('keydown', onKey, true);
369
+ window.addEventListener('scroll', onScroll, true);
370
+ window.addEventListener('resize', onScroll);
206
371
  this.listeners.push(
207
372
  () => doc.removeEventListener('mousemove', onMove, true),
208
373
  () => doc.removeEventListener('click', onClick, true),
209
374
  () => doc.removeEventListener('keydown', onKey, true),
375
+ () => window.removeEventListener('scroll', onScroll, true),
376
+ () => window.removeEventListener('resize', onScroll),
210
377
  );
378
+ this.renderDock();
379
+ this.renderHelp();
211
380
  this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });
212
381
  }
213
382
 
214
- private outline(el: Element | null): void {
215
- if (!this.highlight) return;
216
- if (!el || el === document.body || el === document.documentElement) {
217
- this.highlight.style.display = 'none';
383
+ /** The dashboard's context: words, campaign, the variant's edits (validated like the runtime does). */
384
+ private applyContext(data: Record<string, unknown>): void {
385
+ this.synced = true;
386
+ this.t = mergeStrings(data.strings);
387
+ this.dir = data.dir === 'rtl' ? 'rtl' : 'ltr';
388
+ this.wrap?.setAttribute('dir', this.dir);
389
+ const list = <T>(v: unknown, map: (x: any) => T | null, max: number): T[] =>
390
+ (Array.isArray(v) ? v : [])
391
+ .map(map)
392
+ .filter((x): x is T => x !== null)
393
+ .slice(0, max);
394
+ this.ctx = {
395
+ campaignName: clip(data.campaignName, 120),
396
+ 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),
399
+ sample: {},
400
+ };
401
+ if (data.sample && typeof data.sample === 'object') {
402
+ for (const [k, v] of Object.entries(data.sample as Record<string, unknown>).slice(0, 100)) {
403
+ if (/^user\.[A-Za-z0-9_.]{1,80}$/.test(k) && typeof v === 'string') this.ctx.sample[k] = v.slice(0, 200);
404
+ }
405
+ }
406
+ if (Array.isArray(data.edits)) {
407
+ this.edits = list(data.edits, (e) => trustedEdit(e), MAX_EDITS).map((e) => {
408
+ const { personalized: _p, ...rest } = e;
409
+ return rest;
410
+ });
411
+ this.history = [];
412
+ }
413
+ this.renderPreview();
414
+ this.renderDock();
415
+ this.renderHelp();
416
+ if (this.draft) this.renderPanel();
417
+ if (typeof data.focusId === 'string') this.focusEdit(data.focusId);
418
+ }
419
+
420
+ // ── selection ────────────────────────────────────────────────────────────
421
+
422
+ /** Outline an element (hover: dashed + label; selected: solid). */
423
+ private place(box: HTMLElement | null, el: Element | null, withLabel = false): void {
424
+ if (!box) return;
425
+ if (!el || !el.isConnected) {
426
+ box.style.display = 'none';
218
427
  return;
219
428
  }
220
429
  const r = el.getBoundingClientRect();
221
- Object.assign(this.highlight.style, { display: 'block', top: `${r.top}px`, left: `${r.left}px`, width: `${r.width}px`, height: `${r.height}px` });
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` });
431
+ box.textContent = '';
432
+ const label = `${this.t[kindKey(el.tagName)]} · ${el.tagName.toLowerCase()}`;
433
+ box.appendChild(h('span', { class: 'chip', 'data-j': 'label' }, withLabel ? `${label} - ${this.t.clickToEdit}` : label));
434
+ }
435
+
436
+ private move(dir: 'up' | 'down', from: Element): void {
437
+ 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;
439
+ this.select(next);
440
+ }
441
+
442
+ /** The element is chosen: open the panel on it (or on one of its edits). */
443
+ select(el: Element, edit?: PageEditWire): void {
444
+ if (!this.active) return;
445
+ this.selected = el;
446
+ this.hovered = null;
447
+ this.place(this.hoverBox, null);
448
+ this.place(this.selBox, el);
449
+ this.popOpen = false;
450
+ const selector = edit ? edit.selector : robustSelector(el) || '';
451
+ this.showCss = !selector;
452
+ this.draft = edit ? this.draftOf(edit) : this.newDraft(el, selector);
453
+ this.renderPanel();
454
+ this.renderDock();
455
+ this.renderHelp();
456
+ this.renderPreview();
457
+ }
458
+
459
+ private enabled(action: Action, el: Element | null): boolean {
460
+ if (!el) return true;
461
+ if (action === 'text') return el.tagName !== 'IMG' && !!this.orig(el).text;
462
+ if (action === 'link') return el.tagName === 'A';
463
+ if (action === 'image') return el.tagName === 'IMG';
464
+ return true;
465
+ }
466
+
467
+ private newDraft(el: Element, selector: string): Draft {
468
+ const o = this.orig(el);
469
+ 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 };
471
+ }
472
+
473
+ private draftOf(e: PageEditWire): Draft {
474
+ const action = ACTION_OF[e.operation];
475
+ return {
476
+ action,
477
+ text: e.operation === 'replace_text' ? e.value || '' : '',
478
+ url: action === 'link' || action === 'image' ? e.value || '' : '',
479
+ slotName: e.placementKey || '',
480
+ position: e.position || 'after',
481
+ selector: e.selector,
482
+ editingId: e.id,
483
+ touched: true,
484
+ };
485
+ }
486
+
487
+ /** The element as the page had it, before any preview of this editor. */
488
+ private orig(el: Element): { text: string; href: string | null; src: string | null } {
489
+ return this.originals.get(el) || { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') };
490
+ }
491
+
492
+ /** Jump to an edit: from the dock's list, or the dashboard ("Edit on site"). */
493
+ focusEdit(id: unknown): boolean {
494
+ const edit = this.edits.filter((e) => e.id === id)[0];
495
+ if (!edit || !this.active) return false;
496
+ const el = pageMatches(edit.selector)[0] || null;
497
+ if (el) {
498
+ try {
499
+ el.scrollIntoView({ block: 'center' });
500
+ } catch {
501
+ /* old browsers */
502
+ }
503
+ this.select(el, edit);
504
+ } else {
505
+ this.selected = null;
506
+ this.place(this.selBox, null);
507
+ this.draft = this.draftOf(edit);
508
+ this.showCss = true;
509
+ this.renderPanel();
510
+ this.renderDock();
511
+ this.renderHelp();
512
+ this.renderPreview();
513
+ }
514
+ return true;
515
+ }
516
+
517
+ // ── the edit ─────────────────────────────────────────────────────────────
518
+
519
+ /** The draft as an edit, or null while a field is not valid yet. */
520
+ private draftEdit(d: Draft): PageEditWire | null {
521
+ const base = { id: d.editingId || '', selector: d.selector.trim() };
522
+ if (!isSafeSelector(base.selector)) return null;
523
+ const operation = OPERATION_OF[d.action];
524
+ if (d.action === 'hide') return { ...base, operation };
525
+ if (d.action === 'text') return d.text.trim() && d.text.length <= MAX_TEXT ? { ...base, operation, value: d.text } : null;
526
+ if (d.action === 'link' || d.action === 'image') return isSafeEditUrl(d.url) ? { ...base, operation, value: d.url.trim() } : null;
527
+ const key = slugify(d.slotName);
528
+ return PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: d.position } : null;
529
+ }
530
+
531
+ private save(): void {
532
+ const d = this.draft;
533
+ const edit = d && this.draftEdit(d);
534
+ 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 });
537
+ }
538
+
539
+ /**
540
+ * Validate like the server does, post the edit to the dashboard, keep it
541
+ * in the list (and on the page). `value` is the text, the address or the
542
+ * slot name (made a placement key).
543
+ */
544
+ pick(el: Element | null, selector: string, operation: PageEditOperation, value: string, opts: { id?: string; position?: PageEditPosition } = {}): boolean {
545
+ const id = opts.id || newEditId();
546
+ const tag = el ? el.tagName.toLowerCase() : '';
547
+ const text = el ? this.orig(el).text.slice(0, 200) : '';
548
+ let edit: PageEditWire | null = null;
549
+ if (isSafeSelector(selector)) {
550
+ const base = { id, selector: selector.trim() };
551
+ if (operation === 'hide') edit = { ...base, operation };
552
+ else if (operation === 'replace_text') edit = (value || text) && (value || text).length <= MAX_TEXT ? { ...base, operation, value: value || text } : null;
553
+ else if (operation === 'replace_image' || operation === 'replace_link') edit = isSafeEditUrl(value) ? { ...base, operation, value: value.trim() } : null;
554
+ else if (operation === 'insert_placement') {
555
+ const key = slugify(value);
556
+ edit = PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: opts.position || 'after' } : null;
557
+ }
558
+ }
559
+ if (!edit) return false;
560
+ const msg: EditorPick = { type: EDITOR_MESSAGES.PICK, ...edit, tag, text } as EditorPick;
561
+ this.send(msg as unknown as Record<string, unknown>);
562
+ const at = this.edits.map((e) => e.id).indexOf(id);
563
+ this.history.push({ id, before: at >= 0 ? this.edits[at] : null });
564
+ if (at >= 0) this.edits[at] = edit;
565
+ else this.edits.push(edit);
566
+ this.closePanel();
567
+ return true;
222
568
  }
223
569
 
224
- private unselect(): void {
570
+ private cancel(): void {
571
+ this.closePanel();
572
+ }
573
+
574
+ private closePanel(): void {
575
+ this.draft = null;
225
576
  this.selected = null;
226
- if (this.panel) this.panel.textContent = 'Joryio editor - click an element on the page. Esc to finish.';
577
+ this.panel?.remove();
578
+ this.panel = null;
579
+ this.wrap?.classList.remove('open');
580
+ this.place(this.selBox, null);
581
+ this.renderPreview();
582
+ this.renderDock();
583
+ this.renderHelp();
227
584
  }
228
585
 
229
- /** The element is chosen: its selector and the operations that fit it, as buttons. */
230
- select(el: Element): void {
231
- const selector = robustSelector(el);
232
- if (!this.panel) return;
233
- if (!selector) {
234
- this.panel.textContent = 'This element has no stable selector. Choose its parent or another element.';
235
- return;
586
+ /** Undo the last saved edit: a new one is removed, a changed one goes back to what it was. */
587
+ undo(): boolean {
588
+ if (!this.synced) return false;
589
+ const last = this.history.pop();
590
+ if (!last) return false;
591
+ const at = this.edits.map((e) => e.id).indexOf(last.id);
592
+ if (last.before) {
593
+ if (at >= 0) this.edits[at] = last.before;
594
+ const b = last.before;
595
+ this.send({ type: EDITOR_MESSAGES.PICK, ...b, tag: '', text: '' });
596
+ } else {
597
+ if (at >= 0) this.edits.splice(at, 1);
598
+ this.send({ type: EDITOR_SESSION_MESSAGES.REMOVE, id: last.id });
236
599
  }
237
- this.selected = el;
238
- this.outline(el);
239
- const panel = this.panel;
240
- panel.textContent = '';
241
- const line = (text: string, mono = false) => {
242
- const p = document.createElement('div');
243
- p.textContent = text;
244
- if (mono) p.style.cssText = 'font-family:ui-monospace,monospace;font-size:12px;opacity:.8;word-break:break-all;margin:4px 0 8px';
245
- panel.appendChild(p);
600
+ if (this.draft) this.closePanel();
601
+ else {
602
+ this.renderPreview();
603
+ this.renderDock();
604
+ }
605
+ return true;
606
+ }
607
+
608
+ /** "Save & return to Joryio": every edit is already with the dashboard; say so, stop, go back. */
609
+ done(): void {
610
+ this.send({ type: EDITOR_SESSION_MESSAGES.DONE });
611
+ this.stop();
612
+ try {
613
+ this.opener.focus();
614
+ } catch {
615
+ /* not allowed */
616
+ }
617
+ try {
618
+ window.close();
619
+ } catch {
620
+ /* not a tab the dashboard opened */
621
+ }
622
+ }
623
+
624
+ // ── live preview ─────────────────────────────────────────────────────────
625
+
626
+ private clearPreview(): void {
627
+ for (const off of this.previewUndo.splice(0).reverse()) {
628
+ try {
629
+ off();
630
+ } catch {
631
+ /* the element went away */
632
+ }
633
+ }
634
+ }
635
+
636
+ /** Every edit, and the draft in place of the edit it changes, applied to the page. */
637
+ private renderPreview(): void {
638
+ this.clearPreview();
639
+ if (!this.active) return;
640
+ const d = this.draft;
641
+ const draft = d ? this.draftEdit(d) : null;
642
+ const shown: PageEditWire[] = [];
643
+ for (const e of this.edits) shown.push(d && d.editingId === e.id ? draft || e : e);
644
+ 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);
646
+ if (this.selected) this.place(this.selBox, this.selected);
647
+ }
648
+
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);
653
+ const root = n.attachShadow({ mode: 'open' });
654
+ root.appendChild(h('style', null, PREVIEW_CSS));
655
+ build(root);
656
+ return n;
657
+ }
658
+
659
+ private applyPreview(e: PageEditWire, el: Element): void {
660
+ if (!this.originals.has(el)) this.originals.set(el, { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') });
661
+ const undo = this.previewUndo;
662
+ const attr = (name: string, value: string | null) => {
663
+ const before = el.getAttribute(name);
664
+ if (value === null) el.removeAttribute(name);
665
+ else el.setAttribute(name, value);
666
+ undo.push(() => (before === null ? el.removeAttribute(name) : el.setAttribute(name, before)));
246
667
  };
247
- line(`<${el.tagName.toLowerCase()}> ${(el.textContent || '').trim().slice(0, 60)}`);
248
- line(selector, true);
249
- const input = document.createElement('input');
250
- input.setAttribute('data-joryio-editor', 'value');
251
- input.style.cssText = 'width:100%;box-sizing:border-box;padding:6px 8px;border-radius:6px;border:0;margin-bottom:8px;color:#0f172a';
252
- input.placeholder = 'New text, https:// address or placement key';
253
- panel.appendChild(input);
254
- const row = document.createElement('div');
255
- row.style.cssText = 'display:flex;flex-wrap:wrap;gap:6px';
256
- const labels: Record<PageEditOperation, string> = {
257
- replace_text: 'Replace text',
258
- replace_image: 'Replace image',
259
- replace_link: 'Replace link',
260
- hide: 'Hide',
261
- insert_placement: 'Insert placement after',
668
+ const hide = () => {
669
+ const s = (el as HTMLElement).style;
670
+ if (!s) return;
671
+ const display = s.getPropertyValue('display');
672
+ const priority = s.getPropertyPriority('display');
673
+ s.setProperty('display', 'none', 'important');
674
+ undo.push(() => (display ? s.setProperty('display', display, priority) : s.removeProperty('display')));
262
675
  };
263
- for (const op of operationsFor(el)) {
264
- const b = document.createElement('button');
265
- b.type = 'button';
266
- b.textContent = labels[op];
267
- b.setAttribute('data-joryio-op', op);
268
- b.style.cssText = 'padding:6px 10px;border-radius:6px;border:0;background:#14b8a6;color:#fff;cursor:pointer';
269
- b.addEventListener('click', (e) => {
270
- e.preventDefault();
271
- e.stopPropagation();
272
- this.pick(el, selector, op, input.value.trim());
676
+ const insert = (n: Node, where: PageEditPosition) => {
677
+ const parent = el.parentNode;
678
+ if (where === 'before' && parent) parent.insertBefore(n, el);
679
+ else if ((where === 'after' || where === 'replace') && parent) parent.insertBefore(n, el.nextSibling);
680
+ else if (where === 'prepend') el.insertBefore(n, el.firstChild);
681
+ else el.appendChild(n);
682
+ undo.push(() => n.parentNode && n.parentNode.removeChild(n));
683
+ };
684
+ switch (e.operation) {
685
+ case 'replace_text': {
686
+ const kids = Array.from(el.childNodes);
687
+ el.textContent = previewText(e.value || '', this.ctx.sample);
688
+ undo.push(() => {
689
+ el.textContent = '';
690
+ for (const k of kids) el.appendChild(k);
691
+ });
692
+ break;
693
+ }
694
+ case 'replace_link':
695
+ attr('href', e.value || null);
696
+ break;
697
+ case 'replace_image':
698
+ attr('srcset', null);
699
+ attr('src', e.value || null);
700
+ break;
701
+ case 'hide': {
702
+ 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');
704
+ hide();
705
+ break;
706
+ }
707
+ case 'insert_placement': {
708
+ const where = e.position || 'after';
709
+ 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)))),
711
+ where,
712
+ );
713
+ if (where === 'replace') hide();
714
+ break;
715
+ }
716
+ }
717
+ }
718
+
719
+ // ── rendering ────────────────────────────────────────────────────────────
720
+
721
+ private renderHelp(): void {
722
+ this.help?.remove();
723
+ this.help = null;
724
+ let dismissed = false;
725
+ try {
726
+ dismissed = localStorage.getItem(HELP_DISMISSED_KEY) === '1';
727
+ } catch {
728
+ /* storage blocked: show it */
729
+ }
730
+ if (dismissed || this.draft || !this.wrap) return;
731
+ const t = this.t;
732
+ const row = (k: string, v: string) => h('div', { class: 'row' }, h('span', { class: 'kbd' }, k), v);
733
+ const close = h('button', { class: 'x', type: 'button', 'aria-label': t.dismiss, title: t.dismiss, 'data-j': 'help-dismiss' }, icon('close', 13));
734
+ close.addEventListener('click', () => {
735
+ // persisted: localStorage of this site's origin, in the marketer's browser - the card is a one-time tip.
736
+ try {
737
+ localStorage.setItem(HELP_DISMISSED_KEY, '1');
738
+ } catch {
739
+ /* storage blocked: hidden for this session only */
740
+ }
741
+ this.help?.remove();
742
+ this.help = null;
743
+ });
744
+ this.help = h('div', { class: 'help', 'data-j': 'help', role: 'note' }, close, h('h3', null, t.helpTitle), row('↑', t.helpUp), row('↓', t.helpDown), row(t.helpClickKey, t.helpClick));
745
+ this.wrap.appendChild(this.help);
746
+ }
747
+
748
+ private editTitle(e: PageEditWire): string {
749
+ const el = pageMatches(e.selector)[0];
750
+ const kind = this.t[el ? kindKey(el.tagName) : kindKey(e.selector, true)];
751
+ return `${this.t[ACTION_LABEL[ACTION_OF[e.operation]]]} · ${kind}`;
752
+ }
753
+
754
+ private togglePop(open: boolean): void {
755
+ this.popOpen = open;
756
+ this.renderDock();
757
+ }
758
+
759
+ private renderDock(): void {
760
+ if (!this.wrap) return;
761
+ const t = this.t;
762
+ this.dock?.remove();
763
+ const n = this.edits.length;
764
+ const sub = [this.ctx.variantName ? fill(t.variant, { name: this.ctx.variantName }) : '', location.pathname || '/'].filter(Boolean).join(' · ');
765
+ const countBtn = h('button', { class: 'db', type: 'button', 'aria-expanded': String(this.popOpen), 'data-j': 'edits' }, n === 1 ? t.editsOne : fill(t.editsMany, { n }), icon(this.popOpen ? 'down' : 'up', 11));
766
+ countBtn.addEventListener('click', () => this.togglePop(!this.popOpen));
767
+ const canUndo = this.synced && this.history.length > 0;
768
+ const undoBtn = h('button', { class: 'ib', type: 'button', 'aria-label': t.undo, title: this.synced ? t.undo : t.undoOffline, disabled: !canUndo, 'data-j': 'undo' }, icon('undo', 14));
769
+ undoBtn.addEventListener('click', () => this.undo());
770
+ const doneBtn = h('button', { class: 'go', type: 'button', 'data-j': 'done' }, t.saveReturn);
771
+ doneBtn.addEventListener('click', () => this.done());
772
+ const dock = h(
773
+ 'div',
774
+ { class: 'dock', 'data-j': 'dock', role: 'toolbar', 'aria-label': t.title },
775
+ h('span', { class: 'logo', 'aria-hidden': 'true' }, 'J'),
776
+ h('span', { class: 'name', 'data-j': 'campaign' }, this.ctx.campaignName || t.title),
777
+ h('span', { class: 'sub' }, `· ${sub}`),
778
+ h('span', { class: 'sep' }),
779
+ h('span', { class: 'hint', 'data-j': 'hint' }, icon('cursor', 13), this.draft ? t.hintEditing : t.hintPoint),
780
+ h('span', { class: 'sep' }),
781
+ countBtn,
782
+ undoBtn,
783
+ doneBtn,
784
+ );
785
+ if (this.popOpen) {
786
+ const pop = h('div', { class: 'pop', 'data-j': 'edit-list', role: 'menu' });
787
+ if (!n) pop.appendChild(h('div', { class: 'empty' }, t.noEdits));
788
+ 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));
790
+ b.addEventListener('click', () => this.focusEdit(e.id));
791
+ pop.appendChild(b);
792
+ });
793
+ dock.appendChild(pop);
794
+ }
795
+ this.dock = dock;
796
+ this.wrap.appendChild(dock);
797
+ }
798
+
799
+ private renderPanel(): void {
800
+ const d = this.draft;
801
+ if (!d || !this.wrap) return;
802
+ const t = this.t;
803
+ const el = this.selected;
804
+ this.panel?.remove();
805
+ this.wrap.classList.add('open');
806
+
807
+ // Header: breadcrumb (+ up / down), the element, its matches.
808
+ const crumbs = h('div', { class: 'crumbs', 'data-j': 'crumbs' });
809
+ if (el) {
810
+ const chain: Element[] = [];
811
+ for (let n: Element | null = el; n && n !== document.body && n !== document.documentElement; n = n.parentElement) chain.unshift(n);
812
+ const shown = chain.slice(-3);
813
+ const crumb = (label: string, target: Element | null, cur: boolean) => {
814
+ const b = h('button', { class: cur ? 'crumb cur' : 'crumb', type: 'button', 'data-j': 'crumb', 'aria-current': cur ? 'true' : undefined, disabled: !target }, label);
815
+ if (target && !cur) b.addEventListener('click', () => this.select(target));
816
+ return b;
817
+ };
818
+ crumbs.appendChild(crumb(t.page, null, false));
819
+ 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));
821
+ up.addEventListener('click', () => this.move('up', el));
822
+ 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
+ down.addEventListener('click', () => this.move('down', el));
824
+ crumbs.appendChild(h('span', { class: 'nav' }, up, down));
825
+ }
826
+ const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)];
827
+ const snippet = el ? (el.tagName === 'IMG' ? el.getAttribute('alt') || '' : this.orig(el).text) : '';
828
+ const title = h('div', { class: 'title', 'data-j': 'title' }, snippet ? `${kind} "${snippet.slice(0, 40)}"` : kind);
829
+ const pill = h('span', { class: 'pill', 'data-j': 'matches' });
830
+ const header = h('div', { class: 'hd' }, crumbs, h('div', { class: 'tr' }, title, pill));
831
+
832
+ // Body: action tiles, the action's fields, the CSS selector.
833
+ const tiles = h('div', { class: 'tiles', role: 'radiogroup', 'aria-label': t.whatToDo });
834
+ for (const a of ACTIONS) {
835
+ const on = d.action === a;
836
+ const enabled = on || this.enabled(a, el);
837
+ 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));
839
+ b.addEventListener('click', () => {
840
+ 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) || '';
844
+ this.renderPanel();
845
+ this.renderPreview();
273
846
  });
274
- row.appendChild(b);
847
+ tiles.appendChild(b);
275
848
  }
276
- panel.appendChild(row);
277
- }
278
-
279
- /** Validate like the server does, then hand the pick to the dashboard. */
280
- pick(el: Element, selector: string, operation: PageEditOperation, value: string): boolean {
281
- const base: EditorPick = { type: EDITOR_MESSAGES.PICK, selector, operation, tag: el.tagName.toLowerCase(), text: (el.textContent || '').trim().slice(0, 200) };
282
- let msg: EditorPick | null = null;
283
- if (operation === 'hide') msg = base;
284
- else if (operation === 'replace_text') msg = value || base.text ? { ...base, value: (value || base.text).slice(0, 2000) } : null;
285
- else if (operation === 'replace_image' || operation === 'replace_link') msg = isSafeEditUrl(value) ? { ...base, value } : null;
286
- else if (operation === 'insert_placement') msg = PLACEMENT_KEY_PATTERN.test(value) ? { ...base, placementKey: value, position: 'after' } : null;
287
- if (!msg) {
288
- if (this.panel) {
289
- const warn = document.createElement('div');
290
- warn.style.cssText = 'margin-top:6px;color:#fca5a5';
291
- warn.textContent =
292
- operation === 'insert_placement' ? 'Enter a placement key (lowercase letters, digits, _).' : 'Enter an address starting with https:// (or http://).';
293
- this.panel.appendChild(warn);
849
+ const fields = h('div', { 'data-j': 'fields' });
850
+ const saveBtn = h('button', { class: 'save', type: 'button', 'data-j': 'save' });
851
+ const refresh = () => {
852
+ const valid = !!this.draftEdit(d);
853
+ saveBtn.disabled = !valid;
854
+ saveBtn.textContent = fill(t.save, { action: t[ACTION_LABEL[d.action]] });
855
+ const n = pageMatches(d.selector).length;
856
+ pill.className = `pill ${n === 1 ? 'ok' : n > 1 ? 'many' : 'none'}`;
857
+ pill.textContent = n === 1 ? t.matchOne : n > 1 ? fill(t.matchMany, { n }) : t.matchNone;
858
+ };
859
+ const changed = () => {
860
+ d.touched = true;
861
+ refresh();
862
+ this.renderPreview();
863
+ };
864
+ this.renderFields(fields, d, el, changed);
865
+
866
+ const cssToggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showCss), 'data-j': 'css-toggle' }, icon('code', 13), t.css, icon(this.showCss ? 'up' : 'down', 10));
867
+ cssToggle.addEventListener('click', () => {
868
+ this.showCss = !this.showCss;
869
+ this.renderPanel();
870
+ });
871
+ const body = h('div', { class: 'bd' }, h('span', { class: 'lbl' }, t.whatToDo), tiles, fields, cssToggle);
872
+ if (this.showCss) {
873
+ const input = h('input', { class: 'mono', dir: 'ltr', 'aria-label': t.css, spellcheck: 'false', 'data-j': 'selector' });
874
+ input.value = d.selector;
875
+ const note = h('div', { class: 'help2' });
876
+ const sync = () => {
877
+ const ok = isSafeSelector(d.selector);
878
+ note.className = ok ? 'help2' : 'err';
879
+ note.textContent = !d.selector.trim() ? t.noSelector : ok ? fill(t.cssHelp, { n: pageMatches(d.selector).length }) : t.cssBad;
880
+ };
881
+ input.addEventListener('input', () => {
882
+ d.selector = input.value;
883
+ sync();
884
+ changed();
885
+ });
886
+ sync();
887
+ body.append(h('div', { class: 'mt' }, input, note));
888
+ }
889
+
890
+ const cancel = h('button', { class: 'cancel', type: 'button', 'data-j': 'cancel' }, t.cancel);
891
+ cancel.addEventListener('click', () => this.cancel());
892
+ saveBtn.addEventListener('click', () => this.save());
893
+ const panel = h('aside', { class: 'panel', 'data-j': 'panel', role: 'dialog', 'aria-label': t.whatToDo }, header, body, h('div', { class: 'ft' }, cancel, saveBtn));
894
+ refresh();
895
+ this.panel = panel;
896
+ this.wrap.appendChild(panel);
897
+ }
898
+
899
+ /** One field set per action. Typing updates the draft and the page, never re-renders the field typed in. */
900
+ private renderFields(box: HTMLElement, d: Draft, el: Element | null, changed: () => void): void {
901
+ const t = this.t;
902
+ box.textContent = '';
903
+ const was = (v: string | null) => (v ? h('span', { class: 'was', title: v }, fill(t.was, { value: v.slice(0, 60) })) : null);
904
+ 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
+ }
929
+ changed();
930
+ });
931
+ 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();
942
+ }
943
+ changed();
944
+ });
945
+ chips.appendChild(c);
294
946
  }
295
- return false;
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
+ } else if (d.action === 'link' || d.action === 'image') {
950
+ 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
+ input.value = d.url;
952
+ const err = h('div', { class: 'err' });
953
+ const check = () => (err.textContent = d.url.trim() && !isSafeEditUrl(d.url) ? t.urlBad : '');
954
+ input.addEventListener('input', () => {
955
+ d.url = input.value;
956
+ check();
957
+ changed();
958
+ });
959
+ check();
960
+ const before = el ? (d.action === 'image' ? this.orig(el).src : this.orig(el).href) : null;
961
+ box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, d.action === 'link' ? t.newLink : t.newImage), was(before)), input, err);
962
+ } else if (d.action === 'hide') {
963
+ const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)].toLowerCase();
964
+ box.appendChild(h('div', { class: 'note', 'data-j': 'hide-note' }, fill(t.hideNote, { kind })));
965
+ } else {
966
+ const input = h('input', { class: 'slotin', dir: 'auto', 'data-j': 'slot-name', 'aria-label': t.slotName, maxlength: '80' });
967
+ input.value = d.slotName;
968
+ const saved = h('span', { class: 'key', 'data-j': 'slot-key' });
969
+ const help = h('div', { class: 'help2' });
970
+ const sync = () => {
971
+ const key = slugify(d.slotName);
972
+ saved.textContent = key || '-';
973
+ help.textContent = '';
974
+ help.append(`${t.savedAs} `, saved, key ? '' : ` · ${t.slotEmpty}`);
975
+ };
976
+ input.addEventListener('input', () => {
977
+ d.slotName = input.value;
978
+ sync();
979
+ changed();
980
+ });
981
+ sync();
982
+ box.append(h('label', { class: 'lbl' }, t.slotName), input, help);
983
+ if (this.ctx.placements.length) {
984
+ const chips = h('div', { class: 'chips', 'data-j': 'placements' });
985
+ for (const p of this.ctx.placements.slice(0, 12)) {
986
+ const c = h('button', { class: 'vc', type: 'button', title: p.name || p.key, 'data-j': 'placement' }, p.key);
987
+ c.addEventListener('click', () => {
988
+ d.slotName = p.key;
989
+ input.value = p.key;
990
+ sync();
991
+ changed();
992
+ });
993
+ chips.appendChild(c);
994
+ }
995
+ box.appendChild(chips);
996
+ }
997
+ box.appendChild(h('div', { class: 'help2' }, t.slotHelp));
998
+ const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-label': t.where, 'data-j': 'positions' });
999
+ for (const [pos, label] of POSITIONS) {
1000
+ const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(d.position === pos), 'data-j': `pos-${pos}` }, t[label]);
1001
+ b.addEventListener('click', () => {
1002
+ d.position = pos;
1003
+ for (const x of Array.from(seg.children)) x.setAttribute('aria-checked', String(x === b));
1004
+ changed();
1005
+ });
1006
+ seg.appendChild(b);
1007
+ }
1008
+ box.append(h('div', { class: 'mt' }, h('span', { class: 'lbl' }, t.where), seg));
296
1009
  }
297
- this.send(msg as unknown as Record<string, unknown>);
298
- this.unselect();
299
- return true;
300
1010
  }
301
1011
  }