@drgd/aura
Version:
Extract color palettes from any image. Works on both server and client.
2 lines • 2.35 kB
JavaScript
import{a as y,b as L,c as I,d as M,e as x,f as v}from"./chunk-VRJCZRLL.js";import{useState as D,useEffect as F}from"react";var $=2e3,k=1500*1500;function R(e,n,o){if(e<=o&&n<=o)return{width:e,height:n};let t=e/n;return t>1?{width:o,height:Math.round(o/t)}:{width:Math.round(o*t),height:o}}async function S(e,n={}){if(!e)throw new Error("[@drgd/aura] - Image URL is required");let o=n.paletteSize??6;if(o<1||o>12)throw new Error("[@drgd/aura] - Number of colors must be between 1 and 12");n.validateUrl!==!1&&await x(e);let t=await new Promise((r,l)=>{let c=new Image;c.crossOrigin="anonymous",c.onload=()=>r(c),c.onerror=C=>l(new Error(`[@drgd/aura] - Failed to load image: ${C.toString()}`)),c.src=e}),{width:a,height:g}=R(t.width,t.height,$),u=document.createElement("canvas"),d=u.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("[@drgd/aura] - Could not get canvas context");u.width=a,u.height=g,d.drawImage(t,0,0,a,g);let s=d.getImageData(0,0,u.width,u.height).data,m=new Map;for(let r=0;r<s.length;r+=4){let l=s[r],c=s[r+1],C=s[r+2];if(s[r+3]===0)continue;let E=`${l},${c},${C}`,A=m.get(E);A?A.count++:m.set(E,new y(l,c,C))}let h=Array.from(m.values()),b=h.reduce((r,l)=>r+l.count,0),i=Math.ceil(Math.sqrt(o)),w=M(h,i),p=I(w,o);return a*g>k&&console.warn(`[@drgd/aura] - Processing large image (${a}x${g}px). Consider using a smaller image for better performance.`),p.map(r=>({hex:L(r.r,r.g,r.b),weight:r.count/b})).sort((r,l)=>l.weight-r.weight)}function W(e,n={}){let[o,t]=D({colors:[],isLoading:!1,error:null}),{paletteSize:a=6,fallbackColors:g,onError:u}=n,d=g??v;return F(()=>{if(!e){t({colors:d.slice(0,a),isLoading:!1,error:null});return}let f=e;typeof window<"u"&&f.startsWith("/")&&!f.startsWith("//")&&(f=`${window.location.origin}${f}`);let s=!0,m=new AbortController;async function h(b){t(i=>({...i,isLoading:!0,error:null}));try{let i=setTimeout(()=>{if(s){m.abort();let p=new Error("[@drgd/aura] - Color extraction timed out");t({colors:d.slice(0,a),isLoading:!1,error:p}),n.onError?.(p)}},1e4),w=await S(b,{paletteSize:a});clearTimeout(i),s&&t({colors:w,isLoading:!1,error:null})}catch(i){if(!s)return;let w=i instanceof Error?i:new Error(String(i));t({colors:d.slice(0,a),isLoading:!1,error:w}),n.onError?.(w)}}return h(f),()=>{s=!1,m.abort()}},[e,a,u]),o}export{W as useAura};
//# sourceMappingURL=client.js.map