react-color-pikr
Version:
A modern, customizable React color picker component library with 8-digit HEX alpha support
23 lines (22 loc) • 17.9 kB
JavaScript
(function(S,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],m):(S=typeof globalThis<"u"?globalThis:S||self,m(S.ReactColorPikr={},S.React))})(this,function(S,m){"use strict";var Z={exports:{}},L={};/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ie;function pe(){if(ie)return L;ie=1;var r=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function o(c,i,a){var d=null;if(a!==void 0&&(d=""+a),i.key!==void 0&&(d=""+i.key),"key"in i){a={};for(var l in i)l!=="key"&&(a[l]=i[l])}else a=i;return i=a.ref,{$$typeof:r,type:c,key:d,ref:i!==void 0?i:null,props:a}}return L.Fragment=n,L.jsx=o,L.jsxs=o,L}var X={};/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ce;function be(){return ce||(ce=1,process.env.NODE_ENV!=="production"&&function(){function r(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case O:return"Fragment";case K:return"Profiler";case U:return"StrictMode";case z:return"Suspense";case V:return"SuspenseList";case q:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case j:return"Portal";case N:return(e.displayName||"Context")+".Provider";case y:return(e._context.displayName||"Context")+".Consumer";case W:var s=e.render;return e=e.displayName,e||(e=s.displayName||s.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case P:return s=e.displayName||null,s!==null?s:r(e.type)||"Memo";case F:s=e._payload,e=e._init;try{return r(e(s))}catch{}}return null}function n(e){return""+e}function o(e){try{n(e);var s=!1}catch{s=!0}if(s){s=console;var p=s.error,E=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return p.call(s,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",E),n(e)}}function c(e){if(e===O)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===F)return"<...>";try{var s=r(e);return s?"<"+s+">":"<...>"}catch{return"<...>"}}function i(){var e=B.A;return e===null?null:e.getOwner()}function a(){return Error("react-stack-top-frame")}function d(e){if(te.call(e,"key")){var s=Object.getOwnPropertyDescriptor(e,"key").get;if(s&&s.isReactWarning)return!1}return e.key!==void 0}function l(e,s){function p(){t||(t=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",s))}p.isReactWarning=!0,Object.defineProperty(e,"key",{get:p,configurable:!0})}function h(){var e=r(this.type);return u[e]||(u[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function x(e,s,p,E,C,_,oe,ae){return p=_.ref,e={$$typeof:I,type:e,key:s,props:_,_owner:C},(p!==void 0?p:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:h}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:oe}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:ae}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function w(e,s,p,E,C,_,oe,ae){var k=s.children;if(k!==void 0)if(E)if(J(k)){for(E=0;E<k.length;E++)T(k[E]);Object.freeze&&Object.freeze(k)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else T(k);if(te.call(s,"key")){k=r(e);var $=Object.keys(s).filter(function(Ee){return Ee!=="key"});E=0<$.length?"{key: someKey, "+$.join(": ..., ")+": ...}":"{key: someKey}",Y[k+E]||($=0<$.length?"{"+$.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
let props = %s;
<%s {...props} />
React keys must be passed directly to JSX without using spread:
let props = %s;
<%s key={someKey} {...props} />`,E,k,$,k),Y[k+E]=!0)}if(k=null,p!==void 0&&(o(p),k=""+p),d(s)&&(o(s.key),k=""+s.key),"key"in s){p={};for(var se in s)se!=="key"&&(p[se]=s[se])}else p=s;return k&&l(p,typeof e=="function"?e.displayName||e.name||"Unknown":e),x(e,k,_,C,i(),p,oe,ae)}function T(e){typeof e=="object"&&e!==null&&e.$$typeof===I&&e._store&&(e._store.validated=1)}var f=m,I=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),O=Symbol.for("react.fragment"),U=Symbol.for("react.strict_mode"),K=Symbol.for("react.profiler"),y=Symbol.for("react.consumer"),N=Symbol.for("react.context"),W=Symbol.for("react.forward_ref"),z=Symbol.for("react.suspense"),V=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),q=Symbol.for("react.activity"),ee=Symbol.for("react.client.reference"),B=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te=Object.prototype.hasOwnProperty,J=Array.isArray,G=console.createTask?console.createTask:function(){return null};f={react_stack_bottom_frame:function(e){return e()}};var t,u={},b=f.react_stack_bottom_frame.bind(f,a)(),R=G(c(a)),Y={};X.Fragment=O,X.jsx=function(e,s,p,E,C){var _=1e4>B.recentlyCreatedOwnerStacks++;return w(e,s,p,!1,E,C,_?Error("react-stack-top-frame"):b,_?G(c(e)):R)},X.jsxs=function(e,s,p,E,C){var _=1e4>B.recentlyCreatedOwnerStacks++;return w(e,s,p,!0,E,C,_?Error("react-stack-top-frame"):b,_?G(c(e)):R)}}()),X}var ue;function xe(){return ue||(ue=1,process.env.NODE_ENV==="production"?Z.exports=pe():Z.exports=be()),Z.exports}var g=xe();function le(r){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(r);if(n)return{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16),a:parseInt(n[4],16)/255};const o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(r);return o?{r:parseInt(o[1],16),g:parseInt(o[2],16),b:parseInt(o[3],16)}:null}function Q(r,n,o){const c=i=>{const a=Math.round(Math.max(0,Math.min(255,i))).toString(16);return a.length===1?"0"+a:a};return`#${c(r)}${c(n)}${c(o)}`}function fe(r,n,o,c){const i=l=>{const h=Math.round(Math.max(0,Math.min(255,l))).toString(16);return h.length===1?"0"+h:h},a=Math.round(Math.max(0,Math.min(1,c))*255).toString(16),d=a.length===1?"0"+a:a;return`#${i(r)}${i(n)}${i(o)}${d}`}function H(r,n,o){r/=255,n/=255,o/=255;const c=Math.max(r,n,o),i=Math.min(r,n,o),a=c-i;let d=0;const l=c===0?0:a/c,h=c;if(a!==0)switch(c){case r:d=((n-o)/a+(n<o?6:0))/6;break;case n:d=((o-r)/a+2)/6;break;case o:d=((r-n)/a+4)/6;break}return{h:Math.round(d*360),s:Math.round(l*100),v:Math.round(h*100)}}function A(r,n,o){r=r/360,n=n/100,o=o/100;const c=Math.floor(r*6),i=r*6-c,a=o*(1-n),d=o*(1-i*n),l=o*(1-(1-i)*n);let h,x,w;switch(c%6){case 0:h=o,x=l,w=a;break;case 1:h=d,x=o,w=a;break;case 2:h=a,x=o,w=l;break;case 3:h=a,x=d,w=o;break;case 4:h=l,x=a,w=o;break;case 5:h=o,x=a,w=d;break;default:h=x=w=0}return{r:Math.round(h*255),g:Math.round(x*255),b:Math.round(w*255)}}function de(r,n,o){r/=255,n/=255,o/=255;const c=Math.max(r,n,o),i=Math.min(r,n,o),a=c-i;let d=0,l=0;const h=(c+i)/2;if(a!==0)switch(l=h>.5?a/(2-c-i):a/(c+i),c){case r:d=((n-o)/a+(n<o?6:0))/6;break;case n:d=((o-r)/a+2)/6;break;case o:d=((r-n)/a+4)/6;break}return{h:Math.round(d*360),s:Math.round(l*100),l:Math.round(h*100)}}function me(r,n,o){r=r/360,n=n/100,o=o/100;const c=(l,h,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<1/6?l+(h-l)*6*x:x<1/2?h:x<2/3?l+(h-l)*(2/3-x)*6:l);let i,a,d;if(n===0)i=a=d=o;else{const l=o<.5?o*(1+n):o+n-o*n,h=2*o-l;i=c(h,l,r+1/3),a=c(h,l,r),d=c(h,l,r-1/3)}return{r:Math.round(i*255),g:Math.round(a*255),b:Math.round(d*255)}}function D(r){if(r.startsWith("#"))return le(r);const n=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);return n?{r:parseInt(n[1]),g:parseInt(n[2]),b:parseInt(n[3]),a:n[4]?parseFloat(n[4]):void 0}:null}function re(r){return r.a!==void 0?`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`:`rgb(${r.r}, ${r.g}, ${r.b})`}function ge(r){return(.299*r.r+.587*r.g+.114*r.b)/255>.5?"#000000":"#ffffff"}const ne={colorSwatch:{borderRadius:"4px",border:"2px solid #ffffff",cursor:"pointer",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.1)",transition:"transform 0.1s ease, box-shadow 0.1s ease",display:"flex",alignItems:"center",justifyContent:"center"},colorSwatchSelected:{transform:"scale(1.1)",boxShadow:"0 0 0 2px #007bff"},swatchCheckmark:{fontSize:"12px",fontWeight:"bold",userSelect:"none",pointerEvents:"none"}},he=({color:r,size:n=24,selected:o=!1,onClick:c,className:i=""})=>{const a=D(r),d=a?ge(a):"#000000";return g.jsx("div",{style:{...ne.colorSwatch,...o?ne.colorSwatchSelected:{},width:n,height:n,backgroundColor:r,cursor:c?"pointer":"default"},className:i,onClick:c,role:c?"button":void 0,tabIndex:c?0:void 0,onKeyDown:l=>{c&&(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),c())},children:o&&g.jsx("div",{style:{...ne.swatchCheckmark,color:d},children:"✓"})})},v={colorPicker:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif',background:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",padding:"16px",userSelect:"none"},colorPickerDisabled:{opacity:.6,pointerEvents:"none"},colorPreview:{marginBottom:"12px"},colorPreviewCurrent:{width:"100%",height:"40px",borderRadius:"6px",border:"1px solid #e0e0e0",background:"#ffffff",transition:"border-color 0.2s ease",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)",cursor:"pointer"},saturationArea:{position:"relative",marginBottom:"12px",borderRadius:"4px",cursor:"crosshair",overflow:"hidden"},saturationOverlay:{position:"absolute",top:0,left:0,right:0,bottom:0},saturationPointer:{position:"absolute",width:"14px",height:"14px",border:"2px solid #ffffff",borderRadius:"50%",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.8), 0 2px 4px rgba(0, 0, 0, 0.3)",transform:"translate(-50%, -50%)",pointerEvents:"none",cursor:"crosshair",transition:"box-shadow 0.1s ease"},hueSlider:{position:"relative",height:"12px",marginBottom:"12px",borderRadius:"6px",background:"linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)",cursor:"pointer"},huePointer:{position:"absolute",top:"-3px",width:"18px",height:"18px",border:"2px solid #ffffff",borderRadius:"50%",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.8), 0 2px 4px rgba(0, 0, 0, 0.3)",transform:"translateX(-50%)",pointerEvents:"none",cursor:"pointer",transition:"box-shadow 0.1s ease"},alphaSlider:{position:"relative",height:"12px",marginBottom:"12px",borderRadius:"6px",cursor:"pointer"},alphaBackground:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"#f0f0f0",borderRadius:"6px"},alphaOverlay:{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"6px"},alphaPointer:{position:"absolute",top:"-3px",width:"18px",height:"18px",border:"2px solid #ffffff",borderRadius:"50%",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.8), 0 2px 4px rgba(0, 0, 0, 0.3)",transform:"translateX(-50%)",pointerEvents:"none",cursor:"pointer",transition:"box-shadow 0.1s ease"},formatToggle:{display:"flex",gap:"4px",marginBottom:"12px"},formatButton:{padding:"6px 12px",border:"1px solid #e0e0e0",borderRadius:"4px",background:"#ffffff",color:"#666666",fontSize:"12px",fontWeight:"500",cursor:"pointer",transition:"all 0.2s ease",fontFamily:"inherit"},formatButtonActive:{background:"#007bff",color:"#ffffff",borderColor:"#007bff"},formatButtonDisabled:{opacity:.6,cursor:"not-allowed"},colorInput:{width:"100%",padding:"8px 12px",border:"1px solid #e0e0e0",borderRadius:"4px",fontSize:"14px",fontFamily:"Monaco, Menlo, Ubuntu Mono, monospace",background:"#ffffff",color:"#2c3e50",marginBottom:"12px",transition:"border-color 0.2s ease",boxSizing:"border-box"},presets:{display:"flex",flexWrap:"wrap",gap:"6px",marginTop:"8px"}},M=(...r)=>Object.assign({},...r.filter(Boolean)),ve=["#FF0000","#FF8000","#FFFF00","#80FF00","#00FF00","#00FF80","#00FFFF","#0080FF","#0000FF","#8000FF","#FF00FF","#FF0080","#000000","#404040","#808080","#BFBFBF","#FFFFFF"],Re=({value:r="#FF0000",onChange:n,format:o="hex",onFormatChange:c,showAlpha:i=!1,showColorFormat:a=!0,showPresets:d=!0,presetColors:l=ve,width:h=280,height:x=200,className:w="",disabled:T=!1})=>{const[f,I]=m.useState(()=>{const t=typeof r=="string"?D(r)||{r:255,g:0,b:0}:r;return H(t.r,t.g,t.b)}),[j,O]=m.useState(null),[U,K]=m.useState(o),[y,N]=m.useState(()=>{if(typeof r=="string"){const t=D(r);return t?.a!==void 0?t.a:1}return typeof r=="object"&&r.a!==void 0?r.a:1}),W=m.useRef(null),z=m.useRef(null),V=m.useRef(null);m.useEffect(()=>{if(typeof r=="string"){const t=D(r);t&&(I(H(t.r,t.g,t.b)),t.a!==void 0&&N(t.a))}},[r]),m.useEffect(()=>{K(o)},[o]);const P=m.useCallback(()=>{const t=A(f.h,f.s,f.v);switch(U){case"hex":return i&&y<1?fe(t.r,t.g,t.b,y):Q(t.r,t.g,t.b);case"rgb":return i&&y<1?`rgba(${t.r}, ${t.g}, ${t.b}, ${y.toFixed(2)})`:`rgb(${t.r}, ${t.g}, ${t.b})`;case"hsv":return i&&y<1?`hsva(${f.h.toFixed(2)}, ${f.s.toFixed(2)}%, ${f.v.toFixed(2)}%, ${y.toFixed(2)})`:`hsv(${f.h.toFixed(2)}, ${f.s.toFixed(2)}%, ${f.v.toFixed(2)}%)`;case"hsl":{const u=de(t.r,t.g,t.b);return i&&y<1?`hsla(${u.h.toFixed(2)}, ${u.s.toFixed(2)}%, ${u.l.toFixed(2)}%, ${y.toFixed(2)})`:`hsl(${u.h.toFixed(2)}, ${u.s.toFixed(2)}%, ${u.l.toFixed(2)}%)`}default:return Q(t.r,t.g,t.b)}},[f,U,i,y]),F=m.useCallback(t=>{if(I(t),n){const u=P();n(u)}},[n,P]),q=m.useCallback(t=>{if(T)return;O("saturation");const u="touches"in t?t.touches[0].clientX:t.clientX,b="touches"in t?t.touches[0].clientY:t.clientY,R=W.current?.getBoundingClientRect();if(R){const Y=Math.max(0,Math.min(100,(u-R.left)/R.width*100)),e=Math.max(0,Math.min(100,(1-(b-R.top)/R.height)*100));F({...f,s:Y,v:e})}t.preventDefault()},[T,f,F]),ee=m.useCallback(t=>{if(T)return;O("hue");const u="touches"in t?t.touches[0].clientX:t.clientX,b=z.current?.getBoundingClientRect();if(b){const R=Math.max(0,Math.min(360,(u-b.left)/b.width*360));F({...f,h:R})}t.preventDefault()},[T,f,F]),B=m.useCallback(t=>{if(T||!i)return;O("alpha");const u="touches"in t?t.touches[0].clientX:t.clientX,b=V.current?.getBoundingClientRect();if(b){const R=Math.max(0,Math.min(1,(u-b.left)/b.width));N(R),n&&n(P())}t.preventDefault()},[T,i,n,P]),te=m.useCallback(t=>{if(T)return;const u=D(t);if(u){const b=H(u.r,u.g,u.b);I(b),u.a!==void 0&&N(u.a),n&&n(t)}},[T,n]);m.useEffect(()=>{const t=b=>{if(!j)return;const R="touches"in b?b.touches[0].clientX:b.clientX,Y="touches"in b?b.touches[0].clientY:b.clientY;if(j==="saturation"){const e=W.current?.getBoundingClientRect();if(e){const s=Math.max(0,Math.min(100,(R-e.left)/e.width*100)),p=Math.max(0,Math.min(100,(1-(Y-e.top)/e.height)*100));F({...f,s,v:p})}}else if(j==="hue"){const e=z.current?.getBoundingClientRect();if(e){const s=Math.max(0,Math.min(360,(R-e.left)/e.width*360));F({...f,h:s})}}else if(j==="alpha"){const e=V.current?.getBoundingClientRect();if(e){const s=Math.max(0,Math.min(1,(R-e.left)/e.width));N(s),n&&n(P())}}b.preventDefault()},u=()=>{O(null)};return j&&(document.addEventListener("mousemove",t),document.addEventListener("mouseup",u),document.addEventListener("touchmove",t),document.addEventListener("touchend",u)),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",u),document.removeEventListener("touchmove",t),document.removeEventListener("touchend",u)}},[j,f,F,n,P]);const J=A(f.h,f.s,f.v),G=`linear-gradient(to right, #fff, ${Q(A(f.h,100,100).r,A(f.h,100,100).g,A(f.h,100,100).b)})`;return g.jsxs("div",{style:M(v.colorPicker,T?v.colorPickerDisabled:void 0,{width:h,minHeight:x}),className:w,children:[g.jsx("div",{style:v.colorPreview,children:g.jsx("div",{style:M(v.colorPreviewCurrent,{backgroundColor:re(i?{...J,a:y}:J)})})}),g.jsx("div",{ref:W,style:M(v.saturationArea,{background:G,height:x*.6}),onMouseDown:q,onTouchStart:q,children:g.jsx("div",{style:M(v.saturationOverlay,{background:"linear-gradient(to top, #000, transparent)"}),children:g.jsx("div",{style:M(v.saturationPointer,{left:`${f.s}%`,top:`${100-f.v}%`})})})}),g.jsx("div",{ref:z,style:v.hueSlider,onMouseDown:ee,onTouchStart:ee,children:g.jsx("div",{style:M(v.huePointer,{left:`${f.h/360*100}%`})})}),i&&g.jsxs("div",{ref:V,style:v.alphaSlider,onMouseDown:B,onTouchStart:B,children:[g.jsx("div",{style:v.alphaBackground}),g.jsx("div",{style:M(v.alphaOverlay,{background:`linear-gradient(to right, transparent, ${re(J)})`})}),g.jsx("div",{style:M(v.alphaPointer,{left:`${y*100}%`})})]}),a&&g.jsx("div",{style:v.formatToggle,children:["hex","rgb","hsv","hsl"].map(t=>g.jsx("button",{style:M(v.formatButton,U===t?v.formatButtonActive:void 0,T?v.formatButtonDisabled:void 0),onClick:()=>{K(t),c&&c(t)},disabled:T,children:t.toUpperCase()},t))}),g.jsx("input",{type:"text",value:P(),onChange:t=>{const u=D(t.target.value);if(u){const b=H(u.r,u.g,u.b);F(b)}},disabled:T,style:v.colorInput}),d&&l&&l.length>0&&g.jsx("div",{style:v.presets,children:l.map((t,u)=>g.jsx(he,{color:t,size:20,onClick:()=>te(t)},u))})]})};S.ColorPicker=Re,S.ColorSwatch=he,S.hexToRgb=le,S.hslToRgb=me,S.hsvToRgb=A,S.rgbToHex=Q,S.rgbToHexAlpha=fe,S.rgbToHsl=de,S.rgbToHsv=H,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})});