import l,{createContext as A,Fragment as H,useContext as F,useEffect as M,useMemo as P,useRef as U,useState as I}from"react";import{useControllable as K}from'../../hooks/use-controllable.js';import{useDisposables as B}from'../../hooks/use-disposables.js';import{useEvent as h}from'../../hooks/use-event.js';import{useId as O}from'../../hooks/use-id.js';import{useResolveButtonType as W}from'../../hooks/use-resolve-button-type.js';import{useSyncRefs as N}from'../../hooks/use-sync-refs.js';import{Features as J,Hidden as X}from'../../internal/hidden.js';import{isDisabledReactIssue7711 as j}from'../../utils/bugs.js';import{attemptSubmit as $}from'../../utils/form.js';import{compact as q,forwardRefWithAs as z,render as g}from'../../utils/render.js';import{Description as Q,useDescriptions as V}from'../description/description.js';import{Keys as D}from'../keyboard.js';import{Label as Y,useLabels as Z}from'../label/label.js';let S=A(null);S.displayName="GroupContext";let ee=H;function te(r){var u;let[n,p]=I(null),[c,T]=Z(),[o,b]=V(),a=P(()=>({switch:n,setSwitch:p,labelledby:c,describedby:o}),[n,p,c,o]),d={},y=r;return l.createElement(b,{name:"Switch.Description"},l.createElement(T,{name:"Switch.Label",props:{htmlFor:(u=a.switch)==null?void 0:u.id,onClick(m){n&&(m.currentTarget.tagName==="LABEL"&&m.preventDefault(),n.click(),n.focus({preventScroll:!0}))}}},l.createElement(S.Provider,{value:a},g({ourProps:d,theirProps:y,defaultTag:ee,name:"Switch.Group"}))))}let ne="button";function re(r,n){var E;let p=O(),{id:c=`headlessui-switch-${p}`,checked:T,defaultChecked:o=!1,onChange:b,disabled:a=!1,name:d,value:y,form:u,...m}=r,t=F(S),f=U(null),C=N(f,n,t===null?null:t.setSwitch),[i,s]=K(T,b,o),w=h(()=>s==null?void 0:s(!i)),L=h(e=>{if(j(e.currentTarget))return e.preventDefault();e.preventDefault(),w()}),x=h(e=>{e.key===D.Space?(e.preventDefault(),w()):e.key===D.Enter&&$(e.currentTarget)}),v=h(e=>e.preventDefault()),G=P(()=>({checked:i}),[i]),R={id:c,ref:C,role:"switch",type:W(r,f),tabIndex:r.tabIndex===-1?0:(E=r.tabIndex)!=null?E:0,"aria-checked":i,"aria-labelledby":t==null?void 0:t.labelledby,"aria-describedby":t==null?void 0:t.describedby,disabled:a,onClick:L,onKeyUp:x,onKeyPress:v},k=B();return M(()=>{var _;let e=(_=f.current)==null?void 0:_.closest("form");e&&o!==void 0&&k.addEventListener(e,"reset",()=>{s(o)})},[f,s]),l.createElement(l.Fragment,null,d!=null&&i&&l.createElement(X,{features:J.Hidden,...q({as:"input",type:"checkbox",hidden:!0,readOnly:!0,disabled:a,form:u,checked:i,name:d,value:y})}),g({ourProps:R,theirProps:m,slot:G,defaultTag:ne,name:"Switch"}))}let oe=z(re),ie=te,_e=Object.assign(oe,{Group:ie,Label:Y,Description:Q});export{_e as Switch};
