visbug-editor 0.3.0 → 0.4.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.
@@ -10,4 +10,4 @@ const e={on:function(e,t,r){return e.split(" ").forEach(e=>this.addEventListener
10
10
 
11
11
  * Licensed under the MIT license
12
12
  */
13
- const Qa="undefined"!=typeof navigator&&navigator.userAgent.toLowerCase().indexOf("firefox")>0;function eo(e,t,r,a){e.addEventListener?e.addEventListener(t,r,a):e.attachEvent&&e.attachEvent("on".concat(t),r)}function to(e,t,r,a){e.removeEventListener?e.removeEventListener(t,r,a):e.detachEvent&&e.detachEvent("on".concat(t),r)}function ro(e,t){const r=t.slice(0,t.length-1);for(let t=0;t<r.length;t++)r[t]=e[r[t].toLowerCase()];return r}function ao(e){"string"!=typeof e&&(e="");const t=(e=e.replace(/\s/g,"")).split(",");let r=t.lastIndexOf("");for(;r>=0;)t[r-1]+=",",t.splice(r,1),r=t.lastIndexOf("");return t}const oo={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,arrowup:38,arrowdown:40,arrowleft:37,arrowright:39,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":Qa?173:189,"=":Qa?61:187,";":Qa?59:186,"'":222,"{":219,"}":221,"[":219,"]":221,"\\":220},so={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,meta:91,command:91},no={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},io={16:!1,18:!1,17:!1,91:!1},lo={};for(let e=1;e<20;e++)oo["f".concat(e)]=111+e;let co=[],ho=null,po="all";const uo=new Map,go=e=>oo[e.toLowerCase()]||so[e.toLowerCase()]||e.toUpperCase().charCodeAt(0);function mo(e){po=e||"all"}function fo(){return po||"all"}function xo(e){if(void 0===e)Object.keys(lo).forEach(e=>{Array.isArray(lo[e])&&lo[e].forEach(e=>wo(e)),delete lo[e]}),Mo(null);else if(Array.isArray(e))e.forEach(e=>{e.key&&wo(e)});else if("object"==typeof e)e.key&&wo(e);else if("string"==typeof e){for(var t=arguments.length,r=new Array(t>1?t-1:0),a=1;a<t;a++)r[a-1]=arguments[a];let[o,s]=r;"function"==typeof o&&(s=o,o=""),wo({key:e,scope:o,method:s,splitKey:"+"})}}const wo=e=>{let{key:t,scope:r,method:a,splitKey:o="+"}=e;ao(t).forEach(e=>{const t=e.split(o),s=t.length,n=t[s-1],i="*"===n?"*":go(n);if(!lo[i])return;r||(r=fo());const l=s>1?ro(so,t):[],c=[];lo[i]=lo[i].filter(e=>{const t=(!a||e.method===a)&&e.scope===r&&function(e,t){const r=e.length>=t.length?e:t,a=e.length>=t.length?t:e;let o=!0;for(let e=0;e<r.length;e++)-1===a.indexOf(r[e])&&(o=!1);return o}(e.mods,l);return t&&c.push(e.element),!t}),c.forEach(e=>Mo(e))})};function bo(e,t,r,a){if(t.element!==a)return;let o;if(t.scope===r||"all"===t.scope){o=t.mods.length>0;for(const e in io)Object.prototype.hasOwnProperty.call(io,e)&&(!io[e]&&t.mods.indexOf(+e)>-1||io[e]&&-1===t.mods.indexOf(+e))&&(o=!1);(0!==t.mods.length||io[16]||io[18]||io[17]||io[91])&&!o&&"*"!==t.shortcut||(t.keys=[],t.keys=t.keys.concat(co),!1===t.method(e,t)&&(e.preventDefault?e.preventDefault():e.returnValue=!1,e.stopPropagation&&e.stopPropagation(),e.cancelBubble&&(e.cancelBubble=!0)))}}function vo(e,t){const r=lo["*"];let a=e.keyCode||e.which||e.charCode;if(e.key&&"capslock"===e.key.toLowerCase())return;if(!yo.filter.call(this,e))return;if(93!==a&&224!==a||(a=91),-1===co.indexOf(a)&&229!==a&&co.push(a),["metaKey","ctrlKey","altKey","shiftKey"].forEach(t=>{const r=no[t];e[t]&&-1===co.indexOf(r)?co.push(r):!e[t]&&co.indexOf(r)>-1?co.splice(co.indexOf(r),1):"metaKey"===t&&e[t]&&(co=co.filter(e=>e in no||e===a))}),a in io){io[a]=!0;for(const t in so)if(Object.prototype.hasOwnProperty.call(so,t)){const r=no[so[t]];yo[t]=e[r]}if(!r)return}for(const t in io)Object.prototype.hasOwnProperty.call(io,t)&&(io[t]=e[no[t]]);e.getModifierState&&(!e.altKey||e.ctrlKey)&&e.getModifierState("AltGraph")&&(-1===co.indexOf(17)&&co.push(17),-1===co.indexOf(18)&&co.push(18),io[17]=!0,io[18]=!0);const o=fo();if(r)for(let a=0;a<r.length;a++)r[a].scope===o&&("keydown"===e.type&&r[a].keydown||"keyup"===e.type&&r[a].keyup)&&bo(e,r[a],o,t);if(!(a in lo))return;const s=lo[a],n=s.length;for(let r=0;r<n;r++)if(("keydown"===e.type&&s[r].keydown||"keyup"===e.type&&s[r].keyup)&&s[r].key){const a=s[r],{splitKey:n}=a,i=a.key.split(n),l=[];for(let e=0;e<i.length;e++)l.push(go(i[e]));l.sort().join("")===co.sort().join("")&&bo(e,a,o,t)}}function yo(e,t,r){co=[];const a=ao(e);let o=[],s="all",n=document,i=0,l=!1,c=!0,h="+",d=!1,p=!1;for(void 0===r&&"function"==typeof t&&(r=t),"[object Object]"===Object.prototype.toString.call(t)&&(t.scope&&(s=t.scope),t.element&&(n=t.element),t.keyup&&(l=t.keyup),void 0!==t.keydown&&(c=t.keydown),void 0!==t.capture&&(d=t.capture),"string"==typeof t.splitKey&&(h=t.splitKey),!0===t.single&&(p=!0)),"string"==typeof t&&(s=t),p&&xo(e,s);i<a.length;i++)o=[],(e=a[i].split(h)).length>1&&(o=ro(so,e)),(e="*"===(e=e[e.length-1])?"*":go(e))in lo||(lo[e]=[]),lo[e].push({keyup:l,keydown:c,scope:s,mods:o,shortcut:a[i],method:r,key:a[i],splitKey:h,element:n});if(void 0!==n&&window){if(!uo.has(n)){const e=function(){return vo(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.event,n)},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.event;vo(e,n),function(e){let t=e.keyCode||e.which||e.charCode;e.key&&"capslock"===e.key.toLowerCase()&&(t=go(e.key));const r=co.indexOf(t);if(r>=0&&co.splice(r,1),e.key&&"meta"===e.key.toLowerCase()&&co.splice(0,co.length),93!==t&&224!==t||(t=91),t in io){io[t]=!1;for(const e in so)so[e]===t&&(yo[e]=!1)}}(e)};uo.set(n,{keydownListener:e,keyupListenr:t,capture:d}),eo(n,"keydown",e,d),eo(n,"keyup",t,d)}if(!ho){const e=()=>{co=[]};ho={listener:e,capture:d},eo(window,"focus",e,d)}}}function Mo(e){const t=Object.values(lo).flat();if(t.findIndex(t=>{let{element:r}=t;return r===e})<0){const{keydownListener:t,keyupListenr:r,capture:a}=uo.get(e)||{};t&&r&&(to(e,"keyup",r,a),to(e,"keydown",t,a),uo.delete(e))}if(t.length<=0||uo.size<=0){if(Object.keys(uo).forEach(e=>{const{keydownListener:t,keyupListenr:r,capture:a}=uo.get(e)||{};t&&r&&(to(e,"keyup",r,a),to(e,"keydown",t,a),uo.delete(e))}),uo.clear(),Object.keys(lo).forEach(e=>delete lo[e]),ho){const{listener:e,capture:t}=ho;to(window,"focus",e,t),ho=null}}}const ko={getPressedKeyString:function(){return co.map(e=>{return t=e,Object.keys(oo).find(e=>oo[e]===t)||(e=>Object.keys(so).find(t=>so[t]===e))(e)||String.fromCharCode(e);var t})},setScope:mo,getScope:fo,deleteScope:function(e,t){let r,a;e||(e=fo());for(const t in lo)if(Object.prototype.hasOwnProperty.call(lo,t))for(r=lo[t],a=0;a<r.length;)if(r[a].scope===e){r.splice(a,1).forEach(e=>{let{element:t}=e;return Mo(t)})}else a++;fo()===e&&mo(t||"all")},getPressedKeyCodes:function(){return co.slice(0)},getAllKeyCodes:function(){const e=[];return Object.keys(lo).forEach(t=>{lo[t].forEach(t=>{let{key:r,scope:a,mods:o,shortcut:s}=t;e.push({scope:a,shortcut:s,mods:o,keys:r.split("+").map(e=>go(e))})})}),e},isPressed:function(e){return"string"==typeof e&&(e=go(e)),-1!==co.indexOf(e)},filter:function(e){const t=e.target||e.srcElement,{tagName:r}=t;let a=!0;const o="INPUT"===r&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(t.type);return(t.isContentEditable||(o||"TEXTAREA"===r||"SELECT"===r)&&!t.readOnly)&&(a=!1),a},trigger:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"all";Object.keys(lo).forEach(r=>{lo[r].filter(r=>r.scope===t&&r.shortcut===e).forEach(e=>{e&&e.method&&e.method()})})},unbind:xo,keyMap:oo,modifier:so,modifierMap:no};for(const e in ko)Object.prototype.hasOwnProperty.call(ko,e)&&(yo[e]=ko[e]);if("undefined"!=typeof window){const e=window.hotkeys;yo.noConflict=t=>(t&&window.hotkeys===yo&&(window.hotkeys=e),yo),window.hotkeys=yo}const So="up,down,left,right".split(",").reduce((e,t)=>`${e},${t},alt+${t},shift+${t},shift+alt+${t}`,"").substring(1);function Co(e){const t={elements:[]};yo(So,(r,a)=>{r.cancelBubble||(r.preventDefault(),function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>Po(e)).map(e=>D(e)).map(e=>({el:e,...Eo(e,t),amount:t.split("+").includes("shift")?10:1,negative:$o(e,t)})).map(e=>Object.assign(e,{position:e.negative?e.current+e.amount:e.current-e.amount})).forEach(({el:e,style:a,position:o,current:s})=>{if(e instanceof SVGElement){const a=e.getAttribute("transform");Ao(e,t,o);const s=e.getAttribute("transform");r&&r.push(new p({element:e,attribute:"transform",oldValue:a,newValue:s}))}else{const t=e.style[a],s=o+"px";r&&r.push(new d({element:e,property:a,oldValue:t,newValue:s})),e.style[a]=s}}),e.length>1&&r&&r.endBatch()}(t.elements,a.key,e))});return{onNodesSelected:r=>{t.elements.forEach(e=>e.teardown()),t.elements=r.map(t=>function({el:e,surface:t=e,cursor:r="move",clickEvent:a,historyManager:o}){const s={surface:t,mouse:{down:!1,x:0,y:0},element:{x:0,y:0},travelDistance:0,historyManager:o,initialPosition:null,initialTransform:null,zIndex:null},n=()=>{e.style.transition="none",t.style.cursor=r,t.addEventListener("mousedown",l,!0),t.addEventListener("mouseup",c,!0),document.addEventListener("mousemove",h,!0)},i=()=>{e.style.transition=null,t.style.cursor=null,t.removeEventListener("mousedown",l,!0),t.removeEventListener("mouseup",c,!0),document.removeEventListener("mousemove",h,!0)},l=t=>{if(t.target===s.surface){if(t.preventDefault(),null==s.zIndex&&(s.zIndex=e.style.zIndex,e.style.zIndex=9999999999999),"static"==getComputedStyle(e).position&&(e.style.position="relative"),e.style.willChange="top,left",e instanceof SVGElement){const t=e.getAttribute("transform"),[r,a]=t?_o(t):[0,0];s.element.x=r,s.element.y=a,s.historyManager&&(s.initialTransform=t||null)}else s.element.x=parseInt(E(e,"left")),s.element.y=parseInt(E(e,"top")),s.historyManager&&(s.initialPosition={left:e.style.left,top:e.style.top});s.mouse.x=t.clientX,s.mouse.y=t.clientY,s.mouse.down=!0,s.travelDistance=0}},c=t=>{if(t.target!==s.surface)return;if(t.preventDefault(),t.stopPropagation(),null!=s.zIndex&&(e.style.zIndex=s.zIndex,s.zIndex=null),s.mouse.down=!1,e.style.willChange=null,e instanceof SVGElement){const t=e.getAttribute("transform"),[r,a]=t?_o(t):[0,0];s.historyManager&&s.initialTransform!==t&&(s.historyManager.push(new p({element:e,attribute:"transform",oldValue:s.initialTransform,newValue:t})),s.initialTransform=null),s.element.x=r,s.element.y=a}else if(s.element.x=parseInt(e.style.left)||0,s.element.y=parseInt(e.style.top)||0,s.historyManager&&s.initialPosition){const t=e.style.left,r=e.style.top,a=s.initialPosition.left!==t,o=s.initialPosition.top!==r;(a||o)&&(a&&o&&s.historyManager.beginBatch(),a&&s.historyManager.push(new d({element:e,property:"left",oldValue:s.initialPosition.left,newValue:t})),o&&s.historyManager.push(new d({element:e,property:"top",oldValue:s.initialPosition.top,newValue:r})),a&&o&&s.historyManager.endBatch()),s.initialPosition=null}const r=!s.travelDistance||s.travelDistance<5;a&&r&&a(t),s.travelDistance=0},h=t=>{s.mouse.down&&(t.preventDefault(),t.stopPropagation(),e instanceof SVGElement?e.setAttribute("transform",`translate(\n ${s.element.x+t.clientX-s.mouse.x},\n ${s.element.y+t.clientY-s.mouse.y}\n )`):(e.style.left=s.element.x+t.clientX-s.mouse.x+"px",e.style.top=s.element.y+t.clientY-s.mouse.y+"px"),s.travelDistance+=1)};return n(),e.teardown=i,e}({el:t,historyManager:e}))},disconnect:()=>{t.elements.forEach(e=>e.teardown()),yo.unbind(So),yo.unbind("up,down,left,right")}}}const Eo=(e,t)=>{let r,a;if(e instanceof SVGElement){const o=e.attr("transform"),[s,n]=o?_o(o):[0,0];r="transform",a=t.includes("down")||t.includes("up")?n:s}else{const o=O(t).toLowerCase();r="top"===o||"bottom"===o?"top":"left",a=E(e,r),a="auto"===a?0:parseInt(a,10)}return{style:r,current:a}},_o=e=>e.substring(e.indexOf("(")+1,e.indexOf(")")).split(",").map(e=>parseFloat(e)),Ao=(e,t,r)=>{const a=e.attr("transform"),[o,s]=a?_o(a):[0,0],n=t.includes("down")||t.includes("up")?`${o},${r}`:`${r},${s}`;e.attr("transform",`translate(${n})`)},$o=(e,t)=>t.includes("right")||t.includes("down"),Po=e=>(e instanceof HTMLElement&&(e.style.position="relative"),e),Lo={historyManager:null,originalText:new WeakMap},zo=({target:e})=>{if(Lo.historyManager&&Lo.originalText.has(e)){const t=Lo.originalText.get(e),r=e.textContent;t!==r&&Lo.historyManager.push(new g({element:e,oldText:t,newText:r})),Lo.originalText.delete(e)}e.removeAttribute("contenteditable"),e.removeAttribute("spellcheck"),e.removeEventListener("blur",zo),e.removeEventListener("keydown",No)},No=e=>{"Escape"!==e.key&&"Esc"!==e.key?e.stopPropagation():Bo()},Bo=(e,r)=>{t('[spellcheck="true"]').forEach(e=>zo({target:e})),window.getSelection().empty()};const To="up,down,left,right".split(",").reduce((e,t)=>`${e},${t},shift+${t}`,"").substring(1),Ro=`${T}+up,${T}+down`;function Io({selection:e,historyManager:t}){return yo(To,(r,a)=>{if(r.cancelBubble)return;r.preventDefault();let o=e(),s=a.key.split("+");s.includes("left")||s.includes("right")?s.includes("shift")?function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"letterSpacing",current:parseFloat(E(e,"letterSpacing")),amount:.1,negative:t.split("+").includes("left")})).map(e=>Object.assign(e,{current:"normal"==e.current||isNaN(e.current)?0:e.current})).map(e=>Object.assign(e,{value:e.negative?(e.current-e.amount).toFixed(2):(e.current+e.amount).toFixed(2)})).forEach(({el:e,style:t,value:a,current:o})=>{const s=`${o}px`,n=`${a<=-2?-2:a}px`;r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t):function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"textAlign",current:E(e,"textAlign"),direction:t.split("+").includes("left")})).map(e=>Object.assign(e,{value:e.direction?Do[e.current]-1:Do[e.current]+1})).forEach(({el:e,style:t,value:a,current:o})=>{const s=o,n=Fo[a<0?0:a>=2?2:a];r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t):s.includes("shift")?function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"lineHeight",current:parseInt(E(e,"lineHeight")),amount:1,negative:t.split("+").includes("down")})).map(e=>Object.assign(e,{current:"normal"==e.current||isNaN(e.current)?1.14*parseInt(E(e.el,"fontSize")):e.current})).map(e=>Object.assign(e,{value:e.negative?e.current-e.amount:e.current+e.amount})).forEach(({el:e,style:t,value:a,current:o})=>{const s=`${o}px`,n=`${a}px`;r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t):function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"fontSize",current:parseInt(E(e,"fontSize")),amount:t.split("+").includes("shift")?10:1,negative:t.split("+").includes("down")})).map(e=>Object.assign(e,{font_size:e.negative?e.current-e.amount:e.current+e.amount})).forEach(({el:e,style:t,font_size:a,current:o})=>{const s=`${o}px`,n=`${a<=6?6:a}px`;r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t)}),yo(Ro,(r,a)=>{r.preventDefault();let o=a.key.split("+");!function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"fontWeight",current:E(e,"fontWeight"),direction:t.split("+").includes("down")})).map(e=>Object.assign(e,{value:e.direction?Oo[e.current]-1:Oo[e.current]+1})).forEach(({el:e,style:t,value:a,current:o})=>{const s=jo[a<0?0:a>=jo.length?jo.length:a],n=o,i=String(s);r&&r.push(new d({element:e,property:t,oldValue:n,newValue:i})),e.style[t]=s}),e.length>1&&r&&r.endBatch()}(e(),o.includes("up")?"up":"down",t)}),yo("cmd+b",r=>{const a=e();a.length>1&&t&&t.beginBatch(),a.forEach(e=>{const r=e.style.fontWeight;t&&t.push(new d({element:e,property:"fontWeight",oldValue:r,newValue:"bold"==e.style.fontWeight?"":"bold"})),e.style.fontWeight="bold"==e.style.fontWeight?null:"bold"}),a.length>1&&t&&t.endBatch()}),yo("cmd+i",r=>{const a=e();a.length>1&&t&&t.beginBatch(),a.forEach(e=>{const r=e.style.fontStyle;t&&t.push(new d({element:e,property:"fontStyle",oldValue:r,newValue:"italic"==e.style.fontStyle?"":"italic"})),e.style.fontStyle="italic"==e.style.fontStyle?null:"italic"}),a.length>1&&t&&t.endBatch()}),()=>{yo.unbind(To),yo.unbind(Ro),yo.unbind("cmd+b,cmd+i"),yo.unbind("up,down,left,right")}}const Oo={normal:2,bold:5,light:0,"":2,100:0,200:1,300:2,400:3,500:4,600:5,700:6,800:7,900:8,1e3:9},jo=[100,200,300,400,500,600,700,800,900,1e3];const Do={start:0,left:0,center:1,right:2},Fo=["left","center","right"];let Vo,Ho=[],Wo=[];const qo={watching:!0,historyManager:null,imageCache:new Map};const Yo=e=>{e.on("dragover",Qo),e.on("dragleave",es),e.on("drop",ts),t(document.body).on("dragover",Qo),t(document.body).on("dragleave",es),t(document.body).on("drop",ts),t(document.body).on("dragstart",Zo),t(document.body).on("dragend",Jo)},Ko=e=>{e.off("dragover",Qo),e.off("dragleave",es),e.off("drop",ts),t(document.body).off("dragover",Qo),t(document.body).off("dragleave",es),t(document.body).off("drop",ts),t(document.body).off("dragstart",Zo),t(document.body).off("dragend",Jo),e=[]},Uo=e=>new Promise((t,r)=>{let a=new FileReader;a.readAsDataURL(e),a.onloadend=()=>t(a.result)}),Go=async e=>{if(qo.imageCache.has(e)||e.startsWith("data:")||e.startsWith("blob:"))return qo.imageCache.get(e)||e;try{const t=await fetch(e),r=await t.blob(),a=URL.createObjectURL(r);return qo.imageCache.set(e,a),a}catch(t){return console.warn("Failed to cache image:",e,t),e}},Xo=e=>qo.imageCache.get(e)||e,Zo=({target:e})=>Vo=e,Jo=e=>Vo=void 0,Qo=async e=>{e.preventDefault(),e.stopPropagation();const r=t("img[data-selected=true], [data-selected=true] > img");Ho.some(t=>t===e.target)&&(r.length?(r.some(t=>t==e.target)&&!fs(e)&&r.forEach(e=>ps(e)),r.forEach((e,t)=>cs(e,t))):(fs(e)||ps(e.target),cs(e.currentTarget,0)))},es=e=>{e.stopPropagation();const r=t("img[data-selected=true], [data-selected=true] > img");r.some(t=>t===e.target)?r.forEach(e=>gs(e)):gs(e.target),hs()},ts=async e=>{e.stopPropagation(),e.preventDefault();const r=await rs(Vo,e);if(r.length){const a=t("img[data-selected=true], [data-selected=true] > img"),o=as(a,e);if(o.length)os(o,r);else{const t=ns(Ho,e);is(t,r[0])}}hs()},rs=async(e,t)=>e?[e.currentSrc]:t.dataTransfer.files.length?await Promise.all([...t.dataTransfer.files].filter(e=>e.type.includes("image")).map(Uo)):[],as=(e,t)=>e.length?e:"IMG"!==t.target.nodeName||e.length?[]:[t.target],os=async(e,t)=>{e.length>1&&qo.historyManager&&qo.historyManager.beginBatch();let r=0;for(const a of e)ms(a),await ss(a,t[r]),r=++r%t.length;e.length>1&&qo.historyManager&&qo.historyManager.endBatch()},ss=async(e,t)=>{const r=e.getAttribute("src"),a=e.getAttribute("srcset")||"";!r||r.startsWith("data:")||r.startsWith("blob:")||Go(r).catch(()=>{});let o=t;t.startsWith("data:")||t.startsWith("blob:")||(o=await Go(t)),e.src=o,""!==e.srcset&&(e.srcset=o),qo.historyManager&&(qo.historyManager.push(new p({element:e,attribute:"src",oldValue:Xo(r)||r,newValue:o})),""!==a&&qo.historyManager.push(new p({element:e,attribute:"srcset",oldValue:Xo(a)||a,newValue:o})));const s=ls(e);s.length&&qo.historyManager&&s.forEach(e=>{const t=e.getAttribute("srcset");e.srcset=o,qo.historyManager.push(new p({element:e,attribute:"srcset",oldValue:Xo(t)||t,newValue:o}))})},ns=(e,t)=>e.filter(e=>e.contains(t.target)),is=(e,t)=>{e.length>1&&qo.historyManager&&qo.historyManager.beginBatch(),e.forEach(e=>{if(ms(e),"none"!=window.getComputedStyle(e).backgroundImage){const r=e.style.backgroundImage,a=`url(${t})`;qo.historyManager&&qo.historyManager.push(new d({element:e,property:"backgroundImage",oldValue:r,newValue:a})),e.style.backgroundImage=a}}),e.length>1&&qo.historyManager&&qo.historyManager.endBatch()},ls=e=>Array.from(e.parentElement.children).filter(e=>"SOURCE"===e.nodeName).filter(e=>!e.media||window.matchMedia(e.media).matches),cs=(e,t)=>{const r=e.getBoundingClientRect(),a=Wo[t];a?a.update=r:(Wo[t]=document.createElement("visbug-overlay"),Wo[t].position=r,document.body.appendChild(Wo[t]))},hs=()=>{Wo.forEach(e=>e.remove()),Wo=[]},ds=e=>{const r=/url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)/i;return t("*").reduce((e,t)=>{const a=E(t,"background-image");return r.exec(a)&&e.push(t),e},[])},ps=async e=>{if(!["lastSrc","lastSrcset","lastSiblings","lastBackgroundImage"].some(t=>e[t])){const t=Vo.currentSrc;if("none"!==window.getComputedStyle(e).backgroundImage)e.lastBackgroundImage=window.getComputedStyle(e).backgroundImage,e.style.backgroundImage=`url(${t})`;else{us(e),e.src=t,""!==e.srcset&&(e.srcset=t);const r=ls(e);r.length&&r.forEach(e=>{e.srcset=t})}}},us=e=>{e.lastSrc=e.src,e.lastSrcset=e.srcset;const t=ls(e);t.length&&t.forEach(e=>{e.lastSrcset=e.srcset,e.lastSrc=e.src})},gs=e=>{e.lastSrc&&(e.src=e.lastSrc),e.lastSrcset&&(e.srcset=e.lastSrcset);const t=ls(e);t.length&&t.forEach(e=>{e.lastSrcset&&(e.srcset=e.lastSrcset),e.lastSrc&&(e.src=e.lastSrc)}),e.lastBackgroundImage&&(e.style.backgroundImage=e.lastBackgroundImage),ms(e)},ms=e=>{["lastSrc","lastSrcset","lastBackgroundImage"].forEach(t=>e[t]=null);const t=ls(e);t&&t.forEach(e=>{e.lastSrcset=null,e.lastSrc=null})},fs=e=>e.dataTransfer.types.some(e=>"Files"===e);class xs{constructor(e={}){if(!e.container)throw new Error("VisBugEditor requires a container element");this.container=e.container,this.mode=e.mode,this.initialTool=e.initialTool||"position",this.options=e,this.onToolChange=e.onToolChange,this.onSelectionChange=e.onSelectionChange,this.onChange=e.onChange,this.onImageUpload=e.onImageUpload,this.currentTool=null,this.activeFeature=null,this.selectorEngine=null,this.isInitialized=!1,this.ignoreSelectors=[],this.uiContainer="inside"===this.mode?this.container:document.body,this.historyManager=new f,this.historyManager.on("change",()=>{this.onChange&&this.onChange({canUndo:this.historyManager.canUndo(),canRedo:this.historyManager.canRedo()})}),this.init()}init(){try{this.selectorEngine=function(e){const r=e.container,a=e.historyManager,o=e.getUIContainer();let s=[],n=[],i=[],l=[],c=[];const h={target:null,element:null,label:null},d=t=>!(!t||!e.ignoreSelectors||0===e.ignoreSelectors.length)&&e.ignoreSelectors.some(e=>{try{return t.matches(e)}catch(t){return console.warn(`Invalid CSS selector in ignore list: ${e}`),!1}}),g=()=>{r.addEventListener("click",m,!0),r.addEventListener("dblclick",f,!0),r.addEventListener("selectstart",L),r.addEventListener("mousemove",x),document.addEventListener("copy",F),document.addEventListener("cut",H),document.addEventListener("paste",Y),P(),yo("esc",z),yo(`${T}+d`,B),yo("backspace,del,delete",R),yo("alt+del,alt+backspace",O),yo("tab,shift+tab,enter,shift+enter",j)},m=e=>{const t=I(e.clientX,e.clientY);(!V(t)&&!d(t)||s.filter(e=>e==t).length)&&(e.preventDefault(),e.altKey||e.stopPropagation(),e.shiftKey||v({silent:!0}),e.shiftKey&&t.hasAttribute("data-selected")?b(t.getAttribute("data-label-id")):w(t))},f=t=>{t.preventDefault(),t.stopPropagation(),V(t.target)||e.onDoubleClick&&e.onDoubleClick(t.target)},x=e=>{const t=I(e.clientX,e.clientY);if(!V(t)&&!d(t))return t.hasAttribute("data-selected")||"visbug-hover"===t.nodeName?y():void(h.target&&h.target===t||(y(),h.target=t,h.element=M(t),h.label=S(t,k(t))));h.element&&y()},w=e=>{if(V(e)||d(e)||e.hasAttribute("data-pseudo-select"))return;if(e.hasAttribute("data-selected"))return;h.target===e&&y(),e.setAttribute("data-selected",!0),e.setAttribute("data-selected-hide",!0),s.unshift(e);const t=e.getAttribute("data-label-id")||"label_"+Number(new Date);e.hasAttribute("data-label-id")||e.setAttribute("data-label-id",t);const r=C(e,t),a=S(e,k(e),t);l.push(r),i.push(a);const o=A(e,{label:a,handle:r});o.observe(e,{attributes:!0,attributeFilter:["style","class"]});const n=new MutationObserver(()=>{a&&document.body.contains(a)&&E(e,a),r&&document.body.contains(r)&&_(e,r)});return e.parentElement&&n.observe(e.parentElement,{childList:!0,subtree:!1}),c.push({element:e,observer:o,parentObserver:n,label:a,handle:r}),W(e,()=>{a&&a.remove(),r&&r.remove(),o.disconnect(),n.disconnect(),s=s.filter(t=>t!==e),i=i.filter(e=>e!==a),l=l.filter(e=>e!==r),c=c.filter(t=>t.element!==e),$()}),$(),e},b=e=>{const r=c.find(t=>t.element.getAttribute("data-label-id")===e);r&&(r.observer.disconnect(),r.parentObserver.disconnect(),c=c.filter(e=>e!==r)),[...i,...l].filter(t=>t.getAttribute("data-label-id")===e).forEach(e=>e.remove()),s.filter(t=>t.getAttribute("data-label-id")===e).forEach(e=>t(e).attr({"data-selected":null,"data-selected-hide":null,"data-label-id":null,"data-pseudo-select":null})),s=s.filter(t=>t.getAttribute("data-label-id")!==e),$()},v=({silent:e=!1}={})=>{c.forEach(e=>{e.observer.disconnect(),e.parentObserver.disconnect()}),c=[],s.forEach(e=>e.removeAttribute("data-selected")&&e.removeAttribute("data-selected-hide")&&e.removeAttribute("data-label-id")&&e.removeAttribute("data-pseudo-select")),i.forEach(e=>e.remove()),l.forEach(e=>e.remove()),s=[],l=[],i=[],e||$()},y=()=>{h.element&&(h.element.remove(),h.element=null),h.label&&(h.label.remove(),h.label=null),h.target=null},M=e=>{const t=document.createElement("visbug-hover"),r=e.getBoundingClientRect();return t.position={el:e,boundingRect:r,isFixed:q(e),uiContainer:o},o.appendChild(t),t},k=e=>`${e.nodeName.toLowerCase()}${N(e)}`,S=(e,t,r)=>{const a=document.createElement("visbug-label"),s=e.getBoundingClientRect();return a.text=t,a.position={boundingRect:s,isFixed:q(e),uiContainer:o},r&&a.setAttribute("data-label-id",r),o.appendChild(a),a},C=(e,t)=>{const r=document.createElement("visbug-handles");return e.getBoundingClientRect(),r.position={el:e,node_label_id:t,isFixed:q(e),uiContainer:o},r.setAttribute("data-label-id",t),r.historyManager=a,o.appendChild(r),r},E=(e,t)=>{t.text=k(e),t.update={boundingRect:e.getBoundingClientRect(),isFixed:q(e),uiContainer:o}},_=(e,t)=>{t.position={el:e,node_label_id:e.getAttribute("data-label-id"),isFixed:q(e),uiContainer:o}},A=(e,{label:t,handle:r})=>new MutationObserver(a=>{t&&document.body.contains(t)&&E(e,t),r&&document.body.contains(r)&&_(e,r)}),$=()=>{const t=s;n.forEach(e=>e(t)),e.onSelectionChange&&e.onSelectionChange(t)},P=()=>{const e=document.body;document.addEventListener("keydown",t=>{t[T+"Key"]&&!e.hasAttribute("data-"+T)&&e.setAttribute("data-"+T,!0)}),document.addEventListener("keyup",t=>{!t[T+"Key"]&&e.hasAttribute("data-"+T)&&e.removeAttribute("data-"+T)})},L=e=>e.preventDefault(),z=e=>{e.preventDefault(),v(),y()},B=e=>{if(e.preventDefault(),!a||!s.length)return;const t=[];s.forEach(e=>{const r=e.cloneNode(!0);r.removeAttribute("data-selected"),r.removeAttribute("data-label-id"),e.parentNode.insertBefore(r,e.nextSibling),t.push(new u({element:r,oldParent:null,oldNextSibling:null,newParent:e.parentNode,newNextSibling:e.nextSibling}))}),t.length&&a.push(t)},R=e=>{if(e.preventDefault(),!a||!s.length)return;const t=s.map(e=>{const t=e.parentNode,r=e.nextSibling;return new u({element:e,oldParent:t,oldNextSibling:r,newParent:null,newNextSibling:null})});s.forEach(e=>e.remove()),v(),t.length&&a.push(t)},O=e=>{if(e.preventDefault(),!a||!s.length)return;const t=s.map(e=>{const t=e.getAttribute("style")||"";return new p({element:e,attribute:"style",oldValue:t,newValue:""})});s.forEach(e=>e.removeAttribute("style")),t.length&&a.push(t)},j=e=>{if(!s.length)return;e.preventDefault(),e.stopPropagation();const t=s[0];let r;"Tab"!==e.key||e.shiftKey?"Tab"===e.key&&e.shiftKey?r=t.previousElementSibling:"Enter"!==e.key||e.shiftKey?"Enter"===e.key&&e.shiftKey&&(r=t.parentElement):r=t.firstElementChild:r=t.nextElementSibling,r&&!V(r)&&(v({silent:!0}),w(r))};let D=null;const F=e=>{s.length&&(e.preventDefault(),D=s[0].cloneNode(!0),e.clipboardData.setData("text/html",s[0].outerHTML),e.clipboardData.setData("text/plain",s[0].textContent))},H=e=>{s.length&&(F(e),R(e))},Y=e=>{if(!s.length||!D)return;e.preventDefault();const t=s[0],r=D.cloneNode(!0);t.parentNode.insertBefore(r,t.nextSibling),a&&a.push(new u({element:r,oldParent:null,oldNextSibling:null,newParent:t.parentNode,newNextSibling:t.nextSibling}))};return g(),{listen:g,disconnect:()=>{r.removeEventListener("click",m,!0),r.removeEventListener("dblclick",f,!0),r.removeEventListener("selectstart",L),r.removeEventListener("mousemove",x),document.removeEventListener("copy",F),document.removeEventListener("cut",H),document.removeEventListener("paste",Y),yo.unbind(`esc,${T}+d,backspace,del,delete,alt+del,alt+backspace,tab,shift+tab,enter,shift+enter`)},unselect_all:v,select:w,unselect:b,onSelectedUpdate:e=>{if("function"==typeof e)return n.push(e),()=>{n=n.filter(t=>t!==e)}},selection:()=>s,labels:()=>i,handles:()=>l}}(this),this.selectorEngine.onSelectedUpdate(e=>{this.onSelectionChange&&this.onSelectionChange(e),this.activeFeature?.onNodesSelected&&this.activeFeature.onNodesSelected(e)}),e=this.historyManager,qo.historyManager=e,Ho=t([...document.images,...t("picture"),...ds()]),Ko(Ho),Yo(Ho),this.initialTool&&this.activateTool(this.initialTool),this.isInitialized=!0,console.log("VisBugEditor initialized successfully")}catch(e){throw console.error("Failed to initialize VisBugEditor:",e),e}var e}getEditingContext(){return this.container}getUIContainer(){return this.uiContainer}activateTool(e){switch(this.activeFeature?.disconnect&&(this.activeFeature.disconnect(),this.activeFeature=null),e){case"position":this.activeFeature=Co(this.historyManager);const r=this.getSelectedElements();r.length>0&&this.activeFeature.onNodesSelected(r);break;case"text":this.activeFeature={onNodesSelected:e=>{e.length>0&&function(e,r){e.length&&(Lo.historyManager=r,e.map(e=>{let a=t(e);r&&Lo.originalText.set(e,e.textContent),a.attr({contenteditable:!0,spellcheck:!0}),e.focus(),F(e,!0),a.on("keydown",No),a.on("blur",zo)}))}(e,this.historyManager)},disconnect:()=>{}};break;case"font":this.activeFeature=Io({selection:()=>this.getSelectedElements(),historyManager:this.historyManager});break;default:return void console.warn(`Unknown tool: ${e}`)}this.currentTool=e,this.onToolChange&&this.onToolChange(e),console.log(`Activated tool: ${e}`)}getCurrentTool(){return this.currentTool}selectElement(e){this.selectorEngine&&this.selectorEngine.select(e)}selectElements(e){this.selectorEngine&&(this.selectorEngine.unselect_all({silent:!0}),e.forEach(e=>this.selectorEngine.select(e)))}getSelectedElements(){return this.selectorEngine?this.selectorEngine.selection():[]}clearSelection(){this.selectorEngine&&this.selectorEngine.unselect_all()}undo(){return this.historyManager.undo()}redo(){return this.historyManager.redo()}canUndo(){return this.historyManager.canUndo()}canRedo(){return this.historyManager.canRedo()}getHistory(){return this.historyManager.getHistory()}clearHistory(){this.historyManager.clear()}ignoreList(e){if(!Array.isArray(e))throw new Error("ignoreList expects an array of CSS selector strings");return this.ignoreSelectors=e,this}getIgnoreList(){return[...this.ignoreSelectors]}getContent(){const e=this.getEditingContext().cloneNode(!0);e.querySelectorAll("visbug-handles, visbug-label, visbug-hover, visbug-overlay, [data-visbug-ignore]").forEach(e=>e.remove());return e.querySelectorAll("[data-selected], [data-label-id], [data-visbug]").forEach(e=>{e.removeAttribute("data-selected"),e.removeAttribute("data-label-id"),e.removeAttribute("data-visbug")}),e.innerHTML}setContent(e){const t=this.getEditingContext();this.clearSelection(),this.removeEditorUI(),t.innerHTML=e,!1!==this.options.clearHistoryOnSetContent&&this.historyManager.clear()}removeEditorUI(){this.getUIContainer().querySelectorAll("visbug-handles, visbug-label, visbug-hover, visbug-overlay, [data-visbug-ignore]").forEach(e=>e.remove())}on(e,t){console.log(`Event listener added: ${e}`)}off(e,t){console.log(`Event listener removed: ${e}`)}destroy(){this.activeFeature?.disconnect&&this.activeFeature.disconnect(),this.selectorEngine?.disconnect&&this.selectorEngine.disconnect(),this.removeEditorUI(),this.historyManager.clear(),this.isInitialized=!1,this.currentTool=null,this.activeFeature=null,this.selectorEngine=null,console.log("VisBugEditor destroyed")}}const ws="0.3.0";export{f as HistoryManager,ws as VERSION,xs as VisBugEditor,Ya as utilities};
13
+ const Qa="undefined"!=typeof navigator&&navigator.userAgent.toLowerCase().indexOf("firefox")>0;function eo(e,t,r,a){e.addEventListener?e.addEventListener(t,r,a):e.attachEvent&&e.attachEvent("on".concat(t),r)}function to(e,t,r,a){e.removeEventListener?e.removeEventListener(t,r,a):e.detachEvent&&e.detachEvent("on".concat(t),r)}function ro(e,t){const r=t.slice(0,t.length-1);for(let t=0;t<r.length;t++)r[t]=e[r[t].toLowerCase()];return r}function ao(e){"string"!=typeof e&&(e="");const t=(e=e.replace(/\s/g,"")).split(",");let r=t.lastIndexOf("");for(;r>=0;)t[r-1]+=",",t.splice(r,1),r=t.lastIndexOf("");return t}const oo={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,arrowup:38,arrowdown:40,arrowleft:37,arrowright:39,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":Qa?173:189,"=":Qa?61:187,";":Qa?59:186,"'":222,"{":219,"}":221,"[":219,"]":221,"\\":220},so={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,meta:91,command:91},no={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},io={16:!1,18:!1,17:!1,91:!1},lo={};for(let e=1;e<20;e++)oo["f".concat(e)]=111+e;let co=[],ho=null,po="all";const uo=new Map,go=e=>oo[e.toLowerCase()]||so[e.toLowerCase()]||e.toUpperCase().charCodeAt(0);function mo(e){po=e||"all"}function fo(){return po||"all"}function xo(e){if(void 0===e)Object.keys(lo).forEach(e=>{Array.isArray(lo[e])&&lo[e].forEach(e=>wo(e)),delete lo[e]}),Mo(null);else if(Array.isArray(e))e.forEach(e=>{e.key&&wo(e)});else if("object"==typeof e)e.key&&wo(e);else if("string"==typeof e){for(var t=arguments.length,r=new Array(t>1?t-1:0),a=1;a<t;a++)r[a-1]=arguments[a];let[o,s]=r;"function"==typeof o&&(s=o,o=""),wo({key:e,scope:o,method:s,splitKey:"+"})}}const wo=e=>{let{key:t,scope:r,method:a,splitKey:o="+"}=e;ao(t).forEach(e=>{const t=e.split(o),s=t.length,n=t[s-1],i="*"===n?"*":go(n);if(!lo[i])return;r||(r=fo());const l=s>1?ro(so,t):[],c=[];lo[i]=lo[i].filter(e=>{const t=(!a||e.method===a)&&e.scope===r&&function(e,t){const r=e.length>=t.length?e:t,a=e.length>=t.length?t:e;let o=!0;for(let e=0;e<r.length;e++)-1===a.indexOf(r[e])&&(o=!1);return o}(e.mods,l);return t&&c.push(e.element),!t}),c.forEach(e=>Mo(e))})};function bo(e,t,r,a){if(t.element!==a)return;let o;if(t.scope===r||"all"===t.scope){o=t.mods.length>0;for(const e in io)Object.prototype.hasOwnProperty.call(io,e)&&(!io[e]&&t.mods.indexOf(+e)>-1||io[e]&&-1===t.mods.indexOf(+e))&&(o=!1);(0!==t.mods.length||io[16]||io[18]||io[17]||io[91])&&!o&&"*"!==t.shortcut||(t.keys=[],t.keys=t.keys.concat(co),!1===t.method(e,t)&&(e.preventDefault?e.preventDefault():e.returnValue=!1,e.stopPropagation&&e.stopPropagation(),e.cancelBubble&&(e.cancelBubble=!0)))}}function vo(e,t){const r=lo["*"];let a=e.keyCode||e.which||e.charCode;if(e.key&&"capslock"===e.key.toLowerCase())return;if(!yo.filter.call(this,e))return;if(93!==a&&224!==a||(a=91),-1===co.indexOf(a)&&229!==a&&co.push(a),["metaKey","ctrlKey","altKey","shiftKey"].forEach(t=>{const r=no[t];e[t]&&-1===co.indexOf(r)?co.push(r):!e[t]&&co.indexOf(r)>-1?co.splice(co.indexOf(r),1):"metaKey"===t&&e[t]&&(co=co.filter(e=>e in no||e===a))}),a in io){io[a]=!0;for(const t in so)if(Object.prototype.hasOwnProperty.call(so,t)){const r=no[so[t]];yo[t]=e[r]}if(!r)return}for(const t in io)Object.prototype.hasOwnProperty.call(io,t)&&(io[t]=e[no[t]]);e.getModifierState&&(!e.altKey||e.ctrlKey)&&e.getModifierState("AltGraph")&&(-1===co.indexOf(17)&&co.push(17),-1===co.indexOf(18)&&co.push(18),io[17]=!0,io[18]=!0);const o=fo();if(r)for(let a=0;a<r.length;a++)r[a].scope===o&&("keydown"===e.type&&r[a].keydown||"keyup"===e.type&&r[a].keyup)&&bo(e,r[a],o,t);if(!(a in lo))return;const s=lo[a],n=s.length;for(let r=0;r<n;r++)if(("keydown"===e.type&&s[r].keydown||"keyup"===e.type&&s[r].keyup)&&s[r].key){const a=s[r],{splitKey:n}=a,i=a.key.split(n),l=[];for(let e=0;e<i.length;e++)l.push(go(i[e]));l.sort().join("")===co.sort().join("")&&bo(e,a,o,t)}}function yo(e,t,r){co=[];const a=ao(e);let o=[],s="all",n=document,i=0,l=!1,c=!0,h="+",d=!1,p=!1;for(void 0===r&&"function"==typeof t&&(r=t),"[object Object]"===Object.prototype.toString.call(t)&&(t.scope&&(s=t.scope),t.element&&(n=t.element),t.keyup&&(l=t.keyup),void 0!==t.keydown&&(c=t.keydown),void 0!==t.capture&&(d=t.capture),"string"==typeof t.splitKey&&(h=t.splitKey),!0===t.single&&(p=!0)),"string"==typeof t&&(s=t),p&&xo(e,s);i<a.length;i++)o=[],(e=a[i].split(h)).length>1&&(o=ro(so,e)),(e="*"===(e=e[e.length-1])?"*":go(e))in lo||(lo[e]=[]),lo[e].push({keyup:l,keydown:c,scope:s,mods:o,shortcut:a[i],method:r,key:a[i],splitKey:h,element:n});if(void 0!==n&&window){if(!uo.has(n)){const e=function(){return vo(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.event,n)},t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.event;vo(e,n),function(e){let t=e.keyCode||e.which||e.charCode;e.key&&"capslock"===e.key.toLowerCase()&&(t=go(e.key));const r=co.indexOf(t);if(r>=0&&co.splice(r,1),e.key&&"meta"===e.key.toLowerCase()&&co.splice(0,co.length),93!==t&&224!==t||(t=91),t in io){io[t]=!1;for(const e in so)so[e]===t&&(yo[e]=!1)}}(e)};uo.set(n,{keydownListener:e,keyupListenr:t,capture:d}),eo(n,"keydown",e,d),eo(n,"keyup",t,d)}if(!ho){const e=()=>{co=[]};ho={listener:e,capture:d},eo(window,"focus",e,d)}}}function Mo(e){const t=Object.values(lo).flat();if(t.findIndex(t=>{let{element:r}=t;return r===e})<0){const{keydownListener:t,keyupListenr:r,capture:a}=uo.get(e)||{};t&&r&&(to(e,"keyup",r,a),to(e,"keydown",t,a),uo.delete(e))}if(t.length<=0||uo.size<=0){if(Object.keys(uo).forEach(e=>{const{keydownListener:t,keyupListenr:r,capture:a}=uo.get(e)||{};t&&r&&(to(e,"keyup",r,a),to(e,"keydown",t,a),uo.delete(e))}),uo.clear(),Object.keys(lo).forEach(e=>delete lo[e]),ho){const{listener:e,capture:t}=ho;to(window,"focus",e,t),ho=null}}}const ko={getPressedKeyString:function(){return co.map(e=>{return t=e,Object.keys(oo).find(e=>oo[e]===t)||(e=>Object.keys(so).find(t=>so[t]===e))(e)||String.fromCharCode(e);var t})},setScope:mo,getScope:fo,deleteScope:function(e,t){let r,a;e||(e=fo());for(const t in lo)if(Object.prototype.hasOwnProperty.call(lo,t))for(r=lo[t],a=0;a<r.length;)if(r[a].scope===e){r.splice(a,1).forEach(e=>{let{element:t}=e;return Mo(t)})}else a++;fo()===e&&mo(t||"all")},getPressedKeyCodes:function(){return co.slice(0)},getAllKeyCodes:function(){const e=[];return Object.keys(lo).forEach(t=>{lo[t].forEach(t=>{let{key:r,scope:a,mods:o,shortcut:s}=t;e.push({scope:a,shortcut:s,mods:o,keys:r.split("+").map(e=>go(e))})})}),e},isPressed:function(e){return"string"==typeof e&&(e=go(e)),-1!==co.indexOf(e)},filter:function(e){const t=e.target||e.srcElement,{tagName:r}=t;let a=!0;const o="INPUT"===r&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(t.type);return(t.isContentEditable||(o||"TEXTAREA"===r||"SELECT"===r)&&!t.readOnly)&&(a=!1),a},trigger:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"all";Object.keys(lo).forEach(r=>{lo[r].filter(r=>r.scope===t&&r.shortcut===e).forEach(e=>{e&&e.method&&e.method()})})},unbind:xo,keyMap:oo,modifier:so,modifierMap:no};for(const e in ko)Object.prototype.hasOwnProperty.call(ko,e)&&(yo[e]=ko[e]);if("undefined"!=typeof window){const e=window.hotkeys;yo.noConflict=t=>(t&&window.hotkeys===yo&&(window.hotkeys=e),yo),window.hotkeys=yo}const So="up,down,left,right".split(",").reduce((e,t)=>`${e},${t},alt+${t},shift+${t},shift+alt+${t}`,"").substring(1);function Co(e){const t={elements:[]};yo(So,(r,a)=>{r.cancelBubble||(r.preventDefault(),function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>Po(e)).map(e=>D(e)).map(e=>({el:e,...Eo(e,t),amount:t.split("+").includes("shift")?10:1,negative:$o(e,t)})).map(e=>Object.assign(e,{position:e.negative?e.current+e.amount:e.current-e.amount})).forEach(({el:e,style:a,position:o,current:s})=>{if(e instanceof SVGElement){const a=e.getAttribute("transform");Ao(e,t,o);const s=e.getAttribute("transform");r&&r.push(new p({element:e,attribute:"transform",oldValue:a,newValue:s}))}else{const t=e.style[a],s=o+"px";r&&r.push(new d({element:e,property:a,oldValue:t,newValue:s})),e.style[a]=s}}),e.length>1&&r&&r.endBatch()}(t.elements,a.key,e))});return{onNodesSelected:r=>{t.elements.forEach(e=>e.teardown()),t.elements=r.map(t=>function({el:e,surface:t=e,cursor:r="move",clickEvent:a,historyManager:o}){const s={surface:t,mouse:{down:!1,x:0,y:0},element:{x:0,y:0},travelDistance:0,historyManager:o,initialPosition:null,initialTransform:null,zIndex:null},n=()=>{e.style.transition="none",t.style.cursor=r,t.addEventListener("mousedown",l,!0),t.addEventListener("mouseup",c,!0),document.addEventListener("mousemove",h,!0)},i=()=>{e.style.transition=null,t.style.cursor=null,t.removeEventListener("mousedown",l,!0),t.removeEventListener("mouseup",c,!0),document.removeEventListener("mousemove",h,!0)},l=t=>{if(t.target===s.surface){if(t.preventDefault(),null==s.zIndex&&(s.zIndex=e.style.zIndex,e.style.zIndex=9999999999999),"static"==getComputedStyle(e).position&&(e.style.position="relative"),e.style.willChange="top,left",e instanceof SVGElement){const t=e.getAttribute("transform"),[r,a]=t?_o(t):[0,0];s.element.x=r,s.element.y=a,s.historyManager&&(s.initialTransform=t||null)}else s.element.x=parseInt(E(e,"left")),s.element.y=parseInt(E(e,"top")),s.historyManager&&(s.initialPosition={left:e.style.left,top:e.style.top});s.mouse.x=t.clientX,s.mouse.y=t.clientY,s.mouse.down=!0,s.travelDistance=0}},c=t=>{if(t.target!==s.surface)return;if(t.preventDefault(),t.stopPropagation(),null!=s.zIndex&&(e.style.zIndex=s.zIndex,s.zIndex=null),s.mouse.down=!1,e.style.willChange=null,e instanceof SVGElement){const t=e.getAttribute("transform"),[r,a]=t?_o(t):[0,0];s.historyManager&&s.initialTransform!==t&&(s.historyManager.push(new p({element:e,attribute:"transform",oldValue:s.initialTransform,newValue:t})),s.initialTransform=null),s.element.x=r,s.element.y=a}else if(s.element.x=parseInt(e.style.left)||0,s.element.y=parseInt(e.style.top)||0,s.historyManager&&s.initialPosition){const t=e.style.left,r=e.style.top,a=s.initialPosition.left!==t,o=s.initialPosition.top!==r;(a||o)&&(a&&o&&s.historyManager.beginBatch(),a&&s.historyManager.push(new d({element:e,property:"left",oldValue:s.initialPosition.left,newValue:t})),o&&s.historyManager.push(new d({element:e,property:"top",oldValue:s.initialPosition.top,newValue:r})),a&&o&&s.historyManager.endBatch()),s.initialPosition=null}const r=!s.travelDistance||s.travelDistance<5;a&&r&&a(t),s.travelDistance=0},h=t=>{s.mouse.down&&(t.preventDefault(),t.stopPropagation(),e instanceof SVGElement?e.setAttribute("transform",`translate(\n ${s.element.x+t.clientX-s.mouse.x},\n ${s.element.y+t.clientY-s.mouse.y}\n )`):(e.style.left=s.element.x+t.clientX-s.mouse.x+"px",e.style.top=s.element.y+t.clientY-s.mouse.y+"px"),s.travelDistance+=1)};return n(),e.teardown=i,e}({el:t,historyManager:e}))},disconnect:()=>{t.elements.forEach(e=>e.teardown()),yo.unbind(So),yo.unbind("up,down,left,right")}}}const Eo=(e,t)=>{let r,a;if(e instanceof SVGElement){const o=e.attr("transform"),[s,n]=o?_o(o):[0,0];r="transform",a=t.includes("down")||t.includes("up")?n:s}else{const o=O(t).toLowerCase();r="top"===o||"bottom"===o?"top":"left",a=E(e,r),a="auto"===a?0:parseInt(a,10)}return{style:r,current:a}},_o=e=>e.substring(e.indexOf("(")+1,e.indexOf(")")).split(",").map(e=>parseFloat(e)),Ao=(e,t,r)=>{const a=e.attr("transform"),[o,s]=a?_o(a):[0,0],n=t.includes("down")||t.includes("up")?`${o},${r}`:`${r},${s}`;e.attr("transform",`translate(${n})`)},$o=(e,t)=>t.includes("right")||t.includes("down"),Po=e=>(e instanceof HTMLElement&&(e.style.position="relative"),e),Lo={historyManager:null,originalText:new WeakMap},zo=({target:e})=>{if(Lo.historyManager&&Lo.originalText.has(e)){const t=Lo.originalText.get(e),r=e.textContent;t!==r&&Lo.historyManager.push(new g({element:e,oldText:t,newText:r})),Lo.originalText.delete(e)}e.removeAttribute("contenteditable"),e.removeAttribute("spellcheck"),e.removeEventListener("blur",zo),e.removeEventListener("keydown",No)},No=e=>{"Escape"!==e.key&&"Esc"!==e.key?e.stopPropagation():Bo()},Bo=(e,r)=>{t('[spellcheck="true"]').forEach(e=>zo({target:e})),window.getSelection().empty()};const To="up,down,left,right".split(",").reduce((e,t)=>`${e},${t},shift+${t}`,"").substring(1),Ro=`${T}+up,${T}+down`;function Io({selection:e,historyManager:t}){return yo(To,(r,a)=>{if(r.cancelBubble)return;r.preventDefault();let o=e(),s=a.key.split("+");s.includes("left")||s.includes("right")?s.includes("shift")?function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"letterSpacing",current:parseFloat(E(e,"letterSpacing")),amount:.1,negative:t.split("+").includes("left")})).map(e=>Object.assign(e,{current:"normal"==e.current||isNaN(e.current)?0:e.current})).map(e=>Object.assign(e,{value:e.negative?(e.current-e.amount).toFixed(2):(e.current+e.amount).toFixed(2)})).forEach(({el:e,style:t,value:a,current:o})=>{const s=`${o}px`,n=`${a<=-2?-2:a}px`;r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t):function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"textAlign",current:E(e,"textAlign"),direction:t.split("+").includes("left")})).map(e=>Object.assign(e,{value:e.direction?Do[e.current]-1:Do[e.current]+1})).forEach(({el:e,style:t,value:a,current:o})=>{const s=o,n=Fo[a<0?0:a>=2?2:a];r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t):s.includes("shift")?function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"lineHeight",current:parseInt(E(e,"lineHeight")),amount:1,negative:t.split("+").includes("down")})).map(e=>Object.assign(e,{current:"normal"==e.current||isNaN(e.current)?1.14*parseInt(E(e.el,"fontSize")):e.current})).map(e=>Object.assign(e,{value:e.negative?e.current-e.amount:e.current+e.amount})).forEach(({el:e,style:t,value:a,current:o})=>{const s=`${o}px`,n=`${a}px`;r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t):function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"fontSize",current:parseInt(E(e,"fontSize")),amount:t.split("+").includes("shift")?10:1,negative:t.split("+").includes("down")})).map(e=>Object.assign(e,{font_size:e.negative?e.current-e.amount:e.current+e.amount})).forEach(({el:e,style:t,font_size:a,current:o})=>{const s=`${o}px`,n=`${a<=6?6:a}px`;r&&r.push(new d({element:e,property:t,oldValue:s,newValue:n})),e.style[t]=n}),e.length>1&&r&&r.endBatch()}(o,a.key,t)}),yo(Ro,(r,a)=>{r.preventDefault();let o=a.key.split("+");!function(e,t,r){e.length>1&&r&&r.beginBatch();e.map(e=>D(e)).map(e=>({el:e,style:"fontWeight",current:E(e,"fontWeight"),direction:t.split("+").includes("down")})).map(e=>Object.assign(e,{value:e.direction?Oo[e.current]-1:Oo[e.current]+1})).forEach(({el:e,style:t,value:a,current:o})=>{const s=jo[a<0?0:a>=jo.length?jo.length:a],n=o,i=String(s);r&&r.push(new d({element:e,property:t,oldValue:n,newValue:i})),e.style[t]=s}),e.length>1&&r&&r.endBatch()}(e(),o.includes("up")?"up":"down",t)}),yo("cmd+b",r=>{const a=e();a.length>1&&t&&t.beginBatch(),a.forEach(e=>{const r=e.style.fontWeight;t&&t.push(new d({element:e,property:"fontWeight",oldValue:r,newValue:"bold"==e.style.fontWeight?"":"bold"})),e.style.fontWeight="bold"==e.style.fontWeight?null:"bold"}),a.length>1&&t&&t.endBatch()}),yo("cmd+i",r=>{const a=e();a.length>1&&t&&t.beginBatch(),a.forEach(e=>{const r=e.style.fontStyle;t&&t.push(new d({element:e,property:"fontStyle",oldValue:r,newValue:"italic"==e.style.fontStyle?"":"italic"})),e.style.fontStyle="italic"==e.style.fontStyle?null:"italic"}),a.length>1&&t&&t.endBatch()}),()=>{yo.unbind(To),yo.unbind(Ro),yo.unbind("cmd+b,cmd+i"),yo.unbind("up,down,left,right")}}const Oo={normal:2,bold:5,light:0,"":2,100:0,200:1,300:2,400:3,500:4,600:5,700:6,800:7,900:8,1e3:9},jo=[100,200,300,400,500,600,700,800,900,1e3];const Do={start:0,left:0,center:1,right:2},Fo=["left","center","right"];let Vo,Ho=[],Wo=[];const qo={watching:!0,historyManager:null,imageCache:new Map};const Yo=e=>{e.on("dragover",Qo),e.on("dragleave",es),e.on("drop",ts),t(document.body).on("dragover",Qo),t(document.body).on("dragleave",es),t(document.body).on("drop",ts),t(document.body).on("dragstart",Zo),t(document.body).on("dragend",Jo)},Ko=e=>{e.off("dragover",Qo),e.off("dragleave",es),e.off("drop",ts),t(document.body).off("dragover",Qo),t(document.body).off("dragleave",es),t(document.body).off("drop",ts),t(document.body).off("dragstart",Zo),t(document.body).off("dragend",Jo),e=[]},Uo=e=>new Promise((t,r)=>{let a=new FileReader;a.readAsDataURL(e),a.onloadend=()=>t(a.result)}),Go=async e=>{if(qo.imageCache.has(e)||e.startsWith("data:")||e.startsWith("blob:"))return qo.imageCache.get(e)||e;try{const t=await fetch(e),r=await t.blob(),a=URL.createObjectURL(r);return qo.imageCache.set(e,a),a}catch(t){return console.warn("Failed to cache image:",e,t),e}},Xo=e=>qo.imageCache.get(e)||e,Zo=({target:e})=>Vo=e,Jo=e=>Vo=void 0,Qo=async e=>{e.preventDefault(),e.stopPropagation();const r=t("img[data-selected=true], [data-selected=true] > img");Ho.some(t=>t===e.target)&&(r.length?(r.some(t=>t==e.target)&&!fs(e)&&r.forEach(e=>ps(e)),r.forEach((e,t)=>cs(e,t))):(fs(e)||ps(e.target),cs(e.currentTarget,0)))},es=e=>{e.stopPropagation();const r=t("img[data-selected=true], [data-selected=true] > img");r.some(t=>t===e.target)?r.forEach(e=>gs(e)):gs(e.target),hs()},ts=async e=>{e.stopPropagation(),e.preventDefault();const r=await rs(Vo,e);if(r.length){const a=t("img[data-selected=true], [data-selected=true] > img"),o=as(a,e);if(o.length)os(o,r);else{const t=ns(Ho,e);is(t,r[0])}}hs()},rs=async(e,t)=>e?[e.currentSrc]:t.dataTransfer.files.length?await Promise.all([...t.dataTransfer.files].filter(e=>e.type.includes("image")).map(Uo)):[],as=(e,t)=>e.length?e:"IMG"!==t.target.nodeName||e.length?[]:[t.target],os=async(e,t)=>{e.length>1&&qo.historyManager&&qo.historyManager.beginBatch();let r=0;for(const a of e)ms(a),await ss(a,t[r]),r=++r%t.length;e.length>1&&qo.historyManager&&qo.historyManager.endBatch()},ss=async(e,t)=>{const r=e.getAttribute("src"),a=e.getAttribute("srcset")||"";!r||r.startsWith("data:")||r.startsWith("blob:")||Go(r).catch(()=>{});let o=t;t.startsWith("data:")||t.startsWith("blob:")||(o=await Go(t)),e.src=o,""!==e.srcset&&(e.srcset=o),qo.historyManager&&(qo.historyManager.push(new p({element:e,attribute:"src",oldValue:Xo(r)||r,newValue:o})),""!==a&&qo.historyManager.push(new p({element:e,attribute:"srcset",oldValue:Xo(a)||a,newValue:o})));const s=ls(e);s.length&&qo.historyManager&&s.forEach(e=>{const t=e.getAttribute("srcset");e.srcset=o,qo.historyManager.push(new p({element:e,attribute:"srcset",oldValue:Xo(t)||t,newValue:o}))})},ns=(e,t)=>e.filter(e=>e.contains(t.target)),is=(e,t)=>{e.length>1&&qo.historyManager&&qo.historyManager.beginBatch(),e.forEach(e=>{if(ms(e),"none"!=window.getComputedStyle(e).backgroundImage){const r=e.style.backgroundImage,a=`url(${t})`;qo.historyManager&&qo.historyManager.push(new d({element:e,property:"backgroundImage",oldValue:r,newValue:a})),e.style.backgroundImage=a}}),e.length>1&&qo.historyManager&&qo.historyManager.endBatch()},ls=e=>Array.from(e.parentElement.children).filter(e=>"SOURCE"===e.nodeName).filter(e=>!e.media||window.matchMedia(e.media).matches),cs=(e,t)=>{const r=e.getBoundingClientRect(),a=Wo[t];a?a.update=r:(Wo[t]=document.createElement("visbug-overlay"),Wo[t].position=r,document.body.appendChild(Wo[t]))},hs=()=>{Wo.forEach(e=>e.remove()),Wo=[]},ds=e=>{const r=/url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)/i;return t("*").reduce((e,t)=>{const a=E(t,"background-image");return r.exec(a)&&e.push(t),e},[])},ps=async e=>{if(!["lastSrc","lastSrcset","lastSiblings","lastBackgroundImage"].some(t=>e[t])){const t=Vo.currentSrc;if("none"!==window.getComputedStyle(e).backgroundImage)e.lastBackgroundImage=window.getComputedStyle(e).backgroundImage,e.style.backgroundImage=`url(${t})`;else{us(e),e.src=t,""!==e.srcset&&(e.srcset=t);const r=ls(e);r.length&&r.forEach(e=>{e.srcset=t})}}},us=e=>{e.lastSrc=e.src,e.lastSrcset=e.srcset;const t=ls(e);t.length&&t.forEach(e=>{e.lastSrcset=e.srcset,e.lastSrc=e.src})},gs=e=>{e.lastSrc&&(e.src=e.lastSrc),e.lastSrcset&&(e.srcset=e.lastSrcset);const t=ls(e);t.length&&t.forEach(e=>{e.lastSrcset&&(e.srcset=e.lastSrcset),e.lastSrc&&(e.src=e.lastSrc)}),e.lastBackgroundImage&&(e.style.backgroundImage=e.lastBackgroundImage),ms(e)},ms=e=>{["lastSrc","lastSrcset","lastBackgroundImage"].forEach(t=>e[t]=null);const t=ls(e);t&&t.forEach(e=>{e.lastSrcset=null,e.lastSrc=null})},fs=e=>e.dataTransfer.types.some(e=>"Files"===e);class xs{constructor(e={}){if(!e.container)throw new Error("VisBugEditor requires a container element");this.container=e.container,this.mode=e.mode,this.initialTool=e.initialTool||"position",this.options=e,this.onToolChange=e.onToolChange,this.onSelectionChange=e.onSelectionChange,this.onChange=e.onChange,this.onImageUpload=e.onImageUpload,this.currentTool=null,this.activeFeature=null,this.selectorEngine=null,this.isInitialized=!1,this.ignoreSelectors=[],this.uiContainer="inside"===this.mode?this.container:document.body,this.historyManager=new f,this.historyManager.on("change",()=>{this.onChange&&this.onChange({canUndo:this.historyManager.canUndo(),canRedo:this.historyManager.canRedo()})}),this.init()}init(){try{this.selectorEngine=function(e){const r=e.container,a=e.historyManager,o=e.getUIContainer();let s=[],n=[],i=[],l=[],c=[];const h={target:null,element:null,label:null},d=t=>!(!t||!e.ignoreSelectors||0===e.ignoreSelectors.length)&&e.ignoreSelectors.some(e=>{try{return t.matches(e)}catch(t){return console.warn(`Invalid CSS selector in ignore list: ${e}`),!1}}),g=()=>{r.addEventListener("click",m,!0),r.addEventListener("dblclick",f,!0),r.addEventListener("selectstart",L),r.addEventListener("mousemove",x),document.addEventListener("copy",F),document.addEventListener("cut",H),document.addEventListener("paste",Y),P(),yo("esc",z),yo(`${T}+d`,B),yo("backspace,del,delete",R),yo("alt+del,alt+backspace",O),yo("tab,shift+tab,enter,shift+enter",j)},m=e=>{const t=I(e.clientX,e.clientY);(!V(t)&&!d(t)||s.filter(e=>e==t).length)&&(e.preventDefault(),e.altKey||e.stopPropagation(),e.shiftKey||v({silent:!0}),e.shiftKey&&t.hasAttribute("data-selected")?b(t.getAttribute("data-label-id")):w(t))},f=t=>{t.preventDefault(),t.stopPropagation(),V(t.target)||e.onDoubleClick&&e.onDoubleClick(t.target)},x=e=>{const t=I(e.clientX,e.clientY);if(!V(t)&&!d(t))return t.hasAttribute("data-selected")||"visbug-hover"===t.nodeName?y():void(h.target&&h.target===t||(y(),h.target=t,h.element=M(t),h.label=S(t,k(t))));h.element&&y()},w=e=>{if(V(e)||d(e)||e.hasAttribute("data-pseudo-select"))return;if(e.hasAttribute("data-selected"))return;h.target===e&&y(),e.setAttribute("data-selected",!0),e.setAttribute("data-selected-hide",!0),s.unshift(e);const t=e.getAttribute("data-label-id")||"label_"+Number(new Date);e.hasAttribute("data-label-id")||e.setAttribute("data-label-id",t);const r=C(e,t),a=S(e,k(e),t);l.push(r),i.push(a);const o=A(e,{label:a,handle:r});o.observe(e,{attributes:!0,attributeFilter:["style","class"]});const n=new MutationObserver(()=>{a&&document.body.contains(a)&&E(e,a),r&&document.body.contains(r)&&_(e,r)});return e.parentElement&&n.observe(e.parentElement,{childList:!0,subtree:!1}),c.push({element:e,observer:o,parentObserver:n,label:a,handle:r}),W(e,()=>{a&&a.remove(),r&&r.remove(),o.disconnect(),n.disconnect(),s=s.filter(t=>t!==e),i=i.filter(e=>e!==a),l=l.filter(e=>e!==r),c=c.filter(t=>t.element!==e),$()}),$(),e},b=e=>{const r=c.find(t=>t.element.getAttribute("data-label-id")===e);r&&(r.observer.disconnect(),r.parentObserver.disconnect(),c=c.filter(e=>e!==r)),[...i,...l].filter(t=>t.getAttribute("data-label-id")===e).forEach(e=>e.remove()),s.filter(t=>t.getAttribute("data-label-id")===e).forEach(e=>t(e).attr({"data-selected":null,"data-selected-hide":null,"data-label-id":null,"data-pseudo-select":null})),s=s.filter(t=>t.getAttribute("data-label-id")!==e),$()},v=({silent:e=!1}={})=>{c.forEach(e=>{e.observer.disconnect(),e.parentObserver.disconnect()}),c=[],s.forEach(e=>e.removeAttribute("data-selected")&&e.removeAttribute("data-selected-hide")&&e.removeAttribute("data-label-id")&&e.removeAttribute("data-pseudo-select")),i.forEach(e=>e.remove()),l.forEach(e=>e.remove()),s=[],l=[],i=[],e||$()},y=()=>{h.element&&(h.element.remove(),h.element=null),h.label&&(h.label.remove(),h.label=null),h.target=null},M=e=>{const t=document.createElement("visbug-hover"),r=e.getBoundingClientRect();return t.position={el:e,boundingRect:r,isFixed:q(e),uiContainer:o},o.appendChild(t),t},k=e=>`${e.nodeName.toLowerCase()}${N(e)}`,S=(e,t,r)=>{const a=document.createElement("visbug-label"),s=e.getBoundingClientRect();return a.text=t,a.position={boundingRect:s,isFixed:q(e),uiContainer:o},r&&a.setAttribute("data-label-id",r),o.appendChild(a),a},C=(e,t)=>{const r=document.createElement("visbug-handles");return e.getBoundingClientRect(),r.position={el:e,node_label_id:t,isFixed:q(e),uiContainer:o},r.setAttribute("data-label-id",t),r.historyManager=a,o.appendChild(r),r},E=(e,t)=>{t.text=k(e),t.update={boundingRect:e.getBoundingClientRect(),isFixed:q(e),uiContainer:o}},_=(e,t)=>{t.position={el:e,node_label_id:e.getAttribute("data-label-id"),isFixed:q(e),uiContainer:o}},A=(e,{label:t,handle:r})=>new MutationObserver(a=>{t&&document.body.contains(t)&&E(e,t),r&&document.body.contains(r)&&_(e,r)}),$=()=>{const t=s;n.forEach(e=>e(t)),e.onSelectionChange&&e.onSelectionChange(t)},P=()=>{const e=document.body;document.addEventListener("keydown",t=>{t[T+"Key"]&&!e.hasAttribute("data-"+T)&&e.setAttribute("data-"+T,!0)}),document.addEventListener("keyup",t=>{!t[T+"Key"]&&e.hasAttribute("data-"+T)&&e.removeAttribute("data-"+T)})},L=e=>e.preventDefault(),z=e=>{e.preventDefault(),v(),y()},B=e=>{if(e.preventDefault(),!a||!s.length)return;const t=[];s.forEach(e=>{const r=e.cloneNode(!0);r.removeAttribute("data-selected"),r.removeAttribute("data-label-id"),e.parentNode.insertBefore(r,e.nextSibling),t.push(new u({element:r,oldParent:null,oldNextSibling:null,newParent:e.parentNode,newNextSibling:e.nextSibling}))}),t.length&&a.push(t)},R=e=>{if(e.preventDefault(),!a||!s.length)return;const t=s.map(e=>{const t=e.parentNode,r=e.nextSibling;return new u({element:e,oldParent:t,oldNextSibling:r,newParent:null,newNextSibling:null})});s.forEach(e=>e.remove()),v(),t.length&&a.push(t)},O=e=>{if(e.preventDefault(),!a||!s.length)return;const t=s.map(e=>{const t=e.getAttribute("style")||"";return new p({element:e,attribute:"style",oldValue:t,newValue:""})});s.forEach(e=>e.removeAttribute("style")),t.length&&a.push(t)},j=e=>{if(!s.length)return;e.preventDefault(),e.stopPropagation();const t=s[0];let r;"Tab"!==e.key||e.shiftKey?"Tab"===e.key&&e.shiftKey?r=t.previousElementSibling:"Enter"!==e.key||e.shiftKey?"Enter"===e.key&&e.shiftKey&&(r=t.parentElement):r=t.firstElementChild:r=t.nextElementSibling,r&&!V(r)&&(v({silent:!0}),w(r))};let D=null;const F=e=>{s.length&&(e.preventDefault(),D=s[0].cloneNode(!0),e.clipboardData.setData("text/html",s[0].outerHTML),e.clipboardData.setData("text/plain",s[0].textContent))},H=e=>{s.length&&(F(e),R(e))},Y=e=>{if(!s.length||!D)return;e.preventDefault();const t=s[0],r=D.cloneNode(!0);t.parentNode.insertBefore(r,t.nextSibling),a&&a.push(new u({element:r,oldParent:null,oldNextSibling:null,newParent:t.parentNode,newNextSibling:t.nextSibling}))};return g(),{listen:g,disconnect:()=>{r.removeEventListener("click",m,!0),r.removeEventListener("dblclick",f,!0),r.removeEventListener("selectstart",L),r.removeEventListener("mousemove",x),document.removeEventListener("copy",F),document.removeEventListener("cut",H),document.removeEventListener("paste",Y),yo.unbind(`esc,${T}+d,backspace,del,delete,alt+del,alt+backspace,tab,shift+tab,enter,shift+enter`)},unselect_all:v,select:w,unselect:b,onSelectedUpdate:e=>{if("function"==typeof e)return n.push(e),()=>{n=n.filter(t=>t!==e)}},selection:()=>s,labels:()=>i,handles:()=>l}}(this),this.selectorEngine.onSelectedUpdate(e=>{this.onSelectionChange&&this.onSelectionChange(e),this.activeFeature?.onNodesSelected&&this.activeFeature.onNodesSelected(e)}),e=this.historyManager,qo.historyManager=e,Ho=t([...document.images,...t("picture"),...ds()]),Ko(Ho),Yo(Ho),this.initialTool&&this.activateTool(this.initialTool),this.isInitialized=!0,console.log("VisBugEditor initialized successfully")}catch(e){throw console.error("Failed to initialize VisBugEditor:",e),e}var e}getEditingContext(){return this.container}getUIContainer(){return this.uiContainer}activateTool(e){switch(this.activeFeature?.disconnect&&(this.activeFeature.disconnect(),this.activeFeature=null),e){case"position":this.activeFeature=Co(this.historyManager);const r=this.getSelectedElements();r.length>0&&this.activeFeature.onNodesSelected(r);break;case"text":this.activeFeature={onNodesSelected:e=>{e.length>0&&function(e,r){e.length&&(Lo.historyManager=r,e.map(e=>{let a=t(e);r&&Lo.originalText.set(e,e.textContent),a.attr({contenteditable:!0,spellcheck:!0}),e.focus(),F(e,!0),a.on("keydown",No),a.on("blur",zo)}))}(e,this.historyManager)},disconnect:()=>{}};break;case"font":this.activeFeature=Io({selection:()=>this.getSelectedElements(),historyManager:this.historyManager});break;default:return void console.warn(`Unknown tool: ${e}`)}this.currentTool=e,this.onToolChange&&this.onToolChange(e),console.log(`Activated tool: ${e}`)}getCurrentTool(){return this.currentTool}selectElement(e){this.selectorEngine&&this.selectorEngine.select(e)}selectElements(e){this.selectorEngine&&(this.selectorEngine.unselect_all({silent:!0}),e.forEach(e=>this.selectorEngine.select(e)))}getSelectedElements(){return this.selectorEngine?this.selectorEngine.selection():[]}clearSelection(){this.selectorEngine&&this.selectorEngine.unselect_all()}undo(){return this.historyManager.undo()}redo(){return this.historyManager.redo()}canUndo(){return this.historyManager.canUndo()}canRedo(){return this.historyManager.canRedo()}getHistory(){return this.historyManager.getHistory()}clearHistory(){this.historyManager.clear()}ignoreList(e){if(!Array.isArray(e))throw new Error("ignoreList expects an array of CSS selector strings");return this.ignoreSelectors=e,this}getIgnoreList(){return[...this.ignoreSelectors]}getContent(){const e=this.getEditingContext().cloneNode(!0);e.querySelectorAll("visbug-handles, visbug-label, visbug-hover, visbug-overlay, [data-visbug-ignore]").forEach(e=>e.remove());return e.querySelectorAll("[data-selected], [data-label-id], [data-visbug]").forEach(e=>{e.removeAttribute("data-selected"),e.removeAttribute("data-label-id"),e.removeAttribute("data-visbug")}),e.innerHTML}setContent(e){const t=this.getEditingContext();this.clearSelection(),this.removeEditorUI(),t.innerHTML=e,!1!==this.options.clearHistoryOnSetContent&&this.historyManager.clear()}removeEditorUI(){this.getUIContainer().querySelectorAll("visbug-handles, visbug-label, visbug-hover, visbug-overlay, [data-visbug-ignore]").forEach(e=>e.remove())}on(e,t){console.log(`Event listener added: ${e}`)}off(e,t){console.log(`Event listener removed: ${e}`)}destroy(){this.activeFeature?.disconnect&&this.activeFeature.disconnect(),this.selectorEngine?.disconnect&&this.selectorEngine.disconnect(),this.removeEditorUI(),this.historyManager.clear(),this.isInitialized=!1,this.currentTool=null,this.activeFeature=null,this.selectorEngine=null,console.log("VisBugEditor destroyed")}}const ws="0.4.0";export{f as HistoryManager,ws as VERSION,xs as VisBugEditor,Ya as utilities};