react-custom-switcher
Version:
Multi-option Switch/Toggle component for React with dragging, snap and customizable UI
2 lines (1 loc) • 8.45 kB
JavaScript
import e from"react";const o=20,t="#666",i="#cacaca",r=5,a=5,n=1.2,s=(e,o)=>o?i:e||t,d=(e,o,t)=>e<0?0:e+t>o?o-t:e,l=(e,o)=>{if(e){const e=document.body.style.overflow;o({height:document.body.style.height,overflow:e}),document.body.style.overflow="hidden",document.body.style.height="100%"}},c=(e,o)=>{e&&(document.body.style.overflow=o.overflow,document.body.style.height=o.height)},u=({options:o,value:r,containerWidth:a,variant:n="primary",switchSize:u,dragEnabled:b=!0,scaleWhileDrag:v=1.2,disabled:m=!1,cssOverrides:p={},callback:h})=>{const y=e.useMemo((()=>((e,o)=>e||("secondary"===o?46:36))(u,n)),[u,n]),g=e.useMemo((()=>(()=>{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)))})()),[]),f=e.useMemo((()=>(({containerWidth:e,switchSize:o,cssOverrides:r})=>({root:{color:"#777"},container:{width:e,height:o,position:"relative",display:"flex",alignItems:"center",WebkitTapHighlightColor:"transparent",WebkitTouchCallout:"none",userSelect:"none"},switch:{width:o,height:o,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:t},switchSecondary:{border:`5px solid ${t}`},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-o,height:"100%",top:"50%",left:"50%",transform:"translate3d(-50%,-50%,0)",display:"flex",alignItems:"center"},divWrap:{position:"absolute",top:"50%",width:o,height:o,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-o,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 !important"},stopScrolling:{height:"100%",overflow:"hidden"}}))({containerWidth:a,switchSize:y,cssOverrides:p})),[a,y,p]),w=e.useRef(null),k=e.useRef(null),[x,D]=e.useState(r),[E,S]=e.useState(!1),[C,z]=e.useState(!1),[L,W]=e.useState(),[P,O]=e.useState(0),[M,$]=e.useState(0),[j,q]=e.useState({height:document.body.style.height,overflow:document.body.style.overflow}),I=(a-y)/(o.length-1),R=e.useCallback((e=>{x!==o[e].value&&(D(o[e].value),h(o[e].value)),S(!0),z(!1)}),[h,o,x]),X=e.useCallback((()=>{z(!0),S(!1)}),[]),G=(e,t)=>{t.stopPropagation(),S(!0),x!==o[e].value&&(D(o[e].value),h(o[e].value))};e.useEffect((()=>{const e=o.findIndex((e=>e.value===x));e>=0&&(O(I*e),$(I*e))}),[x,o,I]),e.useEffect((()=>{D(r)}),[r]),e.useEffect((()=>{const e=e=>{if(null==e.relatedTarget){c(g,j);const e=Math.abs(Math.round(P/I));$(e*I),R(e),z(!1)}};return b&&document.addEventListener("pointerout",e),()=>document.removeEventListener("pointerout",e)}),[P,I,R,b,g,j]),e.useEffect((()=>{const e=()=>{const e=Math.abs(Math.round(P/I));O(e*I),c(g,j),$(e*I),R(e),z(!1)};return b&&(g?document.body.addEventListener("touchend",e):document.body.addEventListener("pointerup",e)),()=>{document.body.removeEventListener("touchend",e),document.body.removeEventListener("pointerup",e)}}),[P,I,R,b,g,j]),e.useEffect((()=>{const e=e=>{if(e.preventDefault(),X(),k.current&&w.current){const o=M+(e.touches[0].clientX-L);O(d(o,w.current.offsetWidth,k.current.offsetWidth))}},o=e=>{if(e.preventDefault(),X(),k.current&&w.current){const o=M+(e.clientX-L);O(d(o,w.current.offsetWidth,k.current.offsetWidth))}};return b&&C&&(g?document.body.addEventListener("touchmove",e):document.body.addEventListener("pointermove",o)),()=>{document.body.removeEventListener("touchmove",e),document.body.removeEventListener("pointermove",o)}}),[C,w,k,b,X,M,L,g]);const T=(e,o)=>{const t=o.find((o=>o.value===e))?.color;return t};return e.createElement("div",{style:f.root},e.createElement("div",{style:f.container,ref:w},e.createElement("div",{style:{...f.draggable,...E?{...f.transition}:void 0,transform:`translateX(${P}px)`},ref:k,onPointerDown:g||m||!b?void 0:e=>{l(g,q),z(!0),W(e.clientX)},onTouchStart:g&&!m&&b?e=>{l(g,q),z(!0),W(e.touches[0].clientX)}:void 0},e.createElement("div",{style:{...f.switch,..."primary"===n?{...f.switchPrimary}:void 0,..."secondary"===n?{...f.switchSecondary}:void 0,...C?{...f.grabbing}:void 0,...m&&"primary"===n?{...f.switchDisabledPrimary}:void 0,...m&&"secondary"===n?{...f.switchDisabledSecondary}:void 0,...m&&p.switchDisabled?{...f.switchDisabled}:void 0,...m||!b?{...f.defaultDisabledCursor}:void 0,transform:C?`scale(${_=v,"number"==typeof _?_:"boolean"==typeof _&&_?1.2:1})`:"scale(1)",..."primary"===n?{backgroundColor:s(T(x,o),m)}:void 0,..."secondary"===n?{borderColor:s(T(x,o),m)}:void 0,...f.switchOverride}})),e.createElement("div",{style:f.divisionsWrap},e.createElement("div",{style:{...f.divLine,..."secondary"===n?{...f.divLineSecondary}:void 0,...f.divLineOverride}}),o.map(((o,t)=>e.createElement("div",{key:`key-${o.value}-${t}`,style:{...f.divWrap,...f.defaultCursor,transform:`translate3d(calc(${t*I}px - 50%), -50%, 0)`},onPointerDown:m||o.value===x?void 0:e=>G(t,e)},e.createElement("div",{style:{...f.division,..."primary"===n?{...f.divisionPrimary}:void 0,...m&&!p.cursorDisabled?{...f.defaultDisabledCursor}:void 0,...f.divisionOverride,...m&&p.cursorDisabled?{...f.disabledCursor}:void 0}}),o.label&&e.createElement("div",{style:{...f.label,..."primary"===n?{...f.labelPrimary}:void 0,..."secondary"===n?{...f.labelSecondary}:void 0,...f.defaultCursor,...f.labelOverride,...m?{...f.labelDisabled}:void 0,...p.cursorDisabled||!m&&x!==o.value?void 0:{...f.defaultDisabledCursor},...p.cursorDisabled&&(m||x===o.value)?{...f.disabledCursor}:void 0},onPointerDown:m?void 0:e=>G(t,e)},o.label)))))));var _};export{u as CustomSwitcher,r as DEFAULT_BORDER_SIZE,i as DEFAULT_DIVISION_COLOR,a as DEFAULT_DIVISION_LINE_HEIGHT,o as DEFAULT_DIVISION_POINT_SIZE,n as DEFAULT_SCALE_WHILE_DRAG,t as DEFAULT_SWITCH_COLOR};