scratch-reveal 1.3.0-dev.0 → 1.3.0-dev.2

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.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class S{ctx;mouseX;mouseY;constructor(t,s,i){this.ctx=t,this.mouseX=s,this.mouseY=i}updateMousePosition(t,s){this.mouseX=t,this.mouseY=s}brush(t,s=0){if(!t)return;const i=Math.atan2(this.mouseY,this.mouseX);if(this.ctx.save(),this.ctx.translate(this.mouseX,this.mouseY),this.ctx.rotate(i),s>0){const e=s,h=s*(t.height/t.width);this.ctx.drawImage(t,-(e/2),-(h/2),e,h)}else this.ctx.drawImage(t,-(t.width/2),-(t.height/2));this.ctx.restore()}}function p(c){return new Promise((t,s)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>t(i),i.onerror=()=>s(new Error(`Image ${c} failed to load`)),i.src=c})}function m(c){let t=0;return((...i)=>{t||(t=requestAnimationFrame(()=>{t=0,c(...i)}))})}const b=`.sr {
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class y{ctx;mouseX;mouseY;constructor(t,s,i){this.ctx=t,this.mouseX=s,this.mouseY=i}updateMousePosition(t,s){this.mouseX=t,this.mouseY=s}brush(t,s=0){if(!t)return;const i=Math.atan2(this.mouseY,this.mouseX);if(this.ctx.save(),this.ctx.translate(this.mouseX,this.mouseY),this.ctx.rotate(i),s>0){const e=s,r=s*(t.height/t.width);this.ctx.drawImage(t,-(e/2),-(r/2),e,r)}else this.ctx.drawImage(t,-(t.width/2),-(t.height/2));this.ctx.restore()}}function p(o){return new Promise((t,s)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>t(i),i.onerror=()=>s(new Error(`Image ${o} failed to load`)),i.src=o})}function S(o){let t=0;return((...i)=>{t||(t=requestAnimationFrame(()=>{t=0,o(...i)}))})}const v=`.sr {
2
2
  position: relative;
3
3
  overflow: hidden;
4
4
  width: 100%;
@@ -58,4 +58,4 @@ scratch-reveal {
58
58
  width: 100%;
59
59
  height: 100%;
60
60
  }
61
- `,w=b;function _(c){return"adoptedStyleSheets"in c}function E(c){if(typeof CSSStyleSheet>"u")return null;try{const t=new CSSStyleSheet;return t.replaceSync(c),t}catch{return null}}const v=E(b),d={width:300,height:300,brushSrc:"",imageMaskSrc:"",imageBackgroundSrc:"",brushSize:0,percentToFinish:60};class y{config;ctx;container;_canvas;dpr=1;brush;maskImage;backgroundImage;brushImage;backgroundEl;brushSize=0;percent=0;done=!1;completing=!1;destroyed=!1;lastProgressEmitMs=0;removeListeners;get canvas(){return this._canvas}constructor(t,s={}){if(this.config={...d,...s},this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("ScratchReveal: container not found");this._canvas=this.createCanvas(this.config.width,this.config.height),this.ctx=this._canvas.getContext("2d",{willReadFrequently:!0}),this.setCanvasScale(this.config.width,this.config.height),this.brush=new S(this.ctx,0,0),this.brushSize=this.config.brushSize,this.container.appendChild(this._canvas)}async init(){if(!this.config.brushSrc)throw new Error('ScratchReveal: "brushSrc" is required');if(!this.config.imageMaskSrc)throw new Error('ScratchReveal: "imageMaskSrc" is required');if(!this.config.imageBackgroundSrc)throw new Error('ScratchReveal: "imageBackgroundSrc" is required');const[t,s,i]=await Promise.all([p(this.config.brushSrc),p(this.config.imageMaskSrc),p(this.config.imageBackgroundSrc)]);return this.destroyed?this:(this.brushImage=t,this.maskImage=s,this.backgroundImage=i,this.drawMask(),this.setBackground(),this.bindEvents(),this)}destroy(){this.destroyed=!0,this.removeListeners?.()}getPercent(){return this.percent}createCanvas(t,s){const i=document.createElement("canvas");return i.className="sr__canvas",i.style.width="100%",i.style.height="100%",i}setCanvasScale(t,s){const i=Math.max(1,Math.min(window.devicePixelRatio||1,3));this.dpr=i,this._canvas.width=Math.round(t*this.dpr),this._canvas.height=Math.round(s*this.dpr),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${s}px`,this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0)}resize(t,s){this.destroyed||this.done||t<=0||s<=0||this._canvas.width===t*this.dpr&&this._canvas.height===s*this.dpr||(this.setCanvasScale(t,s),this.percent=0,this.ctx.globalCompositeOperation="source-over",this.drawMask())}setBrushSize(t){this.destroyed||!Number.isFinite(t)||t<0||(this.brushSize=t)}bindEvents(){const s=m((n,r)=>{this.percent=this.updatePercent();const a=performance.now();(!this.lastProgressEmitMs||a-this.lastProgressEmitMs>=120)&&(this.lastProgressEmitMs=a,this.config.onProgress?.(this.percent)),this.finish(n,r)}),i=m(n=>{(n.buttons&1)!==0&&(this.updatePosition(n),this.scratch(),s(n,i))}),e=n=>{try{this._canvas.releasePointerCapture(n.pointerId)}catch{}this._canvas.removeEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)},h=n=>{n.preventDefault(),this.updatePosition(n),this.scratch(),this._canvas.setPointerCapture(n.pointerId),this._canvas.addEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)};this._canvas.addEventListener("pointerdown",h),this._canvas.addEventListener("pointerup",e),this._canvas.addEventListener("pointercancel",e),this.removeListeners=()=>{this._canvas.removeEventListener("pointerdown",h),this._canvas.removeEventListener("pointerup",e),this._canvas.removeEventListener("pointercancel",e),this._canvas.removeEventListener("pointermove",i)}}updatePosition(t){const s=this._canvas.getBoundingClientRect(),i=s.width?this._canvas.width/s.width:1,e=s.height?this._canvas.height/s.height:1,h=(t.clientX-s.left)*i/this.dpr,n=(t.clientY-s.top)*e/this.dpr;this.brush.updateMousePosition(h,n)}drawMask(){this.maskImage&&(this.ctx.globalCompositeOperation="source-over",this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr),this.ctx.drawImage(this.maskImage,0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr))}setBackground(){if(this.destroyed||!this.backgroundImage||!this.container.contains(this._canvas))return;const t=this.backgroundEl??document.createElement("img");t.src=this.backgroundImage.src,t.className="sr__bg",t.isConnected||this.container.insertBefore(t,this._canvas),this.backgroundEl=t}scratch(){if(!this.brushImage)return;const t=this.brushSize>0?this.brushSize:0;this.ctx.globalCompositeOperation="destination-out",this.ctx.save(),this.brush.brush(this.brushImage,t),this.ctx.restore()}updatePercent(){const s=this.ctx.getImageData(0,0,this._canvas.width,this._canvas.height).data;let i=0;for(let e=3;e<s.length;e+=4)s[e]===0&&i++;return i/(this._canvas.width*this._canvas.height)*100}finish(t,s){if(!this.done&&this.percent>this.config.percentToFinish&&(this.done=!0,this._canvas.style.pointerEvents="none",this.config.onComplete?.(),this.playCompleteEffect(),t&&s)){try{this._canvas.releasePointerCapture(t.pointerId)}catch{}this._canvas.removeEventListener("pointermove",s)}}playCompleteEffect(){if(this.destroyed||this.completing)return;this.completing=!0;const t=350,s="ease-out";this._canvas.style.transition=`opacity ${t}ms ${s}`,this._canvas.style.opacity||(this._canvas.style.opacity="1"),requestAnimationFrame(()=>{this._canvas.style.opacity="0",window.setTimeout(()=>{this.destroyed||this.clear()},t)})}clear(){this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr)}}function f(c="scratch-reveal"){if(typeof window>"u"||!("customElements"in window)||customElements.get(c))return;function t(i,e,h,n){if(!i)return n;const r=i.trim();if(!r)return n;const a=Number.parseFloat(r.endsWith("%")?r.slice(0,-1):r.endsWith("px")?r.slice(0,-2):r);if(!Number.isFinite(a))return n;if(r.endsWith("px"))return Math.max(0,a);const o=Math.min(e,h);return Math.max(0,o*a/100)}class s extends HTMLElement{instance;container;styleEl=null;rebuildScheduled=!1;resizeObserver;lastErrorMessage=null;static get observedAttributes(){return["width","height","complete-percent","brush-src","brush-size","mask-src","background-src","show-status"]}constructor(){super();const e=this.attachShadow({mode:"open"});_(e)&&v?e.adoptedStyleSheets=[v]:(this.styleEl=document.createElement("style"),this.styleEl.textContent=b,e.append(this.styleEl)),this.container=document.createElement("div"),this.container.className="sr",e.append(this.container)}connectedCallback(){this.scheduleRebuild()}disconnectedCallback(){this.instance?.destroy(),this.instance=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0}attributeChangedCallback(e,h,n){if(h!==n){if(e==="brush-size"&&this.instance){const{width:r,height:a}=this.resolveSize(),o=t(this.getAttribute("brush-size"),r,a,d.brushSize);this.instance.setBrushSize(o);return}if((e==="width"||e==="height")&&this.instance){const r=this.resolveSize();this.syncContainerSize(r),this.instance.resize(r.width,r.height);const a=t(this.getAttribute("brush-size"),r.width,r.height,d.brushSize);this.instance.setBrushSize(a),this.updateResizeObserver(r);return}this.scheduleRebuild()}}scheduleRebuild(){this.rebuildScheduled||(this.rebuildScheduled=!0,queueMicrotask(()=>{this.rebuildScheduled=!1,this.isConnected&&this.rebuild()}))}rebuild(){const e=this.resolveSize(),h=this.resolvePercentToFinish(),{brushSrc:n,imageMaskSrc:r,imageBackgroundSrc:a}=this.resolveSources(),o=t(this.getAttribute("brush-size"),e.width,e.height,d.brushSize),u=[];if(n||u.push("brush-src"),r||u.push("mask-src"),a||u.push("background-src"),this.syncContainerSize(e),u.length){this.renderWaiting(u),this.updateResizeObserver(e);return}this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,this.lastErrorMessage=null,this.instance=new y(this.container,{width:e.width,height:e.height,percentToFinish:h,brushSrc:n,brushSize:o,imageMaskSrc:r,imageBackgroundSrc:a,onProgress:l=>{this.dispatchEvent(new CustomEvent("progress",{detail:{percent:l},bubbles:!0,composed:!0}))},onComplete:()=>{this.dispatchEvent(new CustomEvent("complete",{detail:{percent:100},bubbles:!0,composed:!0}))}}),this.instance.init().catch(l=>{const g=l instanceof Error?l.message:"ScratchReveal: init failed";this.renderError(g)}),this.updateResizeObserver(e)}renderError(e){this.instance?.destroy(),this.instance=void 0,this.renderStatus(e,"error"),this.lastErrorMessage!==e&&(this.lastErrorMessage=e,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0,composed:!0})))}renderWaiting(e){const h=`ScratchReveal: waiting for required attribute(s): ${e.join(", ")}`;this.renderStatus(h,"waiting")}renderStatus(e,h){if(this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,!this.hasAttribute("show-status"))return;const n=document.createElement("div");n.className=`sr__status sr__status--${h}`,n.textContent=e,n.setAttribute("role",h==="error"?"alert":"status"),this.container.appendChild(n)}resolveSize(){const e=this.hasAttribute("width"),h=this.hasAttribute("height"),n=this.getBoundingClientRect(),r=Math.round(n.width),a=Math.round(n.height),o=Number(this.getAttribute("width")),u=Number(this.getAttribute("height")),l=e&&Number.isFinite(o)?o:r||d.width,g=h&&Number.isFinite(u)?u:a||d.height;return{hasWidthAttr:e,hasHeightAttr:h,width:l,height:g}}resolvePercentToFinish(){const e=Number(this.getAttribute("complete-percent"));return Number.isFinite(e)?e:d.percentToFinish}resolveSources(){return{brushSrc:(this.getAttribute("brush-src")??"").trim(),imageMaskSrc:(this.getAttribute("mask-src")??"").trim(),imageBackgroundSrc:(this.getAttribute("background-src")??"").trim()}}syncContainerSize(e){e.hasWidthAttr?this.container.style.width=`${e.width}px`:this.container.style.width="100%",e.hasHeightAttr?this.container.style.height=`${e.height}px`:this.container.style.height="100%"}updateResizeObserver(e){(!e.hasWidthAttr||!e.hasHeightAttr)&&"ResizeObserver"in window?(this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>{if(this.hasAttribute("width")&&this.hasAttribute("height")){this.resizeObserver?.disconnect(),this.resizeObserver=void 0;return}const n=this.getBoundingClientRect(),r=Math.round(n.width),a=Math.round(n.height);this.instance?.resize(r,a);const o=t(this.getAttribute("brush-size"),r,a,d.brushSize);this.instance?.setBrushSize(o)}),this.resizeObserver.observe(this)):(this.resizeObserver?.disconnect(),this.resizeObserver=void 0)}}customElements.define(c,s)}function z(c){f(),c.config.globalProperties.$scratchReveal=!0}exports.installScratchReveal=z;exports.registerScratchRevealElement=f;exports.scratchRevealCssText=w;
61
+ `,E=v;function z(o){return"adoptedStyleSheets"in o}function k(o){if(typeof CSSStyleSheet>"u")return null;try{const t=new CSSStyleSheet;return t.replaceSync(o),t}catch{return null}}const w=k(v),g={width:300,height:300,brushSrc:"",imageMaskSrc:"",imageBackgroundSrc:"",brushSize:0,percentToFinish:60};class x{config;ctx;container;_canvas;dpr=1;brush;maskImage;backgroundImage;brushImage;backgroundEl;brushSize=0;percent=0;done=!1;completing=!1;destroyed=!1;lastProgressEmitMs=0;removeListeners;get canvas(){return this._canvas}constructor(t,s={}){if(this.config={...g,...s},this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("ScratchReveal: container not found");this._canvas=this.createCanvas(this.config.width,this.config.height),this.ctx=this._canvas.getContext("2d",{willReadFrequently:!0}),this.setCanvasScale(this.config.width,this.config.height),this.brush=new y(this.ctx,0,0),this.brushSize=this.config.brushSize,this.container.appendChild(this._canvas)}async init(){if(!this.config.brushSrc)throw new Error('ScratchReveal: "brushSrc" is required');if(!this.config.imageMaskSrc)throw new Error('ScratchReveal: "imageMaskSrc" is required');if(!this.config.imageBackgroundSrc)throw new Error('ScratchReveal: "imageBackgroundSrc" is required');const[t,s,i]=await Promise.all([p(this.config.brushSrc),p(this.config.imageMaskSrc),p(this.config.imageBackgroundSrc)]);return this.destroyed?this:(this.brushImage=t,this.maskImage=s,this.backgroundImage=i,this.drawMask(),this.setBackground(),this.bindEvents(),this)}destroy(){this.destroyed=!0,this.removeListeners?.()}getPercent(){return this.percent}createCanvas(t,s){const i=document.createElement("canvas");return i.className="sr__canvas",i.style.width="100%",i.style.height="100%",i}setCanvasScale(t,s){const i=Math.max(1,Math.min(window.devicePixelRatio||1,3));this.dpr=i,this._canvas.width=Math.round(t*this.dpr),this._canvas.height=Math.round(s*this.dpr),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${s}px`,this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0)}resize(t,s){this.destroyed||this.done||t<=0||s<=0||this._canvas.width===t*this.dpr&&this._canvas.height===s*this.dpr||(this.setCanvasScale(t,s),this.percent=0,this.ctx.globalCompositeOperation="source-over",this.drawMask())}setBrushSize(t){this.destroyed||!Number.isFinite(t)||t<0||(this.brushSize=t)}bindEvents(){const s=S((n,h)=>{this.percent=this.updatePercent();const a=performance.now();(!this.lastProgressEmitMs||a-this.lastProgressEmitMs>=120)&&(this.lastProgressEmitMs=a,this.config.onProgress?.(this.percent)),this.finish(n,h)}),i=S(n=>{(n.buttons&1)!==0&&(this.updatePosition(n),this.scratch(),s(n,i))}),e=n=>{try{this._canvas.releasePointerCapture(n.pointerId)}catch{}this._canvas.removeEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)},r=n=>{n.preventDefault(),this.updatePosition(n),this.scratch(),this._canvas.setPointerCapture(n.pointerId),this._canvas.addEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)};this._canvas.addEventListener("pointerdown",r),this._canvas.addEventListener("pointerup",e),this._canvas.addEventListener("pointercancel",e),this.removeListeners=()=>{this._canvas.removeEventListener("pointerdown",r),this._canvas.removeEventListener("pointerup",e),this._canvas.removeEventListener("pointercancel",e),this._canvas.removeEventListener("pointermove",i)}}updatePosition(t){const s=this._canvas.getBoundingClientRect(),i=s.width?this._canvas.width/s.width:1,e=s.height?this._canvas.height/s.height:1,r=(t.clientX-s.left)*i/this.dpr,n=(t.clientY-s.top)*e/this.dpr;this.brush.updateMousePosition(r,n)}drawMask(){this.maskImage&&(this.ctx.globalCompositeOperation="source-over",this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr),this.ctx.drawImage(this.maskImage,0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr))}setBackground(){if(this.destroyed||!this.backgroundImage||!this.container.contains(this._canvas))return;const t=this.backgroundEl??document.createElement("img");t.src=this.backgroundImage.src,t.className="sr__bg",t.isConnected||this.container.insertBefore(t,this._canvas),this.backgroundEl=t}scratch(){if(!this.brushImage)return;const t=this.brushSize>0?this.brushSize:0;this.ctx.globalCompositeOperation="destination-out",this.ctx.save(),this.brush.brush(this.brushImage,t),this.ctx.restore()}updatePercent(){const s=this.ctx.getImageData(0,0,this._canvas.width,this._canvas.height).data;let i=0;for(let e=3;e<s.length;e+=4)s[e]===0&&i++;return i/(this._canvas.width*this._canvas.height)*100}finish(t,s){if(!this.done&&this.percent>this.config.percentToFinish&&(this.done=!0,this._canvas.style.pointerEvents="none",this.config.onComplete?.(),this.playCompleteEffect(),t&&s)){try{this._canvas.releasePointerCapture(t.pointerId)}catch{}this._canvas.removeEventListener("pointermove",s)}}playCompleteEffect(){if(this.destroyed||this.completing)return;this.completing=!0;const t=350,s="ease-out";this._canvas.style.transition=`opacity ${t}ms ${s}`,this._canvas.style.opacity||(this._canvas.style.opacity="1"),requestAnimationFrame(()=>{this._canvas.style.opacity="0",window.setTimeout(()=>{this.destroyed||this.clear()},t)})}clear(){this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr)}}function _(o="scratch-reveal"){if(typeof window>"u"||!("customElements"in window)||customElements.get(o))return;function t(i,e,r,n){if(!i)return n;const h=i.trim();if(!h)return n;const a=Number.parseFloat(h.endsWith("%")?h.slice(0,-1):h.endsWith("px")?h.slice(0,-2):h);if(!Number.isFinite(a))return n;if(h.endsWith("px"))return Math.max(0,a);const c=Math.min(e,r);return Math.max(0,c*a/100)}class s extends HTMLElement{instance;container;styleEl=null;rebuildScheduled=!1;rebuildToken=0;resizeObserver;lastErrorMessage=null;static get observedAttributes(){return["width","height","complete-percent","brush-src","brush-size","mask-src","background-src","show-status"]}constructor(){super();const e=this.attachShadow({mode:"open"});z(e)&&w?e.adoptedStyleSheets=[w]:(this.styleEl=document.createElement("style"),this.styleEl.textContent=v,e.append(this.styleEl)),this.container=document.createElement("div"),this.container.className="sr",e.append(this.container)}connectedCallback(){this.scheduleRebuild()}disconnectedCallback(){this.instance?.destroy(),this.instance=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0}attributeChangedCallback(e,r,n){if(r!==n){if(e==="brush-size"&&this.instance){const{width:h,height:a}=this.resolveSize(),c=t(this.getAttribute("brush-size"),h,a,g.brushSize);this.instance.setBrushSize(c);return}if((e==="width"||e==="height")&&this.instance){const h=this.resolveSize();this.syncContainerSize(h),this.instance.resize(h.width,h.height);const a=t(this.getAttribute("brush-size"),h.width,h.height,g.brushSize);this.instance.setBrushSize(a),this.updateResizeObserver(h);return}this.scheduleRebuild()}}scheduleRebuild(){this.rebuildScheduled||(this.rebuildScheduled=!0,queueMicrotask(()=>{this.rebuildScheduled=!1,this.isConnected&&this.rebuild()}))}async rebuild(){const e=++this.rebuildToken,r=this.resolveSize(),n=this.resolvePercentToFinish(),{brushSrc:h,imageMaskSrc:a,imageBackgroundSrc:c}=this.resolveSources(),l=[];if(h||l.push("brush-src"),a||l.push("mask-src"),c||l.push("background-src"),l.length){this.syncContainerSize(r),this.renderWaiting(l),this.updateResizeObserver(r);return}let u=r;if(!r.hasWidthAttr&&!r.hasHeightAttr&&r.autoWidth===0&&r.autoHeight===0)try{const d=await p(a);if(e!==this.rebuildToken||!this.isConnected)return;const b=d.naturalWidth||d.width,f=d.naturalHeight||d.height;b>0&&f>0&&(u={...r,width:b,height:f})}catch{}this.syncContainerSize(u);const m=t(this.getAttribute("brush-size"),u.width,u.height,g.brushSize);this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,this.lastErrorMessage=null,this.instance=new x(this.container,{width:u.width,height:u.height,percentToFinish:n,brushSrc:h,brushSize:m,imageMaskSrc:a,imageBackgroundSrc:c,onProgress:d=>{this.dispatchEvent(new CustomEvent("progress",{detail:{percent:d},bubbles:!0,composed:!0}))},onComplete:()=>{this.dispatchEvent(new CustomEvent("complete",{detail:{percent:100},bubbles:!0,composed:!0}))}}),this.instance.init().catch(d=>{const b=d instanceof Error?d.message:"ScratchReveal: init failed";this.renderError(b)}),this.updateResizeObserver(u)}renderError(e){this.instance?.destroy(),this.instance=void 0,this.renderStatus(e,"error"),this.lastErrorMessage!==e&&(this.lastErrorMessage=e,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0,composed:!0})))}renderWaiting(e){const r=`ScratchReveal: waiting for required attribute(s): ${e.join(", ")}`;this.renderStatus(r,"waiting")}renderStatus(e,r){if(this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,!this.hasAttribute("show-status"))return;const n=document.createElement("div");n.className=`sr__status sr__status--${r}`,n.textContent=e,n.setAttribute("role",r==="error"?"alert":"status"),this.container.appendChild(n)}resolveSize(){const e=this.hasAttribute("width"),r=this.hasAttribute("height"),n=this.getBoundingClientRect(),h=Math.round(n.width),a=Math.round(n.height),c=Number(this.getAttribute("width")),l=Number(this.getAttribute("height")),u=e&&Number.isFinite(c)?c:h||g.width,m=r&&Number.isFinite(l)?l:a||g.height;return{hasWidthAttr:e,hasHeightAttr:r,width:u,height:m,autoWidth:h,autoHeight:a}}resolvePercentToFinish(){const e=Number(this.getAttribute("complete-percent"));return Number.isFinite(e)?e:g.percentToFinish}resolveSources(){return{brushSrc:(this.getAttribute("brush-src")??"").trim(),imageMaskSrc:(this.getAttribute("mask-src")??"").trim(),imageBackgroundSrc:(this.getAttribute("background-src")??"").trim()}}syncContainerSize(e){e.hasWidthAttr?this.container.style.width=`${e.width}px`:this.container.style.width="100%",e.hasHeightAttr?this.container.style.height=`${e.height}px`:this.container.style.height="100%"}updateResizeObserver(e){(!e.hasWidthAttr||!e.hasHeightAttr)&&"ResizeObserver"in window?(this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>{if(this.hasAttribute("width")&&this.hasAttribute("height")){this.resizeObserver?.disconnect(),this.resizeObserver=void 0;return}const n=this.getBoundingClientRect(),h=Math.round(n.width),a=Math.round(n.height);this.instance?.resize(h,a);const c=t(this.getAttribute("brush-size"),h,a,g.brushSize);this.instance?.setBrushSize(c)}),this.resizeObserver.observe(this)):(this.resizeObserver?.disconnect(),this.resizeObserver=void 0)}}customElements.define(o,s)}function C(o){_(),o.config.globalProperties.$scratchReveal=!0}exports.installScratchReveal=C;exports.registerScratchRevealElement=_;exports.scratchRevealCssText=E;
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- class f {
1
+ class _ {
2
2
  ctx;
3
3
  mouseX;
4
4
  mouseY;
@@ -13,8 +13,8 @@ class f {
13
13
  return;
14
14
  const i = Math.atan2(this.mouseY, this.mouseX);
15
15
  if (this.ctx.save(), this.ctx.translate(this.mouseX, this.mouseY), this.ctx.rotate(i), s > 0) {
16
- const e = s, h = s * (t.height / t.width);
17
- this.ctx.drawImage(t, -(e / 2), -(h / 2), e, h);
16
+ const e = s, r = s * (t.height / t.width);
17
+ this.ctx.drawImage(t, -(e / 2), -(r / 2), e, r);
18
18
  } else
19
19
  this.ctx.drawImage(t, -(t.width / 2), -(t.height / 2));
20
20
  this.ctx.restore();
@@ -26,7 +26,7 @@ function p(o) {
26
26
  i.crossOrigin = "anonymous", i.onload = () => t(i), i.onerror = () => s(new Error(`Image ${o} failed to load`)), i.src = o;
27
27
  });
28
28
  }
29
- function m(o) {
29
+ function S(o) {
30
30
  let t = 0;
31
31
  return ((...i) => {
32
32
  t || (t = requestAnimationFrame(() => {
@@ -34,7 +34,7 @@ function m(o) {
34
34
  }));
35
35
  });
36
36
  }
37
- const b = `.sr {
37
+ const v = `.sr {
38
38
  position: relative;
39
39
  overflow: hidden;
40
40
  width: 100%;
@@ -94,11 +94,11 @@ scratch-reveal {
94
94
  width: 100%;
95
95
  height: 100%;
96
96
  }
97
- `, y = b;
98
- function S(o) {
97
+ `, x = v;
98
+ function y(o) {
99
99
  return "adoptedStyleSheets" in o;
100
100
  }
101
- function w(o) {
101
+ function E(o) {
102
102
  if (typeof CSSStyleSheet > "u") return null;
103
103
  try {
104
104
  const t = new CSSStyleSheet();
@@ -107,7 +107,7 @@ function w(o) {
107
107
  return null;
108
108
  }
109
109
  }
110
- const v = w(b), d = {
110
+ const w = E(v), g = {
111
111
  width: 300,
112
112
  height: 300,
113
113
  brushSrc: "",
@@ -116,7 +116,7 @@ const v = w(b), d = {
116
116
  brushSize: 0,
117
117
  percentToFinish: 60
118
118
  };
119
- class _ {
119
+ class z {
120
120
  config;
121
121
  ctx;
122
122
  container;
@@ -138,11 +138,11 @@ class _ {
138
138
  return this._canvas;
139
139
  }
140
140
  constructor(t, s = {}) {
141
- if (this.config = { ...d, ...s }, this.container = typeof t == "string" ? document.querySelector(t) : t, !this.container)
141
+ if (this.config = { ...g, ...s }, this.container = typeof t == "string" ? document.querySelector(t) : t, !this.container)
142
142
  throw new Error("ScratchReveal: container not found");
143
143
  this._canvas = this.createCanvas(this.config.width, this.config.height), this.ctx = this._canvas.getContext("2d", {
144
144
  willReadFrequently: !0
145
- }), this.setCanvasScale(this.config.width, this.config.height), this.brush = new f(this.ctx, 0, 0), this.brushSize = this.config.brushSize, this.container.appendChild(this._canvas);
145
+ }), this.setCanvasScale(this.config.width, this.config.height), this.brush = new _(this.ctx, 0, 0), this.brushSize = this.config.brushSize, this.container.appendChild(this._canvas);
146
146
  }
147
147
  async init() {
148
148
  if (!this.config.brushSrc)
@@ -179,13 +179,13 @@ class _ {
179
179
  this.destroyed || !Number.isFinite(t) || t < 0 || (this.brushSize = t);
180
180
  }
181
181
  bindEvents() {
182
- const s = m(
183
- (n, r) => {
182
+ const s = S(
183
+ (n, h) => {
184
184
  this.percent = this.updatePercent();
185
185
  const a = performance.now();
186
- (!this.lastProgressEmitMs || a - this.lastProgressEmitMs >= 120) && (this.lastProgressEmitMs = a, this.config.onProgress?.(this.percent)), this.finish(n, r);
186
+ (!this.lastProgressEmitMs || a - this.lastProgressEmitMs >= 120) && (this.lastProgressEmitMs = a, this.config.onProgress?.(this.percent)), this.finish(n, h);
187
187
  }
188
- ), i = m((n) => {
188
+ ), i = S((n) => {
189
189
  (n.buttons & 1) !== 0 && (this.updatePosition(n), this.scratch(), s(n, i));
190
190
  }), e = (n) => {
191
191
  try {
@@ -193,16 +193,16 @@ class _ {
193
193
  } catch {
194
194
  }
195
195
  this._canvas.removeEventListener("pointermove", i), this.percent = this.updatePercent(), this.config.onProgress?.(this.percent), this.finish(n, i);
196
- }, h = (n) => {
196
+ }, r = (n) => {
197
197
  n.preventDefault(), this.updatePosition(n), this.scratch(), this._canvas.setPointerCapture(n.pointerId), this._canvas.addEventListener("pointermove", i), this.percent = this.updatePercent(), this.config.onProgress?.(this.percent), this.finish(n, i);
198
198
  };
199
- this._canvas.addEventListener("pointerdown", h), this._canvas.addEventListener("pointerup", e), this._canvas.addEventListener("pointercancel", e), this.removeListeners = () => {
200
- this._canvas.removeEventListener("pointerdown", h), this._canvas.removeEventListener("pointerup", e), this._canvas.removeEventListener("pointercancel", e), this._canvas.removeEventListener("pointermove", i);
199
+ this._canvas.addEventListener("pointerdown", r), this._canvas.addEventListener("pointerup", e), this._canvas.addEventListener("pointercancel", e), this.removeListeners = () => {
200
+ this._canvas.removeEventListener("pointerdown", r), this._canvas.removeEventListener("pointerup", e), this._canvas.removeEventListener("pointercancel", e), this._canvas.removeEventListener("pointermove", i);
201
201
  };
202
202
  }
203
203
  updatePosition(t) {
204
- const s = this._canvas.getBoundingClientRect(), i = s.width ? this._canvas.width / s.width : 1, e = s.height ? this._canvas.height / s.height : 1, h = (t.clientX - s.left) * i / this.dpr, n = (t.clientY - s.top) * e / this.dpr;
205
- this.brush.updateMousePosition(h, n);
204
+ const s = this._canvas.getBoundingClientRect(), i = s.width ? this._canvas.width / s.width : 1, e = s.height ? this._canvas.height / s.height : 1, r = (t.clientX - s.left) * i / this.dpr, n = (t.clientY - s.top) * e / this.dpr;
205
+ this.brush.updateMousePosition(r, n);
206
206
  }
207
207
  drawMask() {
208
208
  this.maskImage && (this.ctx.globalCompositeOperation = "source-over", this.ctx.clearRect(0, 0, this._canvas.width / this.dpr, this._canvas.height / this.dpr), this.ctx.drawImage(
@@ -253,19 +253,19 @@ class _ {
253
253
  this.ctx.clearRect(0, 0, this._canvas.width / this.dpr, this._canvas.height / this.dpr);
254
254
  }
255
255
  }
256
- function E(o = "scratch-reveal") {
256
+ function k(o = "scratch-reveal") {
257
257
  if (typeof window > "u" || !("customElements" in window) || customElements.get(o)) return;
258
- function t(i, e, h, n) {
258
+ function t(i, e, r, n) {
259
259
  if (!i) return n;
260
- const r = i.trim();
261
- if (!r) return n;
260
+ const h = i.trim();
261
+ if (!h) return n;
262
262
  const a = Number.parseFloat(
263
- r.endsWith("%") ? r.slice(0, -1) : r.endsWith("px") ? r.slice(0, -2) : r
263
+ h.endsWith("%") ? h.slice(0, -1) : h.endsWith("px") ? h.slice(0, -2) : h
264
264
  );
265
265
  if (!Number.isFinite(a)) return n;
266
- if (r.endsWith("px"))
266
+ if (h.endsWith("px"))
267
267
  return Math.max(0, a);
268
- const c = Math.min(e, h);
268
+ const c = Math.min(e, r);
269
269
  return Math.max(0, c * a / 100);
270
270
  }
271
271
  class s extends HTMLElement {
@@ -273,6 +273,7 @@ function E(o = "scratch-reveal") {
273
273
  container;
274
274
  styleEl = null;
275
275
  rebuildScheduled = !1;
276
+ rebuildToken = 0;
276
277
  resizeObserver;
277
278
  lastErrorMessage = null;
278
279
  static get observedAttributes() {
@@ -290,7 +291,7 @@ function E(o = "scratch-reveal") {
290
291
  constructor() {
291
292
  super();
292
293
  const e = this.attachShadow({ mode: "open" });
293
- S(e) && v ? e.adoptedStyleSheets = [v] : (this.styleEl = document.createElement("style"), this.styleEl.textContent = b, e.append(this.styleEl)), this.container = document.createElement("div"), this.container.className = "sr", e.append(this.container);
294
+ y(e) && w ? e.adoptedStyleSheets = [w] : (this.styleEl = document.createElement("style"), this.styleEl.textContent = v, e.append(this.styleEl)), this.container = document.createElement("div"), this.container.className = "sr", e.append(this.container);
294
295
  }
295
296
  connectedCallback() {
296
297
  this.scheduleRebuild();
@@ -298,28 +299,28 @@ function E(o = "scratch-reveal") {
298
299
  disconnectedCallback() {
299
300
  this.instance?.destroy(), this.instance = void 0, this.resizeObserver?.disconnect(), this.resizeObserver = void 0;
300
301
  }
301
- attributeChangedCallback(e, h, n) {
302
- if (h !== n) {
302
+ attributeChangedCallback(e, r, n) {
303
+ if (r !== n) {
303
304
  if (e === "brush-size" && this.instance) {
304
- const { width: r, height: a } = this.resolveSize(), c = t(
305
+ const { width: h, height: a } = this.resolveSize(), c = t(
305
306
  this.getAttribute("brush-size"),
306
- r,
307
+ h,
307
308
  a,
308
- d.brushSize
309
+ g.brushSize
309
310
  );
310
311
  this.instance.setBrushSize(c);
311
312
  return;
312
313
  }
313
314
  if ((e === "width" || e === "height") && this.instance) {
314
- const r = this.resolveSize();
315
- this.syncContainerSize(r), this.instance.resize(r.width, r.height);
315
+ const h = this.resolveSize();
316
+ this.syncContainerSize(h), this.instance.resize(h.width, h.height);
316
317
  const a = t(
317
318
  this.getAttribute("brush-size"),
318
- r.width,
319
- r.height,
320
- d.brushSize
319
+ h.width,
320
+ h.height,
321
+ g.brushSize
321
322
  );
322
- this.instance.setBrushSize(a), this.updateResizeObserver(r);
323
+ this.instance.setBrushSize(a), this.updateResizeObserver(h);
323
324
  return;
324
325
  }
325
326
  this.scheduleRebuild();
@@ -330,29 +331,44 @@ function E(o = "scratch-reveal") {
330
331
  this.rebuildScheduled = !1, this.isConnected && this.rebuild();
331
332
  }));
332
333
  }
333
- rebuild() {
334
- const e = this.resolveSize(), h = this.resolvePercentToFinish(), { brushSrc: n, imageMaskSrc: r, imageBackgroundSrc: a } = this.resolveSources(), c = t(
335
- this.getAttribute("brush-size"),
336
- e.width,
337
- e.height,
338
- d.brushSize
339
- ), u = [];
340
- if (n || u.push("brush-src"), r || u.push("mask-src"), a || u.push("background-src"), this.syncContainerSize(e), u.length) {
341
- this.renderWaiting(u), this.updateResizeObserver(e);
334
+ async rebuild() {
335
+ const e = ++this.rebuildToken, r = this.resolveSize(), n = this.resolvePercentToFinish(), { brushSrc: h, imageMaskSrc: a, imageBackgroundSrc: c } = this.resolveSources(), l = [];
336
+ if (h || l.push("brush-src"), a || l.push("mask-src"), c || l.push("background-src"), l.length) {
337
+ this.syncContainerSize(r), this.renderWaiting(l), this.updateResizeObserver(r);
342
338
  return;
343
339
  }
344
- this.container.replaceChildren(), this.instance?.destroy(), this.instance = void 0, this.lastErrorMessage = null, this.instance = new _(this.container, {
345
- width: e.width,
346
- height: e.height,
347
- percentToFinish: h,
348
- brushSrc: n,
349
- brushSize: c,
350
- imageMaskSrc: r,
351
- imageBackgroundSrc: a,
352
- onProgress: (l) => {
340
+ let u = r;
341
+ if (!r.hasWidthAttr && !r.hasHeightAttr && r.autoWidth === 0 && r.autoHeight === 0)
342
+ try {
343
+ const d = await p(a);
344
+ if (e !== this.rebuildToken || !this.isConnected) return;
345
+ const b = d.naturalWidth || d.width, f = d.naturalHeight || d.height;
346
+ b > 0 && f > 0 && (u = {
347
+ ...r,
348
+ width: b,
349
+ height: f
350
+ });
351
+ } catch {
352
+ }
353
+ this.syncContainerSize(u);
354
+ const m = t(
355
+ this.getAttribute("brush-size"),
356
+ u.width,
357
+ u.height,
358
+ g.brushSize
359
+ );
360
+ this.container.replaceChildren(), this.instance?.destroy(), this.instance = void 0, this.lastErrorMessage = null, this.instance = new z(this.container, {
361
+ width: u.width,
362
+ height: u.height,
363
+ percentToFinish: n,
364
+ brushSrc: h,
365
+ brushSize: m,
366
+ imageMaskSrc: a,
367
+ imageBackgroundSrc: c,
368
+ onProgress: (d) => {
353
369
  this.dispatchEvent(
354
370
  new CustomEvent("progress", {
355
- detail: { percent: l },
371
+ detail: { percent: d },
356
372
  bubbles: !0,
357
373
  composed: !0
358
374
  })
@@ -367,10 +383,10 @@ function E(o = "scratch-reveal") {
367
383
  })
368
384
  );
369
385
  }
370
- }), this.instance.init().catch((l) => {
371
- const g = l instanceof Error ? l.message : "ScratchReveal: init failed";
372
- this.renderError(g);
373
- }), this.updateResizeObserver(e);
386
+ }), this.instance.init().catch((d) => {
387
+ const b = d instanceof Error ? d.message : "ScratchReveal: init failed";
388
+ this.renderError(b);
389
+ }), this.updateResizeObserver(u);
374
390
  }
375
391
  renderError(e) {
376
392
  this.instance?.destroy(), this.instance = void 0, this.renderStatus(e, "error"), this.lastErrorMessage !== e && (this.lastErrorMessage = e, this.dispatchEvent(
@@ -382,21 +398,21 @@ function E(o = "scratch-reveal") {
382
398
  ));
383
399
  }
384
400
  renderWaiting(e) {
385
- const h = `ScratchReveal: waiting for required attribute(s): ${e.join(", ")}`;
386
- this.renderStatus(h, "waiting");
401
+ const r = `ScratchReveal: waiting for required attribute(s): ${e.join(", ")}`;
402
+ this.renderStatus(r, "waiting");
387
403
  }
388
- renderStatus(e, h) {
404
+ renderStatus(e, r) {
389
405
  if (this.container.replaceChildren(), this.instance?.destroy(), this.instance = void 0, !this.hasAttribute("show-status")) return;
390
406
  const n = document.createElement("div");
391
- n.className = `sr__status sr__status--${h}`, n.textContent = e, n.setAttribute("role", h === "error" ? "alert" : "status"), this.container.appendChild(n);
407
+ n.className = `sr__status sr__status--${r}`, n.textContent = e, n.setAttribute("role", r === "error" ? "alert" : "status"), this.container.appendChild(n);
392
408
  }
393
409
  resolveSize() {
394
- const e = this.hasAttribute("width"), h = this.hasAttribute("height"), n = this.getBoundingClientRect(), r = Math.round(n.width), a = Math.round(n.height), c = Number(this.getAttribute("width")), u = Number(this.getAttribute("height")), l = e && Number.isFinite(c) ? c : r || d.width, g = h && Number.isFinite(u) ? u : a || d.height;
395
- return { hasWidthAttr: e, hasHeightAttr: h, width: l, height: g };
410
+ const e = this.hasAttribute("width"), r = this.hasAttribute("height"), n = this.getBoundingClientRect(), h = Math.round(n.width), a = Math.round(n.height), c = Number(this.getAttribute("width")), l = Number(this.getAttribute("height")), u = e && Number.isFinite(c) ? c : h || g.width, m = r && Number.isFinite(l) ? l : a || g.height;
411
+ return { hasWidthAttr: e, hasHeightAttr: r, width: u, height: m, autoWidth: h, autoHeight: a };
396
412
  }
397
413
  resolvePercentToFinish() {
398
414
  const e = Number(this.getAttribute("complete-percent"));
399
- return Number.isFinite(e) ? e : d.percentToFinish;
415
+ return Number.isFinite(e) ? e : g.percentToFinish;
400
416
  }
401
417
  resolveSources() {
402
418
  return {
@@ -414,13 +430,13 @@ function E(o = "scratch-reveal") {
414
430
  this.resizeObserver?.disconnect(), this.resizeObserver = void 0;
415
431
  return;
416
432
  }
417
- const n = this.getBoundingClientRect(), r = Math.round(n.width), a = Math.round(n.height);
418
- this.instance?.resize(r, a);
433
+ const n = this.getBoundingClientRect(), h = Math.round(n.width), a = Math.round(n.height);
434
+ this.instance?.resize(h, a);
419
435
  const c = t(
420
436
  this.getAttribute("brush-size"),
421
- r,
437
+ h,
422
438
  a,
423
- d.brushSize
439
+ g.brushSize
424
440
  );
425
441
  this.instance?.setBrushSize(c);
426
442
  }), this.resizeObserver.observe(this)) : (this.resizeObserver?.disconnect(), this.resizeObserver = void 0);
@@ -428,11 +444,11 @@ function E(o = "scratch-reveal") {
428
444
  }
429
445
  customElements.define(o, s);
430
446
  }
431
- function z(o) {
432
- E(), o.config.globalProperties.$scratchReveal = !0;
447
+ function C(o) {
448
+ k(), o.config.globalProperties.$scratchReveal = !0;
433
449
  }
434
450
  export {
435
- z as installScratchReveal,
436
- E as registerScratchRevealElement,
437
- y as scratchRevealCssText
451
+ C as installScratchReveal,
452
+ k as registerScratchRevealElement,
453
+ x as scratchRevealCssText
438
454
  };
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(u,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(u=typeof globalThis<"u"?globalThis:u||self,p(u.ScratchReveal={}))})(this,(function(u){"use strict";class p{ctx;mouseX;mouseY;constructor(t,s,i){this.ctx=t,this.mouseX=s,this.mouseY=i}updateMousePosition(t,s){this.mouseX=t,this.mouseY=s}brush(t,s=0){if(!t)return;const i=Math.atan2(this.mouseY,this.mouseX);if(this.ctx.save(),this.ctx.translate(this.mouseX,this.mouseY),this.ctx.rotate(i),s>0){const e=s,h=s*(t.height/t.width);this.ctx.drawImage(t,-(e/2),-(h/2),e,h)}else this.ctx.drawImage(t,-(t.width/2),-(t.height/2));this.ctx.restore()}}function b(o){return new Promise((t,s)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>t(i),i.onerror=()=>s(new Error(`Image ${o} failed to load`)),i.src=o})}function f(o){let t=0;return((...i)=>{t||(t=requestAnimationFrame(()=>{t=0,o(...i)}))})}const m=`.sr {
1
+ (function(l,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(l=typeof globalThis<"u"?globalThis:l||self,b(l.ScratchReveal={}))})(this,(function(l){"use strict";class b{ctx;mouseX;mouseY;constructor(t,s,i){this.ctx=t,this.mouseX=s,this.mouseY=i}updateMousePosition(t,s){this.mouseX=t,this.mouseY=s}brush(t,s=0){if(!t)return;const i=Math.atan2(this.mouseY,this.mouseX);if(this.ctx.save(),this.ctx.translate(this.mouseX,this.mouseY),this.ctx.rotate(i),s>0){const e=s,r=s*(t.height/t.width);this.ctx.drawImage(t,-(e/2),-(r/2),e,r)}else this.ctx.drawImage(t,-(t.width/2),-(t.height/2));this.ctx.restore()}}function m(o){return new Promise((t,s)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>t(i),i.onerror=()=>s(new Error(`Image ${o} failed to load`)),i.src=o})}function w(o){let t=0;return((...i)=>{t||(t=requestAnimationFrame(()=>{t=0,o(...i)}))})}const f=`.sr {
2
2
  position: relative;
3
3
  overflow: hidden;
4
4
  width: 100%;
@@ -58,4 +58,4 @@ scratch-reveal {
58
58
  width: 100%;
59
59
  height: 100%;
60
60
  }
61
- `,_=m;function y(o){return"adoptedStyleSheets"in o}function E(o){if(typeof CSSStyleSheet>"u")return null;try{const t=new CSSStyleSheet;return t.replaceSync(o),t}catch{return null}}const S=E(m),d={width:300,height:300,brushSrc:"",imageMaskSrc:"",imageBackgroundSrc:"",brushSize:0,percentToFinish:60};class z{config;ctx;container;_canvas;dpr=1;brush;maskImage;backgroundImage;brushImage;backgroundEl;brushSize=0;percent=0;done=!1;completing=!1;destroyed=!1;lastProgressEmitMs=0;removeListeners;get canvas(){return this._canvas}constructor(t,s={}){if(this.config={...d,...s},this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("ScratchReveal: container not found");this._canvas=this.createCanvas(this.config.width,this.config.height),this.ctx=this._canvas.getContext("2d",{willReadFrequently:!0}),this.setCanvasScale(this.config.width,this.config.height),this.brush=new p(this.ctx,0,0),this.brushSize=this.config.brushSize,this.container.appendChild(this._canvas)}async init(){if(!this.config.brushSrc)throw new Error('ScratchReveal: "brushSrc" is required');if(!this.config.imageMaskSrc)throw new Error('ScratchReveal: "imageMaskSrc" is required');if(!this.config.imageBackgroundSrc)throw new Error('ScratchReveal: "imageBackgroundSrc" is required');const[t,s,i]=await Promise.all([b(this.config.brushSrc),b(this.config.imageMaskSrc),b(this.config.imageBackgroundSrc)]);return this.destroyed?this:(this.brushImage=t,this.maskImage=s,this.backgroundImage=i,this.drawMask(),this.setBackground(),this.bindEvents(),this)}destroy(){this.destroyed=!0,this.removeListeners?.()}getPercent(){return this.percent}createCanvas(t,s){const i=document.createElement("canvas");return i.className="sr__canvas",i.style.width="100%",i.style.height="100%",i}setCanvasScale(t,s){const i=Math.max(1,Math.min(window.devicePixelRatio||1,3));this.dpr=i,this._canvas.width=Math.round(t*this.dpr),this._canvas.height=Math.round(s*this.dpr),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${s}px`,this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0)}resize(t,s){this.destroyed||this.done||t<=0||s<=0||this._canvas.width===t*this.dpr&&this._canvas.height===s*this.dpr||(this.setCanvasScale(t,s),this.percent=0,this.ctx.globalCompositeOperation="source-over",this.drawMask())}setBrushSize(t){this.destroyed||!Number.isFinite(t)||t<0||(this.brushSize=t)}bindEvents(){const s=f((n,r)=>{this.percent=this.updatePercent();const a=performance.now();(!this.lastProgressEmitMs||a-this.lastProgressEmitMs>=120)&&(this.lastProgressEmitMs=a,this.config.onProgress?.(this.percent)),this.finish(n,r)}),i=f(n=>{(n.buttons&1)!==0&&(this.updatePosition(n),this.scratch(),s(n,i))}),e=n=>{try{this._canvas.releasePointerCapture(n.pointerId)}catch{}this._canvas.removeEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)},h=n=>{n.preventDefault(),this.updatePosition(n),this.scratch(),this._canvas.setPointerCapture(n.pointerId),this._canvas.addEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)};this._canvas.addEventListener("pointerdown",h),this._canvas.addEventListener("pointerup",e),this._canvas.addEventListener("pointercancel",e),this.removeListeners=()=>{this._canvas.removeEventListener("pointerdown",h),this._canvas.removeEventListener("pointerup",e),this._canvas.removeEventListener("pointercancel",e),this._canvas.removeEventListener("pointermove",i)}}updatePosition(t){const s=this._canvas.getBoundingClientRect(),i=s.width?this._canvas.width/s.width:1,e=s.height?this._canvas.height/s.height:1,h=(t.clientX-s.left)*i/this.dpr,n=(t.clientY-s.top)*e/this.dpr;this.brush.updateMousePosition(h,n)}drawMask(){this.maskImage&&(this.ctx.globalCompositeOperation="source-over",this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr),this.ctx.drawImage(this.maskImage,0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr))}setBackground(){if(this.destroyed||!this.backgroundImage||!this.container.contains(this._canvas))return;const t=this.backgroundEl??document.createElement("img");t.src=this.backgroundImage.src,t.className="sr__bg",t.isConnected||this.container.insertBefore(t,this._canvas),this.backgroundEl=t}scratch(){if(!this.brushImage)return;const t=this.brushSize>0?this.brushSize:0;this.ctx.globalCompositeOperation="destination-out",this.ctx.save(),this.brush.brush(this.brushImage,t),this.ctx.restore()}updatePercent(){const s=this.ctx.getImageData(0,0,this._canvas.width,this._canvas.height).data;let i=0;for(let e=3;e<s.length;e+=4)s[e]===0&&i++;return i/(this._canvas.width*this._canvas.height)*100}finish(t,s){if(!this.done&&this.percent>this.config.percentToFinish&&(this.done=!0,this._canvas.style.pointerEvents="none",this.config.onComplete?.(),this.playCompleteEffect(),t&&s)){try{this._canvas.releasePointerCapture(t.pointerId)}catch{}this._canvas.removeEventListener("pointermove",s)}}playCompleteEffect(){if(this.destroyed||this.completing)return;this.completing=!0;const t=350,s="ease-out";this._canvas.style.transition=`opacity ${t}ms ${s}`,this._canvas.style.opacity||(this._canvas.style.opacity="1"),requestAnimationFrame(()=>{this._canvas.style.opacity="0",window.setTimeout(()=>{this.destroyed||this.clear()},t)})}clear(){this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr)}}function w(o="scratch-reveal"){if(typeof window>"u"||!("customElements"in window)||customElements.get(o))return;function t(i,e,h,n){if(!i)return n;const r=i.trim();if(!r)return n;const a=Number.parseFloat(r.endsWith("%")?r.slice(0,-1):r.endsWith("px")?r.slice(0,-2):r);if(!Number.isFinite(a))return n;if(r.endsWith("px"))return Math.max(0,a);const c=Math.min(e,h);return Math.max(0,c*a/100)}class s extends HTMLElement{instance;container;styleEl=null;rebuildScheduled=!1;resizeObserver;lastErrorMessage=null;static get observedAttributes(){return["width","height","complete-percent","brush-src","brush-size","mask-src","background-src","show-status"]}constructor(){super();const e=this.attachShadow({mode:"open"});y(e)&&S?e.adoptedStyleSheets=[S]:(this.styleEl=document.createElement("style"),this.styleEl.textContent=m,e.append(this.styleEl)),this.container=document.createElement("div"),this.container.className="sr",e.append(this.container)}connectedCallback(){this.scheduleRebuild()}disconnectedCallback(){this.instance?.destroy(),this.instance=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0}attributeChangedCallback(e,h,n){if(h!==n){if(e==="brush-size"&&this.instance){const{width:r,height:a}=this.resolveSize(),c=t(this.getAttribute("brush-size"),r,a,d.brushSize);this.instance.setBrushSize(c);return}if((e==="width"||e==="height")&&this.instance){const r=this.resolveSize();this.syncContainerSize(r),this.instance.resize(r.width,r.height);const a=t(this.getAttribute("brush-size"),r.width,r.height,d.brushSize);this.instance.setBrushSize(a),this.updateResizeObserver(r);return}this.scheduleRebuild()}}scheduleRebuild(){this.rebuildScheduled||(this.rebuildScheduled=!0,queueMicrotask(()=>{this.rebuildScheduled=!1,this.isConnected&&this.rebuild()}))}rebuild(){const e=this.resolveSize(),h=this.resolvePercentToFinish(),{brushSrc:n,imageMaskSrc:r,imageBackgroundSrc:a}=this.resolveSources(),c=t(this.getAttribute("brush-size"),e.width,e.height,d.brushSize),l=[];if(n||l.push("brush-src"),r||l.push("mask-src"),a||l.push("background-src"),this.syncContainerSize(e),l.length){this.renderWaiting(l),this.updateResizeObserver(e);return}this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,this.lastErrorMessage=null,this.instance=new z(this.container,{width:e.width,height:e.height,percentToFinish:h,brushSrc:n,brushSize:c,imageMaskSrc:r,imageBackgroundSrc:a,onProgress:g=>{this.dispatchEvent(new CustomEvent("progress",{detail:{percent:g},bubbles:!0,composed:!0}))},onComplete:()=>{this.dispatchEvent(new CustomEvent("complete",{detail:{percent:100},bubbles:!0,composed:!0}))}}),this.instance.init().catch(g=>{const v=g instanceof Error?g.message:"ScratchReveal: init failed";this.renderError(v)}),this.updateResizeObserver(e)}renderError(e){this.instance?.destroy(),this.instance=void 0,this.renderStatus(e,"error"),this.lastErrorMessage!==e&&(this.lastErrorMessage=e,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0,composed:!0})))}renderWaiting(e){const h=`ScratchReveal: waiting for required attribute(s): ${e.join(", ")}`;this.renderStatus(h,"waiting")}renderStatus(e,h){if(this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,!this.hasAttribute("show-status"))return;const n=document.createElement("div");n.className=`sr__status sr__status--${h}`,n.textContent=e,n.setAttribute("role",h==="error"?"alert":"status"),this.container.appendChild(n)}resolveSize(){const e=this.hasAttribute("width"),h=this.hasAttribute("height"),n=this.getBoundingClientRect(),r=Math.round(n.width),a=Math.round(n.height),c=Number(this.getAttribute("width")),l=Number(this.getAttribute("height")),g=e&&Number.isFinite(c)?c:r||d.width,v=h&&Number.isFinite(l)?l:a||d.height;return{hasWidthAttr:e,hasHeightAttr:h,width:g,height:v}}resolvePercentToFinish(){const e=Number(this.getAttribute("complete-percent"));return Number.isFinite(e)?e:d.percentToFinish}resolveSources(){return{brushSrc:(this.getAttribute("brush-src")??"").trim(),imageMaskSrc:(this.getAttribute("mask-src")??"").trim(),imageBackgroundSrc:(this.getAttribute("background-src")??"").trim()}}syncContainerSize(e){e.hasWidthAttr?this.container.style.width=`${e.width}px`:this.container.style.width="100%",e.hasHeightAttr?this.container.style.height=`${e.height}px`:this.container.style.height="100%"}updateResizeObserver(e){(!e.hasWidthAttr||!e.hasHeightAttr)&&"ResizeObserver"in window?(this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>{if(this.hasAttribute("width")&&this.hasAttribute("height")){this.resizeObserver?.disconnect(),this.resizeObserver=void 0;return}const n=this.getBoundingClientRect(),r=Math.round(n.width),a=Math.round(n.height);this.instance?.resize(r,a);const c=t(this.getAttribute("brush-size"),r,a,d.brushSize);this.instance?.setBrushSize(c)}),this.resizeObserver.observe(this)):(this.resizeObserver?.disconnect(),this.resizeObserver=void 0)}}customElements.define(o,s)}function k(o){w(),o.config.globalProperties.$scratchReveal=!0}u.installScratchReveal=k,u.registerScratchRevealElement=w,u.scratchRevealCssText=_,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})}));
61
+ `,z=f;function k(o){return"adoptedStyleSheets"in o}function x(o){if(typeof CSSStyleSheet>"u")return null;try{const t=new CSSStyleSheet;return t.replaceSync(o),t}catch{return null}}const y=x(f),g={width:300,height:300,brushSrc:"",imageMaskSrc:"",imageBackgroundSrc:"",brushSize:0,percentToFinish:60};class C{config;ctx;container;_canvas;dpr=1;brush;maskImage;backgroundImage;brushImage;backgroundEl;brushSize=0;percent=0;done=!1;completing=!1;destroyed=!1;lastProgressEmitMs=0;removeListeners;get canvas(){return this._canvas}constructor(t,s={}){if(this.config={...g,...s},this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("ScratchReveal: container not found");this._canvas=this.createCanvas(this.config.width,this.config.height),this.ctx=this._canvas.getContext("2d",{willReadFrequently:!0}),this.setCanvasScale(this.config.width,this.config.height),this.brush=new b(this.ctx,0,0),this.brushSize=this.config.brushSize,this.container.appendChild(this._canvas)}async init(){if(!this.config.brushSrc)throw new Error('ScratchReveal: "brushSrc" is required');if(!this.config.imageMaskSrc)throw new Error('ScratchReveal: "imageMaskSrc" is required');if(!this.config.imageBackgroundSrc)throw new Error('ScratchReveal: "imageBackgroundSrc" is required');const[t,s,i]=await Promise.all([m(this.config.brushSrc),m(this.config.imageMaskSrc),m(this.config.imageBackgroundSrc)]);return this.destroyed?this:(this.brushImage=t,this.maskImage=s,this.backgroundImage=i,this.drawMask(),this.setBackground(),this.bindEvents(),this)}destroy(){this.destroyed=!0,this.removeListeners?.()}getPercent(){return this.percent}createCanvas(t,s){const i=document.createElement("canvas");return i.className="sr__canvas",i.style.width="100%",i.style.height="100%",i}setCanvasScale(t,s){const i=Math.max(1,Math.min(window.devicePixelRatio||1,3));this.dpr=i,this._canvas.width=Math.round(t*this.dpr),this._canvas.height=Math.round(s*this.dpr),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${s}px`,this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0)}resize(t,s){this.destroyed||this.done||t<=0||s<=0||this._canvas.width===t*this.dpr&&this._canvas.height===s*this.dpr||(this.setCanvasScale(t,s),this.percent=0,this.ctx.globalCompositeOperation="source-over",this.drawMask())}setBrushSize(t){this.destroyed||!Number.isFinite(t)||t<0||(this.brushSize=t)}bindEvents(){const s=w((n,h)=>{this.percent=this.updatePercent();const a=performance.now();(!this.lastProgressEmitMs||a-this.lastProgressEmitMs>=120)&&(this.lastProgressEmitMs=a,this.config.onProgress?.(this.percent)),this.finish(n,h)}),i=w(n=>{(n.buttons&1)!==0&&(this.updatePosition(n),this.scratch(),s(n,i))}),e=n=>{try{this._canvas.releasePointerCapture(n.pointerId)}catch{}this._canvas.removeEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)},r=n=>{n.preventDefault(),this.updatePosition(n),this.scratch(),this._canvas.setPointerCapture(n.pointerId),this._canvas.addEventListener("pointermove",i),this.percent=this.updatePercent(),this.config.onProgress?.(this.percent),this.finish(n,i)};this._canvas.addEventListener("pointerdown",r),this._canvas.addEventListener("pointerup",e),this._canvas.addEventListener("pointercancel",e),this.removeListeners=()=>{this._canvas.removeEventListener("pointerdown",r),this._canvas.removeEventListener("pointerup",e),this._canvas.removeEventListener("pointercancel",e),this._canvas.removeEventListener("pointermove",i)}}updatePosition(t){const s=this._canvas.getBoundingClientRect(),i=s.width?this._canvas.width/s.width:1,e=s.height?this._canvas.height/s.height:1,r=(t.clientX-s.left)*i/this.dpr,n=(t.clientY-s.top)*e/this.dpr;this.brush.updateMousePosition(r,n)}drawMask(){this.maskImage&&(this.ctx.globalCompositeOperation="source-over",this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr),this.ctx.drawImage(this.maskImage,0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr))}setBackground(){if(this.destroyed||!this.backgroundImage||!this.container.contains(this._canvas))return;const t=this.backgroundEl??document.createElement("img");t.src=this.backgroundImage.src,t.className="sr__bg",t.isConnected||this.container.insertBefore(t,this._canvas),this.backgroundEl=t}scratch(){if(!this.brushImage)return;const t=this.brushSize>0?this.brushSize:0;this.ctx.globalCompositeOperation="destination-out",this.ctx.save(),this.brush.brush(this.brushImage,t),this.ctx.restore()}updatePercent(){const s=this.ctx.getImageData(0,0,this._canvas.width,this._canvas.height).data;let i=0;for(let e=3;e<s.length;e+=4)s[e]===0&&i++;return i/(this._canvas.width*this._canvas.height)*100}finish(t,s){if(!this.done&&this.percent>this.config.percentToFinish&&(this.done=!0,this._canvas.style.pointerEvents="none",this.config.onComplete?.(),this.playCompleteEffect(),t&&s)){try{this._canvas.releasePointerCapture(t.pointerId)}catch{}this._canvas.removeEventListener("pointermove",s)}}playCompleteEffect(){if(this.destroyed||this.completing)return;this.completing=!0;const t=350,s="ease-out";this._canvas.style.transition=`opacity ${t}ms ${s}`,this._canvas.style.opacity||(this._canvas.style.opacity="1"),requestAnimationFrame(()=>{this._canvas.style.opacity="0",window.setTimeout(()=>{this.destroyed||this.clear()},t)})}clear(){this.ctx.clearRect(0,0,this._canvas.width/this.dpr,this._canvas.height/this.dpr)}}function _(o="scratch-reveal"){if(typeof window>"u"||!("customElements"in window)||customElements.get(o))return;function t(i,e,r,n){if(!i)return n;const h=i.trim();if(!h)return n;const a=Number.parseFloat(h.endsWith("%")?h.slice(0,-1):h.endsWith("px")?h.slice(0,-2):h);if(!Number.isFinite(a))return n;if(h.endsWith("px"))return Math.max(0,a);const c=Math.min(e,r);return Math.max(0,c*a/100)}class s extends HTMLElement{instance;container;styleEl=null;rebuildScheduled=!1;rebuildToken=0;resizeObserver;lastErrorMessage=null;static get observedAttributes(){return["width","height","complete-percent","brush-src","brush-size","mask-src","background-src","show-status"]}constructor(){super();const e=this.attachShadow({mode:"open"});k(e)&&y?e.adoptedStyleSheets=[y]:(this.styleEl=document.createElement("style"),this.styleEl.textContent=f,e.append(this.styleEl)),this.container=document.createElement("div"),this.container.className="sr",e.append(this.container)}connectedCallback(){this.scheduleRebuild()}disconnectedCallback(){this.instance?.destroy(),this.instance=void 0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0}attributeChangedCallback(e,r,n){if(r!==n){if(e==="brush-size"&&this.instance){const{width:h,height:a}=this.resolveSize(),c=t(this.getAttribute("brush-size"),h,a,g.brushSize);this.instance.setBrushSize(c);return}if((e==="width"||e==="height")&&this.instance){const h=this.resolveSize();this.syncContainerSize(h),this.instance.resize(h.width,h.height);const a=t(this.getAttribute("brush-size"),h.width,h.height,g.brushSize);this.instance.setBrushSize(a),this.updateResizeObserver(h);return}this.scheduleRebuild()}}scheduleRebuild(){this.rebuildScheduled||(this.rebuildScheduled=!0,queueMicrotask(()=>{this.rebuildScheduled=!1,this.isConnected&&this.rebuild()}))}async rebuild(){const e=++this.rebuildToken,r=this.resolveSize(),n=this.resolvePercentToFinish(),{brushSrc:h,imageMaskSrc:a,imageBackgroundSrc:c}=this.resolveSources(),p=[];if(h||p.push("brush-src"),a||p.push("mask-src"),c||p.push("background-src"),p.length){this.syncContainerSize(r),this.renderWaiting(p),this.updateResizeObserver(r);return}let u=r;if(!r.hasWidthAttr&&!r.hasHeightAttr&&r.autoWidth===0&&r.autoHeight===0)try{const d=await m(a);if(e!==this.rebuildToken||!this.isConnected)return;const v=d.naturalWidth||d.width,E=d.naturalHeight||d.height;v>0&&E>0&&(u={...r,width:v,height:E})}catch{}this.syncContainerSize(u);const S=t(this.getAttribute("brush-size"),u.width,u.height,g.brushSize);this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,this.lastErrorMessage=null,this.instance=new C(this.container,{width:u.width,height:u.height,percentToFinish:n,brushSrc:h,brushSize:S,imageMaskSrc:a,imageBackgroundSrc:c,onProgress:d=>{this.dispatchEvent(new CustomEvent("progress",{detail:{percent:d},bubbles:!0,composed:!0}))},onComplete:()=>{this.dispatchEvent(new CustomEvent("complete",{detail:{percent:100},bubbles:!0,composed:!0}))}}),this.instance.init().catch(d=>{const v=d instanceof Error?d.message:"ScratchReveal: init failed";this.renderError(v)}),this.updateResizeObserver(u)}renderError(e){this.instance?.destroy(),this.instance=void 0,this.renderStatus(e,"error"),this.lastErrorMessage!==e&&(this.lastErrorMessage=e,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0,composed:!0})))}renderWaiting(e){const r=`ScratchReveal: waiting for required attribute(s): ${e.join(", ")}`;this.renderStatus(r,"waiting")}renderStatus(e,r){if(this.container.replaceChildren(),this.instance?.destroy(),this.instance=void 0,!this.hasAttribute("show-status"))return;const n=document.createElement("div");n.className=`sr__status sr__status--${r}`,n.textContent=e,n.setAttribute("role",r==="error"?"alert":"status"),this.container.appendChild(n)}resolveSize(){const e=this.hasAttribute("width"),r=this.hasAttribute("height"),n=this.getBoundingClientRect(),h=Math.round(n.width),a=Math.round(n.height),c=Number(this.getAttribute("width")),p=Number(this.getAttribute("height")),u=e&&Number.isFinite(c)?c:h||g.width,S=r&&Number.isFinite(p)?p:a||g.height;return{hasWidthAttr:e,hasHeightAttr:r,width:u,height:S,autoWidth:h,autoHeight:a}}resolvePercentToFinish(){const e=Number(this.getAttribute("complete-percent"));return Number.isFinite(e)?e:g.percentToFinish}resolveSources(){return{brushSrc:(this.getAttribute("brush-src")??"").trim(),imageMaskSrc:(this.getAttribute("mask-src")??"").trim(),imageBackgroundSrc:(this.getAttribute("background-src")??"").trim()}}syncContainerSize(e){e.hasWidthAttr?this.container.style.width=`${e.width}px`:this.container.style.width="100%",e.hasHeightAttr?this.container.style.height=`${e.height}px`:this.container.style.height="100%"}updateResizeObserver(e){(!e.hasWidthAttr||!e.hasHeightAttr)&&"ResizeObserver"in window?(this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>{if(this.hasAttribute("width")&&this.hasAttribute("height")){this.resizeObserver?.disconnect(),this.resizeObserver=void 0;return}const n=this.getBoundingClientRect(),h=Math.round(n.width),a=Math.round(n.height);this.instance?.resize(h,a);const c=t(this.getAttribute("brush-size"),h,a,g.brushSize);this.instance?.setBrushSize(c)}),this.resizeObserver.observe(this)):(this.resizeObserver?.disconnect(),this.resizeObserver=void 0)}}customElements.define(o,s)}function R(o){_(),o.config.globalProperties.$scratchReveal=!0}l.installScratchReveal=R,l.registerScratchRevealElement=_,l.scratchRevealCssText=z,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scratch-reveal",
3
- "version": "1.3.0-dev.0",
3
+ "version": "1.3.0-dev.2",
4
4
  "description": "Scratch & reveal Web Component: mask + background with brush-only reveal, Vue-friendly, shadow-styled.",
5
5
  "author": "ux-ui.pro",
6
6
  "license": "MIT",