@accelerated-agency/visual-editor 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/vite.cjs +134 -33
  2. package/dist/vite.js +134 -33
  3. package/package.json +1 -1
package/dist/vite.cjs CHANGED
@@ -12,6 +12,7 @@ var path__default = /*#__PURE__*/_interopDefault(path);
12
12
 
13
13
  // src/visualEditorProxyPlugin.ts
14
14
  var popupHideCss = `<style id="__ce_popup_hide">#CybotCookiebotDialog,#CybotCookiebotDialogBodyUnderlay,#onetrust-consent-sdk,#onetrust-banner-sdk,.cc-window,.cc-banner,.cc-overlay,#cookie-notice,#cookie-banner,#cookie-consent,.cookie-notice,.cookie-banner,.cookie-consent,.cookie-popup,.cookie-bar,.cookie-message,.cookie-alert,.gdpr-banner,.gdpr-consent,.gdpr-popup,.gdpr-overlay,#gdpr-consent,#gdpr-banner,.consent-banner,.consent-popup,.consent-overlay,#consent-banner,#consent-popup,[class*="cookie-consent"],[class*="cookie-banner"],[class*="cookie-notice"],[class*="CookieConsent"],[class*="CookieBanner"],[id*="cookie-consent"],[id*="cookie-banner"],[id*="cookie-notice"],[aria-label*="cookie" i],[aria-label*="consent" i],.klaro,.klaro .cookie-modal,#usercentrics-root,.trustarc-banner,#truste-consent-track,#hs-eu-cookie-confirmation,.osano-cm-window,.osano-cm-dialog,.evidon-banner,#_evidon_banner,.js-cookie-consent,.cookie-disclaimer,.shopify-section-cookies,#shopify-section-cookies,#shopify-pc__banner,#shopify-pc__modal,.privacy-banner,.privacy-popup,[data-testid="cookie-banner"],[data-testid="consent-banner"],.amgdprcookie-bar-container,[data-amcookie-js="bar"],.amgdprjs-bar-template,.amgdprcookie-modal-container,.amgdprcookie-modal-overlay,#cmplz-cookiebanner-container,.cmplz-cookiebanner,#iubenda-cs-banner,.iubenda-cs-container,#qc-cmp2-container,.qc-cmp2-consent-info,#didomi-host,.didomi-popup-container,.didomi-notice,#termly-code-snippet-support,[class*="termly"],[class*="gdprcookie"],[class*="amgdpr"],[id*="gdpr-cookie"],[class*="cookie-modal"],[id*="cookie-modal"],[class*="cookieConsent"],[id*="cookieConsent"],.klaviyo-form,.klaviyo-modal,.klaviyo-popup,[class*="klaviyo"],.privy-popup,.privy-flyout,[id*="privy"],#PopupSignupForm,.popup-signup,.newsletter-popup,.newsletter-modal,[class*="newsletter-popup"],[class*="newsletter-modal"],[id*="newsletter-popup"],.email-popup,.email-modal,[class*="email-popup"],[class*="email-modal"],.signup-popup,.signup-modal,[class*="signup-popup"],[class*="signup-modal"],.subscribe-popup,.subscribe-modal,[class*="subscribe-popup"],#mc_embed_signup,.mc-modal,.mc-banner,.mc-closeModal,.omniconvert-popup,[class*="omniconvert"],.optinmonster-popup,[id*="om-"][class*="campaign"],.sumo-overlay,.sumome-overlay,[class*="sumome"],.hustle-modal,.hustle-popup,[class*="hustle-"],.popup-overlay,.popup-modal,.modal-overlay,[class*="exit-intent"],[class*="exitintent"],.wheelio-popup,[class*="wheelio"],.spin-wheel-popup,.justuno-popup,[class*="justuno"],.wisepops,.wisepops-overlay,[class*="wisepops"],.elegantmodal,.elegant-popup,#zipify-popup,[class*="zipify"],.age-gate,.age-verification,.age-popup,[class*="age-gate"],[class*="age-verif"],[class*="popup-overlay"],[class*="modal-overlay"],[class*="popup-backdrop"]{display:none!important;visibility:hidden!important;opacity:0!important;pointer-events:none!important;height:0!important;overflow:hidden!important;}body.klaviyo-open,body.modal-open,body.popup-open,body.no-scroll,body.noscroll{overflow:auto!important;position:static!important;}</style>`;
15
+ var consentAllowCss = `<style id="__ce_consent_allow">#CybotCookiebotDialog,#CybotCookiebotDialogBodyUnderlay,#onetrust-consent-sdk,#onetrust-banner-sdk,.cc-window,.cc-banner,.cc-overlay,#cookie-notice,#cookie-banner,#cookie-consent,.cookie-notice,.cookie-banner,.cookie-consent,.cookie-popup,.cookie-bar,.cookie-message,.cookie-alert,.gdpr-banner,.gdpr-consent,.gdpr-popup,.gdpr-overlay,#gdpr-consent,#gdpr-banner,.consent-banner,.consent-popup,.consent-overlay,#consent-banner,#consent-popup,[class*="cookie-consent"],[class*="cookie-banner"],[class*="cookie-notice"],[class*="CookieConsent"],[class*="CookieBanner"],[id*="cookie-consent"],[id*="cookie-banner"],[id*="cookie-notice"],[aria-label*="cookie" i],[aria-label*="consent" i],.klaro,.klaro .cookie-modal,#usercentrics-root,.trustarc-banner,#truste-consent-track,#hs-eu-cookie-confirmation,.osano-cm-window,.osano-cm-dialog,.evidon-banner,#_evidon_banner,.js-cookie-consent,.cookie-disclaimer,.shopify-section-cookies,#shopify-section-cookies,#shopify-pc__banner,#shopify-pc__modal,.privacy-banner,.privacy-popup,[data-testid="cookie-banner"],[data-testid="consent-banner"],.amgdprcookie-bar-container,[data-amcookie-js="bar"],.amgdprjs-bar-template,.amgdprcookie-modal-container,.amgdprcookie-modal-overlay,#cmplz-cookiebanner-container,.cmplz-cookiebanner,#iubenda-cs-banner,.iubenda-cs-container,#qc-cmp2-container,.qc-cmp2-consent-info,#didomi-host,.didomi-popup-container,.didomi-notice,#termly-code-snippet-support,[class*="termly"],[class*="gdprcookie"],[class*="amgdpr"],[id*="gdpr-cookie"],[class*="cookie-modal"],[id*="cookie-modal"],[class*="cookieConsent"],[id*="cookieConsent"]{display:revert!important;visibility:visible!important;opacity:1!important;pointer-events:auto!important;height:auto!important;overflow:visible!important;}</style>`;
15
16
  var AI_SYSTEM_PROMPT = `You are a CRO expert. Return JSON only with: hypothesis, mutations, summary. Keep 2-6 precise mutations and only valid selectors from snapshot.`;
