diff --git a/docs/assets/filehandling.4cb07dc9.js b/docs/assets/filehandling.618c218c.js similarity index 82% rename from docs/assets/filehandling.4cb07dc9.js rename to docs/assets/filehandling.618c218c.js index 4bc85fa..faa06af 100644 --- a/docs/assets/filehandling.4cb07dc9.js +++ b/docs/assets/filehandling.618c218c.js @@ -1 +1 @@ -import{i as n,F as o}from"./index.ecc37913.js";import{s as r}from"./vendor.219e5f4d.js";window.launchQueue.setConsumer(async e=>{if(!!e.files.length)for(const t of e.files){const s=await t.getFile();if(s.type.startsWith("image/")){const i=URL.createObjectURL(s);n.addEventListener("load",()=>{URL.revokeObjectURL(i)},{once:!0}),n.src=i,await r(o,t);return}}}); +import{i as n,F as o}from"./index.54ec3c4a.js";import{s as r}from"./vendor.219e5f4d.js";window.launchQueue.setConsumer(async e=>{if(!!e.files.length)for(const t of e.files){const s=await t.getFile();if(s.type.startsWith("image/")){const i=URL.createObjectURL(s);n.addEventListener("load",()=>{URL.revokeObjectURL(i)},{once:!0}),n.src=i,await r(o,t);return}}}); diff --git a/docs/assets/index.54ec3c4a.js b/docs/assets/index.54ec3c4a.js new file mode 100644 index 0000000..35676af --- /dev/null +++ b/docs/assets/index.54ec3c4a.js @@ -0,0 +1,26 @@ +import{_ as st,u as ye,s as P,g as V,C as it,d as ct,o as lt,a as ut,c as dt,p as mt,b as Me,e as pt,f as ht,h as ft,v as gt}from"./vendor.219e5f4d.js";const vt=function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerpolicy&&(o.referrerPolicy=a.referrerpolicy),a.crossorigin==="use-credentials"?o.credentials="include":a.crossorigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}};vt();const yt="modulepreload",Ae={},wt="/",E=function(t,n){return!n||n.length===0?t():Promise.all(n.map(r=>{if(r=`${wt}${r}`,r in Ae)return;Ae[r]=!0;const a=r.endsWith(".css"),o=a?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${r}"]${o}`))return;const s=document.createElement("link");if(s.rel=a?"stylesheet":yt,a||(s.as="script",s.crossOrigin=""),s.href=r,document.head.appendChild(s),a)return new Promise((i,c)=>{s.addEventListener("load",i),s.addEventListener("error",c)})})).then(()=>t())},I=document.querySelector("canvas"),vn=document.querySelector(".menu"),yn=document.querySelector("main"),ze=document.querySelector(".details"),k=document.querySelector(".posterize"),bt=document.querySelector("[for=posterize]"),y=document.querySelector(".color"),Lt=document.querySelector("[for=color]"),C=document.querySelector(".monochrome"),St=document.querySelector("[for=monochrome]"),_=document.querySelector(".consider-dpr"),Et=document.querySelector('[for="consider-dpr"]'),x=document.querySelector(".optimize-curves"),kt=document.querySelector('[for="optimize-curves"]'),A=document.querySelector(".show-advanced"),xt=document.querySelector('[for="show-advanced"]'),h=document.querySelector("img"),we=document.querySelector(".reset-all"),ne=document.querySelector(".open"),re=document.querySelector(".save"),ae=document.querySelector(".copy"),oe=document.querySelector(".paste"),se=document.querySelector(".install"),f=document.querySelector(".svg-output"),Ct=document.querySelector(".debug"),ie=document.querySelector("progress"),ce=document.querySelector(".toast"),le=document.documentElement,be=document.querySelector("details.main"),Le=document.querySelector("summary"),Ne=document.querySelector(".close-options-button"),Ot=document.querySelector(".license"),_t=document.querySelector(".about"),De=document.querySelector("pinch-zoom"),G=window.devicePixelRatio;De.addEventListener("change",()=>{const{x:e,y:t,scale:n}=De;f.setAttribute("transform",`translate(${e}, ${t}) scale(${n})`)});const We=()=>{f.setAttribute("transform","")},ue=(e,t)=>{let n;return function(...a){const o=()=>{clearTimeout(n),e(...a)};clearTimeout(n),n=setTimeout(o,t)}};/*! + * canvas-size + * v1.2.5 + * https://github.com/jhildenbiddle/canvas-size + * (c) 2015-2021 John Hildenbiddle + * MIT license + */function $e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function b(e){for(var t=1;t=0)&&(n[a]=e[a]);return n}function It(e,t){if(e==null)return{};var n=Pt(e,t),r,a;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&(!Object.prototype.propertyIsEnumerable.call(e,r)||(n[r]=e[r]))}return n}function qe(e,t){return jt(e)||At(e,t)||Ue(e,t)||Nt()}function de(e){return Rt(e)||Mt(e)||Ue(e)||zt()}function Rt(e){if(Array.isArray(e))return Se(e)}function jt(e){if(Array.isArray(e))return e}function Mt(e){if(typeof Symbol!="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function At(e,t){var n=e==null?null:typeof Symbol!="undefined"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r=[],a=!0,o=!1,s,i;try{for(n=n.call(e);!(a=(s=n.next()).done)&&(r.push(s.value),!(t&&r.length===t));a=!0);}catch(c){o=!0,i=c}finally{try{!a&&n.return!=null&&n.return()}finally{if(o)throw i}}return r}}function Ue(e,t){if(!!e){if(typeof e=="string")return Se(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Se(e,t)}}function Se(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=o;){var c=t||n?i:1,l=t||r?i:1;a.push([c,l]),i-=s}return a}function me(e){var t=window&&"HTMLCanvasElement"in window,n=window&&"OffscreenCanvas"in window,r=Date.now(),a=e.onError,o=e.onSuccess,s=It(e,Dt),i=null;if(!t)return!1;if(e.useWorker&&n){var c=` + var canvasTest = `.concat(J.toString(),`; + onmessage = function(e) { + canvasTest(e.data); + }; + `),l=new Blob([c],{type:"application/javascript"}),d=URL.createObjectURL(l);i=new Worker(d),URL.revokeObjectURL(d),i.onmessage=function(u){var g=u.data,L=g.width,ee=g.height,te=g.benchmark,ge=g.isTestPass;ge?(K[r].onSuccess(L,ee,te),delete K[r]):K[r].onError(L,ee,te)}}if(e.usePromise)return new Promise(function(u,g){var L=b(b({},e),{},{onError:function(U,H,B){var ve;if(e.sizes.length===0)ve=!0;else{var nt=e.sizes.slice(-1),rt=qe(nt,1),je=qe(rt[0],2),at=je[0],ot=je[1];ve=U===at&&H===ot}a(U,H,B),ve&&g({width:U,height:H,benchmark:B})},onSuccess:function(U,H,B){o(U,H,B),u({width:U,height:H,benchmark:B})}});if(i){var ee=L.onError,te=L.onSuccess;K[r]={onError:ee,onSuccess:te},i.postMessage(s)}else J(L)});if(i)K[r]={onError:a,onSuccess:o},i.postMessage(s);else return J(e)}var Wt={maxArea:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=ke({width:t.max,height:t.max,min:t.min,step:t.step,sizes:de(Ee.area)}),r=b(b(b({},F),t),{},{sizes:n});return me(r)},maxHeight:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=ke({width:1,height:t.max,min:t.min,step:t.step,sizes:de(Ee.height)}),r=b(b(b({},F),t),{},{sizes:n});return me(r)},maxWidth:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=ke({width:t.max,height:1,min:t.min,step:t.step,sizes:de(Ee.width)}),r=b(b(b({},F),t),{},{sizes:n});return me(r)},test:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=b(b({},F),t);return n.sizes=de(n.sizes),n.width&&n.height&&(n.sizes=[[n.width,n.height]]),me(n)}};let He,Ve;const Ge="OffscreenCanvas"in window&&"CanvasFilter"in window;if(Ge)E(()=>import("./preprocessworker.c921728e.js"),[]).then(e=>{const t=e.default;let n=null;const r=I.getContext("2d");He=async()=>{n&&n.terminate(),n=new t;const a=I.cloneNode().transferControlToOffscreen();return n.postMessage({offscreen:a},[a]),new Promise(async o=>{const{width:s,height:i}=Fe();let c;try{c=await createImageBitmap(h)}catch{try{c=await createImageBitmap(h,0,0,s,i)}catch(d){console.error(d.name,d.message),f.innerHTML="",S(d.message);return}}const l=new MessageChannel;l.port1.onmessage=({data:d})=>{l.port1.close(),n&&(n.terminate(),n=null),I.width=s,I.height=i,r.putImageData(d.result,0,0),o(d.result)},n.postMessage({inputImageBitmap:c,posterize:k.checked,rgba:{r:R(p[w.red]),g:R(p[w.green]),b:R(p[w.blue]),a:R(p[w.alpha])},cssFilters:Be(),width:s,height:i,dpr:G},[l.port2])})}});else{const e=I.getContext("2d",{desynchronized:!0});e.scale(G,G),e.imageSmoothingEnabled=!0,Ve=()=>{let{width:t,height:n}=Fe();const r=_.checked?G:1;let a=1;for(;!Wt.test({width:t,height:n});)t=Math.floor(t/2),n=Math.floor(n/2),a/=2;return I.width=t,I.height=n,e.clearRect(0,0,t,n),e.filter=qt(),e.drawImage(h,0,0,r*h.naturalWidth*a,r*h.naturalHeight*a,0,0,t,n),e.getImageData(0,0,t,n)}}const Fe=()=>{const e=Number(p[Ze.scale].value)/100;return{width:Math.ceil(G*h.naturalWidth*e),height:Math.ceil(G*h.naturalHeight*e)}},R=e=>{const t=Number(e.value),n=[];for(let r=0;r<=t;r++)n[r]=Number((1/t*r).toFixed(1));return n},$t=()=>`data:image/svg+xml;utf8, + + + + + + + + + `.replace(/[\r\n]/g,"").replace(/\s+/g," ").trim(),Be=()=>{let e="";for(const[t,n]of Object.entries(Xe)){const r=p[t];n.initial!==Number(r.value)&&(e+=`${t}(${r.value}${r.dataset.unit}) `)}return e},qt=()=>{let e=`${k.checked?`url('${$t()}#posterize') `:""}`;return e+=Be(),e.trim()||"none"};function Ut(){return new Worker("/assets/monochromeworker.3e780118.js",{type:"module"})}let z=null;const Ht=async e=>(z&&z.terminate(),z=new Ut,new Promise(async t=>{const n=new MessageChannel;n.port1.onmessage=({data:a})=>{n.port1.close(),z&&(z.terminate(),z=null),t(a.result)};const r={turdsize:Number(p[v.turdsize].value),alphamax:Number(p[v.alphamax].value),turnpolicy:Number(p[v.turnpolicy].value),opttolerance:Number(p[v.opttolerance].value),opticurve:x.checked?1:0};z.postMessage({imageData:e,params:r},[n.port2])}));function Vt(){return new Worker("/assets/colorworker.3bb51423.js",{type:"module"})}let N=null;const T={},Gt=async e=>(N&&N.terminate(),N=new Vt,new Promise(async t=>{const n=new MessageChannel;n.port1.onmessage=({data:l})=>{n.port1.close(),N&&(N.terminate(),N=null),t(l.result)},ie.value=0;let r="",a="",o="",s=0;T.current&&(clearInterval(T.current),T.current=null),T.current=setInterval(()=>{const l=`${r}${o}${a}`;if(l.length!==s){const d=f.dataset.transform;d&&f.setAttribute("transform",d),f.innerHTML=l,s=l.length}},500);const i=new MessageChannel;i.port1.onmessage=({data:l})=>{const d=Math.floor(l.processed/l.total*100);ie.value=d,l.svg&&(r||(r=l.svg.replace(/(.*?]+>)(.*?)(<\/svg>)/,"$1").replace(/\s+width="\d+(?:\.\d+)?"/,"").replace(/\s+height="\d+(?:\.\d+)"/,""),a=l.svg.replace(/(.*?]+>)(.*?)(<\/svg>)/,"$3")),o+=l.svg.replace(/(.*?]+>)(.*?)(<\/svg>)/,"$2")),l.processed===l.total&&(clearInterval(T.current),T.current=null,i.port1.close(),ie.value=0)};const c={minPathSegments:Number(p[v.minPathLenght].value),strokeWidth:Number(p[v.strokeWidth].value),turdsize:Number(p[v.turdsize].value),alphamax:Number(p[v.alphamax].value),turnpolicy:Number(p[v.turnpolicy].value),opttolerance:Number(p[v.opttolerance].value),opticurve:x.checked?1:0};N.postMessage({imageData:e,params:c},[n.port2,i.port2])}));function Ft(e){switch(e){case"../i18n/de-DE.js":return E(()=>import("./de-DE.0c064cfc.js"),[]);case"../i18n/el-GR.js":return E(()=>import("./el-GR.b0c8940a.js"),[]);case"../i18n/en-US.js":return E(()=>import("./en-US.ca3bb092.js"),[]);default:return new Promise(function(t,n){(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(n.bind(null,new Error("Unknown variable dynamic import: "+e)))})}}function Bt(e){switch(e){case"../i18n/de-DE.js":return E(()=>import("./de-DE.0c064cfc.js"),[]);case"../i18n/el-GR.js":return E(()=>import("./el-GR.b0c8940a.js"),[]);case"../i18n/en-US.js":return E(()=>import("./en-US.ca3bb092.js"),[]);default:return new Promise(function(t,n){(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(n.bind(null,new Error("Unknown variable dynamic import: "+e)))})}}const Je="language",xe=["en","de","el"],Jt=["en-US","de-DE","el-GR"];class Kt{constructor(){this.currentLanguageAndLocale=this.detectLanguageAndLocal(),this.defaultLanguage=xe[0],this.defaultLocale=Jt[0],this.translations=null}detectLanguageAndLocal(){const t=localStorage.getItem(Je);if(t)return JSON.parse(t);let[n,r=null]=navigator.language?.split("-");r&&(r=r.toUpperCase()),(!n||!xe.includes(n))&&(n=xe[0]);const a={language:n,locale:r};return localStorage.setItem(Je,JSON.stringify(a)),a}async getTranslations(){const{language:t,locale:n}=this.currentLanguageAndLocale;this.translations=(await Bt(`../i18n/${t}${n?`-${n}`:""}.js`).catch(()=>Ft(`../i18n/${this.defaultLocale}.js`))).default}t(t){return this.translations[t]}}const m=new Kt;var Qt='';const Ke=(e,t)=>{!e||(e=e.replace(/\s+width="\d+(?:\.\d+)?"/,"").replace(/\s+height="\d+(?:\.\d+)"/,""),f.classList.remove(pe),f.classList.remove(he),f.classList.add(t),f.innerHTML=e,S(`${m.t("svgSize")}: ${e.length} ${m.t("bytes")}`,3e3))},O=async()=>{f.innerHTML="",f.classList.remove(pe,he),T.current&&(clearInterval(T.current),T.current=null);const e=f.getAttribute("transform");f.innerHTML=Qt,e&&(f.dataset.transform=e,f.setAttribute("transform",""));const t=Ge?await He():Ve();if(y.checked){const n=await Gt(t);e&&f.setAttribute("transform",e),Ke(n,pe)}else{const n=await Ht(t);e&&f.setAttribute("transform",e),Ke(n,he)}};function Zt(){return new Worker("/assets/svgoworker.bb79c476.js",{type:"module"})}let D=null;const Q=async e=>(D&&D.terminate(),D=new Zt,new Promise(t=>{const n=new MessageChannel;n.port1.onmessage=({data:r})=>{n.port1.close(),D&&(D.terminate(),D=null),t(r.result)},D.postMessage({svg:e},[n.port2])})),Z="fileHandle",Xt=e=>e?e.name.replace(/\.[^\.]+$/,""):"";ne.addEventListener("click",async()=>{try{const e=await st({mimeTypes:["image/*"],description:"Image files"}),t=URL.createObjectURL(e);h.addEventListener("load",()=>{URL.revokeObjectURL(t)},{once:!0}),h.src=t,ye&&await P(Z,e.handle)}catch(e){console.error(e.name,e.message),S(e.message)}});document.addEventListener("dragover",e=>{e.preventDefault()});document.addEventListener("dragenter",e=>{e.preventDefault(),le.classList.add("dropenter")});document.addEventListener("dragleave",e=>{e.preventDefault(),e.target===document.documentElement&&le.classList.remove("dropenter")});document.addEventListener("drop",async e=>{e.preventDefault(),e.stopPropagation(),le.classList.remove("dropenter");const t=e.dataTransfer.items[0];if(t.kind==="file"){let n;if(h.addEventListener("load",()=>{URL.revokeObjectURL(n)},{once:!0}),ye){const a=await t.getAsFileSystemHandle();if(a.kind!=="file")return;const o=await a.getFile();n=URL.createObjectURL(o),h.src=n,await P(Z,a);return}const r=t.getAsFile();n=URL.createObjectURL(r),h.src=n}});re.addEventListener("click",async()=>{try{let e="",t=f.innerHTML,n=null;ye&&(e=Xt(await V(Z)),n=await showSaveFilePicker({suggestedName:e,types:[{description:"SVG file",accept:{"image/svg+xml":[".svg"]}}]})),S(m.t("optimizingSVG"),1/0),t=await Q(t),S(m.t("savedSVG"));const r=new Blob([t],{type:"image/svg+xml"});await it(r,{fileName:e,description:"SVG file"},n)}catch(e){console.error(e.name,e.message),S(e.message)}});oe.addEventListener("click",async()=>{try{const e=await navigator.clipboard.read();for(const t of e)for(const n of t.types)if(n.startsWith("image/")){const r=await t.getType(n);if(!r)return;const a=URL.createObjectURL(r);h.src=a;return}}catch(e){console.error(e.name,e.message),S(e.message)}});document.addEventListener("paste",e=>{try{if(!e.clipboardData.files.length)return;const t=e.clipboardData.files[0];if(t.type.startsWith("image/")){const n=URL.createObjectURL(t);h.src=n;return}}catch(t){console.error(t.name,t.message),S(t.message)}});ae.addEventListener("click",async()=>{let e=f.innerHTML;S(m.t("optimizingSVG"),1/0);try{"ClipboardItem"in window?await navigator.clipboard.write([new ClipboardItem({"text/plain":new Promise(async t=>{e=await Q(e),t(new Blob([e],{type:"text/plain"}))}),"image/svg+xml":new Promise(async t=>{e=await Q(e),t(new Blob([e],{type:"image/svg+xml"}))})})]):await navigator.clipboard.writeText(await Q(e))}catch(t){console.log(t.name,t.message),e=await Q(e);const n=new Blob([e],{type:"text/plain"}),r=new Blob([e],{type:"image/svg+xml"});try{await navigator.clipboard.write([new ClipboardItem({[r.type]:r,[n.type]:n})])}catch(a){console.warn(a.name,a.message);try{await navigator.clipboard.write([new ClipboardItem({[n.type]:n})])}catch(o){console.error(o.name,o.message),S(o.message);return}}}S(m.t("copiedSVG"))});var Yt='';const Ce="monochromeSettings",Oe="colorSettings",pe="color",he="monochrome",j="%",en="deg",X="steps",Qe="pixels",_e="",tn="segments",M={brightness:"brightness",contrast:"contrast",grayscale:"grayscale",hueRotate:"hue-rotate",invert:"invert",opacity:"opacity",saturate:"saturate",sepia:"sepia"},w={red:"red",green:"green",blue:"blue",alpha:"alpha"},Ze={scale:"scale"},v={minPathLenght:"minPathSegments",strokeWidth:"strokeWidth",turdsize:"turdsize",alphamax:"alphamax",turnpolicy:"turnpolicy",opticurve:"opticurve",opttolerance:"opttolerance"},Xe={[M.brightness]:{unit:j,initial:100,min:0,max:200},[M.contrast]:{unit:j,initial:100,min:0,max:200},[M.grayscale]:{unit:j,initial:0,min:0,max:100},[M.hueRotate]:{unit:en,initial:0,min:0,max:360},[M.invert]:{unit:j,initial:0,min:0,max:100},[M.opacity]:{unit:j,initial:100,min:0,max:100},[M.saturate]:{unit:j,initial:100,min:0,max:200},[M.sepia]:{unit:j,initial:0,min:0,max:100}},nn={[w.red]:{unit:X,initial:5,min:1,max:20},[w.green]:{unit:X,initial:5,min:1,max:20},[w.blue]:{unit:X,initial:5,min:1,max:20},[w.alpha]:{unit:X,initial:1,min:1,max:10}},rn={[Ze.scale]:{unit:j,initial:100,min:1,max:200}},an={[v.turdsize]:{unit:Qe,initial:2,min:0,max:50},[v.alphamax]:{unit:_e,initial:1,min:0,max:1.3334},[v.turnpolicy]:{unit:X,initial:4,min:0,max:6},[v.opttolerance]:{unit:_e,initial:.2,min:0,max:1},[v.minPathLenght]:{unit:tn,initial:0,min:0,max:30},[v.strokeWidth]:{unit:Qe,initial:0,min:0,max:100}},on=[{name:"svgOptions",icon:Me},{name:"colorChannels",icon:pt},{name:"imageSize",icon:ht},{name:"imagePreprocessing",icon:ft}],Te=[Object.entries(an),Object.entries(nn),Object.entries(rn),Object.entries(Xe)],p={},Pe={},W={},Y=(e,t)=>{const n=m.t(e);return` (${e?`${t}${n.length===1?n:` ${n}`}`:t})`},$=e=>{const t=document.createElement("span");return t.classList.add("icon"),t.innerHTML=e,t},sn=(e,t)=>{const n=document.createElement("details");W[e]=n;const r=document.createElement("summary"),a=$(t);return r.append(a),r.append(document.createTextNode(m.t(e))),n.append(r),n},cn=["alphamax","turnpolicy","optimize-curves","opttolerance","minPathSegments"],ln=async(e,t,n)=>{const{unit:r,min:a,max:o,initial:s}=t,i=document.createElement("div");i.classList.add("preprocess-input"),cn.includes(e)&&i.classList.add("advanced");const c=document.createElement("label");c.textContent=m.t(e)||e,c.htmlFor=e;const l=await fe(),d=document.createElement("span");Pe[e]=d,d.textContent=Y(r,l[e]||s);const u=document.createElement("input");p[e]=u,u.id=e,u.type="range",u.class=e,r&&(u.dataset.unit=r),r===_e&&(u.step=.01),u.min=a,u.max=o,u.value=l[e]||s,u.addEventListener("input",()=>{d.textContent=Y(r,u.value)}),Object.keys(w).includes(e)?u.addEventListener("change",ue(async()=>{await q(u),await O()},250)):Object.keys(v).includes(e)?u.addEventListener("change",ue(async()=>{await q(u),await O()},250)):u.addEventListener("change",ue(async()=>{await q(u),await O()},250));const g=document.createElement("button");g.type="button",g.textContent=m.t("reset"),g.addEventListener("click",async()=>{u.value=s,d.textContent=Y(r,s),u.dispatchEvent(new Event("change"))}),c.append(d),i.append(c);const L=document.createElement("div");i.append(L),L.append(u),L.append(g),n.append(i)},Ye=()=>{const e=!k.checked;Object.keys(w).forEach(t=>{p[t].disabled=e})};k.addEventListener("change",async()=>{Ye(),await q(k),await O()});const Ie=async()=>{const e=await fe();k.checked=e[k.id]??k.defaultChecked,Ye(),_.checked=e[_.id]??_.defaultChecked,x.checked=e[x.id]??x.defaultChecked,et(),A.checked=e[A.id]??A.defaultChecked,tt(),Te.forEach(t=>{for(const[n,r]of t){const a=e[p[n].id]||r.initial;p[n].value=a,Pe[n].textContent=Y(r.unit,a)}})};y.addEventListener("change",async()=>{await P(y.id,y.checked),await P(C.id,C.checked),await Ie(),await O()});C.addEventListener("change",async()=>{await P(y.id,y.checked),await P(C.id,C.checked),await Ie(),await O()});_.addEventListener("change",async()=>{await q(_),await O()});const et=()=>{p.opttolerance.disabled=!x.checked};x.addEventListener("change",async()=>{et(),await q(x),await O()});const un=async()=>{await m.getTranslations(),mn();const e=getComputedStyle(document.documentElement).getPropertyValue("--mobile-breakpoint"),t=window.matchMedia(`(max-width: ${e})`),n=()=>{if(t.matches){be.open=!1;return}be.open=!0};n(),t.addEventListener("change",n),y.checked=await V(y.id)??y.defaultChecked,C.checked=await V(C.id)??C.defaultChecked,y.checked&&f.classList.add(pe),C.checked&&f.classList.add(he);const r=[];Te.forEach(async(a,o)=>{const{name:s,icon:i}=on[o],c=sn(s,i);ze.append(c),o<2&&(c.open=!0),s==="colorChannels"?W.colorChannels.append(k.parentNode):s==="svgOptions"?(W.svgOptions.append(y.parentNode),W.svgOptions.append(C.parentNode)):s==="imageSize"&&W.imageSize.append(_.parentNode);for(const[l,d]of a)r.push(ln(l,d,c));Promise.all(r).then(async()=>{for(const[l]of a)l==="opttolerance"&&W.svgOptions.append(x.parentNode),s==="svgOptions"&&W.svgOptions.append(A.parentNode);await Ie()})}),ze.append(we.parentNode),h.addEventListener("load",async()=>{h.width=h.naturalWidth,h.height=h.naturalHeight;const a=await fe();if(h.src!==new URL("/favicon.png",location.href).toString()||Object.keys(a).length>1)setTimeout(async()=>{We(),await O()},100);else{const o=await fetch(`/potraced-${y.checked?"color":"monochrome"}.svg`).then(s=>s.text());f.innerHTML=o}}),h.complete&&h.dispatchEvent(new Event("load")),ie.hidden=!1;try{const a=await V(Z);if(a&&await dn(a)){const o=await a.getFile(),s=URL.createObjectURL(o);h.src=s}}catch(a){console.error(a.name,a.message),await ct(Z)}},dn=async e=>{const t={mode:"read"};return await e.queryPermission(t)==="granted"||await e.requestPermission(t)==="granted"},mn=()=>{Ot.textContent=m.t("license"),_t.textContent=m.t("about"),we.textContent=m.t("resetAll"),bt.textContent=m.t("posterizeInputImage"),Lt.textContent=m.t("colorSVG"),St.textContent=m.t("monochromeSVG"),Et.textContent=m.t("considerDPR"),kt.textContent=m.t("opticurve"),xt.textContent=m.t("showAdvancedControls"),ne.innerHTML="",ne.append($(lt)),ne.append(document.createTextNode(m.t("openImage"))),re.innerHTML="",re.append($(ut)),re.append(document.createTextNode(m.t("saveSVG"))),ae.innerHTML="",ae.append($(dt)),ae.append(document.createTextNode(m.t("copySVG"))),oe.innerHTML="",oe.append($(mt)),oe.append(document.createTextNode(m.t("pasteImage"))),se.innerHTML="",se.append($(Yt)),se.append(document.createTextNode(m.t("install"))),le.dataset.dropText=m.t("dropFileHere"),Le.innerHTML="",Le.append($(Me)),Le.append(document.createTextNode(m.t("tweak"))),Ne.ariaLabel=m.t("closeOptions")};we.addEventListener("click",async()=>{const e=(t,n,r)=>{p[t].value=r,Pe[t].textContent=Y(n,r)};Te.forEach(t=>{for(const[n,r]of t)e(n,r.unit,r.initial)}),x.checked=x.defaultChecked,k.checked=k.defaultChecked,_.checked=_.defaultChecked,await pn(),We(),await O()});Ct.addEventListener("click",()=>{I.classList.toggle("debug")});let Re=null;const S=(e,t=5e3)=>{if(ce.innerHTML=e,ce.hidden=!1,Re&&clearTimeout(Re),t!==1/0){Re=setTimeout(()=>{ce.hidden=!0,ce.textContent=""},t);return}},tt=async()=>{await q(A),document.querySelectorAll(".advanced").forEach(e=>{A.checked?e.style.display="block":e.style.display="none"})};A.addEventListener("change",tt);document.documentElement.style.setProperty("--100vh",`${window.innerHeight}px`);window.addEventListener("resize",ue(()=>{document.documentElement.style.setProperty("--100vh",`${window.innerHeight}px`)},250));Ne.addEventListener("click",()=>{be.open=!1});const pn=async()=>{await P(y.checked?Oe:Ce,{})},fe=async()=>{const e=y.checked?await V(Oe):await V(Ce);return e||{}},q=async e=>{const t=await fe();t[e.id]=e.type==="range"?e.value:e.checked,await P(y.checked?Oe:Ce,t)};function hn(e={}){const{immediate:t=!1,onNeedRefresh:n,onOfflineReady:r,onRegistered:a,onRegisterError:o}=e;let s;const i=async(c=!0)=>{};return"serviceWorker"in navigator&&(s=new gt("/sw.js",{scope:"/",type:"classic"}),s.addEventListener("activated",c=>{c.isUpdate?window.location.reload():r==null||r()}),s.register({immediate:t}).then(c=>{a==null||a(c)}).catch(c=>{o==null||o(c)})),i}(async(e,t,n,r,a,o,s,i,c,l)=>{const d={z:`${e()}`.substr(2),cid:`${t.getItem(c)||(l=`${e()}`.substr(2),t.setItem(c,l),l)}`,ua:i.userAgent,dr:r.referrer||"",sr:`${n.width}x${n.height}`,vp:`${a.clientWidth}x${a.clientHeight}`,sd:`${n.pixelDepth}-bits`,ul:i.language,dl:o(s.href),dp:o(s.pathname),dt:r.title},u=new FormData;for(const[g,L]of Object.entries(d))u.append(g,L);try{await fetch("https://svgcode.glitch.me/",{method:"post",body:u})}catch{}})(Math.random,localStorage,screen,document,document.documentElement,encodeURIComponent,location,navigator,"cid",0);"launchQueue"in window&&E(()=>import("./filehandling.618c218c.js"),["assets/filehandling.618c218c.js","assets/vendor.219e5f4d.js"]);"windowControlsOverlay"in navigator&&E(()=>import("./windowcontrols.d9e79367.js"),["assets/windowcontrols.d9e79367.js","assets/vendor.219e5f4d.js"]);"onbeforeinstallprompt"in window&&"onappinstalled"in window?E(()=>import("./install.9bcfb7b8.js"),["assets/install.9bcfb7b8.js","assets/vendor.219e5f4d.js"]):se.style.display="none";const fn=()=>{let e=!1;const t={get type(){e=!0}};try{new Worker("blob://",t)}finally{return e}};(async()=>{un(),fn()||await E(()=>import("./module-workers-polyfill.min.dc7647fd.js"),[]),hn({onOfflineReady(){S(m.t("readyToWorkOffline"))},onNeedRefresh(){location.reload()}})()})();export{Z as F,yn as a,se as b,ue as d,h as i,vn as m}; diff --git a/docs/assets/index.ecc37913.js b/docs/assets/index.ecc37913.js deleted file mode 100644 index 86b0a74..0000000 --- a/docs/assets/index.ecc37913.js +++ /dev/null @@ -1,26 +0,0 @@ -import{_ as st,u as ye,s as P,g as G,C as it,d as ct,o as lt,a as ut,c as dt,p as mt,b as Me,e as pt,f as ht,h as ft,v as gt}from"./vendor.219e5f4d.js";const vt=function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function t(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerpolicy&&(o.referrerPolicy=a.referrerpolicy),a.crossorigin==="use-credentials"?o.credentials="include":a.crossorigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=t(a);fetch(a.href,o)}};vt();const yt="modulepreload",Ae={},wt="/",k=function(n,t){return!t||t.length===0?n():Promise.all(t.map(r=>{if(r=`${wt}${r}`,r in Ae)return;Ae[r]=!0;const a=r.endsWith(".css"),o=a?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${r}"]${o}`))return;const s=document.createElement("link");if(s.rel=a?"stylesheet":yt,a||(s.as="script",s.crossOrigin=""),s.href=r,document.head.appendChild(s),a)return new Promise((i,c)=>{s.addEventListener("load",i),s.addEventListener("error",c)})})).then(()=>n())},R=document.querySelector("canvas"),gn=document.querySelector(".menu"),vn=document.querySelector("main"),ze=document.querySelector(".details"),E=document.querySelector(".posterize"),bt=document.querySelector("[for=posterize]"),y=document.querySelector(".color"),Lt=document.querySelector("[for=color]"),C=document.querySelector(".monochrome"),St=document.querySelector("[for=monochrome]"),_=document.querySelector(".consider-dpr"),Et=document.querySelector('[for="consider-dpr"]'),x=document.querySelector(".optimize-curves"),xt=document.querySelector('[for="optimize-curves"]'),A=document.querySelector(".show-advanced"),kt=document.querySelector('[for="show-advanced"]'),h=document.querySelector("img"),we=document.querySelector(".reset-all"),te=document.querySelector(".open"),ne=document.querySelector(".save"),re=document.querySelector(".copy"),ae=document.querySelector(".paste"),oe=document.querySelector(".install"),f=document.querySelector(".svg-output"),Ct=document.querySelector(".debug"),se=document.querySelector("progress"),ie=document.querySelector(".toast"),ce=document.documentElement,be=document.querySelector("details.main"),Le=document.querySelector("summary"),Ne=document.querySelector(".close-options-button"),Ot=document.querySelector(".license"),_t=document.querySelector(".about"),De=document.querySelector("pinch-zoom"),V=window.devicePixelRatio;De.addEventListener("change",()=>{const{x:e,y:n,scale:t}=De;f.setAttribute("transform",`translate(${e}, ${n}) scale(${t})`)});const $e=()=>{f.setAttribute("transform","")},le=(e,n)=>{let t;return function(...a){const o=()=>{clearTimeout(t),e(...a)};clearTimeout(t),t=setTimeout(o,n)}};/*! - * canvas-size - * v1.2.5 - * https://github.com/jhildenbiddle/canvas-size - * (c) 2015-2021 John Hildenbiddle - * MIT license - */function We(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),t.push.apply(t,r)}return t}function b(e){for(var n=1;n=0)&&(t[a]=e[a]);return t}function Rt(e,n){if(e==null)return{};var t=Pt(e,n),r,a;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&(!Object.prototype.propertyIsEnumerable.call(e,r)||(t[r]=e[r]))}return t}function qe(e,n){return jt(e)||At(e,n)||Ue(e,n)||Nt()}function ue(e){return It(e)||Mt(e)||Ue(e)||zt()}function It(e){if(Array.isArray(e))return Se(e)}function jt(e){if(Array.isArray(e))return e}function Mt(e){if(typeof Symbol!="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function At(e,n){var t=e==null?null:typeof Symbol!="undefined"&&e[Symbol.iterator]||e["@@iterator"];if(t!=null){var r=[],a=!0,o=!1,s,i;try{for(t=t.call(e);!(a=(s=t.next()).done)&&(r.push(s.value),!(n&&r.length===n));a=!0);}catch(c){o=!0,i=c}finally{try{!a&&t.return!=null&&t.return()}finally{if(o)throw i}}return r}}function Ue(e,n){if(!!e){if(typeof e=="string")return Se(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);if(t==="Object"&&e.constructor&&(t=e.constructor.name),t==="Map"||t==="Set")return Array.from(e);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Se(e,n)}}function Se(e,n){(n==null||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t=o;){var c=n||t?i:1,l=n||r?i:1;a.push([c,l]),i-=s}return a}function de(e){var n=window&&"HTMLCanvasElement"in window,t=window&&"OffscreenCanvas"in window,r=Date.now(),a=e.onError,o=e.onSuccess,s=Rt(e,Dt),i=null;if(!n)return!1;if(e.useWorker&&t){var c=` - var canvasTest = `.concat(J.toString(),`; - onmessage = function(e) { - canvasTest(e.data); - }; - `),l=new Blob([c],{type:"application/javascript"}),m=URL.createObjectURL(l);i=new Worker(m),URL.revokeObjectURL(m),i.onmessage=function(u){var g=u.data,L=g.width,Y=g.height,ee=g.benchmark,ge=g.isTestPass;ge?(K[r].onSuccess(L,Y,ee),delete K[r]):K[r].onError(L,Y,ee)}}if(e.usePromise)return new Promise(function(u,g){var L=b(b({},e),{},{onError:function(U,H,B){var ve;if(e.sizes.length===0)ve=!0;else{var nt=e.sizes.slice(-1),rt=qe(nt,1),je=qe(rt[0],2),at=je[0],ot=je[1];ve=U===at&&H===ot}a(U,H,B),ve&&g({width:U,height:H,benchmark:B})},onSuccess:function(U,H,B){o(U,H,B),u({width:U,height:H,benchmark:B})}});if(i){var Y=L.onError,ee=L.onSuccess;K[r]={onError:Y,onSuccess:ee},i.postMessage(s)}else J(L)});if(i)K[r]={onError:a,onSuccess:o},i.postMessage(s);else return J(e)}var $t={maxArea:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=xe({width:n.max,height:n.max,min:n.min,step:n.step,sizes:ue(Ee.area)}),r=b(b(b({},F),n),{},{sizes:t});return de(r)},maxHeight:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=xe({width:1,height:n.max,min:n.min,step:n.step,sizes:ue(Ee.height)}),r=b(b(b({},F),n),{},{sizes:t});return de(r)},maxWidth:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=xe({width:n.max,height:1,min:n.min,step:n.step,sizes:ue(Ee.width)}),r=b(b(b({},F),n),{},{sizes:t});return de(r)},test:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=b(b({},F),n);return t.sizes=ue(t.sizes),t.width&&t.height&&(t.sizes=[[t.width,t.height]]),de(t)}};let He,Ge;const Ve="OffscreenCanvas"in window&&"CanvasFilter"in window;if(Ve)k(()=>import("./preprocessworker.c921728e.js"),[]).then(e=>{const n=e.default;let t=null;const r=R.getContext("2d");He=async()=>{t&&t.terminate(),t=new n;const a=R.cloneNode().transferControlToOffscreen();return t.postMessage({offscreen:a},[a]),new Promise(async o=>{const{width:s,height:i}=Fe();let c;try{c=await createImageBitmap(h)}catch{try{c=await createImageBitmap(h,0,0,s,i)}catch(m){console.error(m.name,m.message),f.innerHTML="",S(m.message);return}}const l=new MessageChannel;l.port1.onmessage=({data:m})=>{l.port1.close(),t&&(t.terminate(),t=null),R.width=s,R.height=i,r.putImageData(m.result,0,0),o(m.result)},t.postMessage({inputImageBitmap:c,posterize:E.checked,rgba:{r:I(p[w.red]),g:I(p[w.green]),b:I(p[w.blue]),a:I(p[w.alpha])},cssFilters:Be(),width:s,height:i,dpr:V},[l.port2])})}});else{const e=R.getContext("2d",{desynchronized:!0});e.scale(V,V),e.imageSmoothingEnabled=!0,Ge=()=>{let{width:n,height:t}=Fe();const r=_.checked?V:1;let a=1;for(;!$t.test({width:n,height:t});)n=Math.floor(n/2),t=Math.floor(t/2),a/=2;return R.width=n,R.height=t,e.clearRect(0,0,n,t),e.filter=qt(),e.drawImage(h,0,0,r*h.naturalWidth*a,r*h.naturalHeight*a,0,0,n,t),e.getImageData(0,0,n,t)}}const Fe=()=>{const e=Number(p[Ze.scale].value)/100;return{width:Math.ceil(V*h.naturalWidth*e),height:Math.ceil(V*h.naturalHeight*e)}},I=e=>{const n=Number(e.value),t=[];for(let r=0;r<=n;r++)t[r]=Number((1/n*r).toFixed(1));return t},Wt=()=>`data:image/svg+xml;utf8, - - - - - - - - - `.replace(/[\r\n]/g,"").replace(/\s+/g," ").trim(),Be=()=>{let e="";for(const[n,t]of Object.entries(Xe)){const r=p[n];t.initial!==Number(r.value)&&(e+=`${n}(${r.value}${r.dataset.unit}) `)}return e},qt=()=>{let e=`${E.checked?`url('${Wt()}#posterize') `:""}`;return e+=Be(),e.trim()||"none"};function Ut(){return new Worker("/assets/monochromeworker.3e780118.js",{type:"module"})}let z=null;const Ht=async e=>(z&&z.terminate(),z=new Ut,new Promise(async n=>{const t=new MessageChannel;t.port1.onmessage=({data:a})=>{t.port1.close(),z&&(z.terminate(),z=null),n(a.result)};const r={turdsize:Number(p[v.turdsize].value),alphamax:Number(p[v.alphamax].value),turnpolicy:Number(p[v.turnpolicy].value),opttolerance:Number(p[v.opttolerance].value),opticurve:x.checked?1:0};z.postMessage({imageData:e,params:r},[t.port2])}));function Gt(){return new Worker("/assets/colorworker.3bb51423.js",{type:"module"})}let N=null;const T={},Vt=async e=>(N&&N.terminate(),N=new Gt,new Promise(async n=>{const t=new MessageChannel;t.port1.onmessage=({data:l})=>{t.port1.close(),N&&(N.terminate(),N=null),n(l.result)},se.value=0;let r="",a="",o="",s=0;T.current&&(clearInterval(T.current),T.current=null),T.current=setInterval(()=>{const l=`${r}${o}${a}`;l.length!==s&&(f.setAttribute("transform",f.dataset.transform),f.innerHTML=l,s=l.length)},500);const i=new MessageChannel;i.port1.onmessage=({data:l})=>{const m=Math.floor(l.processed/l.total*100);se.value=m,l.svg&&(r||(r=l.svg.replace(/(.*?]+>)(.*?)(<\/svg>)/,"$1").replace(/\s+width="\d+(?:\.\d+)?"/,"").replace(/\s+height="\d+(?:\.\d+)"/,""),a=l.svg.replace(/(.*?]+>)(.*?)(<\/svg>)/,"$3")),o+=l.svg.replace(/(.*?]+>)(.*?)(<\/svg>)/,"$2")),l.processed===l.total&&(clearInterval(T.current),T.current=null,i.port1.close(),se.value=0)};const c={minPathSegments:Number(p[v.minPathLenght].value),strokeWidth:Number(p[v.strokeWidth].value),turdsize:Number(p[v.turdsize].value),alphamax:Number(p[v.alphamax].value),turnpolicy:Number(p[v.turnpolicy].value),opttolerance:Number(p[v.opttolerance].value),opticurve:x.checked?1:0};N.postMessage({imageData:e,params:c},[t.port2,i.port2])}));function Ft(e){switch(e){case"../i18n/de-DE.js":return k(()=>import("./de-DE.0c064cfc.js"),[]);case"../i18n/el-GR.js":return k(()=>import("./el-GR.b0c8940a.js"),[]);case"../i18n/en-US.js":return k(()=>import("./en-US.ca3bb092.js"),[]);default:return new Promise(function(n,t){(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(t.bind(null,new Error("Unknown variable dynamic import: "+e)))})}}function Bt(e){switch(e){case"../i18n/de-DE.js":return k(()=>import("./de-DE.0c064cfc.js"),[]);case"../i18n/el-GR.js":return k(()=>import("./el-GR.b0c8940a.js"),[]);case"../i18n/en-US.js":return k(()=>import("./en-US.ca3bb092.js"),[]);default:return new Promise(function(n,t){(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(t.bind(null,new Error("Unknown variable dynamic import: "+e)))})}}const Je="language",ke=["en","de","el"],Jt=["en-US","de-DE","el-GR"];class Kt{constructor(){this.currentLanguageAndLocale=this.detectLanguageAndLocal(),this.defaultLanguage=ke[0],this.defaultLocale=Jt[0],this.translations=null}detectLanguageAndLocal(){const n=localStorage.getItem(Je);if(n)return JSON.parse(n);let[t,r=null]=navigator.language?.split("-");r&&(r=r.toUpperCase()),(!t||!ke.includes(t))&&(t=ke[0]);const a={language:t,locale:r};return localStorage.setItem(Je,JSON.stringify(a)),a}async getTranslations(){const{language:n,locale:t}=this.currentLanguageAndLocale;this.translations=(await Bt(`../i18n/${n}${t?`-${t}`:""}.js`).catch(()=>Ft(`../i18n/${this.defaultLocale}.js`))).default}t(n){return this.translations[n]}}const d=new Kt;var Qt='';const Ke=(e,n)=>{!e||(e=e.replace(/\s+width="\d+(?:\.\d+)?"/,"").replace(/\s+height="\d+(?:\.\d+)"/,""),f.classList.remove(pe),f.classList.remove(he),f.classList.add(n),f.innerHTML=e,S(`${d.t("svgSize")}: ${e.length} ${d.t("bytes")}`,3e3))},O=async()=>{f.innerHTML="",f.classList.remove(pe,he),T.current&&(clearInterval(T.current),T.current=null);const e=f.getAttribute("transform");f.innerHTML=Qt,f.dataset.transform=e,f.setAttribute("transform","");const n=Ve?await He():Ge();if(y.checked){const t=await Vt(n);f.setAttribute("transform",e),Ke(t,pe)}else{const t=await Ht(n);f.setAttribute("transform",e),Ke(t,he)}};function Zt(){return new Worker("/assets/svgoworker.bb79c476.js",{type:"module"})}let D=null;const me=async e=>(D&&D.terminate(),D=new Zt,new Promise(n=>{const t=new MessageChannel;t.port1.onmessage=({data:r})=>{t.port1.close(),D&&(D.terminate(),D=null),n(r.result)},D.postMessage({svg:e},[t.port2])})),Q="fileHandle",Xt=e=>e?e.name.replace(/\.[^\.]+$/,""):"";te.addEventListener("click",async()=>{try{const e=await st({mimeTypes:["image/*"],description:"Image files"}),n=URL.createObjectURL(e);h.addEventListener("load",()=>{URL.revokeObjectURL(n)},{once:!0}),h.src=n,ye&&await P(Q,e.handle)}catch(e){console.error(e.name,e.message),S(e.message)}});document.addEventListener("dragover",e=>{e.preventDefault()});document.addEventListener("dragenter",e=>{e.preventDefault(),ce.classList.add("dropenter")});document.addEventListener("dragleave",e=>{e.preventDefault(),e.target===document.documentElement&&ce.classList.remove("dropenter")});document.addEventListener("drop",async e=>{e.preventDefault(),e.stopPropagation(),ce.classList.remove("dropenter");const n=e.dataTransfer.items[0];if(n.kind==="file"){let t;if(h.addEventListener("load",()=>{URL.revokeObjectURL(t)},{once:!0}),ye){const a=await n.getAsFileSystemHandle();if(a.kind!=="file")return;const o=await a.getFile();t=URL.createObjectURL(o),h.src=t,await P(Q,a);return}const r=n.getAsFile();t=URL.createObjectURL(r),h.src=t}});ne.addEventListener("click",async()=>{try{let e="",n=f.innerHTML,t=null;ye&&(e=Xt(await G(Q)),t=await showSaveFilePicker({suggestedName:e,types:[{description:"SVG file",accept:{"image/svg+xml":[".svg"]}}]})),S(d.t("optimizingSVG"),1/0),n=await me(n),S(d.t("savedSVG"));const r=new Blob([n],{type:"image/svg+xml"});await it(r,{fileName:e,description:"SVG file"},t)}catch(e){console.error(e.name,e.message),S(e.message)}});ae.addEventListener("click",async()=>{try{const e=await navigator.clipboard.read();for(const n of e)for(const t of n.types)if(t.startsWith("image/")){const r=await n.getType(t);if(!r)return;const a=URL.createObjectURL(r);h.src=a;return}}catch(e){console.error(e.name,e.message),S(e.message)}});document.addEventListener("paste",e=>{try{if(!e.clipboardData.files.length)return;const n=e.clipboardData.files[0];if(n.type.startsWith("image/")){const t=URL.createObjectURL(n);h.src=t;return}}catch(n){console.error(n.name,n.message),S(n.message)}});re.addEventListener("click",async()=>{let e=f.innerHTML;S(d.t("optimizingSVG"),1/0);try{await navigator.clipboard.write([new ClipboardItem({"text/plain":new Promise(async n=>{e=await me(e),n(new Blob([e],{type:"text/plain"}))}),"image/svg+xml":new Promise(async n=>{e=await me(e),n(new Blob([e],{type:"image/svg+xml"}))})})])}catch(n){console.log(n.name,n.message),e=await me(e);const t=new Blob([e],{type:"text/plain"}),r=new Blob([e],{type:"image/svg+xml"});try{await navigator.clipboard.write([new ClipboardItem({[r.type]:r,[t.type]:t})])}catch(a){console.warn(a.name,a.message);try{await navigator.clipboard.write([new ClipboardItem({[t.type]:t})])}catch(o){console.error(o.name,o.message),S(o.message);return}}}S(d.t("copiedSVG"))});var Yt='';const Ce="monochromeSettings",Oe="colorSettings",pe="color",he="monochrome",j="%",en="deg",Z="steps",Qe="pixels",_e="",tn="segments",M={brightness:"brightness",contrast:"contrast",grayscale:"grayscale",hueRotate:"hue-rotate",invert:"invert",opacity:"opacity",saturate:"saturate",sepia:"sepia"},w={red:"red",green:"green",blue:"blue",alpha:"alpha"},Ze={scale:"scale"},v={minPathLenght:"minPathSegments",strokeWidth:"strokeWidth",turdsize:"turdsize",alphamax:"alphamax",turnpolicy:"turnpolicy",opticurve:"opticurve",opttolerance:"opttolerance"},Xe={[M.brightness]:{unit:j,initial:100,min:0,max:200},[M.contrast]:{unit:j,initial:100,min:0,max:200},[M.grayscale]:{unit:j,initial:0,min:0,max:100},[M.hueRotate]:{unit:en,initial:0,min:0,max:360},[M.invert]:{unit:j,initial:0,min:0,max:100},[M.opacity]:{unit:j,initial:100,min:0,max:100},[M.saturate]:{unit:j,initial:100,min:0,max:200},[M.sepia]:{unit:j,initial:0,min:0,max:100}},nn={[w.red]:{unit:Z,initial:5,min:1,max:20},[w.green]:{unit:Z,initial:5,min:1,max:20},[w.blue]:{unit:Z,initial:5,min:1,max:20},[w.alpha]:{unit:Z,initial:1,min:1,max:10}},rn={[Ze.scale]:{unit:j,initial:100,min:1,max:200}},an={[v.turdsize]:{unit:Qe,initial:2,min:0,max:50},[v.alphamax]:{unit:_e,initial:1,min:0,max:1.3334},[v.turnpolicy]:{unit:Z,initial:4,min:0,max:6},[v.opttolerance]:{unit:_e,initial:.2,min:0,max:1},[v.minPathLenght]:{unit:tn,initial:0,min:0,max:30},[v.strokeWidth]:{unit:Qe,initial:0,min:0,max:100}},on=[{name:"svgOptions",icon:Me},{name:"colorChannels",icon:pt},{name:"imageSize",icon:ht},{name:"imagePreprocessing",icon:ft}],Te=[Object.entries(an),Object.entries(nn),Object.entries(rn),Object.entries(Xe)],p={},Pe={},$={},X=(e,n)=>{const t=d.t(e);return` (${e?`${n}${t.length===1?t:` ${t}`}`:n})`},W=e=>{const n=document.createElement("span");return n.classList.add("icon"),n.innerHTML=e,n},sn=(e,n)=>{const t=document.createElement("details");$[e]=t;const r=document.createElement("summary"),a=W(n);return r.append(a),r.append(document.createTextNode(d.t(e))),t.append(r),t},cn=["alphamax","turnpolicy","optimize-curves","opttolerance","minPathSegments"],ln=async(e,n,t)=>{const{unit:r,min:a,max:o,initial:s}=n,i=document.createElement("div");i.classList.add("preprocess-input"),cn.includes(e)&&i.classList.add("advanced");const c=document.createElement("label");c.textContent=d.t(e)||e,c.htmlFor=e;const l=await fe(),m=document.createElement("span");Pe[e]=m,m.textContent=X(r,l[e]||s);const u=document.createElement("input");p[e]=u,u.id=e,u.type="range",u.class=e,r&&(u.dataset.unit=r),r===_e&&(u.step=.01),u.min=a,u.max=o,u.value=l[e]||s,u.addEventListener("input",()=>{m.textContent=X(r,u.value)}),Object.keys(w).includes(e)?u.addEventListener("change",le(async()=>{await q(u),await O()},250)):Object.keys(v).includes(e)?u.addEventListener("change",le(async()=>{await q(u),await O()},250)):u.addEventListener("change",le(async()=>{await q(u),await O()},250));const g=document.createElement("button");g.type="button",g.textContent=d.t("reset"),g.addEventListener("click",async()=>{u.value=s,m.textContent=X(r,s),u.dispatchEvent(new Event("change"))}),c.append(m),i.append(c);const L=document.createElement("div");i.append(L),L.append(u),L.append(g),t.append(i)},Ye=()=>{const e=!E.checked;Object.keys(w).forEach(n=>{p[n].disabled=e})};E.addEventListener("change",async()=>{Ye(),await q(E),await O()});const Re=async()=>{const e=await fe();E.checked=e[E.id]??E.defaultChecked,Ye(),_.checked=e[_.id]??_.defaultChecked,x.checked=e[x.id]??x.defaultChecked,et(),A.checked=e[A.id]??A.defaultChecked,tt(),Te.forEach(n=>{for(const[t,r]of n){const a=e[p[t].id]||r.initial;p[t].value=a,Pe[t].textContent=X(r.unit,a)}})};y.addEventListener("change",async()=>{await P(y.id,y.checked),await P(C.id,C.checked),await Re(),await O()});C.addEventListener("change",async()=>{await P(y.id,y.checked),await P(C.id,C.checked),await Re(),await O()});_.addEventListener("change",async()=>{await q(_),await O()});const et=()=>{p.opttolerance.disabled=!x.checked};x.addEventListener("change",async()=>{et(),await q(x),await O()});const un=async()=>{await d.getTranslations(),mn();const e=getComputedStyle(document.documentElement).getPropertyValue("--mobile-breakpoint"),n=window.matchMedia(`(max-width: ${e})`),t=()=>{if(n.matches){be.open=!1;return}be.open=!0};t(),n.addEventListener("change",t),y.checked=await G(y.id)??y.defaultChecked,C.checked=await G(C.id)??C.defaultChecked,y.checked&&f.classList.add(pe),C.checked&&f.classList.add(he);const r=[];Te.forEach(async(a,o)=>{const{name:s,icon:i}=on[o],c=sn(s,i);ze.append(c),o<2&&(c.open=!0),s==="colorChannels"?$.colorChannels.append(E.parentNode):s==="svgOptions"?($.svgOptions.append(y.parentNode),$.svgOptions.append(C.parentNode)):s==="imageSize"&&$.imageSize.append(_.parentNode);for(const[l,m]of a)r.push(ln(l,m,c));Promise.all(r).then(async()=>{for(const[l]of a)l==="opttolerance"&&$.svgOptions.append(x.parentNode),s==="svgOptions"&&$.svgOptions.append(A.parentNode);await Re()})}),ze.append(we.parentNode),h.addEventListener("load",async()=>{h.width=h.naturalWidth,h.height=h.naturalHeight;const a=await fe();if(h.src!==new URL("/favicon.png",location.href).toString()||Object.keys(a).length>1)setTimeout(async()=>{$e(),await O()},100);else{const o=await fetch(`/potraced-${y.checked?"color":"monochrome"}.svg`).then(s=>s.text());f.innerHTML=o}}),h.complete&&h.dispatchEvent(new Event("load")),se.hidden=!1;try{const a=await G(Q);if(a&&await dn(a)){const o=await a.getFile(),s=URL.createObjectURL(o);h.src=s}}catch(a){console.error(a.name,a.message),await ct(Q)}},dn=async e=>{const n={mode:"read"};return await e.queryPermission(n)==="granted"||await e.requestPermission(n)==="granted"},mn=()=>{Ot.textContent=d.t("license"),_t.textContent=d.t("about"),we.textContent=d.t("resetAll"),bt.textContent=d.t("posterizeInputImage"),Lt.textContent=d.t("colorSVG"),St.textContent=d.t("monochromeSVG"),Et.textContent=d.t("considerDPR"),xt.textContent=d.t("opticurve"),kt.textContent=d.t("showAdvancedControls"),te.innerHTML="",te.append(W(lt)),te.append(document.createTextNode(d.t("openImage"))),ne.innerHTML="",ne.append(W(ut)),ne.append(document.createTextNode(d.t("saveSVG"))),re.innerHTML="",re.append(W(dt)),re.append(document.createTextNode(d.t("copySVG"))),ae.innerHTML="",ae.append(W(mt)),ae.append(document.createTextNode(d.t("pasteImage"))),oe.innerHTML="",oe.append(W(Yt)),oe.append(document.createTextNode(d.t("install"))),ce.dataset.dropText=d.t("dropFileHere"),Le.innerHTML="",Le.append(W(Me)),Le.append(document.createTextNode(d.t("tweak"))),Ne.ariaLabel=d.t("closeOptions")};we.addEventListener("click",async()=>{const e=(n,t,r)=>{p[n].value=r,Pe[n].textContent=X(t,r)};Te.forEach(n=>{for(const[t,r]of n)e(t,r.unit,r.initial)}),x.checked=x.defaultChecked,E.checked=E.defaultChecked,_.checked=_.defaultChecked,await pn(),$e(),await O()});Ct.addEventListener("click",()=>{R.classList.toggle("debug")});let Ie=null;const S=(e,n=5e3)=>{if(ie.innerHTML=e,ie.hidden=!1,Ie&&clearTimeout(Ie),n!==1/0){Ie=setTimeout(()=>{ie.hidden=!0,ie.textContent=""},n);return}},tt=async()=>{await q(A),document.querySelectorAll(".advanced").forEach(e=>{A.checked?e.style.display="block":e.style.display="none"})};A.addEventListener("change",tt);document.documentElement.style.setProperty("--100vh",`${window.innerHeight}px`);window.addEventListener("resize",le(()=>{document.documentElement.style.setProperty("--100vh",`${window.innerHeight}px`)},250));Ne.addEventListener("click",()=>{be.open=!1});const pn=async()=>{await P(y.checked?Oe:Ce,{})},fe=async()=>{const e=y.checked?await G(Oe):await G(Ce);return e||{}},q=async e=>{const n=await fe();n[e.id]=e.type==="range"?e.value:e.checked,await P(y.checked?Oe:Ce,n)};function hn(e={}){const{immediate:n=!1,onNeedRefresh:t,onOfflineReady:r,onRegistered:a,onRegisterError:o}=e;let s;const i=async(c=!0)=>{};return"serviceWorker"in navigator&&(s=new gt("/sw.js",{scope:"/",type:"classic"}),s.addEventListener("activated",c=>{c.isUpdate?window.location.reload():r==null||r()}),s.register({immediate:n}).then(c=>{a==null||a(c)}).catch(c=>{o==null||o(c)})),i}(async(e,n,t,r,a,o,s,i,c,l)=>{const m={z:`${e()}`.substr(2),cid:`${n.getItem(c)||(l=`${e()}`.substr(2),n.setItem(c,l),l)}`,ua:i.userAgent,dr:r.referrer||"",sr:`${t.width}x${t.height}`,vp:`${a.clientWidth}x${a.clientHeight}`,sd:`${t.pixelDepth}-bits`,ul:i.language,dl:o(s.href),dp:o(s.pathname),dt:r.title},u=new FormData;for(const[g,L]of Object.entries(m))u.append(g,L);try{await fetch("https://svgcode.glitch.me/",{method:"post",body:u})}catch{}})(Math.random,localStorage,screen,document,document.documentElement,encodeURIComponent,location,navigator,"cid",0);"launchQueue"in window&&k(()=>import("./filehandling.4cb07dc9.js"),["assets/filehandling.4cb07dc9.js","assets/vendor.219e5f4d.js"]);"windowControlsOverlay"in navigator&&k(()=>import("./windowcontrols.275a60cd.js"),["assets/windowcontrols.275a60cd.js","assets/vendor.219e5f4d.js"]);"onbeforeinstallprompt"in window&&"onappinstalled"in window?k(()=>import("./install.bccde453.js"),["assets/install.bccde453.js","assets/vendor.219e5f4d.js"]):oe.style.display="none";(async()=>{un(),hn({onOfflineReady(){S(d.t("readyToWorkOffline"))},onNeedRefresh(){location.reload()}})()})();export{Q as F,vn as a,oe as b,le as d,h as i,gn as m}; diff --git a/docs/assets/install.bccde453.js b/docs/assets/install.9bcfb7b8.js similarity index 83% rename from docs/assets/install.bccde453.js rename to docs/assets/install.9bcfb7b8.js index edd7915..efd765d 100644 --- a/docs/assets/install.bccde453.js +++ b/docs/assets/install.9bcfb7b8.js @@ -1 +1 @@ -import{b as n}from"./index.ecc37913.js";import"./vendor.219e5f4d.js";let e=null;window.addEventListener("beforeinstallprompt",t=>{t.preventDefault(),e=t,n.style.display="block"});n.addEventListener("click",async()=>{if(!e)return;e.prompt(),(await e.userChoice).outcome==="accepted"&&(n.style.display="none",e=null)});window.addEventListener("appinstalled",t=>{n.style.display="none",e=null}); +import{b as n}from"./index.54ec3c4a.js";import"./vendor.219e5f4d.js";let e=null;window.addEventListener("beforeinstallprompt",t=>{t.preventDefault(),e=t,n.style.display="block"});n.addEventListener("click",async()=>{if(!e)return;e.prompt(),(await e.userChoice).outcome==="accepted"&&(n.style.display="none",e=null)});window.addEventListener("appinstalled",t=>{n.style.display="none",e=null}); diff --git a/docs/assets/module-workers-polyfill.min.dc7647fd.js b/docs/assets/module-workers-polyfill.min.dc7647fd.js new file mode 100644 index 0000000..9964d44 --- /dev/null +++ b/docs/assets/module-workers-polyfill.min.dc7647fd.js @@ -0,0 +1,10 @@ +(function(m){if(!m||m._$P!==!0){if(m){var x,b=Object.defineProperty({},"type",{get:function(){x=!0}});try{var O=URL.createObjectURL(new Blob([""],{type:"text/javascript"}));new m(O,b).terminate(),URL.revokeObjectURL(O)}catch{}if(!x)try{new m("data:text/javascript,",b).terminate()}catch{}if(x)return;(self.Worker=function(t,u){return u&&u.type=="module"&&(u={name:t+` +`+(u.name||"")},t=typeof document=="undefined"?location.href:document.currentScript&&document.currentScript.src||new Error().stack.match(/[(@]((file|https?):\/\/[^)]+?):\d+(:\d+)?(?:\)|$)/m)[1]),new m(t,u)})._$P=!0}typeof document=="undefined"&&function(){var t={},u={};function R(v,r){for(r=r.replace(/^(\.\.\/|\.\/)/,v.replace(/[^/]+$/g,"")+"$1");r!==(r=r.replace(/[^/]+\/\.\.\//g,"")););return r.replace(/\.\//g,"")}var y=[],U=y.push.bind(y);addEventListener("message",U);var P=self.name.match(/^[^\n]+/)[0];self.name=self.name.replace(/^[^\n]*\n/g,""),function v(r,k){var E,s=r;return k&&(r=R(k,r)),t[r]||(t[r]=fetch(r).then(function(j){if((s=j.url)!==r){if(t[s]!=null)return t[s];t[s]=t[r]}return j.text().then(function($){if(!j.ok)throw $;var d={exports:{}};E=u[s]||(u[s]=d.exports);var S=function(f){return v(f,s)},L=[];return $=function(f,i){i=i||[];var a,p=[],h=0;function g(c,n){for(var e,l=/(?:^|,)\s*([\w$]+)(?:\s+as\s+([\w$]+))?\s*/g,o=[];e=l.exec(c);)n?p.push((e[2]||e[1])+":"+e[1]):o.push((e[2]||e[1])+"="+a+"."+e[1]);return o}return(f=f.replace(/(^\s*|[;}\s\n]\s*)import\s*(?:(?:([\w$]+)(?:\s*\,\s*\{([^}]+)\})?|(?:\*\s*as\s+([\w$]+))|\{([^}]*)\})\s*from)?\s*(['"])(.+?)\6/g,function(c,n,e,l,o,w,_,A){return i.push(A),n+="var "+(a="$im$"+ ++h)+"=$require("+_+A+_+")",e&&(n+=";var "+e+" = 'default' in "+a+" ? "+a+".default : "+a),o&&(n+=";var "+o+" = "+a),(l=l||w)&&(n+=";var "+g(l,!1)),n}).replace(/((?:^|[;}\s\n])\s*)export\s*(?:\s+(default)\s+|((?:async\s+)?function\s*\*?|class|const\s|let\s|var\s)\s*([a-zA-Z0-9$_{[]+))/g,function(c,n,e,l,o){if(e){var w="$im$"+ ++h;return p.push("default:"+w),n+"var "+w+"="}return p.push(o+":"+o),n+l+" "+o}).replace(/((?:^|[;}\s\n])\s*)export\s*\{([^}]+)\}\s*;?/g,function(c,n,e){return g(e,!0),n}).replace(/((?:^|[^a-zA-Z0-9$_@`'".])\s*)(import\s*\([\s\S]+?\))/g,"$1$$$2")).replace(/((?:^|[^a-zA-Z0-9$_@`'".])\s*)import\.meta\.url/g,"$1"+JSON.stringify(r))+` +$module.exports={`+p.join(",")+"}"}($,L),Promise.all(L.map(function(f){var i=R(s,f);return i in u?u[i]:v(i)})).then(function(f){$+=` +//# sourceURL=`+r;try{var i=new Function("$import","$require","$module","$exports",$)}catch(e){var a=e.line-1,p=e.column,h=$.split(` +`),g=(h[a-2]||"")+` +`+h[a-1]+` +`+(p==null?"":new Array(p).join("-")+`^ +`)+(h[a]||""),c=new Error(e.message+` + +`+g,r,a);throw c.sourceURL=c.fileName=r,c.line=a,c.column=p,c}var n=i(S,function(e){return f[L.indexOf(e)]},d,d.exports);return n!=null&&(d.exports=n),Object.assign(E,d.exports),d.exports})})}))}(P).then(function(){removeEventListener("message",U),y.map(dispatchEvent)}).catch(function(v){setTimeout(function(){throw v})})}()}})(self.Worker); diff --git a/docs/assets/windowcontrols.275a60cd.js b/docs/assets/windowcontrols.d9e79367.js similarity index 81% rename from docs/assets/windowcontrols.275a60cd.js rename to docs/assets/windowcontrols.d9e79367.js index 2cd0b9c..ba07c36 100644 --- a/docs/assets/windowcontrols.275a60cd.js +++ b/docs/assets/windowcontrols.d9e79367.js @@ -1 +1 @@ -import{d as n,m as s,a as o}from"./index.ecc37913.js";import"./vendor.219e5f4d.js";const e="window-controls-overlay",a=()=>{navigator.windowControlsOverlay.visible?(s.classList.add(e),o.classList.add(e)):(s.classList.remove(e),o.classList.remove(e))};navigator.windowControlsOverlay.addEventListener("geometrychange",n(async()=>{a()},250));a(); +import{d as n,m as s,a as o}from"./index.54ec3c4a.js";import"./vendor.219e5f4d.js";const e="window-controls-overlay",a=()=>{navigator.windowControlsOverlay.visible?(s.classList.add(e),o.classList.add(e)):(s.classList.remove(e),o.classList.remove(e))};navigator.windowControlsOverlay.addEventListener("geometrychange",n(async()=>{a()},250));a(); diff --git a/docs/index.html b/docs/index.html index 39c2a37..9697cac 100644 --- a/docs/index.html +++ b/docs/index.html @@ -143,7 +143,7 @@ } - + diff --git a/docs/sw.js b/docs/sw.js index bbd5ee1..ffb9a7d 100644 --- a/docs/sw.js +++ b/docs/sw.js @@ -1 +1 @@ -if(!self.define){let s,e={};const r=(r,l)=>(r=new URL(r+".js",l).href,e[r]||new Promise((e=>{if("document"in self){const s=document.createElement("script");s.src=r,s.onload=e,document.head.appendChild(s)}else s=r,importScripts(r),e()})).then((()=>{let s=e[r];if(!s)throw new Error(`Module ${r} didn’t register its module`);return s})));self.define=(l,n)=>{const i=s||("document"in self?document.currentScript.src:"")||location.href;if(e[i])return;let o={};const t=s=>r(s,i),u={module:{uri:i},exports:o,require:t};e[i]=Promise.all(l.map((s=>u[s]||t(s)))).then((s=>(n(...s),o)))}}define(["./workbox-6cd28afd"],(function(s){"use strict";self.skipWaiting(),s.clientsClaim(),s.precacheAndRoute([{url:"assets/colorworker.3bb51423.js",revision:null},{url:"assets/de-DE.0c064cfc.js",revision:null},{url:"assets/el-GR.b0c8940a.js",revision:null},{url:"assets/en-US.ca3bb092.js",revision:null},{url:"assets/filehandling.4cb07dc9.js",revision:null},{url:"assets/index.7c07bd9d.css",revision:null},{url:"assets/index.ecc37913.js",revision:null},{url:"assets/install.bccde453.js",revision:null},{url:"assets/monochromeworker.3e780118.js",revision:null},{url:"assets/preprocessworker.88ffa3ad.js",revision:null},{url:"assets/preprocessworker.c921728e.js",revision:null},{url:"assets/svgoworker.bb79c476.js",revision:null},{url:"assets/vendor.219e5f4d.js",revision:null},{url:"assets/windowcontrols.275a60cd.js",revision:null},{url:"index.html",revision:"c6857145a2720d10ee0d3aba543177bd"},{url:"manifest.webmanifest",revision:"2afab6fb30fbe179b8f55c3404813f7f"}],{}),s.cleanupOutdatedCaches(),s.registerRoute(new s.NavigationRoute(s.createHandlerBoundToURL("index.html")))})); +if(!self.define){let s,e={};const r=(r,l)=>(r=new URL(r+".js",l).href,e[r]||new Promise((e=>{if("document"in self){const s=document.createElement("script");s.src=r,s.onload=e,document.head.appendChild(s)}else s=r,importScripts(r),e()})).then((()=>{let s=e[r];if(!s)throw new Error(`Module ${r} didn’t register its module`);return s})));self.define=(l,n)=>{const i=s||("document"in self?document.currentScript.src:"")||location.href;if(e[i])return;let o={};const t=s=>r(s,i),u={module:{uri:i},exports:o,require:t};e[i]=Promise.all(l.map((s=>u[s]||t(s)))).then((s=>(n(...s),o)))}}define(["./workbox-6cd28afd"],(function(s){"use strict";self.skipWaiting(),s.clientsClaim(),s.precacheAndRoute([{url:"assets/colorworker.3bb51423.js",revision:null},{url:"assets/de-DE.0c064cfc.js",revision:null},{url:"assets/el-GR.b0c8940a.js",revision:null},{url:"assets/en-US.ca3bb092.js",revision:null},{url:"assets/filehandling.618c218c.js",revision:null},{url:"assets/index.54ec3c4a.js",revision:null},{url:"assets/index.7c07bd9d.css",revision:null},{url:"assets/install.9bcfb7b8.js",revision:null},{url:"assets/module-workers-polyfill.min.dc7647fd.js",revision:null},{url:"assets/monochromeworker.3e780118.js",revision:null},{url:"assets/preprocessworker.88ffa3ad.js",revision:null},{url:"assets/preprocessworker.c921728e.js",revision:null},{url:"assets/svgoworker.bb79c476.js",revision:null},{url:"assets/vendor.219e5f4d.js",revision:null},{url:"assets/windowcontrols.d9e79367.js",revision:null},{url:"index.html",revision:"d7d2f59960327684b1adca22c1c9d161"},{url:"manifest.webmanifest",revision:"2afab6fb30fbe179b8f55c3404813f7f"}],{}),s.cleanupOutdatedCaches(),s.registerRoute(new s.NavigationRoute(s.createHandlerBoundToURL("index.html")))})); diff --git a/package-lock.json b/package-lock.json index 234daf5..d2022c0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "canvas-size": "^1.2.5", "esm-potrace-wasm": "^0.2.1", "idb-keyval": "^6.1.0", + "module-workers-polyfill": "^0.3.2", "pinch-zoom-element": "^1.1.1", "svgo": "^2.8.0" }, @@ -4841,6 +4842,11 @@ "node": ">= 6" } }, + "node_modules/module-workers-polyfill": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/module-workers-polyfill/-/module-workers-polyfill-0.3.2.tgz", + "integrity": "sha512-zcEMj8vUGYu1Tc5s2GK84MBzRSweec/Ef6F7phRF8QlTfTf2upFNsR3W0lDhvN2E6o1TTXbFIYynD0rQSlynPw==" + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -10765,6 +10771,11 @@ "kind-of": "^6.0.3" } }, + "module-workers-polyfill": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/module-workers-polyfill/-/module-workers-polyfill-0.3.2.tgz", + "integrity": "sha512-zcEMj8vUGYu1Tc5s2GK84MBzRSweec/Ef6F7phRF8QlTfTf2upFNsR3W0lDhvN2E6o1TTXbFIYynD0rQSlynPw==" + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", diff --git a/package.json b/package.json index 33cf8b5..c2cd830 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "canvas-size": "^1.2.5", "esm-potrace-wasm": "^0.2.1", "idb-keyval": "^6.1.0", + "module-workers-polyfill": "^0.3.2", "pinch-zoom-element": "^1.1.1", "svgo": "^2.8.0" }, diff --git a/src/js/clipboard.js b/src/js/clipboard.js index 8b0edc2..84b6d4f 100644 --- a/src/js/clipboard.js +++ b/src/js/clipboard.js @@ -65,20 +65,25 @@ copyButton.addEventListener('click', async () => { let svg = svgOutput.innerHTML; showToast(i18n.t('optimizingSVG'), Infinity); try { - // Safari treats user activation differently: - // https://bugs.webkit.org/show_bug.cgi?id=222262. - await navigator.clipboard.write([ - new ClipboardItem({ - 'text/plain': new Promise(async (resolve) => { - svg = await optimizeSVG(svg); - resolve(new Blob([svg], { type: 'text/plain' })); - }), - 'image/svg+xml': new Promise(async (resolve) => { - svg = await optimizeSVG(svg); - resolve(new Blob([svg], { type: 'image/svg+xml' })); + // Firefox only supports `navigator.clipboard.write()`. + if (!('ClipboardItem' in window)) { + await navigator.clipboard.writeText(await optimizeSVG(svg)); + } else { + // Safari treats user activation differently: + // https://bugs.webkit.org/show_bug.cgi?id=222262. + await navigator.clipboard.write([ + new ClipboardItem({ + 'text/plain': new Promise(async (resolve) => { + svg = await optimizeSVG(svg); + resolve(new Blob([svg], { type: 'text/plain' })); + }), + 'image/svg+xml': new Promise(async (resolve) => { + svg = await optimizeSVG(svg); + resolve(new Blob([svg], { type: 'image/svg+xml' })); + }), }), - }), - ]); + ]); + } } catch (err) { console.log(err.name, err.message); svg = await optimizeSVG(svg); diff --git a/src/js/color.js b/src/js/color.js index 5abc807..d4bea82 100644 --- a/src/js/color.js +++ b/src/js/color.js @@ -54,7 +54,10 @@ const convertToColorSVG = async (imageData) => { intervalID.current = setInterval(() => { const svg = `${prefix}${paths}${suffix}`; if (svg.length !== lastLength) { - svgOutput.setAttribute('transform', svgOutput.dataset.transform); + const transform = svgOutput.dataset.transform; + if (transform) { + svgOutput.setAttribute('transform', transform); + } svgOutput.innerHTML = svg; lastLength = svg.length; } diff --git a/src/js/main.js b/src/js/main.js index 27a09d3..7a5bd3a 100644 --- a/src/js/main.js +++ b/src/js/main.js @@ -37,8 +37,28 @@ if ('onbeforeinstallprompt' in window && 'onappinstalled' in window) { installButton.style.display = 'none'; } +// From https://stackoverflow.com/a/62963963/6255000. +const supportsWorkerType = () => { + let supports = false; + const tester = { + get type() { + supports = true; + }, + }; + try { + new Worker('blob://', tester); + } finally { + return supports; + } +}; + (async () => { initUI(); + if (!supportsWorkerType()) { + await import( + '../.././node_modules/module-workers-polyfill/module-workers-polyfill.min.js' + ); + } const updateSW = registerSW({ onOfflineReady() { diff --git a/src/js/orchestrate.js b/src/js/orchestrate.js index aaab29d..4c9f0b2 100644 --- a/src/js/orchestrate.js +++ b/src/js/orchestrate.js @@ -54,18 +54,24 @@ const startProcessing = async () => { } const transform = svgOutput.getAttribute('transform'); svgOutput.innerHTML = spinnerSVG; - svgOutput.dataset.transform = transform; - svgOutput.setAttribute('transform', ''); + if (transform) { + svgOutput.dataset.transform = transform; + svgOutput.setAttribute('transform', ''); + } const imageData = supportsOffscreenCanvas ? await preProcessInputImage() : preProcessMainCanvas(); if (colorRadio.checked) { const svg = await convertToColorSVG(imageData); - svgOutput.setAttribute('transform', transform); + if (transform) { + svgOutput.setAttribute('transform', transform); + } displayResult(svg, COLOR); } else { const svg = await convertToMonochromeSVG(imageData); - svgOutput.setAttribute('transform', transform); + if (transform) { + svgOutput.setAttribute('transform', transform); + } displayResult(svg, MONOCHROME); } }; diff --git a/vite.config.js b/vite.config.js index d0e26a5..2f08f49 100644 --- a/vite.config.js +++ b/vite.config.js @@ -29,7 +29,11 @@ import webmanifest from './src/manifest.json'; export default { plugins: [ dynamicImportVars({ - include: ['./src/i18n/*', './src/js/filehandling.js'], + include: [ + './src/i18n/*', + './src/js/filehandling.js', + './node_modules/module-workers-polyfill/module-workers-polyfill.min.js', + ], }), vitePWA({ registerType: 'autoUpdate',