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

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,104 @@
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. The New text field shows variables as the
26
+ * same pills (liquid-field.ts) and stores unchanged Liquid. Selecting an
27
+ * element that already has an edit opens that edit.
28
+ * - Every edit shows live on the page while editing (the draft too); the
29
+ * text with the dashboard's sample values for its variables, else their
30
+ * fallbacks, else a placeholder pill with the field name (a custom element
31
+ * with its own shadow root, never page text). Text is set with textContent, addresses must be http(s), the
32
+ * original nodes come back on undo - nothing is ever parsed as HTML.
33
+ * - A dock: campaign · variant · page, the hint, "N edits" (a click jumps to
34
+ * that edit), Undo, "Save & return to Joryio".
35
+ *
36
+ * Messages (constants: EDITOR_MESSAGES in the core, EDITOR_SESSION_MESSAGES
37
+ * here; the dashboard's copy is packages/frontend/src/lib/web-experience.ts):
38
+ *
39
+ * editor -> dashboard
40
+ * joryio:editor-active { url } the editor is up
41
+ * joryio:editor-pick { id, selector, operation, value?, placementKey?, position?, tag, text }
42
+ * a saved edit; `id` is the edit's id - an id the
43
+ * dashboard already has REPLACES that edit
44
+ * joryio:editor-remove { id } undo of a new edit
45
+ * joryio:editor-done {} "Save & return to Joryio"
46
+ * joryio:editor-open-slot { placementKey, campaignId? }
47
+ * "Create content for this slot" (no campaignId) or
48
+ * a campaign of the slot (its id): the dashboard
49
+ * opens that campaign, or a new Placement campaign
50
+ * for the slot; sent only to a dashboard that set
51
+ * `openSlot` in its context
52
+ * joryio:editor-closed {} the editor stopped
53
+ *
54
+ * dashboard -> editor
55
+ * joryio:editor-context { campaignName?, variantName?, edits?, focusId?,
56
+ * attributes?: [{ key, label?, group? } | { name, custom? }],
57
+ * placements?: [{ key, name?, campaigns?: [{ id, name, status, statusLabel? }] }],
58
+ * openSlot?: true,
59
+ * sample?: { "user.firstName": "Lior", ... },
60
+ * strings?: { <EDITOR_STRINGS key>: text }, dir?: 'ltr' | 'rtl' }
61
+ * the variant's edits (shown live and in "N edits"),
62
+ * the words in the marketer's language; enables Undo.
63
+ * `campaigns` per placement (1.4.0-beta.7): the
64
+ * campaigns that fill that slot, shown on a saved
65
+ * slot edit ("In this slot: ..."); `openSlot`: the
66
+ * dashboard handles joryio:editor-open-slot. An
67
+ * editor before beta.7 ignores both.
68
+ * joryio:editor-focus { id } jump to that edit
69
+ * joryio:editor-close {} stop
70
+ *
71
+ * A dashboard that sends no context still works as before this redesign:
72
+ * every save is a pick, the dock counts this session's edits, and Undo stays
73
+ * off (that dashboard would not hear a remove).
16
74
  */
17
75
  import type { Logger } from '../utils/logger';
18
- import { isSafeSelector, isSafeEditUrl, type PageEditOperation } from '../core/page-edits';
76
+ import { isSafeSelector, isSafeEditUrl, trustedEdit, type PageEditOperation, type PageEditPosition, type PageEditWire } from '../core/page-edits';
19
77
  import { EDITOR_MESSAGES } from '../core/editor-gate';
78
+ import { EDITOR_STRINGS, fill, mergeStrings, type EditorStringKey, type EditorStrings } from './editor-strings';
79
+ 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';
20
82
 
21
83
  export { EDITOR_MESSAGES };
22
84
 
85
+ export const EDITOR_SESSION_MESSAGES = {
86
+ CONTEXT: 'joryio:editor-context',
87
+ FOCUS: 'joryio:editor-focus',
88
+ REMOVE: 'joryio:editor-remove',
89
+ DONE: 'joryio:editor-done',
90
+ OPEN_SLOT: 'joryio:editor-open-slot',
91
+ } as const;
92
+
23
93
  /** Attributes that name an element on purpose, most stable first. */
24
94
  const NAMING_ATTRIBUTES = ['data-joryio-id', 'data-testid', 'data-test', 'data-qa', 'data-cy', 'data-id', 'name'];
25
95
  const PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;
96
+ const ATTRIBUTE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
97
+ const MAX_TEXT = 2000;
98
+ const MAX_EDITS = 100;
99
+ const PREVIEW_TAG = 'joryio-editor-preview';
100
+ const OURS = '[data-joryio-editor]';
101
+ const HELP_DISMISSED_KEY = 'jry_editor_help_dismissed';
26
102
 
27
103
  /** CSS.escape, for browsers (and test DOMs) without it. */
28
104
  export function cssEscape(value: string): string {
@@ -40,9 +116,29 @@ export function cssEscape(value: string): string {
40
116
  return out;
41
117
  }
42
118
 
119
+ const isOurs = (el: Element | null): boolean => !!el && !!el.closest(OURS);
120
+ const VAR_PILL = 'var';
121
+
122
+ /** The page element an event on the page is about: a variable pill in the preview stands for the element it is in. */
123
+ function pageTarget(t: EventTarget | null): Element | null {
124
+ let el = t instanceof Element ? t : null;
125
+ 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;
127
+ }
128
+
129
+ /** The page's elements a selector finds - never the editor's own. */
130
+ function pageMatches(selector: string): Element[] {
131
+ if (!isSafeSelector(selector)) return [];
132
+ try {
133
+ return Array.from(document.querySelectorAll(selector)).filter((e) => !isOurs(e));
134
+ } catch {
135
+ return [];
136
+ }
137
+ }
138
+
43
139
  const unique = (doc: Document, selector: string, el: Element): boolean => {
44
140
  try {
45
- const hits = doc.querySelectorAll(selector);
141
+ const hits = Array.from(doc.querySelectorAll(selector)).filter((e) => !isOurs(e));
46
142
  return hits.length === 1 && hits[0] === el;
47
143
  } catch {
48
144
  return false;
@@ -106,21 +202,108 @@ export function operationsFor(el: Element): PageEditOperation[] {
106
202
 
107
203
  export interface EditorPick {
108
204
  type: typeof EDITOR_MESSAGES.PICK;
205
+ /** The edit's id: new edits get a fresh one, an edit opened from the list keeps its own. */
206
+ id: string;
109
207
  selector: string;
110
208
  operation: PageEditOperation;
111
209
  value?: string;
112
210
  placementKey?: string;
113
- position?: 'before' | 'after' | 'prepend' | 'append';
211
+ position?: PageEditPosition;
114
212
  tag: string;
115
213
  text: string;
116
214
  }
117
215
 
216
+ type Action = 'text' | 'link' | 'image' | 'hide' | 'slot';
217
+ const ACTIONS: Action[] = ['text', 'link', 'image', 'hide', 'slot'];
218
+ const OPERATION_OF: Record<Action, PageEditOperation> = { text: 'replace_text', link: 'replace_link', image: 'replace_image', hide: 'hide', slot: 'insert_placement' };
219
+ const ACTION_OF: Record<PageEditOperation, Action> = { replace_text: 'text', replace_link: 'link', replace_image: 'image', hide: 'hide', insert_placement: 'slot' };
220
+ const ACTION_LABEL: Record<Action, EditorStringKey> = { text: 'actText', link: 'actLink', image: 'actImage', hide: 'actHide', slot: 'actSlot' };
221
+ const ACTION_ICON: Record<Action, IconName> = { text: 'text', link: 'link', image: 'image', hide: 'hide', slot: 'slot' };
222
+ const POSITIONS: Array<[PageEditPosition, EditorStringKey]> = [
223
+ ['before', 'posBefore'],
224
+ ['after', 'posAfter'],
225
+ ['replace', 'posReplace'],
226
+ ['prepend', 'posPrepend'],
227
+ ['append', 'posAppend'],
228
+ ];
229
+
230
+ interface Draft {
231
+ action: Action;
232
+ text: string;
233
+ url: string;
234
+ slotName: string;
235
+ position: PageEditPosition;
236
+ selector: string;
237
+ /** The edit being changed (opened from the list or the dashboard), null for a new one. */
238
+ editingId: string | null;
239
+ /** A new draft shows on the page only once something was changed (its untouched text would flatten the element's markup). */
240
+ touched: boolean;
241
+ }
242
+
243
+ interface Var {
244
+ path: string;
245
+ label: string;
246
+ group: string;
247
+ }
248
+
249
+ /** The chips shown before "More…": these when the catalog has them, else its first ones. */
250
+ const COMMON_VARS = ['user.firstName', 'user.lastName', 'user.email', 'user.custom.city'];
251
+ const CHIPS = 4;
252
+
253
+ interface EditorContext {
254
+ campaignName: string;
255
+ variantName: string;
256
+ /** The personalization catalog: Liquid path, label, group ('' for the old `{ name, custom }` shape). */
257
+ attributes: Var[];
258
+ placements: Array<{ key: string; name: string; campaigns: SlotCampaign[] }>;
259
+ sample: Record<string, string>;
260
+ /** The dashboard handles joryio:editor-open-slot: the slot's campaigns and "Create content for this slot" show. */
261
+ openSlot: boolean;
262
+ }
263
+
264
+ /** A campaign that fills a slot, as the dashboard sent it. */
265
+ interface SlotCampaign {
266
+ id: string;
267
+ name: string;
268
+ /** The wire status (`draft`, `active`, ...), and the dashboard's word for it. */
269
+ status: string;
270
+ statusLabel: string;
271
+ }
272
+ const CAMPAIGN_ID = /^[A-Za-z0-9_-]{1,64}$/;
273
+
274
+ 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();
276
+
118
277
  export class VisualEditor {
119
278
  private listeners: Array<() => void> = [];
120
- private highlight: HTMLElement | null = null;
279
+ private active = false;
280
+ private host: HTMLElement | null = null;
281
+ /** Kept for tests: the shadow root is closed to the page. */
282
+ root: ShadowRoot | null = null;
283
+ private wrap: HTMLElement | null = null;
284
+ private hoverBox: HTMLElement | null = null;
285
+ private selBox: HTMLElement | null = null;
286
+ private dock: HTMLElement | null = null;
121
287
  private panel: HTMLElement | null = null;
288
+ private help: HTMLElement | null = null;
289
+ private hovered: Element | null = null;
122
290
  private selected: Element | null = null;
123
- private active = false;
291
+ private draft: Draft | null = null;
292
+ private showCss = false;
293
+ private showLiquid = false;
294
+ /** Closes an open overlay of the panel (the variable picker) on Esc; true when it closed one. */
295
+ private closeOverlay: (() => boolean) | null = null;
296
+ private popOpen = false;
297
+ private edits: PageEditWire[] = [];
298
+ private history: Array<{ id: string; before: PageEditWire | null }> = [];
299
+ /** The dashboard sent a context: it understands remove (Undo) and replace-by-id. */
300
+ private synced = false;
301
+ private t: EditorStrings = { ...EDITOR_STRINGS };
302
+ private dir: 'ltr' | 'rtl' = 'ltr';
303
+ private ctx: EditorContext = { campaignName: '', variantName: '', attributes: [], placements: [], sample: {}, openSlot: false };
304
+ private previewUndo: Array<() => void> = [];
305
+ /** The page's own text / address of an element before any preview, for "Was:". */
306
+ private originals = new WeakMap<Element, { text: string; href: string | null; src: string | null }>();
124
307
 
125
308
  constructor(
126
309
  private dashboardOrigin: string,
@@ -129,7 +312,7 @@ export class VisualEditor {
129
312
  private onStop: () => void = () => undefined,
130
313
  ) {}
131
314
 
132
- /** The token was vouched for by the server: show the picker. */
315
+ /** The token was vouched for by the server: show the editor. */
133
316
  start(): void {
134
317
  if (this.active) return;
135
318
  this.active = true;
@@ -138,6 +321,8 @@ export class VisualEditor {
138
321
  if (!data || typeof data.type !== 'string') return;
139
322
  if (e.origin !== this.dashboardOrigin || e.source !== this.opener) return;
140
323
  if (data.type === EDITOR_MESSAGES.CLOSE) this.stop();
324
+ else if (data.type === EDITOR_SESSION_MESSAGES.CONTEXT) this.applyContext(data as Record<string, unknown>);
325
+ else if (data.type === EDITOR_SESSION_MESSAGES.FOCUS) this.focusEdit((data as { id?: unknown }).id);
141
326
  };
142
327
  window.addEventListener('message', onMessage);
143
328
  this.listeners.push(() => window.removeEventListener('message', onMessage));
@@ -148,15 +333,21 @@ export class VisualEditor {
148
333
  return this.active;
149
334
  }
150
335
 
336
+ /** The edits this editor knows of (the dashboard's, then this session's), in order. */
337
+ editList(): PageEditWire[] {
338
+ return this.edits.slice();
339
+ }
340
+
151
341
  stop(): void {
152
342
  if (!this.active) return;
153
343
  this.send({ type: EDITOR_MESSAGES.CLOSED });
154
344
  this.active = false;
155
345
  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;
346
+ this.clearPreview();
347
+ this.host?.remove();
348
+ this.host = this.root = this.wrap = this.hoverBox = this.selBox = this.dock = this.panel = this.help = null;
349
+ this.selected = this.hovered = null;
350
+ this.draft = null;
160
351
  try {
161
352
  this.onStop();
162
353
  } catch (error) {
@@ -173,129 +364,865 @@ export class VisualEditor {
173
364
  }
174
365
  }
175
366
 
367
+ // ── setup ────────────────────────────────────────────────────────────────
368
+
176
369
  private activate(): void {
177
370
  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]');
371
+ const host = doc.createElement('joryio-editor');
372
+ host.setAttribute('data-joryio-editor', 'root');
373
+ host.setAttribute('style', HOST_STYLE);
374
+ const root = host.attachShadow({ mode: 'closed' });
375
+ root.appendChild(h('style', null, EDITOR_CSS));
376
+ const wrap = h('div', { class: 'r', dir: this.dir });
377
+ this.hoverBox = h('div', { class: 'box', 'data-j': 'hover' });
378
+ this.selBox = h('div', { class: 'box sel', 'data-j': 'selected' });
379
+ wrap.append(this.hoverBox, this.selBox);
380
+ root.appendChild(wrap);
381
+ doc.documentElement.appendChild(host);
382
+ this.host = host;
383
+ this.root = root;
384
+ this.wrap = wrap;
385
+
190
386
  const onMove = (e: MouseEvent) => {
191
- if (this.selected || inEditor(e.target)) return;
192
- this.outline(e.target instanceof Element ? e.target : null);
387
+ const t = e.target instanceof Element ? e.target : null;
388
+ if (isOurs(t) && t!.getAttribute('data-joryio-editor') !== VAR_PILL) return;
389
+ this.hovered = pageTarget(t);
390
+ this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
193
391
  };
194
392
  const onClick = (e: MouseEvent) => {
195
- if (inEditor(e.target)) return;
393
+ if (e.target instanceof Element && e.target.closest('[data-joryio-editor="root"]')) return;
394
+ // A click on the page - a preview of ours included - never reaches the site.
196
395
  e.preventDefault();
197
396
  e.stopPropagation();
198
- if (e.target instanceof Element) this.select(e.target);
397
+ const el = pageTarget(e.target);
398
+ if (el) this.select(el);
199
399
  };
200
400
  const onKey = (e: KeyboardEvent) => {
201
- if (e.key === 'Escape') this.selected ? this.unselect() : this.stop();
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();
406
+ return;
407
+ }
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);
415
+ }
416
+ };
417
+ const onScroll = () => {
418
+ this.place(this.hoverBox, this.hovered === this.selected ? null : this.hovered, true);
419
+ this.place(this.selBox, this.selected);
202
420
  };
203
421
  doc.addEventListener('mousemove', onMove, true);
204
422
  doc.addEventListener('click', onClick, true);
205
423
  doc.addEventListener('keydown', onKey, true);
424
+ window.addEventListener('scroll', onScroll, true);
425
+ window.addEventListener('resize', onScroll);
206
426
  this.listeners.push(
207
427
  () => doc.removeEventListener('mousemove', onMove, true),
208
428
  () => doc.removeEventListener('click', onClick, true),
209
429
  () => doc.removeEventListener('keydown', onKey, true),
430
+ () => window.removeEventListener('scroll', onScroll, true),
431
+ () => window.removeEventListener('resize', onScroll),
210
432
  );
433
+ this.renderDock();
434
+ this.renderHelp();
211
435
  this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });
212
436
  }
213
437
 
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';
438
+ /** The dashboard's context: words, campaign, the variant's edits (validated like the runtime does). */
439
+ private applyContext(data: Record<string, unknown>): void {
440
+ this.synced = true;
441
+ this.t = mergeStrings(data.strings);
442
+ this.dir = data.dir === 'rtl' ? 'rtl' : 'ltr';
443
+ this.wrap?.setAttribute('dir', this.dir);
444
+ const list = <T>(v: unknown, map: (x: any) => T | null, max: number): T[] =>
445
+ (Array.isArray(v) ? v : [])
446
+ .map(map)
447
+ .filter((x): x is T => x !== null)
448
+ .slice(0, max);
449
+ this.ctx = {
450
+ campaignName: clip(data.campaignName, 120),
451
+ variantName: clip(data.variantName, 60),
452
+ // Both shapes: the catalog's { key, label, group } and the older { name, custom }.
453
+ attributes: list(
454
+ data.attributes,
455
+ (a): Var | null =>
456
+ !a
457
+ ? null
458
+ : typeof a.key === 'string' && VAR_PATH.test(a.key)
459
+ ? { path: a.key, label: clip(a.label, 60) || a.key.split('.').pop()!, group: clip(a.group, 40) }
460
+ : typeof a.name === 'string' && ATTRIBUTE_NAME.test(a.name)
461
+ ? { path: `user.${a.custom === true ? 'custom.' : ''}${a.name}`, label: a.name, group: '' }
462
+ : null,
463
+ 400,
464
+ ),
465
+ placements: list(
466
+ data.placements,
467
+ (p) =>
468
+ p && typeof p.key === 'string' && PLACEMENT_KEY_PATTERN.test(p.key)
469
+ ? {
470
+ key: p.key,
471
+ name: clip(p.name, 80),
472
+ campaigns: list(
473
+ p.campaigns,
474
+ (c): SlotCampaign | null =>
475
+ c && typeof c.id === 'string' && CAMPAIGN_ID.test(c.id) ? { id: c.id, name: clip(c.name, 120) || c.id, status: clip(c.status, 30), statusLabel: clip(c.statusLabel, 40) } : null,
476
+ 10,
477
+ ),
478
+ }
479
+ : null,
480
+ 200,
481
+ ),
482
+ sample: {},
483
+ openSlot: data.openSlot === true,
484
+ };
485
+ if (data.sample && typeof data.sample === 'object') {
486
+ for (const [k, v] of Object.entries(data.sample as Record<string, unknown>).slice(0, 100)) {
487
+ if (/^user\.[A-Za-z0-9_.]{1,80}$/.test(k) && typeof v === 'string') this.ctx.sample[k] = v.slice(0, 200);
488
+ }
489
+ }
490
+ if (Array.isArray(data.edits)) {
491
+ this.edits = list(data.edits, (e) => trustedEdit(e), MAX_EDITS).map((e) => {
492
+ const { personalized: _p, ...rest } = e;
493
+ return rest;
494
+ });
495
+ this.history = [];
496
+ }
497
+ this.renderPreview();
498
+ this.renderDock();
499
+ this.renderHelp();
500
+ if (this.draft) this.renderPanel();
501
+ if (typeof data.focusId === 'string') this.focusEdit(data.focusId);
502
+ }
503
+
504
+ // ── selection ────────────────────────────────────────────────────────────
505
+
506
+ /** Outline an element (hover: dashed + label; selected: solid). */
507
+ private place(box: HTMLElement | null, el: Element | null, withLabel = false): void {
508
+ if (!box) return;
509
+ if (!el || !el.isConnected) {
510
+ box.style.display = 'none';
218
511
  return;
219
512
  }
220
513
  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` });
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` });
515
+ box.textContent = '';
516
+ const label = `${this.t[kindKey(el.tagName)]} · ${el.tagName.toLowerCase()}`;
517
+ box.appendChild(h('span', { class: 'chip', 'data-j': 'label' }, withLabel ? `${label} - ${this.t.clickToEdit}` : label));
518
+ }
519
+
520
+ private move(dir: 'up' | 'down', from: Element): void {
521
+ 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;
523
+ this.select(next);
524
+ }
525
+
526
+ /** The edits on an element (its selector finds it, or is the selector the editor would make for it), oldest first. */
527
+ private editsOn(el: Element | null): PageEditWire[] {
528
+ if (!el) return [];
529
+ const own = robustSelector(el);
530
+ return this.edits.filter((e) => e.selector === own || pageMatches(e.selector).indexOf(el) >= 0);
531
+ }
532
+
533
+ /**
534
+ * The element is chosen: open the panel on it. An element that already
535
+ * has an edit (this session's or the dashboard's) opens that edit - the
536
+ * most recent one - like jumping to it from the list: its value, its
537
+ * fallback, and Save updates the same edit.
538
+ */
539
+ select(el: Element, edit?: PageEditWire): void {
540
+ if (!this.active) return;
541
+ edit = edit || this.editsOn(el).pop();
542
+ this.selected = el;
543
+ this.hovered = null;
544
+ this.place(this.hoverBox, null);
545
+ this.place(this.selBox, el);
546
+ this.popOpen = false;
547
+ const selector = edit ? edit.selector : robustSelector(el) || '';
548
+ this.showCss = !selector;
549
+ this.draft = edit ? this.draftOf(edit) : this.newDraft(el, selector);
550
+ this.renderPanel();
551
+ this.renderDock();
552
+ this.renderHelp();
553
+ this.renderPreview();
554
+ }
555
+
556
+ private enabled(action: Action, el: Element | null): boolean {
557
+ if (!el) return true;
558
+ if (action === 'text') return el.tagName !== 'IMG' && !!this.orig(el).text;
559
+ if (action === 'link') return el.tagName === 'A';
560
+ if (action === 'image') return el.tagName === 'IMG';
561
+ return true;
562
+ }
563
+
564
+ private newDraft(el: Element, selector: string): Draft {
565
+ const o = this.orig(el);
566
+ 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 };
568
+ }
569
+
570
+ private draftOf(e: PageEditWire): Draft {
571
+ const action = ACTION_OF[e.operation];
572
+ return {
573
+ action,
574
+ text: e.operation === 'replace_text' ? e.value || '' : '',
575
+ url: action === 'link' || action === 'image' ? e.value || '' : '',
576
+ slotName: e.placementKey || '',
577
+ position: e.position || 'after',
578
+ selector: e.selector,
579
+ editingId: e.id,
580
+ touched: true,
581
+ };
582
+ }
583
+
584
+ /** The element as the page had it, before any preview of this editor. */
585
+ private orig(el: Element): { text: string; href: string | null; src: string | null } {
586
+ return this.originals.get(el) || { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') };
587
+ }
588
+
589
+ /** Jump to an edit: from the dock's list, or the dashboard ("Edit on site"). */
590
+ focusEdit(id: unknown): boolean {
591
+ const edit = this.edits.filter((e) => e.id === id)[0];
592
+ if (!edit || !this.active) return false;
593
+ const el = pageMatches(edit.selector)[0] || null;
594
+ if (el) {
595
+ try {
596
+ el.scrollIntoView({ block: 'center' });
597
+ } catch {
598
+ /* old browsers */
599
+ }
600
+ this.select(el, edit);
601
+ } else {
602
+ this.selected = null;
603
+ this.place(this.selBox, null);
604
+ this.draft = this.draftOf(edit);
605
+ this.showCss = true;
606
+ this.renderPanel();
607
+ this.renderDock();
608
+ this.renderHelp();
609
+ this.renderPreview();
610
+ }
611
+ return true;
612
+ }
613
+
614
+ // ── the edit ─────────────────────────────────────────────────────────────
615
+
616
+ /** The draft as an edit, or null while a field is not valid yet. */
617
+ private draftEdit(d: Draft): PageEditWire | null {
618
+ const base = { id: d.editingId || '', selector: d.selector.trim() };
619
+ if (!isSafeSelector(base.selector)) return null;
620
+ const operation = OPERATION_OF[d.action];
621
+ if (d.action === 'hide') return { ...base, operation };
622
+ if (d.action === 'text') return d.text.trim() && d.text.length <= MAX_TEXT ? { ...base, operation, value: d.text } : null;
623
+ if (d.action === 'link' || d.action === 'image') return isSafeEditUrl(d.url) ? { ...base, operation, value: d.url.trim() } : null;
624
+ const key = slugify(d.slotName);
625
+ return PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: d.position } : null;
626
+ }
627
+
628
+ private save(): void {
629
+ const d = this.draft;
630
+ const edit = d && this.draftEdit(d);
631
+ if (!d || !edit) return;
632
+ const el = this.selected || pageMatches(edit.selector)[0] || null;
633
+ const id = d.editingId || newEditId();
634
+ if (!this.pick(el, edit.selector, edit.operation, edit.value ?? edit.placementKey ?? '', { id, position: edit.position })) return;
635
+ // A saved slot stays open on its edit, with its campaigns or "Create content for this slot".
636
+ if (edit.operation === 'insert_placement' && this.ctx.openSlot) this.focusEdit(id);
637
+ }
638
+
639
+ /** "Create content for this slot" or one of its campaigns: the dashboard opens it, in its own tab. */
640
+ openSlot(placementKey: string, campaignId?: string): boolean {
641
+ if (!this.ctx.openSlot || !PLACEMENT_KEY_PATTERN.test(placementKey)) return false;
642
+ this.send({ type: EDITOR_SESSION_MESSAGES.OPEN_SLOT, placementKey, ...(campaignId ? { campaignId } : {}) });
643
+ try {
644
+ this.opener.focus();
645
+ } catch {
646
+ /* not allowed */
647
+ }
648
+ return true;
649
+ }
650
+
651
+ /**
652
+ * Validate like the server does, post the edit to the dashboard, keep it
653
+ * in the list (and on the page). `value` is the text, the address or the
654
+ * slot name (made a placement key).
655
+ */
656
+ pick(el: Element | null, selector: string, operation: PageEditOperation, value: string, opts: { id?: string; position?: PageEditPosition } = {}): boolean {
657
+ const id = opts.id || newEditId();
658
+ const tag = el ? el.tagName.toLowerCase() : '';
659
+ const text = el ? this.orig(el).text.slice(0, 200) : '';
660
+ let edit: PageEditWire | null = null;
661
+ if (isSafeSelector(selector)) {
662
+ const base = { id, selector: selector.trim() };
663
+ if (operation === 'hide') edit = { ...base, operation };
664
+ else if (operation === 'replace_text') edit = (value || text) && (value || text).length <= MAX_TEXT ? { ...base, operation, value: value || text } : null;
665
+ else if (operation === 'replace_image' || operation === 'replace_link') edit = isSafeEditUrl(value) ? { ...base, operation, value: value.trim() } : null;
666
+ else if (operation === 'insert_placement') {
667
+ const key = slugify(value);
668
+ edit = PLACEMENT_KEY_PATTERN.test(key) ? { ...base, operation, placementKey: key, position: opts.position || 'after' } : null;
669
+ }
670
+ }
671
+ if (!edit) return false;
672
+ const msg: EditorPick = { type: EDITOR_MESSAGES.PICK, ...edit, tag, text } as EditorPick;
673
+ this.send(msg as unknown as Record<string, unknown>);
674
+ const at = this.edits.map((e) => e.id).indexOf(id);
675
+ this.history.push({ id, before: at >= 0 ? this.edits[at] : null });
676
+ if (at >= 0) this.edits[at] = edit;
677
+ else this.edits.push(edit);
678
+ this.closePanel();
679
+ return true;
222
680
  }