16
17
  var BRIDGE_SCRIPT = `(function(){if(window.__CONVERSION_BRIDGE_LOADED__)return;window.__CONVERSION_BRIDGE_LOADED__=true;var CHANNEL='conversion-editor';var highlightEl=null;function send(payload){window.parent.postMessage({channel:CHANNEL,payload:payload},'*');}function qs(selector){try{return document.querySelector(selector);}catch(_){return null;}}function getSelector(el){if(!el||el.nodeType!==1)return'';if(el.id)return'#'+CSS.escape(el.id);var parts=[];var current=el;var depth=0;while(current&&current.nodeType===1&&depth<5){var part=current.tagName.toLowerCase();if(current.classList&&current.classList.length){part+='.'+Array.from(current.classList).slice(0,2).map(function(c){return CSS.escape(c);}).join('.');}var parent=current.parentElement;if(parent){var siblings=Array.from(parent.children).filter(function(s){return s.tagName===current.tagName;});if(siblings.length>1)part+=':nth-of-type('+(siblings.indexOf(current)+1)+')';}parts.unshift(part);current=parent;depth+=1;}return parts.join(' > ');}function payloadOf(el){var rect=el.getBoundingClientRect();var style=window.getComputedStyle(el);return{selector:getSelector(el),tagName:el.tagName.toLowerCase(),textContent:(el.textContent||'').trim().slice(0,500),computedStyles:{color:style.color,backgroundColor:style.backgroundColor,fontSize:style.fontSize,fontWeight:style.fontWeight,lineHeight:style.lineHeight,display:style.display},rect:{top:rect.top,left:rect.left,width:rect.width,height:rect.height}};}function applyMutation(m){var el=qs(m.selector);if(!el)return;switch(m.action){case'setStyle':if(m.property)el.style[m.property]=m.value;break;case'setText':el.textContent=m.value;break;case'setHTML':el.innerHTML=m.value;break;case'setAttribute':if(m.property)el.setAttribute(m.property,m.value);break;case'hide':el.style.display='none';break;case'show':el.style.display='';break;case'insertHTML':if(m.position)el.insertAdjacentHTML(m.position,m.value||'');break;case'insertSection':if(m.position)el.insertAdjacentHTML(m.position,m.sectionHtml||m.value||'');break;case'reorderElement':if(!m.targetSelector)break;var target=qs(m.targetSelector);if(!target||!target.parentNode||!el.parentNode)break;if(m.insertPosition==='before')target.parentNode.insertBefore(el,target);else target.parentNode.insertBefore(el,target.nextSibling);break;default:break;}}function revertMutation(m){var el=qs(m.selector);if(!el)return;switch(m.action){case'setStyle':if(m.property)el.style[m.property]=m.previous||'';break;case'setText':el.textContent=m.previous||'';break;case'setHTML':el.innerHTML=m.previous||'';break;case'setAttribute':if(m.property){if(m.previous!=null)el.setAttribute(m.property,m.previous);else el.removeAttribute(m.property);}break;case'hide':case'show':el.style.display=m.previous||'';break;default:break;}}function captureSnapshot(){var elements=Array.from(document.querySelectorAll('h1,h2,h3,p,button,a,input,select,img,section,div')).slice(0,700).map(function(el){var rect=el.getBoundingClientRect();var cs=window.getComputedStyle(el);return{selector:getSelector(el),parentSelector:el.parentElement?getSelector(el.parentElement):null,tagName:el.tagName.toLowerCase(),textContent:(el.textContent||'').trim().slice(0,300),attributes:Array.from(el.attributes||[]).reduce(function(acc,a){acc[a.name]=a.value;return acc;},{}),computedStyles:{color:cs.color,backgroundColor:cs.backgroundColor,fontSize:cs.fontSize,fontWeight:cs.fontWeight,display:cs.display},childrenCount:el.children?el.children.length:0,aboveFold:rect.top<window.innerHeight,depth:(function(){var d=0,p=el.parentElement;while(p&&d<25){d++;p=p.parentElement;}return d;})()};});send({type:'snapshotCaptured',snapshot:{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},elements:elements}});}function captureTree(){function toNode(el,depth){var rect=el.getBoundingClientRect();var tag=el.tagName.toLowerCase();var type='generic';if(tag==='section')type='section';else if(tag==='img')type='image';else if(tag==='a')type='link';else if(tag==='button')type='button';else if(tag==='form')type='form';else if(['p','h1','h2','h3','h4','h5','h6','span'].indexOf(tag)>=0)type='text';else if(['div','main','article','aside','header','footer','nav'].indexOf(tag)>=0)type='container';var children=Array.from(el.children||[]).slice(0,50).map(function(c){return toNode(c,depth+1);});return{id:getSelector(el),selector:getSelector(el),tagName:tag,label:(el.getAttribute('aria-label')||el.getAttribute('id')||el.className||tag).toString().slice(0,80),type:type,children:children,depth:depth,isAboveFold:rect.top<window.innerHeight,rect:{top:rect.top,left:rect.left,width:rect.width,height:rect.height}};}send({type:'pageTreeCaptured',tree:[toNode(document.body,0)]});}window.addEventListener('message',function(e){var msg=e.data;if(!msg||msg.channel!==CHANNEL||!msg.payload)return;var p=msg.payload;switch(p.type){case'ping':send({type:'pong'});break;case'applyMutation':applyMutation(p.mutation);break;case'applyMutationBatch':(p.mutations||[]).forEach(applyMutation);break;case'revert':revertMutation(p.mutation);break;case'clearAllMutations':window.location.reload();break;case'captureSnapshot':captureSnapshot();break;case'validateSelectors':send({type:'selectorsValidated',results:(p.selectors||[]).map(function(s){var el=qs(s);return{selector:s,found:!!el,tagName:el?el.tagName.toLowerCase():null};})});break;case'scrollToElement':case'selectElement':var target=qs(p.selector);if(target){target.scrollIntoView({behavior:'smooth',block:'center'});send({type:'elementSelected',element:payloadOf(target)});}break;case'hoverElement':var h=qs(p.selector);if(h){if(highlightEl)highlightEl.style.outline='';h.style.outline='2px solid #3b82f6';highlightEl=h;}break;case'capturePageTree':captureTree();break;default:break;}});document.addEventListener('click',function(e){var el=e.target;if(!(el instanceof Element))return;send({type:'elementSelected',element:payloadOf(el)});},true);send({type:'bridgeReady'});})();`;
17
18
  function buildVvvebEditorHtml() {
@@ -999,6 +1000,7 @@ var selectedEl = null;
999
1000
  var selectedElFingerprint = '';
1000
1001
  var selectedElRecoverMisses = 0;
1001
1002
  var MAX_SELECTED_RECOVER_MISSES = 12;
1003
+ var isDeselectingSelection = false;
1002
1004
  var suppressClickUntil = 0;
1003
1005
  var dragAttachDoc = null;
1004
1006
  var currentMainTab = 'design';
@@ -1027,6 +1029,8 @@ var iframeDocLoadingListeners = null;
1027
1029
  // Each entry: {selector, label, cssProp, value, targetEl}
1028
1030
  // cssProp is null for non-CSS attributes (href, alt, classes\u2026)
1029
1031
  var stateChanges = [];
1032
+ /** Per-variation unsaved Design-tab state changes (input edits not yet finalized). */
1033
+ var stateChangesByVarId = {};
1030
1034
  /** Pre-apply DOM snapshots for granular + body changesets (used when removing History rows) */
1031
1035
  var appliedChangesetSnapshots = {};
1032
1036
  /** Canonical JSON fingerprints of persisted changesets per variation (last load / finalize) */
@@ -1041,13 +1045,49 @@ function endSuppressIframeMutationDirty() {
1041
1045
  suppressIframeMutationDirty = Math.max(0, suppressIframeMutationDirty - 1);
1042
1046
  }
1043
1047
 
1048
+ function commitStateChangesForActiveVariation() {
1049
+ if (!activeVarId) return;
1050
+ stateChangesByVarId[activeVarId] = (stateChanges || []).slice();
1051
+ }
1052
+
1053
+ function loadStateChangesForActiveVariation() {
1054
+ if (!activeVarId) {
1055
+ stateChanges = [];
1056
+ return;
1057
+ }
1058
+ stateChanges = (stateChangesByVarId[activeVarId] || []).slice();
1059
+ }
1060
+
1044
1061
  function recoverSelectedElement(forceDeselectOnMiss) {
1045
1062
  if (selectedEl && selectedEl.ownerDocument && selectedEl.ownerDocument.contains(selectedEl)) {
1046
1063
  selectedElRecoverMisses = 0;
1047
1064
  return selectedEl;
1048
1065
  }
1049
1066
  if (!selectedElFingerprint) {
1050
- if (forceDeselectOnMiss) deselectElement();
1067
+ // Nothing to recover; clear stale reference without calling deselectElement
1068
+ // (which can recurse back through toolbar updates during rapid DOM churn).
1069
+ if (forceDeselectOnMiss && selectedEl) {
1070
+ beginSuppressIframeMutationDirty();
1071
+ try {
1072
+ try { selectedEl.classList.remove('vve-selected'); } catch(_) {}
1073
+ selectedEl = null;
1074
+ selectedElRecoverMisses = 0;
1075
+ } finally {
1076
+ endSuppressIframeMutationDirty();
1077
+ }
1078
+ var noSel = document.getElementById('no-sel');
1079
+ if (noSel) noSel.style.display = '';
1080
+ var elInfo = document.getElementById('el-info');
1081
+ if (elInfo) elInfo.style.display = 'none';
1082
+ var rp = document.getElementById('rp-accordion');
1083
+ if (rp) rp.style.display = 'none';
1084
+ var bc = document.getElementById('bc-path');
1085
+ if (bc) {
1086
+ bc.textContent = 'No element selected';
1087
+ bc.style.color = 'var(--text-3)';
1088
+ }
1089
+ syncDomTreeSelection();
1090
+ }
1051
1091
  return null;
1052
1092
  }
1053
1093
  var iframe = document.getElementById('iframeId');
@@ -1067,7 +1107,29 @@ function recoverSelectedElement(forceDeselectOnMiss) {
1067
1107
  }
1068
1108
  selectedElRecoverMisses += 1;
1069
1109
  if (forceDeselectOnMiss && selectedElRecoverMisses >= MAX_SELECTED_RECOVER_MISSES) {
1070
- deselectElement();
1110
+ beginSuppressIframeMutationDirty();
1111
+ try {
1112
+ if (selectedEl) {
1113
+ try { selectedEl.classList.remove('vve-selected'); } catch(_) {}
1114
+ }
1115
+ selectedEl = null;
1116
+ selectedElFingerprint = '';
1117
+ selectedElRecoverMisses = 0;
1118
+ } finally {
1119
+ endSuppressIframeMutationDirty();
1120
+ }
1121
+ var noSel2 = document.getElementById('no-sel');
1122
+ if (noSel2) noSel2.style.display = '';
1123
+ var elInfo2 = document.getElementById('el-info');
1124
+ if (elInfo2) elInfo2.style.display = 'none';
1125
+ var rp2 = document.getElementById('rp-accordion');
1126
+ if (rp2) rp2.style.display = 'none';
1127
+ var bc2 = document.getElementById('bc-path');
1128
+ if (bc2) {
1129
+ bc2.textContent = 'No element selected';
1130
+ bc2.style.color = 'var(--text-3)';
1131
+ }
1132
+ syncDomTreeSelection();
1071
1133
  }
1072
1134
  return null;
1073
1135
  }
@@ -1162,6 +1224,10 @@ function setMode(mode) {
1162
1224
  if (mode === 'navigate') {
1163
1225
  setDragHandleActive(false);
1164
1226
  deselectElement();
1227
+ } else if (mode === 'editor') {
1228
+ // Re-bind interactions immediately when coming back from navigate mode.
1229
+ // This avoids waiting for delayed iframe readiness/load retries.
1230
+ syncIframeInteractions('mode-editor-toggle');
1165
1231
  }
1166
1232
  updateSelectionToolbar();
1167
1233
  }
@@ -1328,6 +1394,7 @@ function logChange(selector, inputId, value, targetEl, originalValue) {
1328
1394
  if (idx >= 0) { stateChanges[idx] = entry; } else { stateChanges.push(entry); }
1329
1395
  }
1330
1396
  if (currentMainTab === 'states') renderStatesTab();
1397
+ commitStateChangesForActiveVariation();
1331
1398
  recomputeEditorDirty();
1332
1399
  }
