react-custom-switcher
Version:
Legacy React multi-option Switch/Toggle component. New development has moved to react-segmented-choice.
3 lines (2 loc) • 9.7 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["react-custom-switcher"]={},e.React)}(this,function(e,t){"use strict";const o="#666",i="#cacaca",r=(e,t)=>t?i:e||o,n=(e,t,o)=>e<0?0:e+o>t?t-o:e,a=(e,t)=>{if(e&&"undefined"!=typeof document){const e=document.body.style.overflow;t({height:document.body.style.height,overflow:e}),document.body.style.overflow="hidden",document.body.style.height="100%"}},s=(e,t)=>{e&&"undefined"!=typeof document&&(document.body.style.overflow=t.overflow,document.body.style.height=t.height)},d=new Set,c=e=>{"production"===process.env.NODE_ENV||"undefined"==typeof console||d.has(e)||(d.add(e),console.warn(e))};e.CustomSwitcher=({options:e,value:d,containerWidth:l,variant:u="primary",switchSize:v,dragEnabled:b=!0,scaleWhileDrag:m=1.2,disabled:p=!1,cssOverrides:h={},callback:f})=>{const y=t.useMemo(()=>((e,t)=>e||("secondary"===t?46:36))(v,u),[v,u]),g="undefined"!=typeof document,w=t.useMemo(()=>(()=>{if("undefined"==typeof navigator)return!1;const e=navigator.userAgent||navigator.vendor;return!(!/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(e)&&!/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(e.substring(0,4)))})(),[]),k=e.length>=2,E=e.length>0,D=t.useMemo(()=>(({containerWidth:e,switchSize:t,cssOverrides:r})=>({root:{color:"#777"},container:{width:e,height:t,position:"relative",display:"flex",alignItems:"center",WebkitTapHighlightColor:"transparent",WebkitTouchCallout:"none",userSelect:"none"},switch:{width:t,height:t,borderRadius:"50%",cursor:r.cursorGrab?r.cursorGrab:"grab",opacity:1,transition:"all 0.4s",pointerEvents:"all",boxSizing:"border-box"},draggable:{position:"absolute",zIndex:1},switchOverride:{...r.switch},switchPrimary:{backgroundColor:o},switchSecondary:{border:`5px solid ${o}`},switchDisabled:{...r.switchDisabled},switchDisabledPrimary:{backgroundColor:i},switchDisabledSecondary:{borderColor:i},grabbing:{cursor:r.cursorGrabbing?r.cursorGrabbing:"grabbing"},transition:{transition:"transform 200ms ease-out"},divisionsWrap:{position:"absolute",width:e-t,height:"100%",top:"50%",left:"50%",transform:"translate3d(-50%,-50%,0)",display:"flex",alignItems:"center"},divWrap:{position:"absolute",top:"50%",width:t,height:t,display:"flex",justifyContent:"center",alignItems:"center"},division:{boxSizing:"border-box",position:"absolute",width:20,height:20,cursor:"pointer"},divisionPrimary:{borderRadius:"50%",backgroundColor:i,border:`5px solid ${i}`},divisionSecondary:{},divisionOverride:{...r.division},divLine:{height:5,width:e-t,borderRadius:2.5,backgroundColor:i},divLineSecondary:{backgroundColor:"transparent"},divLineOverride:{...r.divisionLine},label:{position:"absolute",cursor:"pointer"},labelPrimary:{top:"130%",fontSize:13},labelSecondary:{top:"50%",transform:"translateY(-50%)",fontSize:14},labelDisabled:{opacity:.6},labelOverride:{...r.label},defaultCursor:{cursor:r.cursorDefault?r.cursorDefault:"pointer"},disabledCursor:{cursor:r.cursorDisabled},defaultDisabledCursor:{cursor:"default"},stopScrolling:{height:"100%",overflow:"hidden"}}))({containerWidth:l,switchSize:y,cssOverrides:h}),[l,y,h]),S=t.useRef(null),C=t.useRef(null),[x,L]=t.useState(d),[I,O]=t.useState(!1),[z,_]=t.useState(!1),[T,W]=t.useState(),[P,R]=t.useState(0),[A,j]=t.useState(0),[M,N]=t.useState({height:"",overflow:""}),$=k?(l-y)/(e.length-1):0,q=t.useCallback(t=>E?Math.min(Math.max(t,0),e.length-1):0,[E,e.length]),F=t.useCallback(t=>{if(E)return e[q(t)]},[q,E,e]),G=t.useCallback(()=>!k||$<=0?0:q(Math.abs(Math.round(P/$))),[$,q,k,P]),U=t.useCallback(e=>{const t=F(e);if(!t)return O(!0),void _(!1);x!==t.value&&(L(t.value),f(t.value)),O(!0),_(!1)},[f,x,F]),H=t.useCallback(()=>{_(!0),O(!1)},[]),X=(e,t)=>{const o=F(e);o&&(t.stopPropagation(),O(!0),x!==o.value&&(L(o.value),f(o.value)))};t.useEffect(()=>{k||c("[react-custom-switcher] `options` should include at least 2 entries to render a functional switcher.")},[k]),t.useEffect(()=>{E&&!e.some(e=>e.value===d)&&c("[react-custom-switcher] The provided `value` does not match any option. The switcher will fall back to the first option position.")},[E,e,d]),t.useEffect(()=>{const t=e.findIndex(e=>e.value===x),o=t>=0?t:0;E?(R($*o),j($*o)):(R(0),j(0))},[x,e,$,E]),t.useEffect(()=>{L(d)},[d]),t.useEffect(()=>{const e=e=>{if(null==e.relatedTarget){s(w,M);const e=G();j(e*$),U(e),_(!1)}};return g&&b&&k&&document.addEventListener("pointerout",e),()=>{g&&document.removeEventListener("pointerout",e)}},[$,g,b,G,U,k,w,M]),t.useEffect(()=>{const e=()=>{const e=G();R(e*$),s(w,M),j(e*$),U(e),_(!1)};return g&&b&&k&&(w?(document.body.addEventListener("touchend",e),document.body.addEventListener("touchcancel",e)):document.body.addEventListener("pointerup",e)),()=>{document.body.removeEventListener("touchend",e),document.body.removeEventListener("touchcancel",e),document.body.removeEventListener("pointerup",e)}},[$,g,b,G,U,k,w,M]),t.useEffect(()=>{const e=e=>{if(null!=T&&(e.preventDefault(),H(),C.current&&S.current)){const t=A+(e.touches[0].clientX-T);R(n(t,S.current.offsetWidth,C.current.offsetWidth))}},t=e=>{if(null!=T&&(e.preventDefault(),H(),C.current&&S.current)){const t=A+(e.clientX-T);R(n(t,S.current.offsetWidth,C.current.offsetWidth))}};return g&&b&&k&&z&&(w?document.body.addEventListener("touchmove",e,{passive:!1}):document.body.addEventListener("pointermove",t)),()=>{g&&(document.body.removeEventListener("touchmove",e),document.body.removeEventListener("pointermove",t))}},[g,z,S,C,b,H,k,A,T,w]);const V=(e,t)=>{const o=t.find(t=>t.value===e)?.color;return o};return t.createElement("div",{style:D.root},t.createElement("div",{style:D.container,ref:S},t.createElement("div",{style:{...D.draggable,...I?{...D.transition}:void 0,transform:`translateX(${P}px)`,touchAction:b&&!p&&k?"none":"auto"},ref:C,onPointerDown:!w&&!p&&b&&k?e=>{a(w,N),_(!0),W(e.clientX)}:void 0,onTouchStart:w&&!p&&b&&k?e=>{e.preventDefault(),a(w,N),_(!0),W(e.touches[0].clientX)}:void 0},t.createElement("div",{style:{...D.switch,..."primary"===u?{...D.switchPrimary}:void 0,..."secondary"===u?{...D.switchSecondary}:void 0,...z?{...D.grabbing}:void 0,...p&&"primary"===u?{...D.switchDisabledPrimary}:void 0,...p&&"secondary"===u?{...D.switchDisabledSecondary}:void 0,...p&&h.switchDisabled?{...D.switchDisabled}:void 0,...p||!b?{...D.defaultDisabledCursor}:void 0,transform:z?`scale(${Z=m,"number"==typeof Z?Z:"boolean"==typeof Z&&Z?1.2:1})`:"scale(1)",..."primary"===u?{backgroundColor:r(V(x,e),p)}:void 0,..."secondary"===u?{borderColor:r(V(x,e),p)}:void 0,...D.switchOverride}})),t.createElement("div",{style:D.divisionsWrap},t.createElement("div",{style:{...D.divLine,..."secondary"===u?{...D.divLineSecondary}:void 0,...D.divLineOverride}}),e.map((e,o)=>t.createElement("div",{key:`key-${e.value}-${o}`,style:{...D.divWrap,...D.defaultCursor,transform:`translate3d(calc(${o*$}px - 50%), -50%, 0)`},onPointerDown:!p&&k&&e.value!==x?e=>X(o,e):void 0},t.createElement("div",{style:{...D.division,..."primary"===u?{...D.divisionPrimary}:void 0,...p&&!h.cursorDisabled?{...D.defaultDisabledCursor}:void 0,...D.divisionOverride,...p&&h.cursorDisabled?{...D.disabledCursor}:void 0}}),e.label&&t.createElement("div",{style:{...D.label,..."primary"===u?{...D.labelPrimary}:void 0,..."secondary"===u?{...D.labelSecondary}:void 0,...D.defaultCursor,...D.labelOverride,...p?{...D.labelDisabled}:void 0,...h.cursorDisabled||!p&&x!==e.value?void 0:{...D.defaultDisabledCursor},...h.cursorDisabled&&(p||x===e.value)?{...D.disabledCursor}:void 0},onPointerDown:!p&&k?e=>X(o,e):void 0},e.label))))));var Z},e.DEFAULT_BORDER_SIZE=5,e.DEFAULT_DIVISION_COLOR=i,e.DEFAULT_DIVISION_LINE_HEIGHT=5,e.DEFAULT_DIVISION_POINT_SIZE=20,e.DEFAULT_SCALE_WHILE_DRAG=1.2,e.DEFAULT_SWITCH_COLOR=o});
//# sourceMappingURL=index.js.map