223
681
 
224
- private unselect(): void {
682
+ private cancel(): void {
683
+ this.closePanel();
684
+ }
685
+
686
+ private closePanel(): void {
687
+ this.draft = null;
225
688
  this.selected = null;
226
- if (this.panel) this.panel.textContent = 'Joryio editor - click an element on the page. Esc to finish.';
689
+ this.panel?.remove();
690
+ this.panel = null;
691
+ this.wrap?.classList.remove('open');
692
+ this.place(this.selBox, null);
693
+ this.renderPreview();
694
+ this.renderDock();
695
+ this.renderHelp();
227
696
  }
228
697
 
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;
698
+ /** Undo the last saved edit: a new one is removed, a changed one goes back to what it was. */
699
+ undo(): boolean {
700
+ if (!this.synced) return false;
701
+ const last = this.history.pop();
702
+ if (!last) return false;
703
+ const at = this.edits.map((e) => e.id).indexOf(last.id);
704
+ if (last.before) {
705
+ if (at >= 0) this.edits[at] = last.before;
706
+ const b = last.before;
707
+ this.send({ type: EDITOR_MESSAGES.PICK, ...b, tag: '', text: '' });
708
+ } else {
709
+ if (at >= 0) this.edits.splice(at, 1);
710
+ this.send({ type: EDITOR_SESSION_MESSAGES.REMOVE, id: last.id });
236
711
  }
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);
712
+ if (this.draft) this.closePanel();
713
+ else {
714
+ this.renderPreview();
715
+ this.renderDock();
716
+ }
717
+ return true;
718
+ }
719
+
720
+ /** "Save & return to Joryio": every edit is already with the dashboard; say so, stop, go back. */
721
+ done(): void {
722
+ this.send({ type: EDITOR_SESSION_MESSAGES.DONE });
723
+ this.stop();
724
+ try {
725
+ this.opener.focus();
726
+ } catch {
727
+ /* not allowed */
728
+ }
729
+ try {
730
+ window.close();
731
+ } catch {
732
+ /* not a tab the dashboard opened */
733
+ }
734
+ }
735
+
736
+ // ── live preview ─────────────────────────────────────────────────────────
737
+
738
+ private clearPreview(): void {
739
+ for (const off of this.previewUndo.splice(0).reverse()) {
740
+ try {
741
+ off();
742
+ } catch {
743
+ /* the element went away */
744
+ }
745
+ }
746
+ }
747
+
748
+ /** Every edit, and the draft in place of the edit it changes, applied to the page. */
749
+ private renderPreview(): void {
750
+ this.clearPreview();
751
+ if (!this.active) return;
752
+ const d = this.draft;
753
+ const draft = d ? this.draftEdit(d) : null;
754
+ const shown: PageEditWire[] = [];
755
+ for (const e of this.edits) shown.push(d && d.editingId === e.id ? draft || e : e);
756
+ 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);
758
+ if (this.selected) this.place(this.selBox, this.selected);
759
+ }
760
+
761
+ private previewNode(build: (root: ShadowRoot) => void, style = PREVIEW_HOST_STYLE, kind = 'preview'): HTMLElement {
762
+ const n = document.createElement(PREVIEW_TAG);
763
+ n.setAttribute('data-joryio-editor', kind);
764
+ n.setAttribute('style', style);
765
+ const root = n.attachShadow({ mode: 'open' });
766
+ root.appendChild(h('style', null, PREVIEW_CSS));
767
+ build(root);
768
+ return n;
769
+ }
770
+
771
+ private applyPreview(e: PageEditWire, el: Element): void {
772
+ if (!this.originals.has(el)) this.originals.set(el, { text: shortText(el), href: el.getAttribute('href'), src: el.getAttribute('src') });
773
+ const undo = this.previewUndo;
774
+ const attr = (name: string, value: string | null) => {
775
+ const before = el.getAttribute(name);
776
+ if (value === null) el.removeAttribute(name);
777
+ else el.setAttribute(name, value);
778
+ undo.push(() => (before === null ? el.removeAttribute(name) : el.setAttribute(name, before)));
246
779
  };
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',
780
+ const hide = () => {
781
+ const s = (el as HTMLElement).style;
782
+ if (!s) return;
783
+ const display = s.getPropertyValue('display');
784
+ const priority = s.getPropertyPriority('display');
785
+ s.setProperty('display', 'none', 'important');
786
+ undo.push(() => (display ? s.setProperty('display', display, priority) : s.removeProperty('display')));
262
787
  };
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());
788
+ const insert = (n: Node, where: PageEditPosition) => {
789
+ const parent = el.parentNode;
790
+ if (where === 'before' && parent) parent.insertBefore(n, el);
791
+ else if ((where === 'after' || where === 'replace') && parent) parent.insertBefore(n, el.nextSibling);
792
+ else if (where === 'prepend') el.insertBefore(n, el.firstChild);
793
+ else el.appendChild(n);
794
+ undo.push(() => n.parentNode && n.parentNode.removeChild(n));
795
+ };
796
+ switch (e.operation) {
797
+ case 'replace_text': {
798
+ const kids = Array.from(el.childNodes);
799
+ el.textContent = '';
800
+ // 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));
802
+ undo.push(() => {
803
+ el.textContent = '';
804
+ for (const k of kids) el.appendChild(k);
805
+ });
806
+ break;
807
+ }
808
+ case 'replace_link':
809
+ attr('href', e.value || null);
810
+ break;
811
+ case 'replace_image':
812
+ attr('srcset', null);
813
+ attr('src', e.value || null);
814
+ break;
815
+ case 'hide': {
816
+ 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');
818
+ hide();
819
+ break;
820
+ }
821
+ case 'insert_placement': {
822
+ const where = e.position || 'after';
823
+ 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)))),
825
+ where,
826
+ );
827
+ if (where === 'replace') hide();
828
+ break;
829
+ }
830
+ }
831
+ }
832
+
833
+ // ── rendering ────────────────────────────────────────────────────────────
834
+
835
+ private renderHelp(): void {
836
+ this.help?.remove();
837
+ this.help = null;
838
+ let dismissed = false;
839
+ try {
840
+ dismissed = localStorage.getItem(HELP_DISMISSED_KEY) === '1';
841
+ } catch {
842
+ /* storage blocked: show it */
843
+ }
844
+ if (dismissed || this.draft || !this.wrap) return;
845
+ const t = this.t;
846
+ const row = (k: string, v: string) => h('div', { class: 'row' }, h('span', { class: 'kbd' }, k), v);
847
+ const close = h('button', { class: 'x', type: 'button', 'aria-label': t.dismiss, title: t.dismiss, 'data-j': 'help-dismiss' }, icon('close', 13));
848
+ close.addEventListener('click', () => {
849
+ // persisted: localStorage of this site's origin, in the marketer's browser - the card is a one-time tip.
850
+ try {
851
+ localStorage.setItem(HELP_DISMISSED_KEY, '1');
852
+ } catch {
853
+ /* storage blocked: hidden for this session only */
854
+ }
855
+ this.help?.remove();
856
+ this.help = null;
857
+ });
858
+ 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));
859
+ this.wrap.appendChild(this.help);
860
+ }
861
+
862
+ /** A variable's label from the catalog. */
863
+ private labelOf(path: string): string | undefined {
864
+ const v = this.ctx.attributes.filter((a) => a.path === path)[0];
865
+ return v && v.label;
866
+ }
867
+
868
+ private editTitle(e: PageEditWire): string {
869
+ const el = pageMatches(e.selector)[0];
870
+ const kind = this.t[el ? kindKey(el.tagName) : kindKey(e.selector, true)];
871
+ return `${this.t[ACTION_LABEL[ACTION_OF[e.operation]]]} · ${kind}`;
872
+ }
873
+
874
+ private togglePop(open: boolean): void {
875
+ this.popOpen = open;
876
+ this.renderDock();
877
+ }
878
+
879
+ private renderDock(): void {
880
+ if (!this.wrap) return;
881
+ const t = this.t;
882
+ this.dock?.remove();
883
+ const n = this.edits.length;
884
+ const sub = [this.ctx.variantName ? fill(t.variant, { name: this.ctx.variantName }) : '', location.pathname || '/'].filter(Boolean).join(' · ');
885
+ 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));
886
+ countBtn.addEventListener('click', () => this.togglePop(!this.popOpen));
887
+ const canUndo = this.synced && this.history.length > 0;
888
+ 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));
889
+ undoBtn.addEventListener('click', () => this.undo());
890
+ const doneBtn = h('button', { class: 'go', type: 'button', 'data-j': 'done' }, t.saveReturn);
891
+ doneBtn.addEventListener('click', () => this.done());
892
+ const dock = h(
893
+ 'div',
894
+ { class: 'dock', 'data-j': 'dock', role: 'toolbar', 'aria-label': t.title },
895
+ h('span', { class: 'logo', 'aria-hidden': 'true' }, 'J'),
896
+ h('span', { class: 'name', 'data-j': 'campaign' }, this.ctx.campaignName || t.title),
897
+ h('span', { class: 'sub' }, `· ${sub}`),
898
+ h('span', { class: 'sep' }),
899
+ h('span', { class: 'hint', 'data-j': 'hint' }, icon('cursor', 13), this.draft ? t.hintEditing : t.hintPoint),
900
+ h('span', { class: 'sep' }),
901
+ countBtn,
902
+ undoBtn,
903
+ doneBtn,
904
+ );
905
+ if (this.popOpen) {
906
+ const pop = h('div', { class: 'pop', 'data-j': 'edit-list', role: 'menu' });
907
+ if (!n) pop.appendChild(h('div', { class: 'empty' }, t.noEdits));
908
+ 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));
910
+ b.addEventListener('click', () => this.focusEdit(e.id));
911
+ pop.appendChild(b);
912
+ });
913
+ dock.appendChild(pop);
914
+ }
915
+ this.dock = dock;
916
+ this.wrap.appendChild(dock);
917
+ }
918
+
919
+ private renderPanel(): void {
920
+ const d = this.draft;
921
+ if (!d || !this.wrap) return;
922
+ const t = this.t;
923
+ const el = this.selected;
924
+ this.panel?.remove();
925
+ this.wrap.classList.add('open');
926
+
927
+ // Header: breadcrumb (+ up / down), the element, its matches.
928
+ const crumbs = h('div', { class: 'crumbs', 'data-j': 'crumbs' });
929
+ if (el) {
930
+ const chain: Element[] = [];
931
+ for (let n: Element | null = el; n && n !== document.body && n !== document.documentElement; n = n.parentElement) chain.unshift(n);
932
+ const shown = chain.slice(-3);
933
+ const crumb = (label: string, target: Element | null, cur: boolean) => {
934
+ const b = h('button', { class: cur ? 'crumb cur' : 'crumb', type: 'button', 'data-j': 'crumb', 'aria-current': cur ? 'true' : undefined, disabled: !target }, label);
935
+ if (target && !cur) b.addEventListener('click', () => this.select(target));
936
+ return b;
937
+ };
938
+ crumbs.appendChild(crumb(t.page, null, false));
939
+ 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));
941
+ up.addEventListener('click', () => this.move('up', el));
942
+ 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
+ down.addEventListener('click', () => this.move('down', el));
944
+ crumbs.appendChild(h('span', { class: 'nav' }, up, down));
945
+ }
946
+ const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)];
947
+ const snippet = el ? (el.tagName === 'IMG' ? el.getAttribute('alt') || '' : this.orig(el).text) : '';
948
+ const title = h('div', { class: 'title', 'data-j': 'title' }, snippet ? `${kind} "${snippet.slice(0, 40)}"` : kind);
949
+ const pill = h('span', { class: 'pill', 'data-j': 'matches' });
950
+ const header = h('div', { class: 'hd' }, crumbs, h('div', { class: 'tr' }, title, pill));
951
+
952
+ // Body: action tiles, the action's fields, the CSS selector.
953
+ const tiles = h('div', { class: 'tiles', role: 'radiogroup', 'aria-label': t.whatToDo });
954
+ const mine = this.editsOn(el);
955
+ for (const a of ACTIONS) {
956
+ const on = d.action === a;
957
+ const enabled = on || this.enabled(a, el);
958
+ const off = !enabled ? (a === 'link' ? t.notLink : a === 'image' ? t.notImage : t.noText) : '';
959
+ // The element's own edit of this kind, if it has one: the tile opens it (an element can carry several edits).
960
+ const own = mine.filter((e) => ACTION_OF[e.operation] === a).pop();
961
+ const b = h('button', { class: a === 'slot' ? 'tile slot' : 'tile', type: 'button', role: 'radio', 'aria-checked': String(on), disabled: !enabled, 'data-e': !!own, 'data-j': `action-${a}` }, icon(ACTION_ICON[a]), h('span', null, h('b', null, t[ACTION_LABEL[a]]), off ? h('small', null, off) : null));
962
+ b.addEventListener('click', () => {
963
+ if (!this.draft || this.draft.action === a) return;
964
+ if (own) this.draft = this.draftOf(own);
965
+ else {
966
+ // Another kind of change: a new edit next to the one open (that one stays as it is).
967
+ if (el && this.draft.editingId) this.draft = this.newDraft(el, this.draft.selector);
968
+ this.draft.action = a;
969
+ this.draft.touched = true;
970
+ if ((a === 'link' || a === 'image') && el) this.draft.url = (a === 'image' ? this.orig(el).src : this.orig(el).href) || '';
971
+ }
972
+ this.renderPanel();
973
+ this.renderPreview();
273
974
  });
274
- row.appendChild(b);
975
+ tiles.appendChild(b);
275
976
  }
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);
977
+ const fields = h('div', { 'data-j': 'fields' });
978
+ const saveBtn = h('button', { class: 'save', type: 'button', 'data-j': 'save' });
979
+ const refresh = () => {
980
+ const valid = !!this.draftEdit(d);
981
+ saveBtn.disabled = !valid;
982
+ saveBtn.textContent = fill(t.save, { action: t[ACTION_LABEL[d.action]] });
983
+ const n = pageMatches(d.selector).length;
984
+ pill.className = `pill ${n === 1 ? 'ok' : n > 1 ? 'many' : 'none'}`;
985
+ pill.textContent = n === 1 ? t.matchOne : n > 1 ? fill(t.matchMany, { n }) : t.matchNone;
986
+ };
987
+ const changed = () => {
988
+ d.touched = true;
989
+ refresh();
990
+ this.renderPreview();
991
+ };
992
+ this.renderFields(fields, d, el, changed);
993
+
994
+ 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));
995
+ cssToggle.addEventListener('click', () => {
996
+ this.showCss = !this.showCss;
997
+ this.renderPanel();
998
+ });
999
+ const body = h('div', { class: 'bd' }, h('span', { class: 'lbl' }, t.whatToDo), tiles, fields, cssToggle);
1000
+ if (this.showCss) {
1001
+ const input = h('input', { class: 'mono', dir: 'ltr', 'aria-label': t.css, spellcheck: 'false', 'data-j': 'selector' });
1002
+ input.value = d.selector;
1003
+ const note = h('div', { class: 'help2' });
1004
+ const sync = () => {
1005
+ const ok = isSafeSelector(d.selector);
1006
+ note.className = ok ? 'help2' : 'err';
1007
+ note.textContent = !d.selector.trim() ? t.noSelector : ok ? fill(t.cssHelp, { n: pageMatches(d.selector).length }) : t.cssBad;
1008
+ };
1009
+ input.addEventListener('input', () => {
1010
+ d.selector = input.value;
1011
+ sync();
1012
+ changed();
1013
+ });
1014
+ sync();
1015
+ body.append(h('div', { class: 'mt' }, input, note));
1016
+ }
1017
+
1018
+ const cancel = h('button', { class: 'cancel', type: 'button', 'data-j': 'cancel' }, t.cancel);
1019
+ cancel.addEventListener('click', () => this.cancel());
1020
+ saveBtn.addEventListener('click', () => this.save());
1021
+ const panel = h('aside', { class: 'panel', 'data-j': 'panel', role: 'dialog', 'aria-label': t.whatToDo }, header, body, h('div', { class: 'ft' }, cancel, saveBtn));
1022
+ refresh();
1023
+ this.panel = panel;
1024
+ this.wrap.appendChild(panel);
1025
+ }
1026
+
1027
+ /** One field set per action. Typing updates the draft and the page, never re-renders the field typed in. */
1028
+ private renderFields(box: HTMLElement, d: Draft, el: Element | null, changed: () => void): void {
1029
+ const t = this.t;
1030
+ box.textContent = '';
1031
+ this.closeOverlay = null;
1032
+ const was = (v: string | null) => (v ? h('span', { class: 'was', title: v }, fill(t.was, { value: v.slice(0, 60) })) : null);
1033
+ if (d.action === 'text') {
1034
+ let code: HTMLTextAreaElement | null = null;
1035
+ const textChanged = (v: string) => {
1036
+ d.text = v;
1037
+ if (code && code !== this.root?.activeElement) code.value = v;
1038
+ changed();
1039
+ };
1040
+ // Each pill has its own "If <field> is missing" (a click on it): the `| default:` of that variable only.
1041
+ const field = liquidField({
1042
+ label: t.newText,
1043
+ rawNote: t.rawNote,
1044
+ root: this.root,
1045
+ onChange: textChanged,
1046
+ labelOf: (p) => this.labelOf(p),
1047
+ fallback: { title: t.fallbackFor, help: t.fallbackHelp, bad: t.fallbackBad, done: t.fallbackDone },
1048
+ });
1049
+ field.set(d.text);
1050
+ const add = (v: Var) => field.insert(pathTag(v.path));
1051
+ const vars: Var[] = this.ctx.attributes.length ? this.ctx.attributes : ['firstName', 'lastName'].map((n) => ({ path: `user.${n}`, label: n, group: '' }));
1052
+ const common = COMMON_VARS.map((p) => vars.filter((v) => v.path === p)[0]).filter(Boolean);
1053
+ const shown = common.concat(vars.filter((v) => common.indexOf(v) < 0)).slice(0, CHIPS);
1054
+ const chips = h('div', { class: 'chips', 'data-j': 'chips' }, h('span', null, t.insert));
1055
+ const picker = h('div', { class: 'pk', 'data-j': 'var-picker', hidden: true });
1056
+ for (const v of shown) {
1057
+ const c = h('button', { class: 'vc', type: 'button', title: v.path, 'data-j': 'chip' }, v.label);
1058
+ c.addEventListener('mousedown', (e) => e.preventDefault()); // the caret stays in the text
1059
+ c.addEventListener('click', () => add(v));
1060
+ chips.appendChild(c);
1061
+ }
1062
+ if (vars.length > shown.length) {
1063
+ // "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);
1065
+ const search = h('input', { dir: 'auto', 'aria-label': t.search, placeholder: t.search, 'data-j': 'var-search', role: 'combobox', 'aria-expanded': 'true' });
1066
+ const listEl = h('div', { role: 'listbox', 'aria-label': t.insert, 'data-j': 'var-list' });
1067
+ picker.append(search, listEl);
1068
+ let hits: Var[] = [];
1069
+ let at = 0;
1070
+ const close = () => {
1071
+ if (picker.hidden) return false;
1072
+ picker.hidden = true;
1073
+ more.setAttribute('aria-expanded', 'false');
1074
+ return true;
1075
+ };
1076
+ const pick = (v: Var | undefined) => {
1077
+ if (!v) return;
1078
+ close();
1079
+ add(v);
1080
+ };
1081
+ const draw = () => {
1082
+ const q = search.value.trim().toLowerCase();
1083
+ hits = vars.filter((v) => !q || `${v.label} ${v.path} ${v.group}`.toLowerCase().indexOf(q) >= 0).slice(0, 200);
1084
+ at = Math.min(at, Math.max(hits.length - 1, 0));
1085
+ listEl.textContent = '';
1086
+ if (!hits.length) listEl.appendChild(h('div', { class: 'g' }, t.noMatch));
1087
+ let group: string | null = null;
1088
+ hits.forEach((v, i) => {
1089
+ if (v.group !== group) {
1090
+ group = v.group;
1091
+ if (group) listEl.appendChild(h('div', { class: 'g', role: 'presentation' }, group));
1092
+ }
1093
+ const o = h('div', { class: 'o', role: 'option', id: `jv${i}`, 'aria-selected': String(i === at), 'data-j': 'var-option' }, h('span', { dir: 'auto' }, v.label), h('code', { dir: 'ltr' }, v.path));
1094
+ o.addEventListener('mousedown', (e) => e.preventDefault());
1095
+ o.addEventListener('click', () => pick(v));
1096
+ listEl.appendChild(o);
1097
+ });
1098
+ search.setAttribute('aria-activedescendant', hits.length ? `jv${at}` : '');
1099
+ };
1100
+ search.addEventListener('input', () => {
1101
+ at = 0;
1102
+ draw();
1103
+ });
1104
+ search.addEventListener('keydown', (e) => {
1105
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
1106
+ e.preventDefault();
1107
+ at = (at + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % Math.max(hits.length, 1);
1108
+ draw();
1109
+ const o = listEl.querySelector('[aria-selected="true"]') as HTMLElement | null;
1110
+ if (o && o.scrollIntoView) o.scrollIntoView({ block: 'nearest' });
1111
+ } else if (e.key === 'Enter') {
1112
+ e.preventDefault();
1113
+ pick(hits[at]);
1114
+ }
1115
+ });
1116
+ more.addEventListener('mousedown', (e) => e.preventDefault());
1117
+ more.addEventListener('click', () => {
1118
+ if (close()) return;
1119
+ picker.hidden = false;
1120
+ more.setAttribute('aria-expanded', 'true');
1121
+ search.value = '';
1122
+ at = 0;
1123
+ draw();
1124
+ search.focus();
1125
+ });
1126
+ this.closeOverlay = () => field.closePop() || close();
1127
+ chips.appendChild(more);
1128
+ }
1129
+ // "Liquid code": the stored text itself, for developers; editing it redraws the pills.
1130
+ const toggle = h('button', { class: 'css', type: 'button', 'aria-expanded': String(this.showLiquid), 'data-j': 'liquid-toggle' }, icon('code', 13), t.liquid, icon(this.showLiquid ? 'up' : 'down', 10));
1131
+ toggle.addEventListener('click', () => {
1132
+ this.showLiquid = !this.showLiquid;
1133
+ this.renderPanel();
1134
+ });
1135
+ if (!this.closeOverlay) this.closeOverlay = () => field.closePop();
1136
+ box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, t.newText), was(el ? this.orig(el).text : null)), field.el, chips, picker, toggle);
1137
+ if (this.showLiquid) {
1138
+ const ta = h('textarea', { class: 'mono', rows: '3', dir: 'ltr', spellcheck: 'false', 'aria-label': t.liquid, 'data-j': 'liquid' });
1139
+ ta.value = d.text;
1140
+ ta.addEventListener('input', () => {
1141
+ field.set(ta.value);
1142
+ textChanged(ta.value);
1143
+ });
1144
+ code = ta;
1145
+ box.appendChild(h('div', { class: 'mt' }, ta));
1146
+ }
1147
+ } else if (d.action === 'link' || d.action === 'image') {
1148
+ const input = h('input', { type: 'url', dir: 'ltr', inputmode: 'url', placeholder: 'https://', 'data-j': 'url', 'aria-label': d.action === 'link' ? t.newLink : t.newImage });
1149
+ input.value = d.url;
1150
+ const err = h('div', { class: 'err' });
1151
+ const check = () => (err.textContent = d.url.trim() && !isSafeEditUrl(d.url) ? t.urlBad : '');
1152
+ input.addEventListener('input', () => {
1153
+ d.url = input.value;
1154
+ check();
1155
+ changed();
1156
+ });
1157
+ check();
1158
+ const before = el ? (d.action === 'image' ? this.orig(el).src : this.orig(el).href) : null;
1159
+ box.append(h('div', { class: 'fr' }, h('label', { class: 'lbl' }, d.action === 'link' ? t.newLink : t.newImage), was(before)), input, err);
1160
+ } else if (d.action === 'hide') {
1161
+ const kind = t[el ? kindKey(el.tagName) : kindKey(d.selector, true)].toLowerCase();
1162
+ box.appendChild(h('div', { class: 'note', 'data-j': 'hide-note' }, fill(t.hideNote, { kind })));
1163
+ } else {
1164
+ const input = h('input', { class: 'slotin', dir: 'auto', 'data-j': 'slot-name', 'aria-label': t.slotName, maxlength: '80' });
1165
+ input.value = d.slotName;
1166
+ const saved = h('span', { class: 'key', 'data-j': 'slot-key' });
1167
+ const help = h('div', { class: 'help2' });
1168
+ const sync = () => {
1169
+ const key = slugify(d.slotName);
1170
+ saved.textContent = key || '-';
1171
+ help.textContent = '';
1172
+ help.append(`${t.savedAs} `, saved, key ? '' : ` · ${t.slotEmpty}`);
1173
+ };
1174
+ input.addEventListener('input', () => {
1175
+ d.slotName = input.value;
1176
+ sync();
1177
+ changed();
1178
+ });
1179
+ sync();
1180
+ box.append(h('label', { class: 'lbl' }, t.slotName), input, help);
1181
+ if (this.ctx.placements.length) {
1182
+ const chips = h('div', { class: 'chips', 'data-j': 'placements' });
1183
+ for (const p of this.ctx.placements.slice(0, 12)) {
1184
+ const c = h('button', { class: 'vc', type: 'button', title: p.name || p.key, 'data-j': 'placement' }, p.key);
1185
+ c.addEventListener('click', () => {
1186
+ d.slotName = p.key;
1187
+ input.value = p.key;
1188
+ sync();
1189
+ changed();
1190
+ });
1191
+ chips.appendChild(c);
1192
+ }
1193
+ box.appendChild(chips);
1194
+ }
1195
+ box.appendChild(h('div', { class: 'help2' }, t.slotHelp));
1196
+ const seg = h('div', { class: 'seg', role: 'radiogroup', 'aria-label': t.where, 'data-j': 'positions' });
1197
+ for (const [pos, label] of POSITIONS) {
1198
+ const b = h('button', { type: 'button', role: 'radio', 'aria-checked': String(d.position === pos), 'data-j': `pos-${pos}` }, t[label]);
1199
+ b.addEventListener('click', () => {
1200
+ d.position = pos;
1201
+ for (const x of Array.from(seg.children)) x.setAttribute('aria-checked', String(x === b));
1202
+ changed();
1203
+ });
1204
+ seg.appendChild(b);
1205
+ }
1206
+ box.append(h('div', { class: 'mt' }, h('span', { class: 'lbl' }, t.where), seg));
1207
+ // A saved slot: what fills it, from the dashboard (the key as saved, not as being typed).
1208
+ const savedEdit = this.ctx.openSlot && d.editingId ? this.edits.filter((e) => e.id === d.editingId)[0] : undefined;
1209
+ const key = savedEdit && savedEdit.placementKey;
1210
+ if (key) {
1211
+ const camps = (this.ctx.placements.filter((p) => p.key === key)[0] || { campaigns: [] as SlotCampaign[] }).campaigns;
1212
+ const sec = h('div', { class: 'mt slotc', 'data-j': 'slot-content' });
1213
+ const link = (label: string, j: string, id?: string) => {
1214
+ const b = h('button', { class: 'lnk', type: 'button', 'data-j': j }, label);
1215
+ b.addEventListener('click', () => this.openSlot(key, id));
1216
+ return b;
1217
+ };
1218
+ if (!camps.length) sec.appendChild(link(t.slotCreate, 'slot-create'));
1219
+ else {
1220
+ sec.appendChild(h('span', { class: 'lbl' }, t.slotIn));
1221
+ for (const c of camps) sec.appendChild(link(c.statusLabel || c.status ? `${c.name} (${c.statusLabel || c.status})` : c.name, 'slot-campaign', c.id));
1222
+ sec.appendChild(link(t.slotAddAnother, 'slot-add'));
1223
+ }
1224
+ box.appendChild(sec);
294
1225
  }
295
- return false;
296
1226
  }
297
- this.send(msg as unknown as Record<string, unknown>);
298
- this.unselect();
299
- return true;
300
1227
  }
301
1228
  }