1333
1400
 
@@ -1434,6 +1501,7 @@ function removeStateChange(idx) {
1434
1501
  revertChangeOnDom(change);
1435
1502
  syncDesignInput(change);
1436
1503
  stateChanges.splice(idx, 1);
1504
+ commitStateChangesForActiveVariation();
1437
1505
  renderStatesTab();
1438
1506
  recomputeEditorDirty();
1439
1507
  }
@@ -1444,6 +1512,7 @@ function clearAllStates() {
1444
1512
  syncDesignInput(c);
1445
1513
  });
1446
1514
  stateChanges = [];
1515
+ commitStateChangesForActiveVariation();
1447
1516
  renderStatesTab();
1448
1517
  recomputeEditorDirty();
1449
1518
  }
@@ -1818,7 +1887,9 @@ function handleLoadExperiment(data) {
1818
1887
  experimentData = data;
1819
1888
  variations = Array.isArray(data.variations) ? data.variations : [];
1820
1889
  var prevActive = activeVarId;
1890
+ commitStateChangesForActiveVariation();
1821
1891
  activeVarId = pickActiveVariationIdForLoad(data, variations, prevActive, true);
1892
+ loadStateChangesForActiveVariation();
1822
1893
  writePersistedActiveVariationId(activeVarId);
1823
1894
  renderVariationTabs();
1824
1895
  var urlBarSkip = document.getElementById('url-bar');
@@ -1841,6 +1912,8 @@ function handleLoadExperiment(data) {
1841
1912
  if (!experimentData || prevKey !== nextKey) {
1842
1913
  varHtmlCache = {};
1843
1914
  sessionStructuralChainRowsByVarId = {};
1915
+ stateChangesByVarId = {};
1916
+ stateChanges = [];
1844
1917
  appliedChangesetSnapshots = {};
1845
1918
  appliedStructuralChangesetKeys = {};
1846
1919
  }
@@ -1848,6 +1921,7 @@ function handleLoadExperiment(data) {
1848
1921
  variations = Array.isArray(data.variations) ? data.variations : [];
1849
1922
  var sameExpPage = prevKey === nextKey;
1850
1923
  activeVarId = pickActiveVariationIdForLoad(data, variations, activeVarId, sameExpPage);
1924
+ loadStateChangesForActiveVariation();
1851
1925
  writePersistedActiveVariationId(activeVarId);
1852
1926
  renderVariationTabs();
1853
1927
 
@@ -2132,7 +2206,7 @@ function loadPage(proxyUrl) {
2132
2206
  resetIframeBindings();
2133
2207
  iframe.style.display = 'block';
2134
2208
  setIframePageLoadingUi(true);
2135
- iframe.src = proxyUrl;
2209
+ iframe.src = appendIframeReloadBust(proxyUrl);
2136
2210
  startIframeContentApplyWatcher(navGen);
2137
2211
  scheduleDomTreeRefresh();
2138
2212
  }
@@ -2171,8 +2245,10 @@ function renderVariationTabs() {
2171
2245
  function switchVariation(varId) {
2172
2246
  if (varId === activeVarId) return;
2173
2247
  saveCurrentVariationHtml();
2248
+ commitStateChangesForActiveVariation();
2174
2249
  clearPendingGranularChangesets();
2175
2250
  activeVarId = varId;
2251
+ loadStateChangesForActiveVariation();
2176
2252
  writePersistedActiveVariationId(varId);
2177
2253
  renderVariationTabs();
2178
2254
  deselectElement();
@@ -2208,6 +2284,7 @@ function switchVariation(varId) {
2208
2284
  }
2209
2285
  } catch(_) {}
2210
2286
  if (currentMainTab === 'history') renderHistoryTab();
2287
+ if (currentMainTab === 'states') renderStatesTab();
2211
2288
  recomputeEditorDirty();
2212
2289
  }
2213
2290
 
@@ -2564,12 +2641,13 @@ function buildPersistedChainSetsForVariation(v) {
2564
2641
  var parsed = parseVariationChangesets(v);
2565
2642
  var base = filterGranularChangesetEntries(parsed);
2566
2643
  var sessionExtra = sessionStructuralChainRowsByVarId[v._id] || [];
2567
- if (v._id !== activeVarId) {
2568
- return mergeGranularChainSets(base, sessionExtra);
2569
- }
2644
+ var sourceStateChanges =
2645
+ v._id === activeVarId
2646
+ ? stateChanges
2647
+ : (stateChangesByVarId[v._id] || []);
2570
2648
  var overlay = [];
2571
- for (var si = 0; si < stateChanges.length; si++) {
2572
- var row = stateChangeToChainSet(stateChanges[si]);
2649
+ for (var si = 0; si < sourceStateChanges.length; si++) {
2650
+ var row = stateChangeToChainSet(sourceStateChanges[si]);
2573
2651
  if (row) overlay.push(row);
2574
2652
  }
2575
2653
  return mergeGranularChainSets(mergeGranularChainSets(base, sessionExtra), overlay);
@@ -2693,24 +2771,31 @@ function selectElement(el) {
2693
2771
  }
2694
2772
  }
2695
2773
 
2696
- function deselectElement() {
2697
- setDragHandleActive(false);
2698
- beginSuppressIframeMutationDirty();
2774
+ function deselectElement(options) {
2775
+ if (isDeselectingSelection) return;
2776
+ isDeselectingSelection = true;
2777
+ var skipToolbarUpdate = !!(options && options.skipToolbarUpdate);
2699
2778
  try {
2700
- if (selectedEl) { try { selectedEl.classList.remove('vve-selected'); } catch(_) {} selectedEl = null; }
2701
- selectedElFingerprint = '';
2702
- selectedElRecoverMisses = 0;
2779
+ setDragHandleActive(false);
2780
+ beginSuppressIframeMutationDirty();
2781
+ try {
2782
+ if (selectedEl) { try { selectedEl.classList.remove('vve-selected'); } catch(_) {} selectedEl = null; }
2783
+ selectedElFingerprint = '';
2784
+ selectedElRecoverMisses = 0;
2785
+ } finally {
2786
+ endSuppressIframeMutationDirty();
2787
+ }
2788
+ document.getElementById('no-sel').style.display = '';
2789
+ document.getElementById('el-info').style.display = 'none';
2790
+ document.getElementById('rp-accordion').style.display = 'none';
2791
+ document.getElementById('bc-path').textContent = 'No element selected';
2792
+ document.getElementById('bc-path').style.color = 'var(--text-3)';
2793
+ switchMainTab('design');
2794
+ if (!skipToolbarUpdate) updateSelectionToolbar();
2795
+ syncDomTreeSelection();
2703
2796
  } finally {
2704
- endSuppressIframeMutationDirty();
2797
+ isDeselectingSelection = false;
2705
2798
  }
2706
- document.getElementById('no-sel').style.display = '';
2707
- document.getElementById('el-info').style.display = 'none';
2708
- document.getElementById('rp-accordion').style.display = 'none';
2709
- document.getElementById('bc-path').textContent = 'No element selected';
2710
- document.getElementById('bc-path').style.color = 'var(--text-3)';
2711
- switchMainTab('design');
2712
- updateSelectionToolbar();
2713
- syncDomTreeSelection();
2714
2799
  }
2715
2800
 
2716
2801
  // \u2500\u2500 Iframe selection chrome, floater toolbar, DOM tree \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
@@ -2961,7 +3046,7 @@ function renderDomTree(filterRaw) {
2961
3046
 
2962
3047
  function labelFor(el) {
2963
3048
  var tag = el.tagName.toLowerCase();
2964
- if (el.id) return tag + '#' + el.id.slice(0, 40);
3049
+ if (el.id != null && el.id !== '') return tag + '#' + String(el.id).slice(0, 40);
2965
3050
  var cn = el.className && typeof el.className === 'string' ? el.className.trim() : '';
2966
3051
  if (cn) {
2967
3052
  var parts = cn.split(/s+/).filter(function(x) { return x.indexOf('vve-') !== 0; }).slice(0, 2).join('.');
@@ -3967,6 +4052,7 @@ document.getElementById('btn-close').addEventListener('click', handleClose);
3967
4052
 
3968
4053
  function handleSave() {
3969
4054
  saveCurrentVariationHtml();
4055
+ commitStateChangesForActiveVariation();
3970
4056
  var updatedVariations = variations.map(function(v) {
3971
4057
  var prevParsed = parseVariationChangesets(v);
3972
4058
  var granularPrev = filterGranularChangesetEntries(prevParsed);
@@ -3987,6 +4073,7 @@ function handleSave() {
3987
4073
  variations = updatedVariations;
3988
4074
  varHtmlCache = {};
3989
4075
  sessionStructuralChainRowsByVarId = {};
4076
+ stateChangesByVarId = {};
3990
4077
  stateChanges = [];
3991
4078
  if (currentMainTab === 'states') renderStatesTab();
3992
4079
  captureBaselineFromVariations(variations);
@@ -4143,18 +4230,28 @@ window.addEventListener('load', function() {
4143
4230
  var iframe = document.getElementById('iframeId');
4144
4231
  iframe.addEventListener('load', function() {
4145
4232
  if (!iframe.src || iframe.src === 'about:blank' || iframe.src === window.location.href) return;
4233
+ // New iframe navigation: always drop bindings tied to the previous document.
4234
+ resetIframeBindings();
4146
4235
  var doc = iframe.contentDocument;
4147
- if (!doc || !doc.body) return;
4236
+ if (!doc) {
4237
+ syncIframeInteractions('iframe-load-no-doc');
4238
+ return;
4239
+ }
4148
4240
  var docUrl = '';
4149
4241
  try { docUrl = String(doc.URL || ''); } catch(_) {}
4150
4242
  // Stale events: src may already be the proxy URL while the document is still
4151
- // about:blank (e.g. src cleared then reset to force reload).
4152
- if (docUrl === 'about:blank') return;
4153
- if (!iframeDocMatchesNavigatedSrc(iframe, doc)) return;
4243
+ // about:blank (e.g. src cleared then reset to force reload). Ask sync path to retry.
4244
+ if (docUrl === 'about:blank') {
4245
+ syncIframeInteractions('iframe-load-about-blank');
4246
+ return;
4247
+ }
4154
4248
  attachIframeLoadingUntilComplete(iframe);
4155
- stopIframeContentApplyWatcher();
4156
- deselectElement();
4157
- applyActiveVariationHtml();
4249
+ if (doc.body && iframeDocMatchesNavigatedSrc(iframe, doc)) {
4250
+ stopIframeContentApplyWatcher();
4251
+ deselectElement();
4252
+ applyActiveVariationHtml();
4253
+ }
4254
+ // Always attempt sync; it has its own readiness checks + retry loop.
4158
4255
  syncIframeInteractions('iframe-load');
4159
4256
  });
4160
4257
 
@@ -4482,7 +4579,7 @@ function createVisualEditorMiddleware(options) {
4482
4579
  }
4483
4580
  html = html.replace(/(href|src|action)="\/(?!\/)/g, `$1="${origin}/`);
4484
4581
  const escapedOrigin = origin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4485
- const proxyBase = `/api/conversion-proxy?password=${encodeURIComponent(password)}&url=`;
4582
+ const proxyBase = `/api/conversion-proxy?__ve_reload=${Date.now()}&password=${encodeURIComponent(password)}&url=`;
4486
4583
  html = html.replace(
4487
4584
  new RegExp(`(href|action)="${escapedOrigin}(/[^"]*)"`, "g"),
4488
4585
  (match, attr, urlPath) => {
@@ -4495,6 +4592,7 @@ function createVisualEditorMiddleware(options) {
4495
4592
  );
4496
4593
  if (html.includes("</head>")) {
4497
4594
  html = html.replace("</head>", `${popupHideCss}
4595
+ ${consentAllowCss}
4498
4596
  </head>`);
4499
4597
  }
4500
4598
  html = html.replace(
@@ -4512,7 +4610,7 @@ var PROXY_PASSWORD=${JSON.stringify(password)};
4512
4610
  window.__CONVERSION_EDITOR_ACTIVE__=true;
4513
4611
  function isSkippable(raw){if(!raw||typeof raw!=="string")return true;return raw.startsWith("data:")||raw.startsWith("blob:")||raw.startsWith("javascript:")||raw.startsWith("#");}
4514
4612
  function toAbsolute(raw){if(isSkippable(raw))return raw;try{var base=raw.startsWith("/")||raw.startsWith("//")?TARGET_ORIGIN:TARGET_PAGE_URL;return new URL(raw,base).toString();}catch(_){return raw;}}
4515
- function toProxy(raw){if(isSkippable(raw))return null;var abs=toAbsolute(raw);if(!abs||typeof abs!=="string")return null;try{var parsed=new URL(abs);if(parsed.origin!==TARGET_ORIGIN)return null;return "/api/conversion-proxy?password="+encodeURIComponent(PROXY_PASSWORD||"")+"&url="+encodeURIComponent(parsed.toString());}catch(_){return null;}}
4613
+ function toProxy(raw){if(isSkippable(raw))return null;var abs=toAbsolute(raw);if(!abs||typeof abs!=="string")return null;try{var parsed=new URL(abs);if(parsed.origin!==TARGET_ORIGIN)return null;return "/api/conversion-proxy?__ve_reload="+Date.now()+"&password="+encodeURIComponent(PROXY_PASSWORD||"")+"&url="+encodeURIComponent(parsed.toString());}catch(_){return null;}}
4516
4614
  var nativeAssign=window.location.assign?window.location.assign.bind(window.location):null;
4517
4615
  var nativeReplace=window.location.replace?window.location.replace.bind(window.location):null;
4518
4616
  function safeNavigate(raw,mode){var abs=toAbsolute(raw);var prox=toProxy(raw);if(!prox){try{console.warn("[conversion-proxy] redirect blocked",{mode:mode,requested:raw,resolved:abs,origin:TARGET_ORIGIN});}catch(_){}return false;}try{console.info("[conversion-proxy] redirect intercepted",{mode:mode,requested:raw,resolved:abs,proxied:prox});if(mode==="replace"&&nativeReplace){nativeReplace(prox);return true;}if(nativeAssign){nativeAssign(prox);return true;}window.location.href=prox;return true;}catch(err){try{console.warn("[conversion-proxy] redirect interception failed",{mode:mode,requested:raw,resolved:abs,proxied:prox,error:err&&err.message?err.message:String(err)});}catch(_){}return false;}}
@@ -4585,6 +4683,9 @@ if(window.fetch){
4585
4683
  }
4586
4684
  if(window.XMLHttpRequest&&window.XMLHttpRequest.prototype&&window.XMLHttpRequest.prototype.open){var _open=window.XMLHttpRequest.prototype.open;window.XMLHttpRequest.prototype.open=function(method,url){try{var u=resolveUrl(String(url));if(u&&isNestedMalformedProxy(u)){arguments[1]=EMPTY_JSON_DATA;}else{arguments[1]=toAbsoluteOriginUrl(url);}}catch(_){}return _open.apply(this,arguments);};}
4587
4685
  if(window.navigator&&typeof window.navigator.sendBeacon==="function"){var _beacon=window.navigator.sendBeacon.bind(window.navigator);window.navigator.sendBeacon=function(url,data){try{if(skipNestedProxyNetwork(String(url)))return true;}catch(_){}return _beacon(url,data);};}
4686
+ function withReloadBust(urlRaw){try{var u=resolveUrl(String(urlRaw||""));if(!u)return null;var p=u.pathname||"";var isRootProxyPath=p==="/api/conversion-proxy"||p.indexOf("/api/conversion-proxy/")===0;if(!isRootProxyPath)return null;u.searchParams.set("__ve_reload",String(Date.now()));return u.toString();}catch(_){return null;}}
4687
+ document.addEventListener("click",function(ev){try{var t=ev&&ev.target;if(!t||!t.closest)return;var a=t.closest("a[href]");if(!a)return;var href=a.getAttribute("href")||a.href;var bust=withReloadBust(href);if(bust)a.setAttribute("href",bust);}catch(_){}},true);
4688
+ document.addEventListener("submit",function(ev){try{var f=ev&&ev.target;if(!f||!f.getAttribute)return;var act=f.getAttribute("action")||"";var bust=withReloadBust(act);if(bust)f.setAttribute("action",bust);}catch(_){}},true);
4588
4689
  if(window.navigator&&window.navigator.serviceWorker&&typeof window.navigator.serviceWorker.register==="function"){window.navigator.serviceWorker.register=function(){return Promise.resolve({scope:"disabled-in-editor-proxy"});};}
4589
4690
  }catch(_){}})();</script>`;
4590
4691
  if (html.includes("</head>")) {
package/dist/vite.js CHANGED
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'url';
4
4
 
5
5
  // src/visualEditorProxyPlugin.ts
6
6
  var popupHideCss = `<style id="__ce_popup_hide">#CybotCookiebotDialog,#CybotCookiebotDialogBodyUnderlay,#onetrust-consent-sdk,#onetrust-banner-sdk,.cc-window,.cc-banner,.cc-overlay,#cookie-notice,#cookie-banner,#cookie-consent,.cookie-notice,.cookie-banner,.cookie-consent,.cookie-popup,.cookie-bar,.cookie-message,.cookie-alert,.gdpr-banner,.gdpr-consent,.gdpr-popup,.gdpr-overlay,#gdpr-consent,#gdpr-banner,.consent-banner,.consent-popup,.consent-overlay,#consent-banner,#consent-popup,[class*="cookie-consent"],[class*="cookie-banner"],[class*="cookie-notice"],[class*="CookieConsent"],[class*="CookieBanner"],[id*="cookie-consent"],[id*="cookie-banner"],[id*="cookie-notice"],[aria-label*="cookie" i],[aria-label*="consent" i],.klaro,.klaro .cookie-modal,#usercentrics-root,.trustarc-banner,#truste-consent-track,#hs-eu-cookie-confirmation,.osano-cm-window,.osano-cm-dialog,.evidon-banner,#_evidon_banner,.js-cookie-consent,.cookie-disclaimer,.shopify-section-cookies,#shopify-section-cookies,#shopify-pc__banner,#shopify-pc__modal,.privacy-banner,.privacy-popup,[data-testid="cookie-banner"],[data-testid="consent-banner"],.amgdprcookie-bar-container,[data-amcookie-js="bar"],.amgdprjs-bar-template,.amgdprcookie-modal-container,.amgdprcookie-modal-overlay,#cmplz-cookiebanner-container,.cmplz-cookiebanner,#iubenda-cs-banner,.iubenda-cs-container,#qc-cmp2-container,.qc-cmp2-consent-info,#didomi-host,.didomi-popup-container,.didomi-notice,#termly-code-snippet-support,[class*="termly"],[class*="gdprcookie"],[class*="amgdpr"],[id*="gdpr-cookie"],[class*="cookie-modal"],[id*="cookie-modal"],[class*="cookieConsent"],[id*="cookieConsent"],.klaviyo-form,.klaviyo-modal,.klaviyo-popup,[class*="klaviyo"],.privy-popup,.privy-flyout,[id*="privy"],#PopupSignupForm,.popup-signup,.newsletter-popup,.newsletter-modal,[class*="newsletter-popup"],[class*="newsletter-modal"],[id*="newsletter-popup"],.email-popup,.email-modal,[class*="email-popup"],[class*="email-modal"],.signup-popup,.signup-modal,[class*="signup-popup"],[class*="signup-modal"],.subscribe-popup,.subscribe-modal,[class*="subscribe-popup"],#mc_embed_signup,.mc-modal,.mc-banner,.mc-closeModal,.omniconvert-popup,[class*="omniconvert"],.optinmonster-popup,[id*="om-"][class*="campaign"],.sumo-overlay,.sumome-overlay,[class*="sumome"],.hustle-modal,.hustle-popup,[class*="hustle-"],.popup-overlay,.popup-modal,.modal-overlay,[class*="exit-intent"],[class*="exitintent"],.wheelio-popup,[class*="wheelio"],.spin-wheel-popup,.justuno-popup,[class*="justuno"],.wisepops,.wisepops-overlay,[class*="wisepops"],.elegantmodal,.elegant-popup,#zipify-popup,[class*="zipify"],.age-gate,.age-verification,.age-popup,[class*="age-gate"],[class*="age-verif"],[class*="popup-overlay"],[class*="modal-overlay"],[class*="popup-backdrop"]{display:none!important;visibility:hidden!important;opacity:0!important;pointer-events:none!important;height:0!important;overflow:hidden!important;}body.klaviyo-open,body.modal-open,body.popup-open,body.no-scroll,body.noscroll{overflow:auto!important;position:static!important;}</style>`;
7
+ var consentAllowCss = `<style id="__ce_consent_allow">#CybotCookiebotDialog,#CybotCookiebotDialogBodyUnderlay,#onetrust-consent-sdk,#onetrust-banner-sdk,.cc-window,.cc-banner,.cc-overlay,#cookie-notice,#cookie-banner,#cookie-consent,.cookie-notice,.cookie-banner,.cookie-consent,.cookie-popup,.cookie-bar,.cookie-message,.cookie-alert,.gdpr-banner,.gdpr-consent,.gdpr-popup,.gdpr-overlay,#gdpr-consent,#gdpr-banner,.consent-banner,.consent-popup,.consent-overlay,#consent-banner,#consent-popup,[class*="cookie-consent"],[class*="cookie-banner"],[class*="cookie-notice"],[class*="CookieConsent"],[class*="CookieBanner"],[id*="cookie-consent"],[id*="cookie-banner"],[id*="cookie-notice"],[aria-label*="cookie" i],[aria-label*="consent" i],.klaro,.klaro .cookie-modal,#usercentrics-root,.trustarc-banner,#truste-consent-track,#hs-eu-cookie-confirmation,.osano-cm-window,.osano-cm-dialog,.evidon-banner,#_evidon_banner,.js-cookie-consent,.cookie-disclaimer,.shopify-section-cookies,#shopify-section-cookies,#shopify-pc__banner,#shopify-pc__modal,.privacy-banner,.privacy-popup,[data-testid="cookie-banner"],[data-testid="consent-banner"],.amgdprcookie-bar-container,[data-amcookie-js="bar"],.amgdprjs-bar-template,.amgdprcookie-modal-container,.amgdprcookie-modal-overlay,#cmplz-cookiebanner-container,.cmplz-cookiebanner,#iubenda-cs-banner,.iubenda-cs-container,#qc-cmp2-container,.qc-cmp2-consent-info,#didomi-host,.didomi-popup-container,.didomi-notice,#termly-code-snippet-support,[class*="termly"],[class*="gdprcookie"],[class*="amgdpr"],[id*="gdpr-cookie"],[class*="cookie-modal"],[id*="cookie-modal"],[class*="cookieConsent"],[id*="cookieConsent"]{display:revert!important;visibility:visible!important;opacity:1!important;pointer-events:auto!important;height:auto!important;overflow:visible!important;}</style>`;
7
8
  var AI_SYSTEM_PROMPT = `You are a CRO expert. Return JSON only with: hypothesis, mutations, summary. Keep 2-6 precise mutations and only valid selectors from snapshot.`;
8
9
  var BRIDGE_SCRIPT = `(function(){if(window.__CONVERSION_BRIDGE_LOADED__)return;window.__CONVERSION_BRIDGE_LOADED__=true;var CHANNEL='conversion-editor';var highlightEl=null;function send(payload){window.parent.postMessage({channel:CHANNEL,payload:payload},'*');}function qs(selector){try{return document.querySelector(selector);}catch(_){return null;}}function getSelector(el){if(!el||el.nodeType!==1)return'';if(el.id)return'#'+CSS.escape(el.id);var parts=[];var current=el;var depth=0;while(current&&current.nodeType===1&&depth<5){var part=current.tagName.toLowerCase();if(current.classList&&current.classList.length){part+='.'+Array.from(current.classList).slice(0,2).map(function(c){return CSS.escape(c);}).join('.');}var parent=current.parentElement;if(parent){var siblings=Array.from(parent.children).filter(function(s){return s.tagName===current.tagName;});if(siblings.length>1)part+=':nth-of-type('+(siblings.indexOf(current)+1)+')';}parts.unshift(part);current=parent;depth+=1;}return parts.join(' > ');}function payloadOf(el){var rect=el.getBoundingClientRect();var style=window.getComputedStyle(el);return{selector:getSelector(el),tagName:el.tagName.toLowerCase(),textContent:(el.textContent||'').trim().slice(0,500),computedStyles:{color:style.color,backgroundColor:style.backgroundColor,fontSize:style.fontSize,fontWeight:style.fontWeight,lineHeight:style.lineHeight,display:style.display},rect:{top:rect.top,left:rect.left,width:rect.width,height:rect.height}};}function applyMutation(m){var el=qs(m.selector);if(!el)return;switch(m.action){case'setStyle':if(m.property)el.style[m.property]=m.value;break;case'setText':el.textContent=m.value;break;case'setHTML':el.innerHTML=m.value;break;case'setAttribute':if(m.property)el.setAttribute(m.property,m.value);break;case'hide':el.style.display='none';break;case'show':el.style.display='';break;case'insertHTML':if(m.position)el.insertAdjacentHTML(m.position,m.value||'');break;case'insertSection':if(m.position)el.insertAdjacentHTML(m.position,m.sectionHtml||m.value||'');break;case'reorderElement':if(!m.targetSelector)break;var target=qs(m.targetSelector);if(!target||!target.parentNode||!el.parentNode)break;if(m.insertPosition==='before')target.parentNode.insertBefore(el,target);else target.parentNode.insertBefore(el,target.nextSibling);break;default:break;}}function revertMutation(m){var el=qs(m.selector);if(!el)return;switch(m.action){case'setStyle':if(m.property)el.style[m.property]=m.previous||'';break;case'setText':el.textContent=m.previous||'';break;case'setHTML':el.innerHTML=m.previous||'';break;case'setAttribute':if(m.property){if(m.previous!=null)el.setAttribute(m.property,m.previous);else el.removeAttribute(m.property);}break;case'hide':case'show':el.style.display=m.previous||'';break;default:break;}}function captureSnapshot(){var elements=Array.from(document.querySelectorAll('h1,h2,h3,p,button,a,input,select,img,section,div')).slice(0,700).map(function(el){var rect=el.getBoundingClientRect();var cs=window.getComputedStyle(el);return{selector:getSelector(el),parentSelector:el.parentElement?getSelector(el.parentElement):null,tagName:el.tagName.toLowerCase(),textContent:(el.textContent||'').trim().slice(0,300),attributes:Array.from(el.attributes||[]).reduce(function(acc,a){acc[a.name]=a.value;return acc;},{}),computedStyles:{color:cs.color,backgroundColor:cs.backgroundColor,fontSize:cs.fontSize,fontWeight:cs.fontWeight,display:cs.display},childrenCount:el.children?el.children.length:0,aboveFold:rect.top<window.innerHeight,depth:(function(){var d=0,p=el.parentElement;while(p&&d<25){d++;p=p.parentElement;}return d;})()};});send({type:'snapshotCaptured',snapshot:{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},elements:elements}});}function captureTree(){function toNode(el,depth){var rect=el.getBoundingClientRect();var tag=el.tagName.toLowerCase();var type='generic';if(tag==='section')type='section';else if(tag==='img')type='image';else if(tag==='a')type='link';else if(tag==='button')type='button';else if(tag==='form')type='form';else if(['p','h1','h2','h3','h4','h5','h6','span'].indexOf(tag)>=0)type='text';else if(['div','main','article','aside','header','footer','nav'].indexOf(tag)>=0)type='container';var children=Array.from(el.children||[]).slice(0,50).map(function(c){return toNode(c,depth+1);});return{id:getSelector(el),selector:getSelector(el),tagName:tag,label:(el.getAttribute('aria-label')||el.getAttribute('id')||el.className||tag).toString().slice(0,80),type:type,children:children,depth:depth,isAboveFold:rect.top<window.innerHeight,rect:{top:rect.top,left:rect.left,width:rect.width,height:rect.height}};}send({type:'pageTreeCaptured',tree:[toNode(document.body,0)]});}window.addEventListener('message',function(e){var msg=e.data;if(!msg||msg.channel!==CHANNEL||!msg.payload)return;var p=msg.payload;switch(p.type){case'ping':send({type:'pong'});break;case'applyMutation':applyMutation(p.mutation);break;case'applyMutationBatch':(p.mutations||[]).forEach(applyMutation);break;case'revert':revertMutation(p.mutation);break;case'clearAllMutations':window.location.reload();break;case'captureSnapshot':captureSnapshot();break;case'validateSelectors':send({type:'selectorsValidated',results:(p.selectors||[]).map(function(s){var el=qs(s);return{selector:s,found:!!el,tagName:el?el.tagName.toLowerCase():null};})});break;case'scrollToElement':case'selectElement':var target=qs(p.selector);if(target){target.scrollIntoView({behavior:'smooth',block:'center'});send({type:'elementSelected',element:payloadOf(target)});}break;case'hoverElement':var h=qs(p.selector);if(h){if(highlightEl)highlightEl.style.outline='';h.style.outline='2px solid #3b82f6';highlightEl=h;}break;case'capturePageTree':captureTree();break;default:break;}});document.addEventListener('click',function(e){var el=e.target;if(!(el instanceof Element))return;send({type:'elementSelected',element:payloadOf(el)});},true);send({type:'bridgeReady'});})();`;
9
10
  function buildVvvebEditorHtml() {
@@ -991,6 +992,7 @@ var selectedEl = null;
991
992
  var selectedElFingerprint = '';
992
993
  var selectedElRecoverMisses = 0;
993
994
  var MAX_SELECTED_RECOVER_MISSES = 12;
995
+ var isDeselectingSelection = false;
994
996
  var suppressClickUntil = 0;
995
997
  var dragAttachDoc = null;
996
998
  var currentMainTab = 'design';
@@ -1019,6 +1021,8 @@ var iframeDocLoadingListeners = null;
1019
1021
  // Each entry: {selector, label, cssProp, value, targetEl}
1020
1022
  // cssProp is null for non-CSS attributes (href, alt, classes\u2026)
1021
1023
  var stateChanges = [];
1024
+ /** Per-variation unsaved Design-tab state changes (input edits not yet finalized). */
1025
+ var stateChangesByVarId = {};
1022
1026
  /** Pre-apply DOM snapshots for granular + body changesets (used when removing History rows) */
1023
1027
  var appliedChangesetSnapshots = {};
1024
1028
  /** Canonical JSON fingerprints of persisted changesets per variation (last load / finalize) */
@@ -1033,13 +1037,49 @@ function endSuppressIframeMutationDirty() {
1033
1037
  suppressIframeMutationDirty = Math.max(0, suppressIframeMutationDirty - 1);
1034
1038
  }
1035
1039
 
1040
+ function commitStateChangesForActiveVariation() {
1041
+ if (!activeVarId) return;
1042
+ stateChangesByVarId[activeVarId] = (stateChanges || []).slice();
1043
+ }
1044
+
1045
+ function loadStateChangesForActiveVariation() {
1046
+ if (!activeVarId) {
1047
+ stateChanges = [];
1048
+ return;
1049
+ }
1050
+ stateChanges = (stateChangesByVarId[activeVarId] || []).slice();
1051
+ }
1052
+
1036
1053
  function recoverSelectedElement(forceDeselectOnMiss) {
1037
1054
  if (selectedEl && selectedEl.ownerDocument && selectedEl.ownerDocument.contains(selectedEl)) {
1038
1055
  selectedElRecoverMisses = 0;
1039
1056
  return selectedEl;
1040
1057
  }
1041
1058
  if (!selectedElFingerprint) {
1042
- if (forceDeselectOnMiss) deselectElement();
1059
+ // Nothing to recover; clear stale reference without calling deselectElement
1060
+ // (which can recurse back through toolbar updates during rapid DOM churn).
1061
+ if (forceDeselectOnMiss && selectedEl) {
1062
+ beginSuppressIframeMutationDirty();
1063
+ try {
1064
+ try { selectedEl.classList.remove('vve-selected'); } catch(_) {}
1065
+ selectedEl = null;
1066
+ selectedElRecoverMisses = 0;
1067
+ } finally {
1068
+ endSuppressIframeMutationDirty();
1069
+ }
1070
+ var noSel = document.getElementById('no-sel');
1071
+ if (noSel) noSel.style.display = '';
1072
+ var elInfo = document.getElementById('el-info');
1073
+ if (elInfo) elInfo.style.display = 'none';
1074
+ var rp = document.getElementById('rp-accordion');
1075
+ if (rp) rp.style.display = 'none';
1076
+ var bc = document.getElementById('bc-path');
1077
+ if (bc) {
1078
+ bc.textContent = 'No element selected';
1079
+ bc.style.color = 'var(--text-3)';
1080
+ }
1081
+ syncDomTreeSelection();
1082
+ }
1043
1083
  return null;
1044
1084
  }
1045
1085
  var iframe = document.getElementById('iframeId');
@@ -1059,7 +1099,29 @@ function recoverSelectedElement(forceDeselectOnMiss) {
1059
1099
  }
1060
1100
  selectedElRecoverMisses += 1;
1061
1101
  if (forceDeselectOnMiss && selectedElRecoverMisses >= MAX_SELECTED_RECOVER_MISSES) {
1062
- deselectElement();
1102
+ beginSuppressIframeMutationDirty();
1103
+ try {
1104
+ if (selectedEl) {
1105
+ try { selectedEl.classList.remove('vve-selected'); } catch(_) {}
1106
+ }
1107
+ selectedEl = null;
1108
+ selectedElFingerprint = '';
1109
+ selectedElRecoverMisses = 0;
1110
+ } finally {
1111
+ endSuppressIframeMutationDirty();
1112
+ }
1113
+ var noSel2 = document.getElementById('no-sel');
1114
+ if (noSel2) noSel2.style.display = '';
1115
+ var elInfo2 = document.getElementById('el-info');
1116
+ if (elInfo2) elInfo2.style.display = 'none';
1117
+ var rp2 = document.getElementById('rp-accordion');
1118
+ if (rp2) rp2.style.display = 'none';
1119
+ var bc2 = document.getElementById('bc-path');
1120
+ if (bc2) {
1121
+ bc2.textContent = 'No element selected';
1122
+ bc2.style.color = 'var(--text-3)';
1123
+ }
1124
+ syncDomTreeSelection();
1063
1125
  }
1064
1126
  return null;
1065
1127
  }
@@ -1154,6 +1216,10 @@ function setMode(mode) {
1154
1216
  if (mode === 'navigate') {
1155
1217
  setDragHandleActive(false);
1156
1218
  deselectElement();
1219
+ } else if (mode === 'editor') {
1220
+ // Re-bind interactions immediately when coming back from navigate mode.
1221
+ // This avoids waiting for delayed iframe readiness/load retries.
1222
+ syncIframeInteractions('mode-editor-toggle');
1157
1223
  }
1158
1224
  updateSelectionToolbar();
1159
1225
  }
@@ -1320,6 +1386,7 @@ function logChange(selector, inputId, value, targetEl, originalValue) {
1320
1386
  if (idx >= 0) { stateChanges[idx] = entry; } else { stateChanges.push(entry); }
1321
1387
  }
1322
1388
  if (currentMainTab === 'states') renderStatesTab();
1389
+ commitStateChangesForActiveVariation();
1323
1390
  recomputeEditorDirty();
1324
1391
  }
1325
1392
 
@@ -1426,6 +1493,7 @@ function removeStateChange(idx) {
1426
1493
  revertChangeOnDom(change);
1427
1494
  syncDesignInput(change);
1428
1495
  stateChanges.splice(idx, 1);
1496
+ commitStateChangesForActiveVariation();
1429
1497
  renderStatesTab();
1430
1498
  recomputeEditorDirty();
1431
1499
  }
@@ -1436,6 +1504,7 @@ function clearAllStates() {
1436
1504
  syncDesignInput(c);
1437
1505
  });
1438
1506
  stateChanges = [];
1507
+ commitStateChangesForActiveVariation();
1439
1508
  renderStatesTab();
1440
1509
  recomputeEditorDirty();
1441
1510
  }
@@ -1810,7 +1879,9 @@ function handleLoadExperiment(data) {
1810
1879
  experimentData = data;
1811
1880
  variations = Array.isArray(data.variations) ? data.variations : [];
1812
1881
  var prevActive = activeVarId;
1882
+ commitStateChangesForActiveVariation();
1813
1883
  activeVarId = pickActiveVariationIdForLoad(data, variations, prevActive, true);
1884
+ loadStateChangesForActiveVariation();
1814
1885
  writePersistedActiveVariationId(activeVarId);
1815
1886
  renderVariationTabs();
1816
1887
  var urlBarSkip = document.getElementById('url-bar');
@@ -1833,6 +1904,8 @@ function handleLoadExperiment(data) {
1833
1904
  if (!experimentData || prevKey !== nextKey) {
1834
1905
  varHtmlCache = {};
1835
1906
  sessionStructuralChainRowsByVarId = {};
1907
+ stateChangesByVarId = {};
1908
+ stateChanges = [];
1836
1909
  appliedChangesetSnapshots = {};
1837
1910
  appliedStructuralChangesetKeys = {};
1838
1911
  }
@@ -1840,6 +1913,7 @@ function handleLoadExperiment(data) {
1840
1913
  variations = Array.isArray(data.variations) ? data.variations : [];
1841
1914
  var sameExpPage = prevKey === nextKey;
1842
1915
  activeVarId = pickActiveVariationIdForLoad(data, variations, activeVarId, sameExpPage);
1916
+ loadStateChangesForActiveVariation();
1843
1917
  writePersistedActiveVariationId(activeVarId);
1844
1918
  renderVariationTabs();
1845
1919
 
@@ -2124,7 +2198,7 @@ function loadPage(proxyUrl) {
2124
2198
  resetIframeBindings();
2125
2199
  iframe.style.display = 'block';
2126
2200
  setIframePageLoadingUi(true);
2127
- iframe.src = proxyUrl;
2201
+ iframe.src = appendIframeReloadBust(proxyUrl);
2128
2202
  startIframeContentApplyWatcher(navGen);
2129
2203
  scheduleDomTreeRefresh();
2130
2204
  }
@@ -2163,8 +2237,10 @@ function renderVariationTabs() {
2163
2237
  function switchVariation(varId) {
2164
2238
  if (varId === activeVarId) return;
2165
2239
  saveCurrentVariationHtml();
2240
+ commitStateChangesForActiveVariation();
2166
2241
  clearPendingGranularChangesets();
2167
2242
  activeVarId = varId;
2243
+ loadStateChangesForActiveVariation();
2168
2244
  writePersistedActiveVariationId(varId);
2169
2245
  renderVariationTabs();
2170
2246
  deselectElement();
@@ -2200,6 +2276,7 @@ function switchVariation(varId) {
2200
2276
  }
2201
2277
  } catch(_) {}
2202
2278
  if (currentMainTab === 'history') renderHistoryTab();
2279
+ if (currentMainTab === 'states') renderStatesTab();
2203
2280
  recomputeEditorDirty();
2204
2281
  }
2205
2282
 
@@ -2556,12 +2633,13 @@ function buildPersistedChainSetsForVariation(v) {
2556
2633
  var parsed = parseVariationChangesets(v);
2557
2634
  var base = filterGranularChangesetEntries(parsed);
2558
2635
  var sessionExtra = sessionStructuralChainRowsByVarId[v._id] || [];
2559
- if (v._id !== activeVarId) {
2560
- return mergeGranularChainSets(base, sessionExtra);
2561
- }
2636
+ var sourceStateChanges =
2637
+ v._id === activeVarId
2638
+ ? stateChanges
2639
+ : (stateChangesByVarId[v._id] || []);
2562
2640
  var overlay = [];
2563
- for (var si = 0; si < stateChanges.length; si++) {
2564
- var row = stateChangeToChainSet(stateChanges[si]);
2641
+ for (var si = 0; si < sourceStateChanges.length; si++) {
2642
+ var row = stateChangeToChainSet(sourceStateChanges[si]);
2565
2643
  if (row) overlay.push(row);
2566
2644
  }
2567
2645
  return mergeGranularChainSets(mergeGranularChainSets(base, sessionExtra), overlay);
@@ -2685,24 +2763,31 @@ function selectElement(el) {
2685
2763
  }
2686
2764
  }
2687
2765
 
2688
- function deselectElement() {
2689
- setDragHandleActive(false);
2690
- beginSuppressIframeMutationDirty();
2766
+ function deselectElement(options) {
2767
+ if (isDeselectingSelection) return;
2768
+ isDeselectingSelection = true;
2769
+ var skipToolbarUpdate = !!(options && options.skipToolbarUpdate);
2691
2770
  try {
2692
- if (selectedEl) { try { selectedEl.classList.remove('vve-selected'); } catch(_) {} selectedEl = null; }
2693
- selectedElFingerprint = '';
2694
- selectedElRecoverMisses = 0;
2771
+ setDragHandleActive(false);
2772
+ beginSuppressIframeMutationDirty();
2773
+ try {
2774
+ if (selectedEl) { try { selectedEl.classList.remove('vve-selected'); } catch(_) {} selectedEl = null; }
2775
+ selectedElFingerprint = '';
2776
+ selectedElRecoverMisses = 0;
2777
+ } finally {
2778
+ endSuppressIframeMutationDirty();
2779
+ }
2780
+ document.getElementById('no-sel').style.display = '';
2781
+ document.getElementById('el-info').style.display = 'none';
2782
+ document.getElementById('rp-accordion').style.display = 'none';
2783
+ document.getElementById('bc-path').textContent = 'No element selected';
2784
+ document.getElementById('bc-path').style.color = 'var(--text-3)';
2785
+ switchMainTab('design');
2786
+ if (!skipToolbarUpdate) updateSelectionToolbar();
2787
+ syncDomTreeSelection();
2695
2788
  } finally {
2696
- endSuppressIframeMutationDirty();
2789
+ isDeselectingSelection = false;
2697
2790
  }
2698
- document.getElementById('no-sel').style.display = '';
2699
- document.getElementById('el-info').style.display = 'none';
2700
- document.getElementById('rp-accordion').style.display = 'none';
2701
- document.getElementById('bc-path').textContent = 'No element selected';
2702
- document.getElementById('bc-path').style.color = 'var(--text-3)';
2703
- switchMainTab('design');
2704
- updateSelectionToolbar();
2705
- syncDomTreeSelection();
2706
2791
  }
2707
2792
 
2708
2793
  // \u2500\u2500 Iframe selection chrome, floater toolbar, DOM tree \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
@@ -2953,7 +3038,7 @@ function renderDomTree(filterRaw) {
2953
3038
 
2954
3039
  function labelFor(el) {
2955
3040
  var tag = el.tagName.toLowerCase();
2956
- if (el.id) return tag + '#' + el.id.slice(0, 40);
3041
+ if (el.id != null && el.id !== '') return tag + '#' + String(el.id).slice(0, 40);
2957
3042
  var cn = el.className && typeof el.className === 'string' ? el.className.trim() : '';
2958
3043
  if (cn) {
2959
3044
  var parts = cn.split(/s+/).filter(function(x) { return x.indexOf('vve-') !== 0; }).slice(0, 2).join('.');
@@ -3959,6 +4044,7 @@ document.getElementById('btn-close').addEventListener('click', handleClose);
3959
4044
 
3960
4045
  function handleSave() {
3961
4046
  saveCurrentVariationHtml();
4047
+ commitStateChangesForActiveVariation();
3962
4048
  var updatedVariations = variations.map(function(v) {
3963
4049
  var prevParsed = parseVariationChangesets(v);
3964
4050
  var granularPrev = filterGranularChangesetEntries(prevParsed);
@@ -3979,6 +4065,7 @@ function handleSave() {
3979
4065
  variations = updatedVariations;
3980
4066
  varHtmlCache = {};
3981
4067
  sessionStructuralChainRowsByVarId = {};
4068
+ stateChangesByVarId = {};
3982
4069
  stateChanges = [];
3983
4070
  if (currentMainTab === 'states') renderStatesTab();
3984
4071
  captureBaselineFromVariations(variations);
@@ -4135,18 +4222,28 @@ window.addEventListener('load', function() {
4135
4222
  var iframe = document.getElementById('iframeId');
4136
4223
  iframe.addEventListener('load', function() {
4137
4224
  if (!iframe.src || iframe.src === 'about:blank' || iframe.src === window.location.href) return;
4225
+ // New iframe navigation: always drop bindings tied to the previous document.
4226
+ resetIframeBindings();
4138
4227
  var doc = iframe.contentDocument;
4139
- if (!doc || !doc.body) return;
4228
+ if (!doc) {
4229
+ syncIframeInteractions('iframe-load-no-doc');
4230
+ return;
4231
+ }
4140
4232
  var docUrl = '';
4141
4233
  try { docUrl = String(doc.URL || ''); } catch(_) {}
4142
4234
  // Stale events: src may already be the proxy URL while the document is still
4143
- // about:blank (e.g. src cleared then reset to force reload).
4144
- if (docUrl === 'about:blank') return;
4145
- if (!iframeDocMatchesNavigatedSrc(iframe, doc)) return;
4235
+ // about:blank (e.g. src cleared then reset to force reload). Ask sync path to retry.
4236
+ if (docUrl === 'about:blank') {
4237
+ syncIframeInteractions('iframe-load-about-blank');
4238
+ return;
4239
+ }
4146
4240
  attachIframeLoadingUntilComplete(iframe);
4147
- stopIframeContentApplyWatcher();
4148
- deselectElement();
4149
- applyActiveVariationHtml();
4241
+ if (doc.body && iframeDocMatchesNavigatedSrc(iframe, doc)) {
4242
+ stopIframeContentApplyWatcher();
4243
+ deselectElement();
4244
+ applyActiveVariationHtml();
4245
+ }
4246
+ // Always attempt sync; it has its own readiness checks + retry loop.
4150
4247
  syncIframeInteractions('iframe-load');
4151
4248
  });
4152
4249
 
@@ -4474,7 +4571,7 @@ function createVisualEditorMiddleware(options) {
4474
4571
  }
4475
4572
  html = html.replace(/(href|src|action)="\/(?!\/)/g, `$1="${origin}/`);
4476
4573
  const escapedOrigin = origin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4477
- const proxyBase = `/api/conversion-proxy?password=${encodeURIComponent(password)}&url=`;
4574
+ const proxyBase = `/api/conversion-proxy?__ve_reload=${Date.now()}&password=${encodeURIComponent(password)}&url=`;
4478
4575
  html = html.replace(
4479
4576
  new RegExp(`(href|action)="${escapedOrigin}(/[^"]*)"`, "g"),
4480
4577
  (match, attr, urlPath) => {
@@ -4487,6 +4584,7 @@ function createVisualEditorMiddleware(options) {
4487
4584
  );
4488
4585
  if (html.includes("</head>")) {
4489
4586
  html = html.replace("</head>", `${popupHideCss}
4587
+ ${consentAllowCss}
4490
4588
  </head>`);
4491
4589
  }
4492
4590
  html = html.replace(
@@ -4504,7 +4602,7 @@ var PROXY_PASSWORD=${JSON.stringify(password)};
4504
4602
  window.__CONVERSION_EDITOR_ACTIVE__=true;
4505
4603
  function isSkippable(raw){if(!raw||typeof raw!=="string")return true;return raw.startsWith("data:")||raw.startsWith("blob:")||raw.startsWith("javascript:")||raw.startsWith("#");}
4506
4604
  function toAbsolute(raw){if(isSkippable(raw))return raw;try{var base=raw.startsWith("/")||raw.startsWith("//")?TARGET_ORIGIN:TARGET_PAGE_URL;return new URL(raw,base).toString();}catch(_){return raw;}}
4507
- function toProxy(raw){if(isSkippable(raw))return null;var abs=toAbsolute(raw);if(!abs||typeof abs!=="string")return null;try{var parsed=new URL(abs);if(parsed.origin!==TARGET_ORIGIN)return null;return "/api/conversion-proxy?password="+encodeURIComponent(PROXY_PASSWORD||"")+"&url="+encodeURIComponent(parsed.toString());}catch(_){return null;}}
4605
+ function toProxy(raw){if(isSkippable(raw))return null;var abs=toAbsolute(raw);if(!abs||typeof abs!=="string")return null;try{var parsed=new URL(abs);if(parsed.origin!==TARGET_ORIGIN)return null;return "/api/conversion-proxy?__ve_reload="+Date.now()+"&password="+encodeURIComponent(PROXY_PASSWORD||"")+"&url="+encodeURIComponent(parsed.toString());}catch(_){return null;}}
4508
4606
  var nativeAssign=window.location.assign?window.location.assign.bind(window.location):null;
4509
4607
  var nativeReplace=window.location.replace?window.location.replace.bind(window.location):null;
4510
4608
  function safeNavigate(raw,mode){var abs=toAbsolute(raw);var prox=toProxy(raw);if(!prox){try{console.warn("[conversion-proxy] redirect blocked",{mode:mode,requested:raw,resolved:abs,origin:TARGET_ORIGIN});}catch(_){}return false;}try{console.info("[conversion-proxy] redirect intercepted",{mode:mode,requested:raw,resolved:abs,proxied:prox});if(mode==="replace"&&nativeReplace){nativeReplace(prox);return true;}if(nativeAssign){nativeAssign(prox);return true;}window.location.href=prox;return true;}catch(err){try{console.warn("[conversion-proxy] redirect interception failed",{mode:mode,requested:raw,resolved:abs,proxied:prox,error:err&&err.message?err.message:String(err)});}catch(_){}return false;}}
@@ -4577,6 +4675,9 @@ if(window.fetch){
4577
4675
  }
4578
4676
  if(window.XMLHttpRequest&&window.XMLHttpRequest.prototype&&window.XMLHttpRequest.prototype.open){var _open=window.XMLHttpRequest.prototype.open;window.XMLHttpRequest.prototype.open=function(method,url){try{var u=resolveUrl(String(url));if(u&&isNestedMalformedProxy(u)){arguments[1]=EMPTY_JSON_DATA;}else{arguments[1]=toAbsoluteOriginUrl(url);}}catch(_){}return _open.apply(this,arguments);};}
4579
4677
  if(window.navigator&&typeof window.navigator.sendBeacon==="function"){var _beacon=window.navigator.sendBeacon.bind(window.navigator);window.navigator.sendBeacon=function(url,data){try{if(skipNestedProxyNetwork(String(url)))return true;}catch(_){}return _beacon(url,data);};}
4678
+ function withReloadBust(urlRaw){try{var u=resolveUrl(String(urlRaw||""));if(!u)return null;var p=u.pathname||"";var isRootProxyPath=p==="/api/conversion-proxy"||p.indexOf("/api/conversion-proxy/")===0;if(!isRootProxyPath)return null;u.searchParams.set("__ve_reload",String(Date.now()));return u.toString();}catch(_){return null;}}
4679
+ document.addEventListener("click",function(ev){try{var t=ev&&ev.target;if(!t||!t.closest)return;var a=t.closest("a[href]");if(!a)return;var href=a.getAttribute("href")||a.href;var bust=withReloadBust(href);if(bust)a.setAttribute("href",bust);}catch(_){}},true);
4680
+ document.addEventListener("submit",function(ev){try{var f=ev&&ev.target;if(!f||!f.getAttribute)return;var act=f.getAttribute("action")||"";var bust=withReloadBust(act);if(bust)f.setAttribute("action",bust);}catch(_){}},true);
4580
4681
  if(window.navigator&&window.navigator.serviceWorker&&typeof window.navigator.serviceWorker.register==="function"){window.navigator.serviceWorker.register=function(){return Promise.resolve({scope:"disabled-in-editor-proxy"});};}
4581
4682
  }catch(_){}})();</script>`;
4582
4683
  if (html.includes("</head>")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@accelerated-agency/visual-editor",
3
- "version": "0.2.8",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "description": "Conversion visual editor as a reusable React package",
6
6
  "type": "module",