@micropasts/colour-palette 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ (function(C,T){typeof exports=="object"&&typeof module<"u"?T(exports):typeof define=="function"&&define.amd?define(["exports"],T):(C=typeof globalThis<"u"?globalThis:C||self,T(C.MicroPastsColourPalette={}))})(this,(function(C){"use strict";var T=Object.defineProperty,lt=Object.getOwnPropertyNames,ct=(t,e)=>function(){return t&&(e=(0,t[lt(t)[0]])(t=0)),e},ht=(t,e)=>{for(var r in e)T(t,r,{get:e[r],enumerable:!0})};function ut(){var t;if(k!==void 0)return k;try{const r=document.createElement("canvas").getContext("2d",{colorSpace:"display-p3"});k=!!r&&((t=r.getContextAttributes)==null?void 0:t.call(r).colorSpace)==="display-p3"}catch{k=!1}return k}function dt(t){return t==="display-p3"||t==="auto"}function W(t){return dt(t)&&ut()?"display-p3":"srgb"}function B(t,e,r,n){try{return n==="display-p3"?t.getImageData(0,0,e,r,{colorSpace:"display-p3"}):t.getImageData(0,0,e,r)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError"){const i=new Error('Image is tainted by cross-origin data. Add crossorigin="anonymous" to the <img> tag and ensure the server sends appropriate CORS headers.');throw i.cause=o,i}throw o}}function A(t,e,r,n){const o=W(r),i=document.createElement("canvas");i.width=t,i.height=e;const s=o==="display-p3"?i.getContext("2d",{colorSpace:"display-p3"}):i.getContext("2d");return n(s),{data:B(s,t,e,o).data,width:t,height:e,colorSpace:o}}function q(t,e,r,n){const o=W(n);return{data:B(t,e,r,o).data,width:e,height:r,colorSpace:o}}var k,gt=ct({"src/loaders/canvas-utils.ts"(){}}),mt={};ht(mt,{BrowserPixelLoader:()=>ft});var ft;function w(t){const e=t/255;return e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function y(t){const e=t<=.0031308?12.92*t:1.055*Math.pow(t,.4166666666666667)-.055;return Math.round(Math.max(0,Math.min(255,e*255)))}function z(t,e){const r=[[0,0,0],[0,0,0],[0,0,0]];for(let n=0;n<3;n++)for(let o=0;o<3;o++)r[n][o]=t[n][0]*e[0][o]+t[n][1]*e[1][o]+t[n][2]*e[2][o];return r}function P(t){const[e,r,n]=t[0],[o,i,s]=t[1],[a,l,h]=t[2],c=i*h-s*l,u=-(o*h-s*a),d=o*l-i*a,m=1/(e*c+r*u+n*d);return[[c*m,(n*l-r*h)*m,(r*s-n*i)*m],[u*m,(e*h-n*a)*m,(n*o-e*s)*m],[d*m,(r*a-e*l)*m,(e*i-r*o)*m]]}function I(t,e,r,n){return[t[0][0]*e+t[0][1]*r+t[0][2]*n,t[1][0]*e+t[1][1]*r+t[1][2]*n,t[2][0]*e+t[2][1]*r+t[2][2]*n]}var pt=[[.8189330101,.3618667424,-.1288597137],[.0329845436,.9293118715,.0361456387],[.0482003018,.2643662691,.633851707]],j=[[.4865709486,.2656676932,.1982172852],[.2289745641,.6917385218,.0792869141],[0,.0451133819,1.0439443689]],bt=[[.4123907993,.3575843394,.1804807884],[.2126390059,.7151686788,.0721923154],[.0193308187,.1191947798,.9505321522]],G=z(pt,j),wt=P(G),vt=P(bt),H=z(vt,j),xt=P(H),_t=[.2126,.7152,.0722];function yt(t,e,r){const n=.2104542553*t+.793617785*e-.0040720468*r,o=1.9779984951*t-2.428592205*e+.4505937099*r,i=.0259040371*t+.7827717662*e-.808675766*r,s=Math.sqrt(o*o+i*i);let a=Math.atan2(i,o)*(180/Math.PI);return a<0&&(a+=360),{l:n,c:s,h:a}}function Et(t,e,r){const[n,o,i]=I(G,w(t),w(e),w(r));return yt(Math.cbrt(n),Math.cbrt(o),Math.cbrt(i))}function V(t,e,r,n="srgb"){if(n==="display-p3")return Et(t,e,r);const o=w(t),i=w(e),s=w(r),a=.4122214708*o+.5363325363*i+.0514459929*s,l=.2119034982*o+.6806995451*i+.1073969566*s,h=.0883024619*o+.2817188376*i+.6299787005*s,c=Math.cbrt(a),u=Math.cbrt(l),d=Math.cbrt(h),g=.2104542553*c+.793617785*u-.0040720468*d,m=1.9779984951*c-2.428592205*u+.4505937099*d,f=.0259040371*c+.7827717662*u-.808675766*d,x=Math.sqrt(m*m+f*f);let E=Math.atan2(f,m)*(180/Math.PI);return E<0&&(E+=360),{l:g,c:x,h:E}}function Mt(t,e,r){const n=r*(Math.PI/180),o=e*Math.cos(n),i=e*Math.sin(n),s=t+.3963377774*o+.2158037573*i,a=t-.1055613458*o-.0638541728*i,l=t-.0894841775*o-1.291485548*i;return[s*s*s,a*a*a,l*l*l]}function Ct(t,e,r){const[n,o,i]=Mt(t,e,r),[s,a,l]=I(wt,n,o,i);return[y(s),y(a),y(l)]}function St(t,e,r,n="srgb"){if(n==="display-p3")return Ct(t,e,r);const o=r*(Math.PI/180),i=e*Math.cos(o),s=e*Math.sin(o),a=t+.3963377774*i+.2158037573*s,l=t-.1055613458*i-.0638541728*s,h=t-.0894841775*i-1.291485548*s,c=a*a*a,u=l*l*l,d=h*h*h,g=4.0767416621*c-3.3077115913*u+.2309699292*d,m=-1.2684380046*c+2.6097574011*u-.3413193965*d,f=-.0041960863*c-.7034186147*u+1.707614701*d;return[y(g),y(m),y(f)]}function Lt(t,e="srgb"){const r=new Array(t.length);for(let n=0;n<t.length;n++){const[o,i,s]=t[n],{l:a,c:l,h}=V(o,i,s,e);r[n]=[Math.round(a*255),Math.round(l/.4*255),Math.round(h/360*255)]}return r}function Tt(t,e="srgb"){return t.map(({color:[r,n,o],population:i})=>{const s=r/255,a=n/255*.4,l=o/255*360;return{color:St(s,a,l,e),population:i}})}function X(t,e,r){const[n,o,i]=I(H,w(t),w(e),w(r));return[y(n),y(o),y(i)]}function kt(t,e,r){const[n,o,i]=I(xt,w(t),w(e),w(r));return[y(n),y(o),y(i)]}var S=.001;function It(t,e,r){const[n,o,i]=I(H,w(t),w(e),w(r));return n<-S||n>1+S||o<-S||o>1+S||i<-S||i>1+S}function Ot(t,e,r,n="srgb"){const o=w(t),i=w(e),s=w(r),[a,l,h]=n==="display-p3"?j[1]:_t;return a*o+l*i+h*s}function Ft(t,e,r){const n=t/255,o=e/255,i=r/255,s=Math.max(n,o,i),a=Math.min(n,o,i),l=(s+a)/2;let h=0,c=0;if(s!==a){const u=s-a;c=l>.5?u/(2-s-a):u/(s+a),s===n?h=((o-i)/u+(o<i?6:0))/6:s===o?h=((i-n)/u+2)/6:h=((n-o)/u+4)/6}return{h:Math.round(h*360),s:Math.round(c*100),l:Math.round(l*100)}}function Y(t,e){const r=Math.max(t,e),n=Math.min(t,e);return(r+.05)/(n+.05)}var Rt=class{constructor(t,e,r,n,o,i="srgb"){this._r=t,this._g=e,this._b=r,this.gamut=i,this.population=n,this.proportion=o}get srgb(){return this._srgb||(this._srgb=this.gamut==="display-p3"?X(this._r,this._g,this._b):[this._r,this._g,this._b]),this._srgb}rgb(t="srgb"){if(t===this.gamut)return{r:this._r,g:this._g,b:this._b};const[e,r,n]=t==="display-p3"?kt(this._r,this._g,this._b):this.srgb;return{r:e,g:r,b:n}}hex(){const[t,e,r]=this.srgb,n=o=>o.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`}hsl(){if(!this._hsl){const[t,e,r]=this.srgb;this._hsl=Ft(t,e,r)}return this._hsl}oklch(){return this._oklch||(this._oklch=V(this._r,this._g,this._b,this.gamut)),this._oklch}css(t){if(t===void 0){if(this.gamut==="display-p3"){const e=r=>+(r/255).toFixed(4);return`color(display-p3 ${e(this._r)} ${e(this._g)} ${e(this._b)})`}t="rgb"}switch(t){case"hsl":{const{h:e,s:r,l:n}=this.hsl();return`hsl(${e}, ${r}%, ${n}%)`}case"oklch":{const{l:e,c:r,h:n}=this.oklch();return`oklch(${e.toFixed(3)} ${r.toFixed(3)} ${n.toFixed(1)})`}case"rgb":default:{const[e,r,n]=this.srgb;return`rgb(${e}, ${r}, ${n})`}}}array(){return[...this.srgb]}toString(){return this.hex()}get textColor(){return this.isDark?"#ffffff":"#000000"}get luminance(){return this._luminance===void 0&&(this._luminance=Ot(this._r,this._g,this._b,this.gamut)),this._luminance}get isDark(){return this.luminance<=.179}get isLight(){return!this.isDark}get contrast(){if(!this._contrast){const t=this.luminance,e=Y(t,1),r=Y(t,0),n=this.isDark?O(255,255,255,0,0):O(0,0,0,0,0);this._contrast={white:Math.round(e*100)/100,black:Math.round(r*100)/100,foreground:n}}return this._contrast}};function O(t,e,r,n,o=0,i="srgb"){return new Rt(t,e,r,n,o,i)}function F(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`region.${e} must be a finite number between 0 and 1 (received ${String(t)})`);if(t<0||t>1)throw new Error(`region.${e} must be between 0 and 1 (received ${t}). Region coordinates are fractions of the image size, not pixels.`);return t}function Z(t){if(t===null||typeof t!="object")throw new Error("region must be an object of the form { x, y, width, height } with values between 0 and 1");const e=F(t.x,"x"),r=F(t.y,"y"),n=F(t.width,"width"),o=F(t.height,"height");if(n<=0||o<=0)throw new Error(`region.width and region.height must be greater than 0 (received ${n} and ${o})`);const i=Math.min(n,1-e),s=Math.min(o,1-r);if(i<=0||s<=0)throw new Error(`region is outside the image: x=${e}, y=${r} leaves no area to sample`);return{x:e,y:r,width:i,height:s}}function Ut(t,e,r){const{x:n,y:o,width:i,height:s}=Z(t),a=Math.min(Math.max(Math.round(n*e),0),Math.max(e-1,0)),l=Math.min(Math.max(Math.round(o*r),0),Math.max(r-1,0)),h=Math.min(Math.max(Math.round(i*e),1),e-a),c=Math.min(Math.max(Math.round(s*r),1),r-l);return{left:a,top:l,width:h,height:c}}function $t(t,e){return t instanceof Uint8ClampedArray?new Uint8ClampedArray(e):new Uint8Array(e)}function At(t,e){if(!e)return t;const{width:r,height:n}=t;if(!r||!n)return t;const o=Ut(e,r,n);if(o.left===0&&o.top===0&&o.width===r&&o.height===n)return t;const i=o.width*4,s=$t(t.data,i*o.height);for(let a=0;a<o.height;a++){const l=((o.top+a)*r+o.left)*4;s.set(t.data.subarray(l,l+i),a*i)}return{data:s,width:o.width,height:o.height,colorSpace:t.colorSpace}}function Pt(t){let{colorCount:e,quality:r}=t;if(typeof e>"u"||!Number.isInteger(e))e=10;else{if(e===1)throw new Error("colorCount should be between 2 and 20. To get one color, call getColor() instead of getPalette()");e=Math.max(e,2),e=Math.min(e,20)}(typeof r>"u"||!Number.isInteger(r)||r<1)&&(r=10);const n=t.ignoreWhite!==void 0?!!t.ignoreWhite:!0,o=typeof t.whiteThreshold=="number"?t.whiteThreshold:250,i=typeof t.alphaThreshold=="number"?t.alphaThreshold:125,s=typeof t.minSaturation=="number"?Math.max(0,Math.min(1,t.minSaturation)):0,a=t.colorSpace??"oklch",l=t.gamut??"srgb",h=t.region!==void 0?Z(t.region):void 0;return{colorCount:e,quality:r,ignoreWhite:n,whiteThreshold:o,alphaThreshold:i,minSaturation:s,colorSpace:a,gamut:l,region:h}}function jt(t,e,r){return r==="srgb"||e!=="display-p3"?"srgb":r==="auto"?t.some(([n,o,i])=>It(n,o,i))?"display-p3":"srgb":"display-p3"}function N(t,e,r,n){const{ignoreWhite:o=!0,whiteThreshold:i=250,alphaThreshold:s=125,minSaturation:a=0}=n,l=[];for(let h=0;h<e;h+=r){const c=h*4,u=t[c],d=t[c+1],g=t[c+2],m=t[c+3];if(!(m!==void 0&&m<s)&&!(o&&u>i&&d>i&&g>i)){if(a>0){const f=Math.max(u,d,g);if(f===0||(f-Math.min(u,d,g))/f<a)continue}l.push([u,d,g])}}return l}function Ht(t,e,r){let n=0,o=0,i=0,s=0;for(let a=0;a<e;a+=r){const l=a*4;n+=t[l],o+=t[l+1],i+=t[l+2],s++}return s===0?null:[Math.round(n/s),Math.round(o/s),Math.round(i/s)]}function Nt(t,e,r,n,o,i="srgb"){const s=e*r,a={ignoreWhite:n.ignoreWhite,whiteThreshold:n.whiteThreshold,alphaThreshold:n.alphaThreshold,minSaturation:n.minSaturation};let l=N(t,s,n.quality,a);l.length===0&&(l=N(t,s,n.quality,{...a,ignoreWhite:!1})),l.length===0&&(l=N(t,s,n.quality,{...a,ignoreWhite:!1,alphaThreshold:0}));const h=i,c=jt(l,h,n.gamut),u=p=>h===c?p:X(p[0],p[1],p[2]);let d;const g=new Set,m=[];for(const p of l){const v=p.join(",");if(!g.has(v)&&(g.add(v),m.push(p),m.length>n.colorCount))break}if(m.length<=n.colorCount){const p=new Map;for(const v of l){const b=v.join(",");p.set(b,(p.get(b)||0)+1)}d=m.map(v=>({color:v,population:p.get(v.join(","))}))}else if(n.colorSpace==="oklch"){const p=Lt(l,h);d=Tt(o.quantize(p,n.colorCount),h)}else d=o.quantize(l,n.colorCount);if(d.length>0){const p=d.reduce((v,b)=>v+b.population,0);return d.map(({color:v,population:b})=>{const[U,$,ue]=u(v);return O(U,$,ue,b,p>0?b/p:0,c)})}const f=Ht(t,s,n.quality);if(!f)return null;const[x,E,_]=u(f);return[O(x,E,_,1,1,c)]}var R=5,M=8-R,Dt=1e3,Wt=.75,Bt=1<<3*R;function L(t,e,r){return(t<<2*R)+(e<<R)+r}var qt=class at{constructor(e,r,n,o,i,s,a){this.r1=e,this.r2=r,this.g1=n,this.g2=o,this.b1=i,this.b2=s,this.histo=a}volume(e=!1){return(this._volume===void 0||e)&&(this._volume=(this.r2-this.r1+1)*(this.g2-this.g1+1)*(this.b2-this.b1+1)),this._volume}count(e=!1){if(this._count===void 0||e){let r=0;for(let n=this.r1;n<=this.r2;n++)for(let o=this.g1;o<=this.g2;o++)for(let i=this.b1;i<=this.b2;i++)r+=this.histo[L(n,o,i)]||0;this._count=r}return this._count}copy(){return new at(this.r1,this.r2,this.g1,this.g2,this.b1,this.b2,this.histo)}avg(e=!1){if(this._avg===void 0||e){const r=1<<M;if(this.r1===this.r2&&this.g1===this.g2&&this.b1===this.b2)this._avg=[this.r1<<M,this.g1<<M,this.b1<<M];else{let n=0,o=0,i=0,s=0;for(let a=this.r1;a<=this.r2;a++)for(let l=this.g1;l<=this.g2;l++)for(let h=this.b1;h<=this.b2;h++){const c=this.histo[L(a,l,h)]||0;n+=c,o+=c*(a+.5)*r,i+=c*(l+.5)*r,s+=c*(h+.5)*r}n?this._avg=[~~(o/n),~~(i/n),~~(s/n)]:this._avg=[~~(r*(this.r1+this.r2+1)/2),~~(r*(this.g1+this.g2+1)/2),~~(r*(this.b1+this.b2+1)/2)]}}return this._avg}},Q=class{constructor(t){this.comparator=t,this.contents=[],this.sorted=!1}sort(){this.contents.sort(this.comparator),this.sorted=!0}push(t){this.contents.push(t),this.sorted=!1}peek(t){return this.sorted||this.sort(),this.contents[t??this.contents.length-1]}pop(){return this.sorted||this.sort(),this.contents.pop()}size(){return this.contents.length}map(t){return this.contents.map(t)}};function zt(t){const e=new Uint32Array(Bt);for(const r of t){const n=r[0]>>M,o=r[1]>>M,i=r[2]>>M;e[L(n,o,i)]++}return e}function Gt(t,e){let r=1e6,n=0,o=1e6,i=0,s=1e6,a=0;for(const l of t){const h=l[0]>>M,c=l[1]>>M,u=l[2]>>M;h<r?r=h:h>n&&(n=h),c<o?o=c:c>i&&(i=c),u<s?s=u:u>a&&(a=u)}return new qt(r,n,o,i,s,a,e)}function Vt(t,e){if(!e.count())return;if(e.count()===1)return[e.copy(),null];const r=e.r2-e.r1+1,n=e.g2-e.g1+1,o=e.b2-e.b1+1,i=Math.max(r,n,o);let s=0;const a=[],l=[];if(i===r)for(let c=e.r1;c<=e.r2;c++){let u=0;for(let d=e.g1;d<=e.g2;d++)for(let g=e.b1;g<=e.b2;g++)u+=t[L(c,d,g)]||0;s+=u,a[c]=s}else if(i===n)for(let c=e.g1;c<=e.g2;c++){let u=0;for(let d=e.r1;d<=e.r2;d++)for(let g=e.b1;g<=e.b2;g++)u+=t[L(d,c,g)]||0;s+=u,a[c]=s}else for(let c=e.b1;c<=e.b2;c++){let u=0;for(let d=e.r1;d<=e.r2;d++)for(let g=e.g1;g<=e.g2;g++)u+=t[L(d,g,c)]||0;s+=u,a[c]=s}a.forEach((c,u)=>{l[u]=s-c});function h(c){const u=c+"1",d=c+"2";for(let g=e[u];g<=e[d];g++)if(a[g]>s/2){const m=e.copy(),f=e.copy(),x=g-e[u],E=e[d]-g;let _;for(x<=E?_=Math.min(e[d]-1,~~(g+E/2)):_=Math.max(e[u],~~(g-1-x/2));!a[_];)_++;let p=l[_];for(;!p&&a[_-1];)p=l[--_];return m[d]=_,f[u]=m[d]+1,[m,f]}}return h(i===r?"r":i===n?"g":"b")}function J(t,e,r){let n=t.size(),o=0;for(;o<Dt;){if(n>=e)return;o++;const i=t.pop();if(!i.count()){t.push(i);continue}const s=Vt(r,i);if(!s||!s[0])return;t.push(s[0]),s[1]&&(t.push(s[1]),n++)}}function Xt(t,e){if(!t.length||e<2||e>256)return[];const r=zt(t),n=Gt(t,r),o=new Q((a,l)=>a.count()-l.count());o.push(n),J(o,Wt*e,r);const i=new Q((a,l)=>a.count()*a.volume()-l.count()*l.volume());for(;o.size();)i.push(o.pop());J(i,e,r);const s=[];for(;i.size();){const a=i.pop();s.push({color:a.avg(),population:a.count()})}return s}var Yt=class{async init(){}quantize(t,e){return Xt(t,e)}};gt();var Zt=new Yt;function Qt(t,e){const r=K(t,{colorCount:5,...e});return r?r[0]:null}function K(t,e){const r=Pt(e??{}),n=(e==null?void 0:e.quantizer)??Zt,o=At(Jt(t,r.gamut),r.region);return Nt(o.data,o.width,o.height,r,n,o.colorSpace??"srgb")}function Jt(t,e){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return Kt(t,e);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)return q(t.getContext("2d"),t.width,t.height,e);if(typeof ImageData<"u"&&t instanceof ImageData)return{data:t.data,width:t.width,height:t.height,colorSpace:t.colorSpace??"srgb"};if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)return te(t,e);if(typeof ImageBitmap<"u"&&t instanceof ImageBitmap)return A(t.width,t.height,e,r=>r.drawImage(t,0,0));if(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){const r=t.getContext("2d");if(!r)throw new Error("Could not get 2D context from OffscreenCanvas.");return q(r,t.width,t.height,e)}throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}function Kt(t,e){if(!t.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColorSync/getPaletteSync.');if(!t.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");return A(t.naturalWidth,t.naturalHeight,e,r=>r.drawImage(t,0,0,t.naturalWidth,t.naturalHeight))}function te(t,e){if(t.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColorSync/getPaletteSync.');const r=t.videoWidth,n=t.videoHeight;if(!r||!n)throw new Error("Video has no dimensions. It may not have loaded successfully.");return A(r,n,e,o=>o.drawImage(t,0,0,r,n))}function tt(t,e=0){const{r,g:n,b:o}=t.rgb(),{h:i,s,l:a}=t.hsl(),l=Math.round(r),h=Math.round(n),c=Math.round(o),u=t.hex().toUpperCase(),d=`rgb(${l}, ${h}, ${c})`,g=`hsl(${Math.round(i)}, ${Math.round(s)}%, ${Math.round(a)}%)`,m=!!t.isDark;return{index:e,hex:u,rgb:d,hsl:g,values:{hex:u,rgb:d,hsl:g},isDark:m,textClass:m?"text-white":"text-slate-900"}}function et(t,{colourCount:e=8,quality:r=10,colorSpace:n="oklch"}={}){if(!t)throw new Error("No image or canvas element provided for colour extraction.");const o=Math.max(2,Math.min(20,Number(e)||8)),i=Qt(t,{quality:r,colorSpace:n}),s=K(t,{colorCount:o,quality:r,colorSpace:n});if(!i)throw new Error("Could not extract colours. Ensure the image is loaded and allows CORS.");return{dominant:tt(i,0),palette:(Array.isArray(s)?s:[]).map((a,l)=>tt(a,l+1))}}const ee=new Set(["http:","https:","blob:"]),re=new Set(["image/jpeg","image/png","image/webp","image/gif","image/avif"]),ne=15*1024*1024;function rt(t,{allowDataImage:e=!1}={}){if(typeof t!="string")throw new Error("Image URL must be a string.");const r=t.trim();if(!r)throw new Error("Image URL cannot be empty.");if(e&&/^data:image\/(png|jpe?g|webp|gif|avif);base64,[a-z0-9+/=]+$/i.test(r))return r;let n;try{n=new URL(r,window.location.origin)}catch{throw new Error("Invalid image URL.")}if(!ee.has(n.protocol))throw new Error(`Unsupported URL protocol: ${n.protocol}`);return n.href}function oe(t){return t.length<12?!1:t[0]===255&&t[1]===216&&t[2]===255||t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71||t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56||t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80||t[4]===102&&t[5]===116&&t[6]===121&&t[7]===112}async function ie(t,{maxBytes:e=ne}={}){if(!(t instanceof File))throw new Error("Invalid file input.");if(!re.has(t.type))throw new Error("Unsupported image format. Please select a JPEG, PNG, WebP, GIF, or AVIF file.");if(t.size<=0||t.size>e){const o=Math.round(e/1048576);throw new Error(`Image file must be under ${o} MB.`)}const r=await t.slice(0,16).arrayBuffer(),n=new Uint8Array(r);if(!oe(n))throw new Error("File contents do not match a valid raster image signature.");return t}function nt(t,e=8){const r=Number.parseInt(t,10);return Number.isNaN(r)?e:Math.max(2,Math.min(20,r))}function se({showImageSelect:t=!0,showColourCount:e=!0,showThemeSwitcher:r=!0,colourCounts:n,colourCount:o,colourFormat:i,onFile:s,onCount:a,onFormat:l,onTheme:h}){const c=document.createElement("div"),u=t||e,d=n.map(b=>`<option value="${b}" ${b===o?"selected":""}>${b} colours</option>`).join("");c.className="flex flex-wrap items-center justify-between gap-2 pb-3 border-b border-slate-200 dark:border-slate-800",c.innerHTML=`
2
+ <div class="flex items-center gap-2 ${u?"":"hidden"}">
3
+ <label class="${t?"inline-flex":"hidden"} cursor-pointer items-center px-3 py-1.5 rounded-lg text-xs font-medium bg-indigo-600 text-white hover:bg-indigo-500">
4
+ <span>Select image</span>
5
+ <input type="file" accept="image/*" class="mp-file hidden" />
6
+ </label>
7
+ <select aria-label="Colour count" class="${e?"":"hidden"} mp-count rounded-lg border border-slate-300 dark:border-slate-700 bg-transparent px-2 py-1.5 text-xs">
8
+ ${d}
9
+ </select>
10
+ </div>
11
+ <div class="flex items-center gap-2 ml-auto">
12
+ <select aria-label="Colour format" class="mp-format rounded-lg border border-slate-300 dark:border-slate-700 bg-transparent px-2 py-1.5 text-xs">
13
+ <option value="hex" ${i==="hex"?"selected":""}>HEX</option>
14
+ <option value="rgb" ${i==="rgb"?"selected":""}>RGB</option>
15
+ <option value="hsl" ${i==="hsl"?"selected":""}>HSL</option>
16
+ </select>
17
+ <button type="button" class="${r?"":"hidden"} mp-theme rounded-lg border border-slate-300 dark:border-slate-700 px-2.5 py-1.5 text-xs hover:bg-slate-100 dark:hover:bg-slate-800">
18
+ Theme
19
+ </button>
20
+ </div>
21
+ `;const g=c.querySelector(".mp-file"),m=c.querySelector(".mp-count"),f=c.querySelector(".mp-format"),x=c.querySelector(".mp-theme"),E=b=>{var $;const U=($=b.target.files)==null?void 0:$[0];U&&s(U)},_=b=>a(Number(b.target.value)),p=b=>l(b.target.value),v=()=>h();return g==null||g.addEventListener("change",E),m==null||m.addEventListener("change",_),f==null||f.addEventListener("change",p),x==null||x.addEventListener("click",v),{el:c,setCount:b=>{m&&(m.value=String(b))},setFormat:b=>{f&&(f.value=b)},destroy:()=>{g==null||g.removeEventListener("change",E),m==null||m.removeEventListener("change",_),f==null||f.removeEventListener("change",p),x==null||x.removeEventListener("click",v)}}}async function ot(t){var e;try{await((e=navigator.clipboard)==null?void 0:e.writeText(t))}catch{}}function it(t,e,r){const n=t.values[e],o=document.createElement("button");return o.type="button",o.style.backgroundColor=t.rgb,o.className=`group relative flex flex-col justify-between min-h-16 p-2.5 rounded-lg border border-black/10 text-left transition-transform active:scale-95 ${t.textClass}`,o.title=`Click to copy ${n}`,o.innerHTML=`
22
+ <span class="font-mono text-xs font-semibold truncate">${n}</span>
23
+ <span class="font-mono text-[10px] opacity-75 truncate">${e==="hex"?t.rgb:t.hex}</span>
24
+ <span class="mp-badge hidden group-hover:inline-block absolute top-1.5 right-1.5 text-[10px] px-1.5 py-0.5 rounded bg-black/30 text-white">Copy</span>
25
+ `,o.addEventListener("click",async()=>{await ot(n);const i=o.querySelector(".mp-badge");i&&(i.textContent="Copied",i.classList.remove("hidden"),window.setTimeout(()=>{i.textContent="Copy",i.classList.add("hidden")},1100)),r==null||r(n,t)}),o}function ae({onCopy:t}){const e=document.createElement("div");e.className="space-y-3",e.innerHTML=`
26
+ <div>
27
+ <div class="text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-1">Dominant</div>
28
+ <div class="mp-dominant"></div>
29
+ </div>
30
+ <div>
31
+ <div class="flex items-center justify-between mb-1">
32
+ <span class="text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Palette</span>
33
+ <button type="button" class="mp-copy-all text-[11px] font-medium text-indigo-600 dark:text-indigo-400 hover:underline">
34
+ Copy all strings
35
+ </button>
36
+ </div>
37
+ <div class="mp-grid grid grid-cols-2 sm:grid-cols-4 gap-2"></div>
38
+ </div>
39
+ `;const r=e.querySelector(".mp-dominant"),n=e.querySelector(".mp-grid"),o=e.querySelector(".mp-copy-all");let i=null,s="hex";const a=async()=>{if(!i)return;const h=i.palette.map(c=>c.values[s]).join(", ");await ot(h),o.textContent="Copied!",window.setTimeout(()=>{o.textContent="Copy all strings"},1200),t==null||t(h,i.palette)};o.addEventListener("click",a);function l(h,c="hex"){i=h,s=c,r.innerHTML="",r.appendChild(it(h.dominant,c,t)),n.innerHTML="",h.palette.forEach(u=>{n.appendChild(it(u,c,t))})}return{el:e,render:l,destroy:()=>{o.removeEventListener("click",a)}}}const D=new Set(["hex","rgb","hsl"]),st=15*1024*1024,le={imageUrl:"",image:null,colourCount:8,colourCounts:[5,8,12],colourFormat:"hex",theme:"dark",showInput:null,showImageSelect:!0,showColourCount:!0,showThemeSwitcher:!0,maxFileSize:st,proxyRoutes:null,proxyUrl:"",onExtract:null,onCopy:null,onError:null};function ce(t,e){const n=(Array.isArray(t)?t:[5,8,12]).map(o=>Number.parseInt(o,10)).filter(o=>!Number.isNaN(o)&&o>=2&&o<=20);return n.includes(e)||n.push(e),[...new Set(n)].sort((o,i)=>o-i)}class he{constructor(e,r={}){if(this.container=typeof e=="string"?document.querySelector(e):e,!this.container)throw new Error("ColourPalette target element not found.");const n={...le,...r};typeof n.showInput=="boolean"&&!("showImageSelect"in r)&&(n.showImageSelect=n.showInput),n.colourCount=nt(n.colourCount,8),n.colourCounts=ce(n.colourCounts,n.colourCount),n.colourFormat=D.has(n.colourFormat)?n.colourFormat:"hex",n.maxFileSize=typeof n.maxFileSize=="number"&&n.maxFileSize>0?n.maxFileSize:st,this.options=n,this.result=null,this._objectUrl=null,this._build(),this.setTheme(this.options.theme),this.options.image?this.setImageElement(this.options.image):this.options.imageUrl&&this.loadImage(this.options.imageUrl)}resolveUrl(e){const{proxyRoutes:r,proxyUrl:n}=this.options;if(typeof r=="function"){const o=r(e);if(o)return o}else if(r&&typeof r=="object"){for(const[o,i]of Object.entries(r))if(typeof e=="string"&&e.startsWith(o))return String(i)+e.slice(o.length)}return n?`${n}${encodeURIComponent(e)}`:e}loadImage(e){try{const r=this.resolveUrl(e),n=rt(r,{allowDataImage:!0});this._revokeObjectUrl(),this.imgEl.crossOrigin="anonymous",this.imgEl.src=n}catch(r){this._fail(r)}}setImageElement(e){try{if(e instanceof HTMLCanvasElement){this._revokeObjectUrl(),this.imgEl.removeAttribute("crossorigin"),this.imgEl.src=e.toDataURL("image/png");return}if(e instanceof HTMLImageElement){const r=e.currentSrc||e.src,n=rt(r,{allowDataImage:!0});this._revokeObjectUrl(),this.imgEl.crossOrigin="anonymous",this.imgEl.src=n;return}throw new Error("Expected an HTMLImageElement or HTMLCanvasElement.")}catch(r){this._fail(r)}}setColourCount(e){this.options.colourCount=nt(e,this.options.colourCount),this.toolbar.setCount(this.options.colourCount),this._runExtraction()}setFormat(e){D.has(e)&&(this.options.colourFormat=e,this.toolbar.setFormat(e),this.result&&this.swatches.render(this.result,e))}setTheme(e){this.options.theme=e==="light"?"light":"dark",this.root.classList.toggle("dark",this.options.theme==="dark")}toggleTheme(){this.setTheme(this.options.theme==="dark"?"light":"dark")}getColours(e=this.options.colourFormat){const r=D.has(e)?e:this.options.colourFormat;return this.result?this.result.palette.map(n=>n.values[r]):[]}_build(){this.root=document.createElement("div"),this.root.className="mp-colour-palette rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100 p-4 space-y-4 font-sans",this.toolbar=se({showImageSelect:this.options.showImageSelect,showColourCount:this.options.showColourCount,showThemeSwitcher:this.options.showThemeSwitcher,colourCounts:this.options.colourCounts,colourCount:this.options.colourCount,colourFormat:this.options.colourFormat,onFile:e=>this._loadFile(e),onCount:e=>this.setColourCount(e),onFormat:e=>this.setFormat(e),onTheme:()=>this.toggleTheme()}),this.errorEl=document.createElement("div"),this.errorEl.className="hidden rounded-lg border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-xs text-rose-600 dark:text-rose-300",this.bodyEl=document.createElement("div"),this.bodyEl.className="hidden grid grid-cols-1 md:grid-cols-12 gap-4 items-start",this.bodyEl.innerHTML=`
40
+ <div class="md:col-span-4 rounded-lg overflow-hidden border border-slate-200 dark:border-slate-800 bg-slate-100 dark:bg-slate-950 flex items-center justify-center">
41
+ <img alt="Source artwork" class="mp-img max-h-56 w-auto object-contain" />
42
+ </div>
43
+ <div class="md:col-span-8 mp-swatches"></div>
44
+ `,this.imgEl=this.bodyEl.querySelector(".mp-img"),this.swatches=ae({onCopy:(e,r)=>{var n,o;return(o=(n=this.options).onCopy)==null?void 0:o.call(n,e,r)}}),this.bodyEl.querySelector(".mp-swatches").appendChild(this.swatches.el),this.onImgLoad=()=>this._runExtraction(),this.onImgError=()=>this._fail(new Error("Failed to load image (check URL, file, or CORS headers).")),this.imgEl.addEventListener("load",this.onImgLoad),this.imgEl.addEventListener("error",this.onImgError),this.root.append(this.toolbar.el,this.errorEl,this.bodyEl),this.container.innerHTML="",this.container.appendChild(this.root)}async _loadFile(e){try{await ie(e,{maxBytes:this.options.maxFileSize}),this._revokeObjectUrl(),this._objectUrl=URL.createObjectURL(e),this.imgEl.removeAttribute("crossorigin"),this.imgEl.src=this._objectUrl}catch(r){this._fail(r)}}_revokeObjectUrl(){this._objectUrl&&(URL.revokeObjectURL(this._objectUrl),this._objectUrl=null)}_runExtraction(){var e,r;if(!(!this.imgEl.complete||!this.imgEl.naturalWidth))try{this.errorEl.classList.add("hidden"),this.result=et(this.imgEl,{colourCount:this.options.colourCount}),this.bodyEl.classList.remove("hidden"),this.swatches.render(this.result,this.options.colourFormat),(r=(e=this.options).onExtract)==null||r.call(e,this.result)}catch(n){this._fail(n)}}_fail(e){var r,n;this.errorEl.textContent=(e==null?void 0:e.message)||"An unexpected error occurred.",this.errorEl.classList.remove("hidden"),(n=(r=this.options).onError)==null||n.call(r,e)}destroy(){var e,r;this._revokeObjectUrl(),this.imgEl.removeEventListener("load",this.onImgLoad),this.imgEl.removeEventListener("error",this.onImgError),(e=this.toolbar)==null||e.destroy(),(r=this.swatches)==null||r.destroy(),this.container.innerHTML="",this.result=null}}C.ColourPalette=he,C.extractColours=et,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@micropasts/colour-palette",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Lightweight, framework-agnostic image colour palette extractor built with ColorThief and Tailwind CSS v4.",
5
+ "type": "module",
6
+ "main": "./dist/colour-palette.umd.cjs",
7
+ "module": "./dist/colour-palette.js",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/colour-palette.js",
11
+ "require": "./dist/colour-palette.umd.cjs"
12
+ },
13
+ "./style.css": "./dist/colour-palette.css"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE.md"
19
+ ],
20
+ "scripts": {
21
+ "dev": "vite",
22
+ "build": "vite build",
23
+ "build:docs": "vite build --config vite.docs.config.js",
24
+ "preview": "vite preview",
25
+ "test": "vitest run"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/MicroPasts/colour-palette.git"
30
+ },
31
+ "homepage": "https://micropasts.github.io/colour-palette/",
32
+ "bugs": {
33
+ "url": "https://github.com/MicroPasts/colour-palette/issues"
34
+ },
35
+ "keywords": [
36
+ "colour-palette",
37
+ "color-palette",
38
+ "colorthief",
39
+ "micropasts",
40
+ "cultural-heritage",
41
+ "iiif",
42
+ "tailwindcss"
43
+ ],
44
+ "author": "Daniel Pett",
45
+ "license": "MPL-2.0",
46
+ "dependencies": {
47
+ "colorthief": "^3.5.0"
48
+ },
49
+ "devDependencies": {
50
+ "@tailwindcss/vite": "^4.3.5",
51
+ "tailwindcss": "^4.3.5",
52
+ "vite": "^6.3.0",
53
+ "vitest": "^5.1.2"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "allowScripts": {
59
+ "esbuild@0.25.12": true,
60
+ "fsevents@2.3.3": true
61
+ }
62
+ }