figpack-spike-sorting 0.1.11__tar.gz → 0.1.12__tar.gz
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.
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/PKG-INFO +1 -1
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/__init__.py +1 -1
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/figpack_spike_sorting.js +1 -1
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting.egg-info/PKG-INFO +1 -1
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/setup.py +1 -1
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/README.md +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/spike_sorting_extension.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/style.css +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/AutocorrelogramItem.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/Autocorrelograms.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/AverageWaveforms.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/CrossCorrelogramItem.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/CrossCorrelograms.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/RasterPlot.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/RasterPlotItem.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/SortingCuration.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/SpikeAmplitudes.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/SpikeAmplitudesItem.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/SpikeLocations.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/TiledImage.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitLocations.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitMetricsGraph.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitSimilarityMatrix.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitSimilarityScore.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitsTable.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitsTableColumn.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/UnitsTableRow.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/views/__init__.py +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting.egg-info/SOURCES.txt +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting.egg-info/dependency_links.txt +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting.egg-info/requires.txt +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting.egg-info/top_level.txt +0 -0
- {figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/setup.cfg +0 -0
|
@@ -188,7 +188,7 @@ export default theme;`}function qC(t){return typeof t=="number"?`${(t*100).toFix
|
|
|
188
188
|
animation: ${L_} 1.4s ease-in-out infinite;
|
|
189
189
|
`:null,Sj=t=>{const{classes:e,variant:n,color:r,disableShrink:i}=t,s={root:["root",n,`color${Ge(r)}`],svg:["svg"],circle:["circle",`circle${Ge(n)}`,i&&"circleDisableShrink"]};return Er(s,bj,e)},Tj=qt("span",{name:"MuiCircularProgress",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,e[n.variant],e[`color${Ge(n.color)}`]]}})(Cr(({theme:t})=>({display:"inline-block",variants:[{props:{variant:"determinate"},style:{transition:t.transitions.create("transform")}},{props:{variant:"indeterminate"},style:xj||{animation:`${U_} 1.4s linear infinite`}},...Object.entries(t.palette).filter($l()).map(([e])=>({props:{color:e},style:{color:(t.vars||t).palette[e].main}}))]}))),Aj=qt("svg",{name:"MuiCircularProgress",slot:"Svg"})({display:"block"}),Ej=qt("circle",{name:"MuiCircularProgress",slot:"Circle",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.circle,e[`circle${Ge(n.variant)}`],n.disableShrink&&e.circleDisableShrink]}})(Cr(({theme:t})=>({stroke:"currentColor",variants:[{props:{variant:"determinate"},style:{transition:t.transitions.create("stroke-dashoffset")}},{props:{variant:"indeterminate"},style:{strokeDasharray:"80px, 200px",strokeDashoffset:0}},{props:({ownerState:e})=>e.variant==="indeterminate"&&!e.disableShrink,style:wj||{animation:`${L_} 1.4s ease-in-out infinite`}}]}))),Cj=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiCircularProgress"}),{className:i,color:s="primary",disableShrink:o=!1,size:a=40,style:l,thickness:c=3.6,value:u=0,variant:f="indeterminate",...h}=r,d={...r,color:s,disableShrink:o,size:a,thickness:c,value:u,variant:f},g=Sj(d),p={},_={},m={};if(f==="determinate"){const v=2*Math.PI*((so-c)/2);p.strokeDasharray=v.toFixed(3),m["aria-valuenow"]=Math.round(u),p.strokeDashoffset=`${((100-u)/100*v).toFixed(3)}px`,_.transform="rotate(-90deg)"}return R.jsx(Tj,{className:Et(g.root,i),style:{width:a,height:a,..._,...l},ownerState:d,ref:n,role:"progressbar",...m,...h,children:R.jsx(Aj,{className:g.svg,ownerState:d,viewBox:`${so/2} ${so/2} ${so} ${so}`,children:R.jsx(Ej,{className:g.circle,style:p,ownerState:d,cx:so,cy:so,r:(so-c)/2,fill:"none",strokeWidth:c})})})});function Dj(t){return ar("MuiIconButton",t)}const rD=lr("MuiIconButton",["root","disabled","colorInherit","colorPrimary","colorSecondary","colorError","colorInfo","colorSuccess","colorWarning","edgeStart","edgeEnd","sizeSmall","sizeMedium","sizeLarge","loading","loadingIndicator","loadingWrapper"]),Mj=t=>{const{classes:e,disabled:n,color:r,edge:i,size:s,loading:o}=t,a={root:["root",o&&"loading",n&&"disabled",r!=="default"&&`color${Ge(r)}`,i&&`edge${Ge(i)}`,`size${Ge(s)}`],loadingIndicator:["loadingIndicator"],loadingWrapper:["loadingWrapper"]};return Er(a,Dj,e)},Rj=qt(nD,{name:"MuiIconButton",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,n.loading&&e.loading,n.color!=="default"&&e[`color${Ge(n.color)}`],n.edge&&e[`edge${Ge(n.edge)}`],e[`size${Ge(n.size)}`]]}})(Cr(({theme:t})=>({textAlign:"center",flex:"0 0 auto",fontSize:t.typography.pxToRem(24),padding:8,borderRadius:"50%",color:(t.vars||t).palette.action.active,transition:t.transitions.create("background-color",{duration:t.transitions.duration.shortest}),variants:[{props:e=>!e.disableRipple,style:{"--IconButton-hoverBg":t.alpha((t.vars||t).palette.action.active,(t.vars||t).palette.action.hoverOpacity),"&:hover":{backgroundColor:"var(--IconButton-hoverBg)","@media (hover: none)":{backgroundColor:"transparent"}}}},{props:{edge:"start"},style:{marginLeft:-12}},{props:{edge:"start",size:"small"},style:{marginLeft:-3}},{props:{edge:"end"},style:{marginRight:-12}},{props:{edge:"end",size:"small"},style:{marginRight:-3}}]})),Cr(({theme:t})=>({variants:[{props:{color:"inherit"},style:{color:"inherit"}},...Object.entries(t.palette).filter($l()).map(([e])=>({props:{color:e},style:{color:(t.vars||t).palette[e].main}})),...Object.entries(t.palette).filter($l()).map(([e])=>({props:{color:e},style:{"--IconButton-hoverBg":t.alpha((t.vars||t).palette[e].main,(t.vars||t).palette.action.hoverOpacity)}})),{props:{size:"small"},style:{padding:5,fontSize:t.typography.pxToRem(18)}},{props:{size:"large"},style:{padding:12,fontSize:t.typography.pxToRem(28)}}],[`&.${rD.disabled}`]:{backgroundColor:"transparent",color:(t.vars||t).palette.action.disabled},[`&.${rD.loading}`]:{color:"transparent"}}))),Ij=qt("span",{name:"MuiIconButton",slot:"LoadingIndicator"})(({theme:t})=>({display:"none",position:"absolute",visibility:"visible",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:(t.vars||t).palette.action.disabled,variants:[{props:{loading:!0},style:{display:"flex"}}]})),Vl=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiIconButton"}),{edge:i=!1,children:s,className:o,color:a="default",disabled:l=!1,disableFocusRipple:c=!1,size:u="medium",id:f,loading:h=null,loadingIndicator:d,...g}=r,p=q$(f),_=d??R.jsx(Cj,{"aria-labelledby":p,color:"inherit",size:16}),m={...r,edge:i,color:a,disabled:l,disableFocusRipple:c,loading:h,loadingIndicator:_,size:u},v=Mj(m);return R.jsxs(Rj,{id:h?p:f,className:Et(v.root,o),centerRipple:!0,focusRipple:!c,disabled:l||h,ref:n,...g,ownerState:m,children:[typeof h=="boolean"&&R.jsx("span",{className:v.loadingWrapper,style:{display:"contents"},children:R.jsx(Ij,{className:v.loadingIndicator,ownerState:m,children:h&&_})}),s]})});function Pj({props:t,states:e,muiFormControl:n}){return e.reduce((r,i)=>(r[i]=t[i],n&&typeof t[i]>"u"&&(r[i]=n[i]),r),{})}const Oj=D.createContext(void 0);function iD(){return D.useContext(Oj)}function Nj(t){return ar("PrivateSwitchBase",t)}lr("PrivateSwitchBase",["root","checked","disabled","input","edgeStart","edgeEnd"]);const Fj=t=>{const{classes:e,checked:n,disabled:r,edge:i}=t,s={root:["root",n&&"checked",r&&"disabled",i&&`edge${Ge(i)}`],input:["input"]};return Er(s,Nj,e)},Bj=qt(nD,{name:"MuiSwitchBase"})({padding:9,borderRadius:"50%",variants:[{props:{edge:"start",size:"small"},style:{marginLeft:-3}},{props:({edge:t,ownerState:e})=>t==="start"&&e.size!=="small",style:{marginLeft:-12}},{props:{edge:"end",size:"small"},style:{marginRight:-3}},{props:({edge:t,ownerState:e})=>t==="end"&&e.size!=="small",style:{marginRight:-12}}]}),kj=qt("input",{name:"MuiSwitchBase",shouldForwardProp:M_})({cursor:"inherit",position:"absolute",opacity:0,width:"100%",height:"100%",top:0,left:0,margin:0,padding:0,zIndex:1}),sD=D.forwardRef(function(e,n){const{autoFocus:r,checked:i,checkedIcon:s,defaultChecked:o,disabled:a,disableFocusRipple:l=!1,edge:c=!1,icon:u,id:f,inputProps:h,inputRef:d,name:g,onBlur:p,onChange:_,onFocus:m,readOnly:v,required:y=!1,tabIndex:b,type:w,value:x,slots:S={},slotProps:A={},...E}=e,[C,M]=LV({controlled:i,default:!!o}),T=iD(),P=z=>{m&&m(z),T&&T.onFocus&&T.onFocus(z)},I=z=>{p&&p(z),T&&T.onBlur&&T.onBlur(z)},k=z=>{if(z.nativeEvent.defaultPrevented)return;const Q=z.target.checked;M(Q),_&&_(z,Q)};let O=a;T&&typeof O>"u"&&(O=T.disabled);const L=w==="checkbox"||w==="radio",U={...e,checked:C,disabled:O,disableFocusRipple:l,edge:c},$=Fj(U),J={slots:S,slotProps:{input:h,...A}},[ne,j]=zl("root",{ref:n,elementType:Bj,className:$.root,shouldForwardComponentProp:!0,externalForwardedProps:{...J,component:"span",...E},getSlotProps:z=>({...z,onFocus:Q=>{z.onFocus?.(Q),P(Q)},onBlur:Q=>{z.onBlur?.(Q),I(Q)}}),ownerState:U,additionalProps:{centerRipple:!0,focusRipple:!l,disabled:O,role:void 0,tabIndex:null}}),[V,G]=zl("input",{ref:d,elementType:kj,className:$.input,externalForwardedProps:J,getSlotProps:z=>({...z,onChange:Q=>{z.onChange?.(Q),k(Q)}}),ownerState:U,additionalProps:{autoFocus:r,checked:i,defaultChecked:o,disabled:O,id:L?f:void 0,name:g,readOnly:v,required:y,tabIndex:b,type:w,...w==="checkbox"&&x===void 0?{}:{value:x}}});return R.jsxs(ne,{...j,children:[R.jsx(V,{...G}),C?s:u]})}),Uj=I_(R.jsx("path",{d:"M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"})),Lj=I_(R.jsx("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"})),zj=I_(R.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z"}));function $j(t){return ar("MuiCheckbox",t)}const z_=lr("MuiCheckbox",["root","checked","disabled","indeterminate","colorPrimary","colorSecondary","sizeSmall","sizeMedium"]),Vj=t=>{const{classes:e,indeterminate:n,color:r,size:i}=t,s={root:["root",n&&"indeterminate",`color${Ge(r)}`,`size${Ge(i)}`]},o=Er(s,$j,e);return{...e,...o}},jj=qt(sD,{shouldForwardProp:t=>M_(t)||t==="classes",name:"MuiCheckbox",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,n.indeterminate&&e.indeterminate,e[`size${Ge(n.size)}`],n.color!=="default"&&e[`color${Ge(n.color)}`]]}})(Cr(({theme:t})=>({color:(t.vars||t).palette.text.secondary,variants:[{props:{color:"default",disableRipple:!1},style:{"&:hover":{backgroundColor:t.alpha((t.vars||t).palette.action.active,(t.vars||t).palette.action.hoverOpacity)}}},...Object.entries(t.palette).filter($l()).map(([e])=>({props:{color:e,disableRipple:!1},style:{"&:hover":{backgroundColor:t.alpha((t.vars||t).palette[e].main,(t.vars||t).palette.action.hoverOpacity)}}})),...Object.entries(t.palette).filter($l()).map(([e])=>({props:{color:e},style:{[`&.${z_.checked}, &.${z_.indeterminate}`]:{color:(t.vars||t).palette[e].main},[`&.${z_.disabled}`]:{color:(t.vars||t).palette.action.disabled}}})),{props:{disableRipple:!1},style:{"&:hover":{"@media (hover: none)":{backgroundColor:"transparent"}}}}]}))),Hj=R.jsx(Lj,{}),Wj=R.jsx(Uj,{}),Xj=R.jsx(zj,{}),oD=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiCheckbox"}),{checkedIcon:i=Hj,color:s="primary",icon:o=Wj,indeterminate:a=!1,indeterminateIcon:l=Xj,inputProps:c,size:u="medium",disableRipple:f=!1,className:h,slots:d={},slotProps:g={},...p}=r,_=a?l:o,m=a?l:i,v={...r,disableRipple:f,color:s,indeterminate:a,size:u},y=Vj(v),b=g.input??c,[w,x]=zl("root",{ref:n,elementType:jj,className:Et(y.root,h),shouldForwardComponentProp:!0,externalForwardedProps:{slots:d,slotProps:g,...p},ownerState:v,additionalProps:{type:"checkbox",icon:D.cloneElement(_,{fontSize:_.props.fontSize??u}),checkedIcon:D.cloneElement(m,{fontSize:m.props.fontSize??u}),disableRipple:f,slots:d,slotProps:{input:$V(typeof b=="function"?b(v):b,{"data-indeterminate":a})}}});return R.jsx(w,{...x,classes:y})});function qj(t){return ar("MuiFormGroup",t)}lr("MuiFormGroup",["root","row","error"]);const Yj=t=>{const{classes:e,row:n,error:r}=t;return Er({root:["root",n&&"row",r&&"error"]},qj,e)},Kj=qt("div",{name:"MuiFormGroup",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,n.row&&e.row]}})({display:"flex",flexDirection:"column",flexWrap:"wrap",variants:[{props:{row:!0},style:{flexDirection:"row"}}]}),Zj=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiFormGroup"}),{className:i,row:s=!1,...o}=r,a=iD(),l=Pj({props:r,muiFormControl:a,states:["error"]}),c={...r,row:s,error:l.error},u=Yj(c);return R.jsx(Kj,{className:Et(u.root,i),ownerState:c,ref:n,...o})});function Gj(t){return ar("MuiSwitch",t)}const Yn=lr("MuiSwitch",["root","edgeStart","edgeEnd","switchBase","colorPrimary","colorSecondary","sizeSmall","sizeMedium","checked","disabled","input","thumb","track"]),Qj=t=>{const{classes:e,edge:n,size:r,color:i,checked:s,disabled:o}=t,a={root:["root",n&&`edge${Ge(n)}`,`size${Ge(r)}`],switchBase:["switchBase",`color${Ge(i)}`,s&&"checked",o&&"disabled"],thumb:["thumb"],track:["track"],input:["input"]},l=Er(a,Gj,e);return{...e,...l}},Jj=qt("span",{name:"MuiSwitch",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,n.edge&&e[`edge${Ge(n.edge)}`],e[`size${Ge(n.size)}`]]}})({display:"inline-flex",width:34+12*2,height:14+12*2,overflow:"hidden",padding:12,boxSizing:"border-box",position:"relative",flexShrink:0,zIndex:0,verticalAlign:"middle","@media print":{colorAdjust:"exact"},variants:[{props:{edge:"start"},style:{marginLeft:-8}},{props:{edge:"end"},style:{marginRight:-8}},{props:{size:"small"},style:{width:40,height:24,padding:7,[`& .${Yn.thumb}`]:{width:16,height:16},[`& .${Yn.switchBase}`]:{padding:4,[`&.${Yn.checked}`]:{transform:"translateX(16px)"}}}}]}),eH=qt(sD,{name:"MuiSwitch",slot:"SwitchBase",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.switchBase,{[`& .${Yn.input}`]:e.input},n.color!=="default"&&e[`color${Ge(n.color)}`]]}})(Cr(({theme:t})=>({position:"absolute",top:0,left:0,zIndex:1,color:t.vars?t.vars.palette.Switch.defaultColor:`${t.palette.mode==="light"?t.palette.common.white:t.palette.grey[300]}`,transition:t.transitions.create(["left","transform"],{duration:t.transitions.duration.shortest}),[`&.${Yn.checked}`]:{transform:"translateX(20px)"},[`&.${Yn.disabled}`]:{color:t.vars?t.vars.palette.Switch.defaultDisabledColor:`${t.palette.mode==="light"?t.palette.grey[100]:t.palette.grey[600]}`},[`&.${Yn.checked} + .${Yn.track}`]:{opacity:.5},[`&.${Yn.disabled} + .${Yn.track}`]:{opacity:t.vars?t.vars.opacity.switchTrackDisabled:`${t.palette.mode==="light"?.12:.2}`},[`& .${Yn.input}`]:{left:"-100%",width:"300%"}})),Cr(({theme:t})=>({"&:hover":{backgroundColor:t.alpha((t.vars||t).palette.action.active,(t.vars||t).palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},variants:[...Object.entries(t.palette).filter($l(["light"])).map(([e])=>({props:{color:e},style:{[`&.${Yn.checked}`]:{color:(t.vars||t).palette[e].main,"&:hover":{backgroundColor:t.alpha((t.vars||t).palette[e].main,(t.vars||t).palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${Yn.disabled}`]:{color:t.vars?t.vars.palette.Switch[`${e}DisabledColor`]:`${t.palette.mode==="light"?t.lighten(t.palette[e].main,.62):t.darken(t.palette[e].main,.55)}`}},[`&.${Yn.checked} + .${Yn.track}`]:{backgroundColor:(t.vars||t).palette[e].main}}}))]}))),tH=qt("span",{name:"MuiSwitch",slot:"Track"})(Cr(({theme:t})=>({height:"100%",width:"100%",borderRadius:14/2,zIndex:-1,transition:t.transitions.create(["opacity","background-color"],{duration:t.transitions.duration.shortest}),backgroundColor:t.vars?t.vars.palette.common.onBackground:`${t.palette.mode==="light"?t.palette.common.black:t.palette.common.white}`,opacity:t.vars?t.vars.opacity.switchTrack:`${t.palette.mode==="light"?.38:.3}`}))),nH=qt("span",{name:"MuiSwitch",slot:"Thumb"})(Cr(({theme:t})=>({boxShadow:(t.vars||t).shadows[1],backgroundColor:"currentColor",width:20,height:20,borderRadius:"50%"}))),aD=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiSwitch"}),{className:i,color:s="primary",edge:o=!1,size:a="medium",sx:l,slots:c={},slotProps:u={},...f}=r,h={...r,color:s,edge:o,size:a},d=Qj(h),g={slots:c,slotProps:u},[p,_]=zl("root",{className:Et(d.root,i),elementType:Jj,externalForwardedProps:g,ownerState:h,additionalProps:{sx:l}}),[m,v]=zl("thumb",{className:d.thumb,elementType:nH,externalForwardedProps:g,ownerState:h}),y=R.jsx(m,{...v}),[b,w]=zl("track",{className:d.track,elementType:tH,externalForwardedProps:g,ownerState:h});return R.jsxs(p,{..._,children:[R.jsx(eH,{type:"checkbox",icon:y,checkedIcon:y,ref:n,ownerState:h,...f,classes:{...d,root:d.switchBase},slots:{...c.switchBase&&{root:c.switchBase},...c.input&&{input:c.input}},slotProps:{...u.switchBase&&{root:typeof u.switchBase=="function"?u.switchBase(h):u.switchBase},input:{role:"switch"},...u.input&&{input:typeof u.input=="function"?u.input(h):u.input}}}),R.jsx(b,{...w})]})}),lD=D.createContext();function rH(t){return ar("MuiTable",t)}lr("MuiTable",["root","stickyHeader"]);const iH=t=>{const{classes:e,stickyHeader:n}=t;return Er({root:["root",n&&"stickyHeader"]},rH,e)},sH=qt("table",{name:"MuiTable",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,n.stickyHeader&&e.stickyHeader]}})(Cr(({theme:t})=>({display:"table",width:"100%",borderCollapse:"collapse",borderSpacing:0,"& caption":{...t.typography.body2,padding:t.spacing(2),color:(t.vars||t).palette.text.secondary,textAlign:"left",captionSide:"bottom"},variants:[{props:({ownerState:e})=>e.stickyHeader,style:{borderCollapse:"separate"}}]}))),cD="table",oH=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiTable"}),{className:i,component:s=cD,padding:o="normal",size:a="medium",stickyHeader:l=!1,...c}=r,u={...r,component:s,padding:o,size:a,stickyHeader:l},f=iH(u),h=D.useMemo(()=>({padding:o,size:a,stickyHeader:l}),[o,a,l]);return R.jsx(lD.Provider,{value:h,children:R.jsx(sH,{as:s,role:s===cD?null:"table",ref:n,className:Et(f.root,i),ownerState:u,...c})})}),Gp=D.createContext();function aH(t){return ar("MuiTableBody",t)}lr("MuiTableBody",["root"]);const lH=t=>{const{classes:e}=t;return Er({root:["root"]},aH,e)},cH=qt("tbody",{name:"MuiTableBody",slot:"Root"})({display:"table-row-group"}),uH={variant:"body"},uD="tbody",fH=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiTableBody"}),{className:i,component:s=uD,...o}=r,a={...r,component:s},l=lH(a);return R.jsx(Gp.Provider,{value:uH,children:R.jsx(cH,{className:Et(l.root,i),as:s,ref:n,role:s===uD?null:"rowgroup",ownerState:a,...o})})});function hH(t){return ar("MuiTableCell",t)}const dH=lr("MuiTableCell",["root","head","body","footer","sizeSmall","sizeMedium","paddingCheckbox","paddingNone","alignLeft","alignCenter","alignRight","alignJustify","stickyHeader"]),pH=t=>{const{classes:e,variant:n,align:r,padding:i,size:s,stickyHeader:o}=t,a={root:["root",n,o&&"stickyHeader",r!=="inherit"&&`align${Ge(r)}`,i!=="normal"&&`padding${Ge(i)}`,`size${Ge(s)}`]};return Er(a,hH,e)},gH=qt("td",{name:"MuiTableCell",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,e[n.variant],e[`size${Ge(n.size)}`],n.padding!=="normal"&&e[`padding${Ge(n.padding)}`],n.align!=="inherit"&&e[`align${Ge(n.align)}`],n.stickyHeader&&e.stickyHeader]}})(Cr(({theme:t})=>({...t.typography.body2,display:"table-cell",verticalAlign:"inherit",borderBottom:t.vars?`1px solid ${t.vars.palette.TableCell.border}`:`1px solid
|
|
190
190
|
${t.palette.mode==="light"?t.lighten(t.alpha(t.palette.divider,1),.88):t.darken(t.alpha(t.palette.divider,1),.68)}`,textAlign:"left",padding:16,variants:[{props:{variant:"head"},style:{color:(t.vars||t).palette.text.primary,lineHeight:t.typography.pxToRem(24),fontWeight:t.typography.fontWeightMedium}},{props:{variant:"body"},style:{color:(t.vars||t).palette.text.primary}},{props:{variant:"footer"},style:{color:(t.vars||t).palette.text.secondary,lineHeight:t.typography.pxToRem(21),fontSize:t.typography.pxToRem(12)}},{props:{size:"small"},style:{padding:"6px 16px",[`&.${dH.paddingCheckbox}`]:{width:24,padding:"0 12px 0 16px","& > *":{padding:0}}}},{props:{padding:"checkbox"},style:{width:48,padding:"0 0 0 4px"}},{props:{padding:"none"},style:{padding:0}},{props:{align:"left"},style:{textAlign:"left"}},{props:{align:"center"},style:{textAlign:"center"}},{props:{align:"right"},style:{textAlign:"right",flexDirection:"row-reverse"}},{props:{align:"justify"},style:{textAlign:"justify"}},{props:({ownerState:e})=>e.stickyHeader,style:{position:"sticky",top:0,zIndex:2,backgroundColor:(t.vars||t).palette.background.default}}]}))),Qp=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiTableCell"}),{align:i="inherit",className:s,component:o,padding:a,scope:l,size:c,sortDirection:u,variant:f,...h}=r,d=D.useContext(lD),g=D.useContext(Gp),p=g&&g.variant==="head";let _;o?_=o:_=p?"th":"td";let m=l;_==="td"?m=void 0:!m&&p&&(m="col");const v=f||g&&g.variant,y={...r,align:i,component:_,padding:a||(d&&d.padding?d.padding:"normal"),size:c||(d&&d.size?d.size:"medium"),sortDirection:u,stickyHeader:v==="head"&&d&&d.stickyHeader,variant:v},b=pH(y);let w=null;return u&&(w=u==="asc"?"ascending":"descending"),R.jsx(gH,{as:_,ref:n,className:Et(b.root,s),"aria-sort":w,scope:m,ownerState:y,...h})});function mH(t){return ar("MuiTableHead",t)}lr("MuiTableHead",["root"]);const yH=t=>{const{classes:e}=t;return Er({root:["root"]},mH,e)},vH=qt("thead",{name:"MuiTableHead",slot:"Root"})({display:"table-header-group"}),_H={variant:"head"},fD="thead",bH=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiTableHead"}),{className:i,component:s=fD,...o}=r,a={...r,component:s},l=yH(a);return R.jsx(Gp.Provider,{value:_H,children:R.jsx(vH,{as:s,className:Et(l.root,i),ref:n,role:s===fD?null:"rowgroup",ownerState:a,...o})})});function xH(t){return ar("MuiTableRow",t)}const hD=lr("MuiTableRow",["root","selected","hover","head","footer"]),wH=t=>{const{classes:e,selected:n,hover:r,head:i,footer:s}=t;return Er({root:["root",n&&"selected",r&&"hover",i&&"head",s&&"footer"]},xH,e)},SH=qt("tr",{name:"MuiTableRow",slot:"Root",overridesResolver:(t,e)=>{const{ownerState:n}=t;return[e.root,n.head&&e.head,n.footer&&e.footer]}})(Cr(({theme:t})=>({color:"inherit",display:"table-row",verticalAlign:"middle",outline:0,[`&.${hD.hover}:hover`]:{backgroundColor:(t.vars||t).palette.action.hover},[`&.${hD.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),"&:hover":{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.hoverOpacity}`)}}}))),dD="tr",pD=D.forwardRef(function(e,n){const r=Dr({props:e,name:"MuiTableRow"}),{className:i,component:s=dD,hover:o=!1,selected:a=!1,...l}=r,c=D.useContext(Gp),u={...r,component:s,hover:o,selected:a,head:c&&c.variant==="head",footer:c&&c.variant==="footer"},f=wH(u);return R.jsx(SH,{as:s,ref:n,className:Et(f.root,i),role:s===dD?null:"row",ownerState:u,...l})}),TH={paddingLeft:0,paddingRight:0,paddingTop:1,paddingBottom:1},Qu=35,AH=t=>{const e=t.selected?"secondary":"inherit";return R.jsx("span",{title:t.title,children:t.icon?R.jsx(Vl,{title:t.title,onClick:t.onClick,color:e,style:TH,disabled:!!t.disabled,sx:{fontSize:18},children:t.icon},t.elementIndex):R.jsx("button",{title:t.title,onClick:t.onClick,disabled:!!t.disabled,style:{padding:0,margin:0,fontSize:10},children:t.text},t.elementIndex)},t.elementIndex+"-span")},EH=t=>t.useHorizontalLayout?R.jsx(R.Fragment,{}):R.jsx("hr",{},t.elementIndex),CH=t=>{const e=Number.isFinite(t.content)?t.content:0,n=t.contentSigFigs||0,r=Math.abs(e-Math.round(e))*10**(n+1)<1,i=Number.isFinite(t.content)?r&&!t.contentAlwaysShowDecimal?Math.round(e)+"":e.toFixed(t.contentSigFigs||2):t.content||"",s=t.useHorizontalLayout?"span":"div";return ln.createElement(s,{key:t.elementIndex,title:t.title,style:{textAlign:"left",fontWeight:"bold",cursor:"default",fontSize:10}},i)},DH=t=>{switch(t.subtype){case"checkbox":return R.jsx(MH,{...t});case"slider":return R.jsx(RH,{...t});default:return R.jsxs("span",{children:["ERROR: Bad toggle subtype ",t.subtype]},t.elementIndex)}},MH=t=>R.jsx(oD,{checked:t.selected,onClick:t.onClick,style:{padding:0,paddingLeft:0},title:t.title,disabled:t.disabled},t.elementIndex),RH=t=>R.jsx(Zj,{children:R.jsx(aD,{checked:t.selected,size:"small",style:{left:-3},onChange:t.onClick,disabled:t.disabled,title:t.title})},t.elementIndex),IH=t=>{switch(t.type){case"button":return R.jsx(AH,{...t});case"divider":return R.jsx(EH,{...t});case"text":return R.jsx(CH,{...t});case"toggle":return R.jsx(DH,{...t});default:return R.jsx("span",{},t.elementIndex)}},PH=t=>(t||[]).map((e,n)=>({type:e.type||"button",subtype:e.subtype,title:e.title,onClick:e.callback,icon:e.icon||"",text:e.text||"",selected:e.selected,disabled:e.disabled,content:e.content,contentSigFigs:e.contentSigFigs,contentAlwaysShowDecimal:e.boolean,elementIndex:n})),Ju=t=>{const e=D.useMemo(()=>PH(t.customActions),[t.customActions]),n=D.useMemo(()=>e.map((s,o)=>R.jsx(IH,{...s,useHorizontalLayout:t.useHorizontalLayout},o)),[e,t.useHorizontalLayout]),r=D.useMemo(()=>({width:t.width,height:t.height,top:t.top??0,paddingTop:t.topPadding??0}),[t.width,t.height,t.top,t.topPadding]),i=t.useHorizontalLayout?"HorizontalToolbar":"VerticalToolbar";return R.jsx("div",{className:i,style:{...r},children:n})},ef={onlyShowSelected:!1},tf=({options:t,setOptions:e,onRedistributeUnitColors:n})=>R.jsxs("div",{children:[R.jsx(aD,{checked:t.onlyShowSelected,onClick:()=>{e({...t,onlyShowSelected:!t.onlyShowSelected})}}),R.jsx("span",{style:{position:"relative",top:2,overflow:"hidden"},children:"only show selected"})," ",n&&R.jsx("button",{onClick:n,title:"Redistribute unit colors",children:"rc"})]}),OH=(t,e)=>{const n=e-t;let r;n<=30?r=10:n<=120?r=20:n<=300?r=50:n<=600?r=100:n<=1e3?r=150:r=100;const i=[];let s=Math.ceil(t/r);for(;s*r<=e;)i.push(s*r),s++;return i},gD=({binEdgesSec:t,binCounts:e,color:n,width:r,height:i,hideXAxis:s})=>{const o=D.useMemo(()=>(e||[]).map((u,f)=>{const h=(t||[])[f]*1e3,d=(t||[])[f+1]*1e3;return{key:f,xStart:h,xEnd:d,height:u,tooltip:`[${h}, ${d}]: ${u}`,color:n}}),[e,t,n]),{xMin:a,xMax:l}=D.useMemo(()=>o.length>0?{xMin:o[0].xStart,xMax:o[o.length-1].xEnd}:{xMin:0,xMax:1},[o]),c=D.useMemo(()=>OH(a,l).map(f=>({x:f,label:`${f}`})),[a,l]);return e?R.jsx(s9,{bars:o,ticks:s?void 0:c,width:r,height:i,xLabel:s?void 0:"dt (msec)"}):R.jsx("div",{style:{position:"relative",width:r,height:i,color:"orange"}})},NH=10,FH=4,BH=2,Jo=ln.forwardRef((t,e)=>{const{width:n,height:r,initialPosition:i,onChange:s,adjustable:o=!0,positionFromRight:a=!1,direction:l="horizontal"}=t,c=l==="horizontal"?n:r,[u,f]=D.useState(i),[h,d]=D.useState(!1),[g,p]=D.useState({x:0,y:0}),[_,m]=D.useState(0),v=D.useRef(null);if(D.useEffect(()=>{u>c-4?f(c-4):u<4&&c>20&&f(4)},[u,n,c]),!t.children)throw Error("Unexpected: no props.children");let y,b;if(!Array.isArray(t.children))y=t.children,b=null;else{const J=t.children.filter(ne=>ne!==void 0);y=J[0]||null,b=J[1]||null}if(y||(y=b,b=null),!y)throw Error("Splitter must have at least one child.");const w=a?c-u:u,x=o?t.gripThickness??NH:0,S=o?t.gripInnerThickness??FH:0,A=o?t.gripMargin??BH:0,E=w-x/2-A,C=c-E-x-2*A,M={top:0,left:0,width:n,height:r,overflow:"hidden"},T={left:0,top:0,width:l==="horizontal"?E:n,height:l==="horizontal"?r:E,zIndex:0,overflowY:l==="horizontal"?"auto":"hidden",overflowX:l==="horizontal"?"hidden":"auto"},P={left:l==="horizontal"?E+x+2*A:0,top:l==="horizontal"?0:E+x+2*A,width:l==="horizontal"?C:n,height:l==="horizontal"?r:C,zIndex:0,overflowY:l==="horizontal"?"auto":"hidden",overflowX:l==="horizontal"?"hidden":"auto"},I={left:0,top:0,width:l==="horizontal"?x+2*A:n,height:l==="horizontal"?r:x+2*A,backgroundColor:"transparent",cursor:l==="horizontal"?"col-resize":"row-resize",zIndex:9998},k={left:l==="horizontal"?A:0,top:l==="horizontal"?0:A,width:l==="horizontal"?x:n,height:l==="horizontal"?r:x,background:"rgb(230, 230, 230)",cursor:l==="horizontal"?"col-resize":"row-resize"},O={top:l==="horizontal"?0:(x-S)/2,left:l==="horizontal"?(x-S)/2:0,width:l==="horizontal"?S:n,height:l==="horizontal"?r:S,background:"gray",cursor:l==="horizontal"?"col-resize":"row-resize"},L=D.useCallback(J=>{J.preventDefault(),d(!0),p({x:J.clientX,y:J.clientY}),m(w)},[w]),U=D.useCallback(J=>{if(!h)return;const ne=J.clientX-g.x,j=J.clientY-g.y;let G=_+(l==="horizontal"?ne:j);const z=4,Q=c-4;G=Math.max(z,Math.min(Q,G));const ee=a?c-G:G;f(ee),s&&s(ee)},[h,g,_,l,c,a,s]),$=D.useCallback(()=>{d(!1)},[]);return D.useEffect(()=>{if(h)return document.addEventListener("mousemove",U),document.addEventListener("mouseup",$),()=>{document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",$)}},[h,U,$]),b?R.jsxs("div",{className:"splitter",style:{...M,position:"relative"},children:[R.jsx("div",{style:{...T,position:"absolute"},className:"SplitterChild",children:R.jsx(y.type,{...y.props,width:l==="horizontal"?E:n,height:l==="horizontal"?r:E})},"child1"),o&&R.jsx("div",{ref:v,style:{...I,position:"absolute",left:l==="horizontal"?w-x/2-A:0,top:l==="horizontal"?0:w-x/2-A},onMouseDown:L,children:R.jsx("div",{style:{...k,position:"absolute"},children:R.jsx("div",{style:{...O,position:"absolute"}})})},"drag"),R.jsx("div",{style:{...P,position:"absolute"},className:"SplitterChild",children:R.jsx(b.type,{ref:e,...b.props,width:l==="horizontal"?C:n,height:l==="horizontal"?r:C})},"child2")]}):R.jsx(y.type,{...y.props,width:n,height:r})}),kH=({data:t,width:e,height:n})=>{const[r,i]=D.useState(ef),{selectedUnitIds:s,orderedUnitIds:o,plotClickHandlerGenerator:a,unitIdSelectionDispatch:l}=Vr(),[c,u]=D.useState(1),[f,h]=D.useState(!1);D.useEffect(()=>{l({type:$o,newUnitOrder:si(t.autocorrelograms.map(v=>v.unitId))})},[t.autocorrelograms,l]);const d=D.useMemo(()=>t.autocorrelograms.filter(v=>r.onlyShowSelected?s.has(v.unitId):!0).map(v=>({unitId:v.unitId,key:v.unitId,label:`Unit ${v.unitId}`,labelColor:ci(Nt(v.unitId)),clickHandler:r.onlyShowSelected?void 0:a(v.unitId),props:{binEdgesSec:v.binEdgesSec,binCounts:v.binCounts,color:ci(Nt(v.unitId)),width:120*c,height:120*c,hideXAxis:!f}})),[t.autocorrelograms,a,r.onlyShowSelected,s,f,c]),g=D.useMemo(()=>o&&o.length>0?o.map(v=>d.filter(y=>y.unitId===v)[0]).filter(v=>v!==void 0):d,[d,o]),p=D.useMemo(()=>{const v=[{type:"button",callback:()=>u(b=>b*1.3),title:"Increase box size",icon:R.jsx(sp,{})},{type:"button",callback:()=>u(b=>b/1.3),title:"Decrease box size",icon:R.jsx(ip,{})}],y={type:"toggle",subtype:"checkbox",callback:()=>h(b=>!b),title:"Show X Axis",selected:f===!0};return[...v,{type:"divider"},y]},[f]),_=30,m=Qu;return R.jsxs("div",{children:[R.jsxs(Jo,{width:e,height:n-_,initialPosition:m,adjustable:!1,children:[R.jsx(Ju,{width:m,height:n,customActions:p}),R.jsx(tp,{width:0,height:0,children:R.jsx(ep,{plots:g,plotComponent:gD,selectedPlotKeys:r.onlyShowSelected?void 0:s})})]}),R.jsx("div",{style:{position:"absolute",top:n-_,height:_,overflow:"hidden"},children:R.jsx(tf,{options:r,setOptions:i})})]})},Jp=t=>{const[e,n]=D.useState(t?.stateRef.current),r=t?.stateRef,i=t?.onChange;return D.useEffect(()=>{n(r?.current);const s=i?.(o=>{n(o)});return()=>{s&&s()}},[i,r]),e===void 0?{state:void 0,dispatch:void 0}:{state:e,dispatch:t?.dispatch}},UH=(t,e,n)=>{const{state:r,dispatch:i}=Jp(t?.figureAnnotations);D.useEffect(()=>{i&&n&&i({type:"reportViewWithAnnotations"})},[i,n]);const s=D.useMemo(()=>r?.annotations[e],[r,e]),o=D.useMemo(()=>r?.editingAnnotations?(a,l)=>{i&&i({type:"setAnnotation",path:e,key:a,value:l})}:void 0,[i,e,r?.editingAnnotations]);return{annotations:s,setAnnotation:o}},LH=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null);return D.useEffect(()=>{let o=!1;return(async()=>{const l=[],c=t.attrs.num_autocorrelograms||0;if(c===0){o||s({type:"Autocorrelograms",autocorrelograms:[]});return}const u=await t.getDatasetData("bin_edges_sec",{}),f=await t.getDatasetData("bin_counts",{});if(!u||!f){console.error("Failed to load autocorrelograms data");return}const h=Array.from(u),d=new Int32Array(f),g=h.length-1,p=t.attrs.autocorrelograms;for(let _=0;_<c;_++){const m=p[_],v=_*g,y=Array.from(d.slice(v,v+g));l.push({unitId:m.unit_id,binEdgesSec:h,binCounts:y})}o||s({type:"Autocorrelograms",autocorrelograms:l})})(),()=>{o=!0}},[t]),i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(kH,{data:i,width:n,height:r})}):R.jsx("div",{children:"Loading..."})},ui=({context:t,children:e})=>{const{state:n,dispatch:r}=Jp(t);return!r||!n?R.jsx(R.Fragment,{children:"Waiting for context..."}):R.jsx(g3.Provider,{value:{unitSelection:n,unitSelectionDispatch:r},children:e})},zH=t=>{const{unitId:e,mergeGroup:n}=t,r=ci(Nt(e)),i=n?n.map(s=>`${s}`).join(", "):"";return R.jsxs("span",{children:[R.jsx("div",{className:"unitLabel",style:{backgroundColor:r}})," ",`${e}`,n&&n.length>0&&R.jsx("span",{children:` (${i})`},"mergeGroup")]})},$H=(t,e)=>((e||{}).mergeGroups||[]).filter(r=>r.includes(t))[0]||null,VH=t=>{const{selectedUnitIds:e,currentUnitId:n,selectionDispatch:r,rows:i,columns:s,orderedUnitIds:o,visibleUnitIds:a,primarySortRule:l,height:c,selectionDisabled:u,hideSelectionColumn:f}=t,[h,d]=D.useState(l),g=D.useMemo(()=>a&&a.length>0?a:o,[a,o]),p=D.useMemo(()=>a3({selectedUnitIds:e,orderedUnitIds:o,visibleUnitIds:g}),[e,o,g]),_=D.useCallback((b,w)=>{const x=h?.columnName===b?!h?.sortAscending:!0;d({columnName:b,sortAscending:x}),r&&r({type:"UPDATE_SORT_FIELDS",newSortField:b,ascending:x})},[h,r]),m=D.useCallback(()=>{r&&r(p==="all"?{type:"DESELECT_ALL"}:{type:"TOGGLE_SELECT_ALL"})},[p,r]),v=D.useMemo(()=>{const b=g.map(x=>i.get(x)).filter(x=>x!==void 0);if(!h)return b;const w=s.find(x=>x.columnName===h.columnName);return w?[...b].sort((x,S)=>{const A=x.data[h.columnName]?.sortValue,E=S.data[h.columnName]?.sortValue,C=w.sort(A,E);return h.sortAscending?C:-C}):b},[g,i,h,s]),y=b=>h?.columnName!==b?"":h.sortAscending?"↑":"↓";return R.jsx("div",{className:"compact-table-container",style:{height:c?`${c}px`:"100%",overflow:"auto"},children:R.jsxs("table",{className:"compact-table",children:[R.jsx("thead",{children:R.jsxs("tr",{children:[!f&&R.jsx("th",{className:"compact-table-header",children:R.jsx("input",{type:"checkbox",checked:p==="all",ref:b=>{b&&(b.indeterminate=p==="partial")},onChange:m,disabled:u})}),s.map(b=>R.jsxs("th",{className:"compact-table-header",onClick:()=>_(b.columnName,b),title:b.tooltip,style:{cursor:"pointer"},children:[b.label,R.jsx("span",{className:"sort-indicator",children:y(b.columnName)})]},b.columnName))]})}),R.jsx("tbody",{children:v.map(b=>R.jsxs("tr",{className:`compact-table-row ${e.has(b.rowId)?"selected":""} ${n===b.rowId?"current":""}`,children:[!f&&R.jsx("td",{className:"compact-table-cell",children:R.jsx("input",{type:"checkbox",checked:e.has(b.rowId),onChange:w=>{b.checkboxFn&&b.checkboxFn(w)},disabled:u})}),s.map(w=>R.jsx("td",{className:"compact-table-cell",children:w.dataElement(b.data[w.columnName]?.value)},w.columnName))]},b.rowId))})]})})},jH={},eg=(t,e)=>{if(e.type!=="REOPEN_CURATION"&&t.isClosed&&console.log(`WARNING: Applying curation action to a closed sorting curation:
|
|
191
|
-
Action: ${e.type}`),e.type==="SET_CURATION")return e.curation;if(e.type==="CLOSE_CURATION")return{...t,isClosed:!0};if(e.type==="REOPEN_CURATION")return{...t,isClosed:!1};if(e.type==="ADD_UNIT_LABEL"){const n=typeof e.unitId=="object"?e.unitId:[e.unitId],r={...t.labelsByUnit||{}};let i=!1;for(const s of n){const o=r[s+""]||[];o.includes(e.label)||(i=!0,r[s+""]=[...o,e.label].sort())}return i?{...t,labelsByUnit:r}:t}else if(e.type==="TOGGLE_UNIT_LABEL"){const n=typeof e.unitId=="object"?e.unitId:[e.unitId];let r=!0;for(const i of n)((t.labelsByUnit||{})[i+""]||[]).includes(e.label)||(r=!1);return r?eg(t,{type:"REMOVE_UNIT_LABEL",unitId:e.unitId,label:e.label}):eg(t,{type:"ADD_UNIT_LABEL",unitId:e.unitId,label:e.label})}else if(e.type==="REMOVE_UNIT_LABEL"){const n=typeof e.unitId=="object"?e.unitId:[e.unitId],r={...t.labelsByUnit||{}};let i=!1;for(const s of n){const o=r[s+""]||[];o.includes(e.label)&&(i=!0,r[s+""]=o.filter(a=>a!==e.label))}return i?{...t,labelsByUnit:r}:t}else{if(e.type==="MERGE_UNITS")return{...t,mergeGroups:vD([...t.mergeGroups||[],e.unitIds])};if(e.type==="UNMERGE_UNITS")return{...t,mergeGroups:vD((t.mergeGroups||[]).map(n=>n.filter(r=>!e.unitIds.includes(r))))};if(e.type==="SET_LABEL_CHOICES")return{...t,labelChoices:e.labelChoices}}return t},HH={sortingCuration:jH,sortingCurationDispatch:t=>{console.warn("No sortingCurationDispatch function provided.")},curating:!1},mD=ln.createContext(HH),yD=()=>{const t=D.useContext(mD);if(!t)throw Error("useSortingCuration must be used within a SortingCurationContext.Provider");return t},WH=(t,e)=>t.filter(n=>e.includes(n)),XH=(t,e)=>[...t,...e.filter(n=>!t.includes(n))].sort(),vD=t=>{const e=t.map(r=>[...r]);let n=!0;for(;n;){n=!1;for(let r=0;r<e.length;r++){const i=e[r];for(let s=r+1;s<e.length;s++){const o=e[s];WH(i,o).length>0&&(e[r]=XH(i,o),e[s]=[],n=!0)}}}return e.filter(r=>r.length>=2)},_D=({data:t,width:e,height:n})=>{const[r,i]=D.useState({...ef,onlyShowSelected:!1}),{selectedUnitIds:s,currentUnitId:o,orderedUnitIds:a,visibleUnitIds:l,primarySortRule:c,checkboxClickHandlerGenerator:u,unitIdSelectionDispatch:f}=Vr(),{sortingCuration:h}=yD(),d=D.useMemo(()=>r.onlyShowSelected?l?l.filter(w=>s.has(w)):[...s]:l,[l,s,r.onlyShowSelected]),g=D.useMemo(()=>{const w=[];return w.push({columnName:"_unitId",label:"Unit",tooltip:"Unit ID",sort:(x,S)=>Nt(x)-Nt(S),dataElement:x=>R.jsx(zH,{unitId:x.unitId,mergeGroup:x.mergeGroup}),calculating:!1}),h&&w.push({columnName:"_labels",label:"Labels",tooltip:"Curation labels",sort:(x,S)=>x<S?-1:x>S?1:0,dataElement:x=>R.jsx("span",{children:x.join(", ")}),calculating:!1}),t.similarityScores&&w.push({columnName:"_similarity",label:"Similarity",tooltip:"Similarity with current unit",sort:(x,S)=>{if(x.unitId===o)return 1;if(S.unitId===o)return-1;const A=x.score,E=S.score;return A===void 0&&E!==void 0?-1:A!==void 0&&E===void 0?1:A===void 0&&E===void 0?0:A!==void 0&&E!==void 0?A<E?-1:A>E?1:0:0},dataElement:x=>R.jsx("span",{children:x}),calculating:!1,onlyAllowDescendingSort:!0}),t.columns.filter(x=>x.key!=="unitId").forEach(x=>{w.push({columnName:x.key,label:x.label,tooltip:x.label,sort:x.dtype==="str"?(S,A)=>S<A?-1:S>A?1:0:x.dtype==="int"?(S,A)=>S-A:x.dtype=="bool"?(S,A)=>(S?1:0)-(A?1:0):x.dtype==="float"?(S,A)=>S-A:(S,A)=>S-A,dataElement:S=>R.jsx("span",{children:S}),calculating:!1})}),w},[t.columns,o,h,t.similarityScores]),p=D.useMemo(()=>{for(let x=0;x<0;x++)a.push("never-added");const w={};if(t.similarityScores&&o!==void 0)for(const x of t.similarityScores)x.unitId1===o?w[x.unitId2]=x.similarity:x.unitId2===o&&(w[x.unitId1]=x.similarity);return t.rows.map(x=>{const S=(h?.labelsByUnit||{})[`${x.unitId}`]||[],A={value:{unitId:x.unitId,mergeGroup:$H(x.unitId,h)},sortValue:x.unitId},E=w[x.unitId],C={_unitId:A,_labels:{value:S,sortValue:S.join(", ")},_similarity:{value:E!==void 0?E.toFixed(3):void 0,sortValue:{unitId:x.unitId,score:E}}};for(const M of t.columns){const T=`${x.values[M.key]!==void 0?x.values[M.key]:""}`;C[M.key]={value:T,sortValue:x.values[M.key]}}return{rowId:x.unitId,data:C,checkboxFn:u(x.unitId)}})},[t.rows,t.columns,o,t.similarityScores,h,u,a]);D.useEffect(()=>{f({type:$o,newUnitOrder:si(p.map(w=>w.rowId))})},[p,f]);const _=D.useMemo(()=>{const w=new Map;return p.forEach(x=>w.set(x.rowId,x)),w},[p]),m=30,v=D.useMemo(()=>({width:e-20,height:n-m,top:0,position:"relative",overflowY:"auto"}),[e,n]),y=D.useCallback(w=>{if(w.ctrlKey)return w.key==="ArrowDown"?f({type:u3}):w.key==="ArrowUp"?f({type:f3}):w.key==="Home"?f({type:h3}):w.key==="End"&&f({type:d3}),!1},[f]),b=D.useCallback(()=>{f({type:"REDISTRIBUTE_UNIT_COLORS"})},[f]);return R.jsxs("div",{children:[R.jsx("div",{style:v,onKeyDown:y,children:R.jsx(VH,{columns:g,rows:_,orderedUnitIds:a,visibleUnitIds:d,selectedUnitIds:s,currentUnitId:o,selectionDispatch:f,primarySortRule:c})}),R.jsx("div",{style:{position:"absolute",top:n-m,height:m,overflow:"hidden"},children:R.jsx(tf,{options:r,setOptions:i,onRedistributeUnitColors:b})})]})},qH=({defaultLabelOptions:t,width:e,height:n})=>{const{selectedUnitIdsArray:r}=Vr(),{sortingCuration:i,sortingCurationDispatch:s,curating:o}=yD(),{labelChoices:a=[],labelsByUnit:l={},mergeGroups:c=[],isClosed:u=!1}=i,[f,h]=D.useState(""),[d,g]=D.useState(!1),p=D.useMemo(()=>a.length===0&&t.length>0&&o?(s({type:"SET_LABEL_CHOICES",labelChoices:t}),t):a,[a,t,s,o]);D.useEffect(()=>{},[p]);const _=D.useCallback(V=>{if(r.length===0)return"none";const G=r.filter(z=>(l[z.toString()]||[]).includes(V));return G.length===0?"none":G.length===r.length?"full":"partial"},[r,l]),m=D.useCallback(V=>{o&&(r.length===0||u||s({type:"TOGGLE_UNIT_LABEL",unitId:r,label:V}))},[r,u,s,o]),v=D.useCallback(()=>{if(!o)return;const V=f.trim();V&&!p.includes(V)&&(s({type:"SET_LABEL_CHOICES",labelChoices:[...p,V]}),h(""))},[f,p,s,o]),y=D.useCallback(V=>Object.values(l).some(G=>G.includes(V)),[l]),b=D.useCallback(V=>{o&&(y(V)||s({type:"SET_LABEL_CHOICES",labelChoices:p.filter(G=>G!==V)}))},[p,s,y,o]),w=D.useCallback(V=>c.find(G=>G.includes(V)),[c]),x=D.useMemo(()=>{if(r.length===0)return{canMerge:!1,canUnmerge:!1,groupsInvolved:[],unmergedUnits:[]};const V=new Set,G=[];r.forEach(ee=>{const ce=w(ee);ce?V.add(ce):G.push(ee)});const z=r.length>=2,Q=V.size>0;return{canMerge:z,canUnmerge:Q,groupsInvolved:Array.from(V),unmergedUnits:G}},[r,w]),S=D.useCallback(()=>{o&&(r.length<2||u||s({type:"MERGE_UNITS",unitIds:r}))},[r,u,s,o]),A=D.useCallback(()=>{o&&(r.length===0||u||s({type:"UNMERGE_UNITS",unitIds:r}))},[r,u,s,o]),E=D.useCallback(()=>{o&&s(u?{type:"REOPEN_CURATION"}:{type:"CLOSE_CURATION"})},[u,s,o]),C=D.useMemo(()=>r.length===0?"No units selected":r.length<=5?`Units: ${r.join(", ")}`:`${r.length} units selected`,[r]),M={width:e,height:n,padding:"8px",fontSize:"12px",fontFamily:"Arial, sans-serif",border:"1px solid #ddd",borderRadius:"4px",backgroundColor:"#fafafa",overflow:"auto",display:"flex",flexDirection:"column",gap:"8px"},T={marginBottom:"6px"},P={fontWeight:"bold",marginBottom:"4px",fontSize:"11px",color:"#333"},I={display:"inline-flex",alignItems:"center",padding:"2px 6px",margin:"2px",backgroundColor:"#e0e0e0",borderRadius:"12px",fontSize:"10px",border:"1px solid #ccc"},k={marginLeft:"4px",cursor:"pointer",color:"#666",fontWeight:"bold"},O={padding:"2px 4px",fontSize:"10px",border:"1px solid #ccc",borderRadius:"2px",marginRight:"4px",flex:1},L={padding:"2px 6px",fontSize:"10px",border:"1px solid #ccc",borderRadius:"2px",backgroundColor:"#f0f0f0",cursor:"pointer"},U={display:"inline-flex",alignItems:"center",margin:"2px 8px 2px 0",cursor:r.length>0&&!u?"pointer":"default",opacity:r.length>0&&!u?1:.5},$={...T,textAlign:"center"},J={...L,backgroundColor:u?"#f8d7da":"#d4edda",borderColor:u?"#f5c6cb":"#c3e6cb",color:u?"#721c24":"#155724"},ne={display:"flex",alignItems:"center",cursor:"pointer",fontSize:"11px",fontWeight:"bold",color:"#333",marginBottom:"4px"},j={marginRight:"4px",fontSize:"10px",transform:d?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s"};return R.jsxs("div",{style:M,children:[R.jsxs("div",{style:T,children:[R.jsx("div",{style:P,children:"Selected Units"}),R.jsx("div",{style:{fontSize:"10px",color:"#666"},children:C})]}),R.jsxs("div",{style:T,children:[R.jsx("div",{style:P,children:"Label Assignment"}),p.map(V=>{const G=_(V);return R.jsxs("div",{style:U,onClick:o?()=>m(V):void 0,children:[R.jsx("input",{type:"checkbox",checked:G==="full",ref:z=>{z&&(z.indeterminate=G==="partial")},onChange:()=>{},style:{marginRight:"4px"},disabled:r.length===0||u}),R.jsx("span",{style:{fontSize:"10px"},children:V})]},V)}),r.length===0&&R.jsx("div",{style:{fontSize:"10px",color:"#999",fontStyle:"italic"},children:"Select units to assign labels"})]}),R.jsxs("div",{style:T,children:[R.jsx("div",{style:P,children:"Unit Merging"}),r.length>0&&x.groupsInvolved.length>0&&R.jsxs("div",{style:{marginBottom:"6px"},children:[R.jsx("div",{style:{fontSize:"10px",color:"#666",marginBottom:"2px"},children:"Merge groups involving selected units:"}),x.groupsInvolved.map((V,G)=>{const z={...I,backgroundColor:"#e3f2fd",borderColor:"#90caf9",color:"#1565c0"};return R.jsx("span",{style:z,children:V.join(", ")},G)})]}),R.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center",flexWrap:"wrap"},children:[R.jsx("button",{onClick:o?S:void 0,style:{...L,backgroundColor:x.canMerge&&!u?"#d4edda":"#f8f9fa",borderColor:x.canMerge&&!u?"#c3e6cb":"#dee2e6",color:x.canMerge&&!u?"#155724":"#6c757d",cursor:x.canMerge&&!u?"pointer":"default"},disabled:!x.canMerge||u,title:u?"Cannot merge when curation is closed":r.length<2?"Select 2 or more units to merge":"Merge selected units",children:"Merge Selected"}),R.jsx("button",{onClick:o?A:void 0,style:{...L,backgroundColor:x.canUnmerge&&!u?"#fff3cd":"#f8f9fa",borderColor:x.canUnmerge&&!u?"#ffeaa7":"#dee2e6",color:x.canUnmerge&&!u?"#856404":"#6c757d",cursor:x.canUnmerge&&!u?"pointer":"default"},disabled:!x.canUnmerge||u,title:u?"Cannot unmerge when curation is closed":x.canUnmerge?"Unmerge selected units":"Select units that are part of merge groups to unmerge",children:"Unmerge Selected"})]}),r.length>0&&R.jsxs("div",{style:{fontSize:"10px",color:"#666",marginTop:"4px"},children:[x.groupsInvolved.length>0&&R.jsxs("div",{children:["Selected units in"," ",x.groupsInvolved.length," merge group(s)"]}),x.unmergedUnits.length>0&&R.jsxs("div",{children:[x.unmergedUnits.length," unmerged unit(s) selected"]})]}),r.length===0&&R.jsx("div",{style:{fontSize:"10px",color:"#999",fontStyle:"italic",marginTop:"4px"},children:"Select units to merge or unmerge"})]}),R.jsxs("div",{style:T,children:[R.jsxs("div",{style:ne,onClick:()=>g(!d),children:[R.jsx("span",{style:j,children:"▶"}),"Manage Label Choices"]}),d&&R.jsxs("div",{children:[R.jsx("div",{style:{marginBottom:"4px"},children:p.map(V=>{const G=y(V);return R.jsxs("span",{style:I,children:[V,!u&&!G&&R.jsx("span",{style:k,onClick:o?()=>b(V):void 0,title:"Remove label choice",children:"×"})]},V)})}),!u&&R.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[R.jsx("input",{type:"text",value:f,onChange:V=>h(V.target.value),onKeyPress:V=>V.key==="Enter"&&o&&v(),placeholder:"Add label...",style:O}),R.jsx("button",{onClick:o?v:void 0,style:L,disabled:!f.trim(),children:"Add"})]})]})]}),R.jsxs("div",{style:$,children:[R.jsx("button",{onClick:o?E:void 0,style:J,children:u?"Reopen Curation":"Finalize Curation"}),R.jsxs("div",{style:{fontSize:"10px",color:"#666",marginTop:"2px"},children:["Status: ",u?"Closed":"Open"]})]})]})},YH=({zarrGroup:t,contexts:e,width:n,height:r})=>R.jsx(ui,{context:e.unitSelection,children:R.jsx(bD,{contexts:e,editable:!0,children:R.jsx(KH,{zarrGroup:t,contexts:e,width:n,height:r})})}),KH=({zarrGroup:t,width:e,height:n})=>{const r=t.attrs.default_label_options||[];return R.jsx(qH,{defaultLabelOptions:r,width:e,height:n})},bD=({contexts:t,children:e,editable:n})=>{const{annotations:r,setAnnotation:i}=UH(t,"/",n),s=D.useMemo(()=>{try{return JSON.parse(r?.sorting_curation||"{}")}catch(a){return console.error("Error parsing sorting_curation:",a),{}}},[r]),o=D.useMemo(()=>a=>{if(!i)return;const l=eg(s,a);i("sorting_curation",JSON.stringify(l))},[i,s]);return R.jsx(mD.Provider,{value:{sortingCuration:s,sortingCurationDispatch:o,curating:!!i},children:e})},ZH=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.columns||[],d=await t.getDatasetData("rows_data",{});if(!d||d.length===0)throw new Error("Empty rows data");const g=new Uint8Array(d),p=new TextDecoder("utf-8").decode(g),_=JSON.parse(p);let m;try{const v=await t.getDatasetData("similarity_scores_data",{});if(v&&v.length>0){const y=new Uint8Array(v),b=new TextDecoder("utf-8").decode(y);m=JSON.parse(b)}}catch(v){console.warn("No similarity scores data found: "+v)}if(u)return;s({type:"UnitsTable",columns:h,rows:_,similarityScores:m})}catch(h){console.error("Error loading units table data:",h),a(`Failed to load units table data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading units table data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(bD,{contexts:e,editable:!1,children:R.jsx(_D,{data:i,width:n,height:r})})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No units table data available"})},GH=t=>{const{ampScaleFactor:e,setAmpScaleFactor:n}=t,r=()=>{n(e*1.2)},i=()=>{n(e/1.2)},s=()=>{n(1)};return[{type:"button",callback:r,title:"Scale amplitude up [shift + mouse-wheel]",icon:R.jsx(b9,{}),keyCode:38},{type:"button",callback:s,title:"Reset scale amplitude",icon:R.jsx($E,{})},{type:"button",callback:i,title:"Scale amplitude down [shift + mouse-wheel]",icon:R.jsx(y9,{}),keyCode:40}]},xD={forward:[[1,0,0],[0,1,0]],inverse:[[1,0,0],[0,1,0]]},fi=(t,e)=>({x:e.x*t.forward[0][0]+e.y*t.forward[0][1]+t.forward[0][2],y:e.x*t.forward[1][0]+e.y*t.forward[1][1]+t.forward[1][2]}),jl=(t,e)=>({x:e.x*t.inverse[0][0]+e.y*t.inverse[0][1]+t.inverse[0][2],y:e.x*t.inverse[1][0]+e.y*t.inverse[1][1]+t.inverse[1][2]}),QH=(t,e)=>({forward:wD(t.forward,e.forward),inverse:wD(e.inverse,t.inverse)}),JH=t=>({forward:[...t.map(e=>[...e])],inverse:tW(t)}),eW=t=>({forward:t.inverse,inverse:t.forward}),nf=t=>t.forward[0][0]*t.forward[1][1]-t.forward[0][1]*t.forward[1][0],wD=(t,e)=>[[t[0][0]*e[0][0]+t[0][1]*e[1][0],t[0][0]*e[0][1]+t[0][1]*e[1][1],t[0][0]*e[0][2]+t[0][1]*e[1][2]+t[0][2]],[t[1][0]*e[0][0]+t[1][1]*e[1][0],t[1][0]*e[0][1]+t[1][1]*e[1][1],t[1][0]*e[0][2]+t[1][1]*e[1][2]+t[1][2]]],tW=t=>{const e=[[t[0][0],t[0][1]],[t[1][0],t[1][1]]],n=[t[0][2],t[1][2]],r=e[0][0]*e[1][1]-e[0][1]*e[1][0],i=[[e[1][1]/r,-e[0][1]/r],[-e[1][0]/r,e[0][0]/r]],s=[i[0][0]*n[0]+i[0][1]*n[1],i[1][0]*n[0]+i[1][1]*n[1]];return[[i[0][0],i[0][1],-s[0]],[i[1][0],i[1][1],-s[1]]]},nW={paddingLeft:6,paddingRight:6,paddingTop:0,paddingBottom:0},rW=({hoveredInfo:t,onSelectSimilarUnits:e})=>R.jsxs("span",{children:[e&&R.jsx(Vl,{style:nW,onClick:e,title:"Select similar units",children:"all"}),t?R.jsxs("span",{children:["Units ",t.unitId1,"/",t.unitId2," |"," ",t.value!==void 0?`value: ${t.value}`:""]}):R.jsx("span",{})]}),rf=(t,e,n={})=>{const r=n.shift!==void 0?n.shift:!0,i=n.shift!==void 0?n.alt:!1,[s,o]=D.useState(xD),a=D.useCallback(l=>{if(r&&!l.shiftKey||!r&&l.shiftKey||i&&!l.altKey||!i&&l.altKey)return;const c=l.currentTarget.getBoundingClientRect(),u={x:l.clientX-c.x,y:l.clientY-c.y},f=l.deltaY,h=1.3;let d=JH([[h,0,(1-h)*u.x],[0,h,(1-h)*u.y]]);f>0&&(d=eW(d));let g=QH(d,s);const p=fi(g,{x:0,y:0}),_=fi(g,{x:t,y:e});return 0<=p.x&&p.x<t&&0<=p.y&&p.y<e&&0<=_.x&&_.x<t&&0<=_.y&&_.y<e&&(g=xD),o(g),!1},[s,e,t,r,i]);return{affineTransform:s,handleWheel:a}},iW=({unitIds1:t,unitIds2:e,selectedUnitIds:n,onSetSelectedUnitIds:r,matrix:i,range:s,setHoveredInfo:o,width:a,height:l})=>{const c=Math.min(a,l),u=(a-c)/2,f=(l-c)/2,{affineTransform:h,handleWheel:d}=rf(a,l,{shift:!0,alt:!1}),g=D.useMemo(()=>b=>fi(h,{x:u+b.i1/t.length*c,y:f+b.i2/e.length*c}),[t.length,e.length,c,u,f,h]),p=D.useMemo(()=>b=>{const w=jl(h,b),x=Math.floor((w.x-u)/c*t.length),S=Math.floor((w.y-f)/c*e.length);return 0<=x&&x<t.length&&0<=S&&S<e.length?{i1:x,i2:S}:void 0},[t.length,e.length,c,u,f,h]),_=D.useCallback(b=>{b.clearRect(0,0,a,l),b.fillStyle="rgb(100, 100, 80)";const w=g({i1:0,i2:0}),x=g({i1:t.length,i2:e.length});b.fillRect(w.x,w.y,x.x-w.x,x.y-w.y),t.forEach((S,A)=>{e.forEach((E,C)=>{const{x:M,y:T}=g({i1:A,i2:C}),{x:P,y:I}=g({i1:A+1,i2:C+1}),k=SD(i[A][C],s,!1);b.fillStyle=k;const O=P-M>=10?3:P-M>=6?2:P-M>=4?1:0;if(b.fillRect(M,T,P-M-O,I-T-O),n.has(S)&&n.has(E)){const L=SD(i[A][C],s,!0);b.strokeStyle=L,b.lineWidth=O,b.strokeRect(M,T,P-M-O,I-T-O)}})})},[g,i,t,e,n,a,l,s]),m=D.useCallback(b=>{const w=b.currentTarget.getBoundingClientRect(),x={x:b.clientX-w.x,y:b.clientY-w.y},S=p(x);S&&r([t[S.i1],e[S.i2]])},[r,t,e,p]),v=D.useCallback(b=>{const w=b.currentTarget.getBoundingClientRect(),x={x:b.clientX-w.x,y:b.clientY-w.y},S=p(x);o(S?{unitId1:t[S.i1],unitId2:e[S.i2],value:i[S.i1][S.i2]}:void 0)},[p,i,o,t,e]),y=D.useCallback(()=>{o(void 0)},[o]);return R.jsx("div",{style:{width:a,height:l,position:"relative"},onMouseDown:m,onWheel:d,onMouseMove:v,onMouseLeave:y,children:R.jsx(qn,{width:a,height:l,draw:_,drawData:null})})},SD=(t,e,n)=>{if(isNaN(t))return n?"rgb(0, 0, 255)":"rgb(50, 20, 0)";const r=Math.min(255,Math.max(0,Math.floor((t-e[0])/(e[1]-e[0])*255))),i=Math.min(255,Math.max(0,255-r-30));return n?`rgb(${i}, ${i}, 255)`:`rgb(${r}, ${r}, ${r})`},sW=[0,1],oW=({data:t,width:e,height:n})=>{const{selectedUnitIds:r,visibleUnitIds:i,unitIdSelectionDispatch:s}=Vr(),[o,a]=D.useState(void 0);D.useEffect(()=>{s({type:$o,newUnitOrder:si(t.unitIds)})},[t.unitIds,s]);const l=D.useMemo(()=>t.unitIds.filter(g=>!i||i.includes(g)),[t.unitIds,i]),c=D.useMemo(()=>{const g={};return l.forEach((p,_)=>{g[p]=_}),g},[l]),u=D.useMemo(()=>{const g=[];l.forEach(()=>{const p=[];l.forEach(()=>{p.push(NaN)}),g.push(p)});for(const p of t.similarityScores){const _=c[p.unitId1],m=c[p.unitId2];g[_][m]=p.similarity}return g},[c,l,t.similarityScores]),f=D.useCallback(g=>{s({type:"SET_SELECTION",incomingSelectedUnitIds:g})},[s]),h=D.useCallback(()=>{const g=[...r][0];if(!g)return;const p=c[g],_=[];for(let v=0;v<l.length;v++)if(v!==p){const y=u[p][v];isNaN(y)||_.push({id:l[v],similarity:y})}_.sort((v,y)=>y.similarity-v.similarity);const m=[g,..._.slice(0,4).map(v=>v.id)];s({type:"SET_SELECTION",incomingSelectedUnitIds:m})},[c,r,u,s,l]),d=20;return R.jsxs("div",{children:[R.jsx("div",{style:{position:"absolute",height:n-d,width:e},children:R.jsx(iW,{unitIds1:l,unitIds2:l,selectedUnitIds:r,onSetSelectedUnitIds:f,matrix:u,range:t.range||sW,setHoveredInfo:a,width:e,height:n-d})}),R.jsx("div",{style:{position:"absolute",top:n-d,height:d,width:e},children:R.jsx(rW,{hoveredInfo:o,onSelectSimilarUnits:r.size===1?h:void 0})})]})},ea={border:"rgb(30, 30, 30)",base:"rgb(0, 0, 255)",selected:"rgb(50, 200, 50)",hover:"rgb(128, 128, 255)",selectedHover:"rgb(200, 200, 196)",dragged:"rgb(0, 0, 196)",draggedSelected:"rgb(180, 180, 150)",dragRect:"rgba(196, 196, 196, 0.5)",textLight:"rgb(228, 228, 228)",textDark:"rgb(32, 32, 32)"},aW=2*Math.PI,lW=(t,e)=>{const{layoutMode:n,affineTransform:r}=e;if(t.save(),r){const i=r.forward;t.transform(i[0][0],i[1][0],i[0][1],i[1][1],i[0][2],i[1][2])}n==="geom"?uW(t,e):cW(t,e),t.restore()},cW=(t,e)=>{const{pixelElectrodes:n,pixelRadius:r,showLabels:i,xMargin:s}=e,o=r>5&&i,a=e.colors??ea,l=o?2*r:0;t.clearRect(0,0,t.canvas.width,t.canvas.height);const c=s+l,u=t.canvas.width-s;if(t.beginPath(),n.forEach(f=>{t.moveTo(c,f.pixelY),t.lineTo(u,f.pixelY)}),t.strokeStyle=a.border,t.stroke(),o){const f=c-.5*r;t.font=`${r-3}px Arial`,t.fillStyle=a.textDark,t.textAlign="right",t.textBaseline="middle",n.forEach(h=>{t.fillText(`${h.e.label}`,f,h.pixelY)})}},uW=(t,e)=>{const{pixelElectrodes:n,selectedElectrodeIds:r,hoveredElectrodeId:i,draggedElectrodeIds:s,pixelRadius:o,showLabels:a,offsetLabels:l}=e,c=o>5&&a,u=e.colors??ea,f=n.map(h=>{const d=r.includes(h.e.id),g=(i??-1)===h.e.id,p=s.includes(h.e.id),_=d?p?u.draggedSelected:g?u.selectedHover:u.selected:p?u.dragged:g?u.hover:u.base;return{...h,color:_,textColor:d||g&&!p?u.textDark:u.textLight}});if(t.clearRect(0,0,t.canvas.width,t.canvas.height),f.forEach(h=>{t.fillStyle=h.color,t.beginPath(),t.ellipse(h.pixelX,h.pixelY,o,o,0,0,aW),t.fill()}),c){t.font=`${o}px Arial`,t.textAlign=l?"right":"center",t.textBaseline="middle";const h=l?1.4*o:0;f.forEach(d=>{t.fillStyle=l?u.textDark:d.textColor,t.fillText(`${d.e.label}`,d.pixelX-h,d.pixelY)})}},tg=t=>t.reduce((e,n)=>e<=n?e:n,1/0),ng=t=>t.reduce((e,n)=>e>=n?e:n,-1/0),Hl=10,sf=10,TD=(t,e)=>{const n=e||{};return e&&(Object.keys(n).length!==t.length||t.some(i=>!n[`${i}`]))?(console.warn("Attempt to compute electrode locations with mismatched lists. Skipping..."),[]):t.map(i=>{const s=n[`${i}`]||[i,0];return{id:i,label:`${i}`,x:s[0],y:s[1]}})},AD=new Map,ED=t=>{const e=JSON.stringify(t),n=AD.get(e);if(n!==void 0)return n;let r=Number.MAX_VALUE;t.forEach(s=>{t.forEach(o=>{const a=CE([s.x-o.x,s.y-o.y]);a!==0&&(r=Math.min(r,a))})});const i=.45*r;return AD.set(e,i),i},CD=(t,e)=>({xmin:tg(t.map(n=>n.x))-e,xmax:ng(t.map(n=>n.x))+e,ymin:tg(t.map(n=>n.y))-e,ymax:ng(t.map(n=>n.y))+e}),fW=t=>{const e=ED(t),n=CD(t,e),r=Gd(n),i=DE(n),s={x:r/2+n.xmin,y:i/2+n.ymin};return{boxAspect:r/i,boxCenter:s}},hW=t=>{const e={xmin:tg(t.map(n=>n.x)),xmax:ng(t.map(n=>n.x)),ymin:tg(t.map(n=>n.y)),ymax:ng(t.map(n=>n.y))};return e.xmin===e.xmax&&e.ymin===e.ymax?t.map((n,r)=>({...n,x:r,y:0})):t},dW=(t,e)=>t9(n=>{const r=Hl+n[0]*(t-2*Hl),i=sf+n[1]*(e-2*sf);return[r,i]}),pW=(t,e)=>{const n=t.map((s,o)=>({e:s,ind:o})).sort((s,o)=>-s.e.y+o.e.y).map(s=>s.ind),r=[];for(let s=0;s<t.length;s++)r.push([0,0]);for(let s=0;s<n.length;s++){const o=n[s];r[o]=[.5,(.5+s)/(1+t.length)]}const i=Qv(e,r);return t.map((s,o)=>{const[a,l]=i[o];return{e:s,pixelX:a,pixelY:l}})},gW=(t,e,n,r,i)=>{const s=t-Hl*2,o=e-sf*2,a=Gd(i),l=DE(i);return Pz(s/a,o/l,r/n)},mW=(t,e,n,r)=>{const i=Gd(r),s=(t-i*n)/2,o=[n,0,s-r.xmin*n],a=[0,-n,(e+n*(r.ymin+r.ymax))/2];return[o,a,[0,0,1]]},yW=(t,e,n,r={})=>{const i=(t-Hl*2)/(e-sf*2),s=hW(n),{boxAspect:o}=fW(s);return r.disableAutoRotate||o===1||i===1||o>1==i>1?{electrodes:n,rotated:!1}:{electrodes:n.map(a=>({...a,x:a.y,y:-a.x})),rotated:!0}},vW=(t,e)=>{const n=t.map(i=>[i.x,i.y]),r=Qv(e,n);return t.map((i,s)=>{const[o,a]=r[s];return{e:i,pixelX:o,pixelY:a}})},DD=(t,e,n)=>{for(const r of t)if(CE([r.pixelX-n[0],r.pixelY-n[1]])<e)return r.e.id},MD=(t,e,n)=>{const r=e.xmin-n,i=e.xmax+n,s=e.ymin-n,o=e.ymax+n;return t.filter(a=>a.pixelX>r&&a.pixelX<i&&a.pixelY>s&&a.pixelY<o).map(a=>a.e.id)},rg=(t,e,n,r="geom",i=PD,s)=>{if(r==="vertical"){const p=dW(t,e),_=pW(n,p),m=(e-2*sf)/(1+n.length);return{transform:p,convertedElectrodes:_,pixelRadius:m}}const{electrodes:o,rotated:a}=yW(t,e,n,{disableAutoRotate:s.disableAutoRotate}),l=ED(o),c=CD(o,l),u=gW(t,e,l,i,c),f=l*u;let h=mW(t,e,u,c);const d=(t-Gd(c)*u)/2,g=vW(o,h);return a&&(h=[[-h[0][1],h[0][0],h[0][2]],[-h[1][1],h[1][0],h[1][2]],[-h[2][1],h[2][0],h[2][2]]]),{transform:h,convertedElectrodes:g,pixelRadius:f,xMargin:d}},RD={isActive:!1},_W=(t,e)=>{if(e.type==="INITIALIZE"){const{width:n,height:r,electrodes:i,layoutMode:s,maxElectrodePixelRadius:o}=e,{convertedElectrodes:a,pixelRadius:l,xMargin:c}=rg(n,r,i,s,o,{disableAutoRotate:e.disableAutoRotate});return{...t,convertedElectrodes:a,pixelRadius:l,draggedElectrodeIds:[],hoveredElectrodeId:void 0,dragState:RD,xMarginWidth:c??Hl}}else if(e.type==="DRAGUPDATE"){const n=Kz(t.dragState,e.dragAction);if(!n.isActive&&n.dragRect){const r=RE(n.dragRect),i=MD(t.convertedElectrodes,r,t.pixelRadius),s=e.dragAction.shift?[...i,...e.selectedElectrodeIds||[]]:i;return{...t,draggedElectrodeIds:[],hoveredElectrodeId:void 0,pendingSelectedElectrodeIds:s,dragState:RD}}else if(n.dragRect){const r=RE(n.dragRect),i=MD(t.convertedElectrodes,r,t.pixelRadius);return i.length===t.draggedElectrodeIds.length&&i.filter(s=>!t.draggedElectrodeIds.includes(s)).length===0?{...t,hoveredElectrodeId:void 0,dragState:n}:{...t,hoveredElectrodeId:void 0,draggedElectrodeIds:i,dragState:n}}else return{...t,dragState:n}}else if(e.type==="UPDATEHOVER"){const n=DD(t.convertedElectrodes,t.pixelRadius,e.point);return n===t.hoveredElectrodeId?t:{...t,hoveredElectrodeId:n}}else if(e.type==="UPDATECLICK"){const n=DD(t.convertedElectrodes,t.pixelRadius,e.point);if(n===void 0)return!(e.shift||e.ctrl)&&e.selectedElectrodeIds.length>0?{...t,pendingSelectedElectrodeIds:[]}:t;const r=e.ctrl?e.selectedElectrodeIds.includes(n)?e.selectedElectrodeIds.filter(i=>i!==n):[...e.selectedElectrodeIds,n]:e.shift?[...e.selectedElectrodeIds,n]:[n];return{...t,hoveredElectrodeId:void 0,pendingSelectedElectrodeIds:r}}else return console.log("Error: unrecognized verb in electrode geometry reducer."),t},ID=!1,PD=25,OD={showLabels:!0,maxElectrodePixelRadius:PD},bW=t=>{const e=t.currentTarget.getBoundingClientRect();return[t.clientX-e.x,t.clientY-e.y]},ND=()=>({selectedElectrodeIds:[],setSelectedElectrodeIds:t=>{}}),FD=t=>{const{width:e,height:n,electrodes:r,disableAutoRotate:i,affineTransform:s}=t,{selectedElectrodeIds:o,setSelectedElectrodeIds:a}=ND(),l=t.disableSelection??!1,c=t.offsetLabels??!1,u=t.colors??ea,f=t.layoutMode??"geom",h=t.maxElectrodePixelRadius||OD.maxElectrodePixelRadius,[d,g]=D.useReducer(_W,{convertedElectrodes:[],pixelRadius:-1,draggedElectrodeIds:[],pendingSelectedElectrodeIds:o||[],dragState:{isActive:!1},xMarginWidth:-1}),{affineTransform:p,handleWheel:_}=rf(e,n,{shift:!0,alt:!1}),m=D.useMemo(()=>{const C=d.convertedElectrodes.map(M=>{const T=fi(p,{x:M.pixelX,y:M.pixelY});return{...M,pixelX:T.x,pixelY:T.y}});return{...d,convertedElectrodes:C,pixelRadius:d.pixelRadius*Math.sqrt(nf(p))}},[p,d]),v=D.useMemo(()=>C=>{const M=bW(C),T=jl(p,{x:M[0],y:M[1]});return[T.x,T.y]},[p]);D.useEffect(()=>{g({type:"INITIALIZE",electrodes:r,width:e,height:n,maxElectrodePixelRadius:h,layoutMode:f,disableAutoRotate:i})},[e,n,r,f,h,i]),D.useEffect(()=>{a(d.pendingSelectedElectrodeIds)},[a,d.pendingSelectedElectrodeIds]);const y=D.useRef(null),b=D.useRef(0),w=l||R.jsx(e9,{width:e,height:n,newState:d.dragState}),x=D.useCallback(C=>{if(!Gz(C,{nextDragStateUpdate:y,nextFrame:b,reducer:g,reducerOtherProps:{type:"DRAGUPDATE"}})){const T=v(C);g({type:"UPDATEHOVER",point:T})}},[v]),S=D.useCallback(C=>{Qz(C,{nextDragStateUpdate:y,reducer:g,reducerOtherProps:{type:"DRAGUPDATE"}})},[]),A=D.useCallback(C=>{if(d.dragState.isActive)Jz(C,{nextDragStateUpdate:y,reducer:g,reducerOtherProps:{type:"DRAGUPDATE",selectedElectrodeIds:o}});else{const M=v(C);g({type:"UPDATECLICK",point:M,shift:C.shiftKey,ctrl:C.ctrlKey,selectedElectrodeIds:o||[]})}},[d.dragState.isActive,o,v]),E=D.useMemo(()=>{const C={pixelElectrodes:m.convertedElectrodes,selectedElectrodeIds:o||[],hoveredElectrodeId:d.hoveredElectrodeId,draggedElectrodeIds:d.draggedElectrodeIds,pixelRadius:m.pixelRadius,showLabels:t.showLabels??OD.showLabels,offsetLabels:c,layoutMode:t.layoutMode??"geom",xMargin:d.xMarginWidth,colors:u,affineTransform:s};return R.jsx(qn,{width:e,height:n,draw:lW,drawData:C})},[e,n,m.convertedElectrodes,o,d.hoveredElectrodeId,d.draggedElectrodeIds,m.pixelRadius,t.showLabels,c,t.layoutMode,d.xMarginWidth,u,s]);return D.useMemo(()=>ID,[d.convertedElectrodes,o,d.hoveredElectrodeId,d.draggedElectrodeIds,d.pixelRadius,t.showLabels,c,t.layoutMode,d.xMarginWidth,e,n,u]),R.jsxs("div",{style:{width:e,height:n,position:"relative"},onMouseMove:x,onMouseUp:A,onMouseDown:S,onWheel:_,children:[w,ID,E]})},xW=t=>1/t,ta=(t,e,n,r,i)=>{const s=[];return n.forEach((o,a)=>{for(const l of e){const c=l.electrodeIndices.indexOf(a);if(c>=0){let u;const f=l.waveformStdDev,h=l.waveformPercentiles;if(r==="normal"?u=l.waveform[c]:r==="lower"?u=f?l.waveform[c].map((d,g)=>l.waveform[c][g]-f[c][g]):void 0:r==="upper"?u=f?l.waveform[c].map((d,g)=>l.waveform[c][g]+f[c][g]):void 0:r==="percentile1"?u=h?l.waveform[c].map((d,g)=>h[0][c][g]):void 0:r==="percentile2"?u=h?l.waveform[c].map((d,g)=>h[1][c][g]):void 0:r==="percentile3"?u=h&&2<h.length?l.waveform[c].map((d,g)=>h[2][c][g]):void 0:r==="percentile4"&&(u=h&&3<h.length?l.waveform[c].map((d,g)=>h[3][c][g]):void 0),u){const d=u.map((p,_)=>[(u?.length||0)/2+(_-(u?.length||0)/2)*i,p]),g=Qv(t,d);s.push({pointsInPaintBox:g,offsetFromParentCenter:[o.pixelX,o.pixelY],color:l.waveformColors.base})}}}}),s},wW=(t,e)=>{const{pixelSpacePaths:n,pixelSpacePathsLower:r,pixelSpacePathsUpper:i,pixelSpacePathsPercentile1:s,pixelSpacePathsPercentile2:o,pixelSpacePathsPercentile3:a,pixelSpacePathsPercentile4:l,xMargin:c,waveformWidth:u,affineTransform:f,useUnitColors:h}=e;if(!n||n.length===0)return;if(t.resetTransform(),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.save(),f){const v=f.forward;t.transform(v[0][0],v[1][0],v[0][1],v[1][1],v[0][2],v[1][2])}t.translate(c,0);const d=t.getTransform();r&&i&&r.forEach((v,y)=>{const b=r[y],w=i[y];t.fillStyle="#dddddd",t.strokeStyle="#bbbbbb",t.lineWidth=1,t.translate(b.offsetFromParentCenter[0],b.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(b.pointsInPaintBox[0][0],b.pointsInPaintBox[0][1]);for(let x=0;x<b.pointsInPaintBox.length;x++)t.lineTo(b.pointsInPaintBox[x][0],b.pointsInPaintBox[x][1]);for(let x=w.pointsInPaintBox.length-1;x>=0;x--)t.lineTo(w.pointsInPaintBox[x][0],w.pointsInPaintBox[x][1]);t.fill(),t.stroke(),t.setTransform(d)});let g,p,_,m;s&&o&&a&&l?(g=s,p=o,_=a,m=l):s&&o&&!a&&!l?(g=void 0,p=s,_=o,m=void 0):(g=void 0,p=void 0,_=void 0,m=void 0),g&&g.length>0&&m&&m.length>0&&g.forEach((v,y)=>{if(!g||!m)throw Error("unexpected");const b=g[y],w=m[y];t.fillStyle="#dddddd",t.strokeStyle="#dddddd",t.lineWidth=1,t.translate(b.offsetFromParentCenter[0],b.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(b.pointsInPaintBox[0][0],b.pointsInPaintBox[0][1]);for(let x=0;x<b.pointsInPaintBox.length;x++)t.lineTo(b.pointsInPaintBox[x][0],b.pointsInPaintBox[x][1]);for(let x=w.pointsInPaintBox.length-1;x>=0;x--)t.lineTo(w.pointsInPaintBox[x][0],w.pointsInPaintBox[x][1]);t.fill(),t.stroke(),t.setTransform(d)}),p&&p.length>0&&p.length>0&&_&&_.length>0&&p.forEach((v,y)=>{if(!p||!_)throw Error("unexpected");const b=p[y],w=_[y];t.fillStyle="#bbbbbb",t.strokeStyle="#bbbbbb",t.lineWidth=1,t.translate(b.offsetFromParentCenter[0],b.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(b.pointsInPaintBox[0][0],b.pointsInPaintBox[0][1]);for(let x=0;x<b.pointsInPaintBox.length;x++)t.lineTo(b.pointsInPaintBox[x][0],b.pointsInPaintBox[x][1]);for(let x=w.pointsInPaintBox.length-1;x>=0;x--)t.lineTo(w.pointsInPaintBox[x][0],w.pointsInPaintBox[x][1]);t.fill(),t.stroke(),t.setTransform(d)}),n.forEach(v=>{t.strokeStyle=h?v.color:"black",t.lineWidth=u,t.translate(v.offsetFromParentCenter[0],v.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(v.pointsInPaintBox[0][0],v.pointsInPaintBox[0][1]),v.pointsInPaintBox.forEach(y=>{t.lineTo(y[0],y[1])}),t.stroke(),t.setTransform(d)}),t.restore()},SW=t=>{const{electrodes:e,waveforms:n,oneElectrodeHeight:r,oneElectrodeWidth:i,yScale:s,horizontalStretchFactor:o,width:a,height:l,layoutMode:c,waveformWidth:u,affineTransform:f,useUnitColors:h}=t;return D.useMemo(()=>{const g=n.length>0&&n[0].waveform.length>0?n[0].waveform[0].length:0,p=i/g,_=-i*(.5+1/g),m=s*r/2,v=Ze([[p,0,_],[0,-m,0],[0,0,1]]).toArray(),y=ta(v,n,e,"normal",o),b=ta(v,n,e,"lower",o),w=ta(v,n,e,"upper",o);let x=ta(v,n,e,"percentile1",o),S=ta(v,n,e,"percentile2",o),A=ta(v,n,e,"percentile3",o),E=ta(v,n,e,"percentile4",o);x.length===0&&(x=void 0),S.length===0&&(S=void 0),A.length===0&&(A=void 0),E.length===0&&(E=void 0);const C=c==="vertical"?(a-i)/2:0,M={pixelSpacePaths:y,pixelSpacePathsLower:b,pixelSpacePathsUpper:w,pixelSpacePathsPercentile1:x,pixelSpacePathsPercentile2:S,pixelSpacePathsPercentile3:A,pixelSpacePathsPercentile4:E,xMargin:C,waveformWidth:u,affineTransform:f,useUnitColors:h};return R.jsx(qn,{width:a,height:l,draw:wW,drawData:M})},[n,e,s,a,l,i,r,c,u,f,o,h])},TW={colors:{border:"rgb(120, 100, 120)",base:"rgb(240, 240, 240)",selected:"rgb(196, 196, 128)",hover:"rgb(128, 128, 255)",selectedHover:"rgb(200, 200, 196)",dragged:"rgb(0, 0, 196)",draggedSelected:"rgb(180, 180, 150)",dragRect:"rgba(196, 196, 196, 0.5)",textLight:"rgb(162, 162, 162)",textDark:"rgb(32, 150, 150)"}},AW=t=>{const e=t.colors??TW.colors,{electrodes:n,waveforms:r,ampScaleFactor:i,horizontalStretchFactor:s,layoutMode:o,hideElectrodes:a,width:l,height:c,showChannelIds:u,useUnitColors:f,waveformWidth:h,disableAutoRotate:d}=t,g=1e3,{handleWheel:p,affineTransform:_}=rf(l,c,{shift:!0,alt:!0}),m=D.useMemo(()=>R.jsx(FD,{electrodes:n,width:l,height:c,layoutMode:o,colors:e,showLabels:u,maxElectrodePixelRadius:g,disableSelection:!0,disableAutoRotate:d,affineTransform:_}),[n,l,c,o,e,u,d,_]),{convertedElectrodes:v,pixelRadius:y,xMargin:b}=rg(l,c,n,o,g,{disableAutoRotate:d}),w=b||Hl,x=D.useMemo(()=>xW(t.peakAmplitude),[t.peakAmplitude]),S=D.useMemo(()=>i*x,[i,x]),A=o==="geom"?y*2:c/n.length,E=o==="geom"?y*2:l-w-(u?2*y:0),C=R.jsx(SW,{electrodes:v,waveforms:r,oneElectrodeHeight:A,oneElectrodeWidth:E,horizontalStretchFactor:s,yScale:S,width:l,height:c,layoutMode:o,waveformWidth:h,affineTransform:_,useUnitColors:f});return R.jsxs("div",{style:{width:l,height:c,position:"relative"},onWheel:p,children:[!a&&m,C]})},EW=({allChannelIds:t,channelIds:e,units:n,layoutMode:r,hideElectrodes:i,channelLocations:s,samplingFrequency:o,peakAmplitude:a,ampScaleFactor:l,horizontalStretchFactor:c,showChannelIds:u,useUnitColors:f,showReferenceProbe:h,disableAutoRotate:d,width:g,height:p})=>{const _=D.useMemo(()=>{const w=s||{};return e.map(x=>({id:x,label:`${x}`,x:w[`${x}`]!==void 0?w[`${x}`][0]:Nt(x),y:w[`${x}`]!==void 0?w[`${x}`][1]:0}))},[e,s]),m=D.useMemo(()=>{const w=s||{};return t.map(x=>({id:x,label:`${x}`,x:w[`${x}`]!==void 0?w[`${x}`][0]:Nt(x),y:w[`${x}`]!==void 0?w[`${x}`][1]:0}))},[t,s]),v=g/4,y=D.useMemo(()=>n.map(w=>{const x={base:w.waveformColor},S=[];for(const A of w.channelIds)S.push(_.map(E=>E.id).indexOf(A));return{electrodeIndices:S,waveform:w.waveform,waveformStdDev:w.waveformStdDev,waveformPercentiles:w.waveformPercentiles,waveformColors:x}}),[_,n]),b=R.jsx(AW,{waveforms:y,electrodes:_,ampScaleFactor:l,horizontalStretchFactor:c,layoutMode:s?r:"vertical",hideElectrodes:i,width:h?g-v:g,height:p,showLabels:!0,peakAmplitude:a,samplingFrequency:o,showChannelIds:u,useUnitColors:f,waveformWidth:2,disableAutoRotate:d});return h?R.jsxs("div",{style:{position:"relative",width:g,height:p},children:[R.jsx("div",{style:{position:"absolute",left:0,top:0,width:v,height:p},children:R.jsx(FD,{electrodes:m,disableSelection:!1,width:v,height:p})}),R.jsx("div",{style:{position:"absolute",left:v,top:0,width:g-v,height:p},children:b})]}):b},CW=({data:t,width:e,height:n})=>{const r=D.useMemo(()=>{const z=[];for(const Q of t.averageWaveforms)for(const ee of Q.channelIds)z.includes(ee)||z.push(ee);return si(z)},[t.averageWaveforms]),[i,s]=D.useState({...ef,onlyShowSelected:!1}),{selectedUnitIds:o,currentUnitId:a,orderedUnitIds:l,plotClickHandlerGenerator:c,unitIdSelectionDispatch:u}=Vr(),[f,h]=D.useState(1),[d,g]=D.useState("geom"),[p,_]=D.useState(!0),[m,v]=D.useState(!1),[y,b]=D.useState(t.showReferenceProbe||!1),[w,x]=D.useState(!1),[S,A]=D.useState(1),[E,C]=D.useState(!0),[M,T]=D.useState(!0);D.useEffect(()=>{u({type:$o,newUnitOrder:si(t.averageWaveforms.map(z=>z.unitId))})},[t.averageWaveforms,u]);const[P,I]=D.useState(2),k=D.useMemo(()=>{let z=0;return t.averageWaveforms.forEach(Q=>{Q.waveform.forEach(ee=>{ee.forEach(ce=>{const se=Math.abs(ce);se>z&&(z=se)})})}),z},[t.averageWaveforms]),O=D.useMemo(()=>t.averageWaveforms.filter(z=>i.onlyShowSelected?o.has(z.unitId):!0).map(z=>{const Q=[{channelIds:z.channelIds,waveform:MW(z.waveform),waveformStdDev:p&&!w?z.waveformStdDev:void 0,waveformPercentiles:p&&!w&&z.waveformPercentiles?RW(z.waveformPercentiles,z.waveform):void 0,waveformColor:ci(Nt(z.unitId))}],ee={allChannelIds:r,channelIds:z.channelIds,units:Q,layoutMode:d,hideElectrodes:E,channelLocations:t.channelLocations,samplingFrequency:t.samplingFrequency,peakAmplitude:k,ampScaleFactor:f,horizontalStretchFactor:S,showChannelIds:m,useUnitColors:M,width:120*P+(y?120*P/4:0),height:120*P,showReferenceProbe:y,disableAutoRotate:!0};return{unitId:z.unitId,key:z.unitId,label:`Unit ${z.unitId}`,labelColor:ci(Nt(z.unitId)),clickHandler:i.onlyShowSelected?void 0:c(z.unitId),props:ee}}),[t.averageWaveforms,t.channelLocations,t.samplingFrequency,r,k,d,f,c,i.onlyShowSelected,o,P,p,m,y,w,S,E,M]),L=D.useMemo(()=>l?l.map(z=>O.filter(Q=>Q.unitId===z)[0]).filter(z=>z!==void 0):O,[O,l]),U=D.useMemo(()=>w?DW(L):L,[L,w]),$=D.useMemo(()=>[{type:"button",callback:()=>{A(z=>z*1.1)},title:"Increase horizontal stretch [alt + mouse-wheel]",icon:R.jsx(_9,{})},{type:"button",callback:()=>{A(1)},title:"Reset scale amplitude",icon:R.jsx($E,{})},{type:"button",callback:()=>{A(z=>z/1.1)},title:"Decrease horizontal stretch [alt + mouse-wheel]",icon:R.jsx(v9,{})}],[]),J=D.useMemo(()=>{const z=GH({ampScaleFactor:f,setAmpScaleFactor:h}),Q={type:"toggle",subtype:"checkbox",callback:()=>g(ve=>ve==="geom"?"vertical":"geom"),title:"Show electrode geometry",selected:d==="geom"},ee={type:"toggle",subtype:"checkbox",callback:()=>C(ve=>!ve),title:"Show electrodes",selected:!E},ce=[{type:"button",callback:()=>I(ve=>ve*1.3),title:"Increase box size",icon:R.jsx(sp,{})},{type:"button",callback:()=>I(ve=>ve/1.3),title:"Decrease box size",icon:R.jsx(ip,{})}],se={type:"toggle",subtype:"checkbox",callback:()=>_(ve=>!ve),title:"Show waveform stdev",selected:p===!0},ue={type:"toggle",subtype:"checkbox",callback:()=>v(ve=>!ve),title:"Show channel IDs",selected:m===!0},be={type:"toggle",subtype:"checkbox",callback:()=>b(ve=>!ve),title:"Show reference probes",selected:y===!0},le={type:"toggle",subtype:"checkbox",callback:()=>x(ve=>!ve),title:"Show overlapping",selected:w===!0},ye={type:"toggle",subtype:"checkbox",callback:()=>T(ve=>!ve),title:"Use unit colors",selected:M===!0};return[{type:"divider"},...ce,{type:"divider"},...z,{type:"divider"},...$,{type:"divider"},Q,ee,{type:"divider"},se,{type:"divider"},ue,{type:"divider"},be,{type:"divider"},le,{type:"divider"},ye]},[d,f,p,m,w,y,$,E,M]),ne=D.useCallback(z=>{z.shiftKey&&!z.altKey?z.deltaY<0?h(Q=>Q*1.3):h(Q=>Q/1.3):z.altKey&&!z.shiftKey&&(z.deltaY<0?A(Q=>Q*1.1):A(Q=>Q/1.1))},[]),j=30,V=D.useCallback(z=>{z&&z.addEventListener("wheel",Q=>{(Q.shiftKey||Q.altKey)&&Q.preventDefault()})},[]),G=Qu;return R.jsxs("div",{ref:z=>V(z),onWheel:ne,children:[R.jsxs(Jo,{width:e,height:n-j,initialPosition:G,adjustable:!1,children:[R.jsx(Ju,{width:G,height:n,customActions:J}),R.jsx(tp,{width:0,height:0,children:R.jsx(ep,{plots:U,plotComponent:EW,selectedPlotKeys:i.onlyShowSelected?void 0:o,currentPlotKey:a})})]}),R.jsx("div",{style:{position:"absolute",top:n-j,height:j,overflow:"hidden"},children:R.jsx(tf,{options:i,setOptions:s})})]})},DW=t=>{if(t.length===0)return t;const e={...t[0],props:{...t[0].props}},n=e.props;e.key="overlapping",e.label="Overlapping",e.labelColor="black",e.unitId="overlapping",n.height*=3;const r=new Set;for(const s of t)for(const o of s.props.channelIds)r.add(o);const i=si([...r]);return n.channelIds=i,n.units=t.map(s=>s.props.units[0]),[e]},MW=t=>t.map(e=>{const n=BD(e);return e.map(r=>r-n)}),RW=(t,e)=>{const n=[];for(let r=0;r<t.length;r++)n.push(t[r].map((i,s)=>{const o=BD(e[s]);return i.map(a=>a-o)}));return n},BD=t=>t.length>0?Hz(t):0,IW=t=>R.jsx(ui,{context:t.contexts.unitSelection,children:R.jsx(PW,{...t})}),PW=({zarrGroup:t,width:e,height:n})=>{const[r,i]=D.useState(null);return D.useEffect(()=>{let s=!1;return(async()=>{const a=[],l=t.attrs.num_average_waveforms||0,c=t.attrs.average_waveforms,u=c.length;u!==l&&console.warn(`numUnits (${u}) !== numAverageWaveforms (${l})`);for(let h=0;h<l;h++){const d=`waveform_${h}`,g=await t.getGroup(d);if(!g){console.warn(`No group for ${d}`);continue}if(g.datasets.find(w=>w.name==="waveform")===void 0){console.warn(`No waveform dataset for ${d}`);continue}const p=await t.getDataset(`${d}/waveform`);if(!p){console.warn(`Could not load waveform dataset for ${d}`);continue}const _=p.shape,m=await t.getDatasetData(`${d}/waveform`,{});let v;g.datasets.find(w=>w.name==="waveform_std_dev")===void 0?v=void 0:v=await t.getDatasetData(`${d}/waveform_std_dev`,{});let y,b;if(g.datasets.find(w=>w.name==="waveform_percentiles")===void 0)y=void 0;else{const w=await t.getDataset(`${d}/waveform_percentiles`);w?(y=await t.getDatasetData(`${d}/waveform_percentiles`,{}),b=w.shape[0]):(console.warn(`Could not load waveform_percentiles dataset for ${d}`),y=void 0)}if(m){const w=c.find(x=>x.name===d);w&&a.push({unitId:w.unit_id,channelIds:w.channel_ids,waveform:kD(m,_),waveformStdDev:v?kD(v,_):void 0,waveformPercentiles:y&&b?OW(y,[b,_[0],_[1]]):void 0})}}const f=t.attrs.channel_locations;s||i({type:"AverageWaveforms",averageWaveforms:a,channelLocations:f})})(),()=>{s=!0}},[t]),r?R.jsx(CW,{data:r,width:e,height:n}):R.jsx("div",{children:"Loading..."})},kD=(t,e)=>{if(e.length!==2)throw Error("shape.length should be 2");const[n,r]=e;if(t.length!==n*r)throw Error(`data.length does not match shape. Expected ${n*r}, got ${t.length}`);const i=[];for(let s=0;s<r;s++){const o=[];for(let a=0;a<n;a++)o.push(t[a*r+s]);i.push(o)}return i},OW=(t,e)=>{if(e.length!==3)throw Error("shape.length should be 3");const[n,r,i]=e;if(t.length!==n*r*i)throw Error(`data.length does not match shape. Expected ${n*r*i}, got ${t.length}`);const s=[];for(let o=0;o<n;o++){const a=[];for(let l=0;l<r;l++){const c=[];for(let u=0;u<i;u++)c.push(t[o*r*i+l*i+u]);a.push(c)}s.push(a)}return s},UD=20,NW=({data:t,width:e,height:n})=>{const[r,i]=D.useState(!1),{selectedUnitIds:s}=Vr(),o=D.useMemo(()=>si([...s]),[s]),a=t.hideUnitSelector,l=D.useMemo(()=>{const m=t.crossCorrelograms.filter(y=>o.includes(y.unitId1)&&o.includes(y.unitId2)),v=[];for(const y of o)for(const b of o){const w=m.filter(x=>x.unitId1===y&&x.unitId2===b)[0];w?v.push(w):v.push(void 0)}return v},[t.crossCorrelograms,o]),c=a?0:100,u=Qu,f=e-c-u,h=n,d=D.useMemo(()=>{const m=o.length,{plotWidth:v,plotHeight:y}=LD(f,h,m);return l.map((b,w)=>({key:`${w}`,unitId:b?b.unitId1:0,label:b?v>80?`Unit ${b.unitId1}/${b.unitId2}`:`${b.unitId1}/${b.unitId2}`:"",labelColor:"black",clickHandler:void 0,props:{binEdgesSec:b?b.binEdgesSec:void 0,binCounts:b?b.binCounts:void 0,color:b?.unitId1===b?.unitId2?ci(Nt(b?.unitId1)):"gray",width:v,height:y,hideXAxis:!r}}))},[l,f,h,o,r]),g=D.useMemo(()=>[{type:"toggle",subtype:"checkbox",callback:()=>i(v=>!v),title:"Show X Axis",selected:r===!0}],[r]),p=D.useMemo(()=>{const m=new Set;t.crossCorrelograms.forEach(y=>{m.add(y.unitId1),m.add(y.unitId2)});const v=si(Array.from(m));return{type:"UnitsTable",columns:[],rows:v.map(y=>({unitId:y,values:{}}))}},[t.crossCorrelograms]),_=R.jsxs(Jo,{width:e-c,height:n,initialPosition:u,adjustable:!1,children:[R.jsx(Ju,{width:u,height:n,customActions:g}),R.jsx(tp,{width:0,height:0,disableScroll:!0,children:o.length>UD?R.jsxs("div",{children:["Not showing cross-correlogram matrix. Too many units selected (max ="," ",UD,")."]}):o.length===0?R.jsx("div",{children:"Select one or more units to view cross-correlograms."}):R.jsx(ep,{plots:d,plotComponent:gD,selectedPlotKeys:void 0,numPlotsPerRow:o.length})})]});return a?_:R.jsxs("div",{style:{position:"relative",width:e,height:n},children:[R.jsx("div",{style:{position:"absolute",left:0,top:0,width:c,height:n,borderRight:"1px solid #ccc",boxSizing:"border-box",padding:10,backgroundColor:"#f9f9f9"},children:R.jsx(_D,{data:p,width:c,height:n})}),R.jsx("div",{style:{position:"absolute",left:c,top:0,width:e-c,height:n},children:_})]})},LD=(t,e,n)=>{const r=Math.min((t-30-(n-1)*7)/n,(e-30-(n-1)*7)/n);return{plotWidth:r,plotHeight:r}},FW=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null);return D.useEffect(()=>{let o=!1;return(async()=>{const l=[],c=t.attrs.num_cross_correlograms||0;if(c===0){o||s({type:"CrossCorrelograms",crossCorrelograms:[],hideUnitSelector:t.attrs.hide_unit_selector||!1});return}const u=await t.getDatasetData("bin_edges_sec",{}),f=await t.getDatasetData("bin_counts",{});if(!u||!f){console.error("Failed to load cross-correlograms data");return}const h=Array.from(u),d=new Int32Array(f),g=h.length-1,p=t.attrs.cross_correlograms;for(let m=0;m<c;m++){const v=p[m],y=m*g,b=Array.from(d.slice(y,y+g));l.push({unitId1:v.unit_id1,unitId2:v.unit_id2,binEdgesSec:h,binCounts:b})}const _=t.attrs.hide_unit_selector||!1;o||s({type:"CrossCorrelograms",crossCorrelograms:l,hideUnitSelector:_})})(),()=>{o=!0}},[t]),i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(NW,{data:i,width:n,height:r})}):R.jsx("div",{children:"Loading..."})},BW=1.4,kW=(t,e,n,r)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: * Attempt to call zoomTime() with uninitialized state ${t}.`),{visibleStartTimeSec:t.visibleStartTimeSec,visibleEndTimeSec:t.visibleEndTimeSec};const i=t.endTimeSec-t.startTimeSec,s=t.visibleEndTimeSec-t.visibleStartTimeSec;if(s===i&&e==="out")return{visibleStartTimeSec:t.startTimeSec,visibleEndTimeSec:t.endTimeSec};let o=n??BW;o=e==="in"?1/o:o;const a=Math.min(s*o,i);if(a>=i)return{...t,visibleStartTimeSec:t.startTimeSec,visibleEndTimeSec:t.endTimeSec};const l=r!==void 0?r:t.currentTime??t.visibleStartTimeSec+s/2,c=(l-t.visibleStartTimeSec)/s;let u=Math.max(l-c*a,t.startTimeSec);const f=Math.min(u+a,t.endTimeSec);return u=f-a,{visibleStartTimeSec:u,visibleEndTimeSec:f}},zD=(t,e)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: Attempt to call panTime() with uninitialized state ${t}.`),t;const n=t.visibleEndTimeSec-t.visibleStartTimeSec;let r=t.visibleStartTimeSec,i=t.visibleEndTimeSec;if(e>0)i=Math.min(t.visibleEndTimeSec+e,t.endTimeSec),r=Math.max(i-n,t.startTimeSec);else if(e<0)r=Math.max(t.visibleStartTimeSec+e,t.startTimeSec),i=Math.min(r+n,t.endTimeSec);else return t;const o=!0?t.currentTime:void 0;return r===t.visibleStartTimeSec&&i===t.visibleEndTimeSec?t:{...t,visibleStartTimeSec:r,visibleEndTimeSec:i,currentTimeSec:o}},UW=(t,e)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: * Attempt to call panTime() with uninitialized state ${t}.`),{visibleStartTimeSec:t.visibleStartTimeSec,visibleEndTimeSec:t.visibleEndTimeSec};const n=t.visibleEndTimeSec-t.visibleStartTimeSec,r=e.panAmountPct/100*n*(e.type==="back"?-1:1);return zD(t,r)},LW=(t,e)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: Attempt to call panTime() with uninitialized state ${t}.`),t;const n=e.deltaT;return zD(t,n)},$D=ln.createContext(void 0),ig=()=>{const t=D.useContext($D);if(!t)throw new Error("useTimeseriesSelection must be used within a TimeseriesSelectionContext");const e=t.dispatch,n=D.useCallback(a=>{e({type:"initializeTimeseries",startTimeSec:a.startTimeSec,endTimeSec:a.endTimeSec,initialVisibleStartTimeSec:a.initialVisibleStartTimeSec,initialVisibleEndTimeSec:a.initialVisibleEndTimeSec})},[e]),r=D.useCallback((a,l)=>{e({type:"setVisibleTimeRange",visibleStartTimeSec:a,visibleEndTimeSec:l})},[e]),i=D.useCallback((a,l)=>{e({type:"setCurrentTime",currentTime:a,ensureVisible:l?.ensureVisible})},[e]),s=D.useCallback(a=>{e({type:"zoomVisibleTimeRange",factor:a})},[e]),o=D.useCallback(a=>{e({type:"translateVisibleTimeRangeFrac",frac:a})},[e]);if(t===void 0)throw new Error("useTimeseriesSelection must be used within a TimeseriesSelectionContext.Provider");return{initializeTimeseriesSelection:n,setVisibleTimeRange:r,setCurrentTime:i,zoomVisibleTimeRange:s,translateVisibleTimeRangeFrac:o,timeseriesSelection:t.timeseriesSelection,startTimeSec:t.timeseriesSelection.startTimeSec,endTimeSec:t.timeseriesSelection.endTimeSec,visibleStartTimeSec:t.timeseriesSelection.visibleStartTimeSec,visibleEndTimeSec:t.timeseriesSelection.visibleEndTimeSec,currentTime:t.timeseriesSelection.currentTime}},sg=()=>{const{visibleStartTimeSec:t,visibleEndTimeSec:e,currentTime:n,setCurrentTime:r,startTimeSec:i,endTimeSec:s,setVisibleTimeRange:o}=ig(),a=D.useCallback((h,d,g)=>{const p=kW({visibleStartTimeSec:t,visibleEndTimeSec:e,currentTime:n,startTimeSec:i,endTimeSec:s},h,d,g);p.visibleStartTimeSec!==void 0&&p.visibleEndTimeSec!==void 0&&o(p.visibleStartTimeSec,p.visibleEndTimeSec)},[t,e,n,i,s,o]),l=D.useCallback((h,d)=>{const g=UW({visibleStartTimeSec:t,visibleEndTimeSec:e,startTimeSec:i,endTimeSec:s,currentTime:n},{type:h,panAmountPct:d??10});g.visibleStartTimeSec!==void 0&&g.visibleEndTimeSec!==void 0&&o(g.visibleStartTimeSec,g.visibleEndTimeSec)},[t,e,i,s,n,o]),c=D.useCallback(h=>{const d=LW({visibleStartTimeSec:t,visibleEndTimeSec:e,startTimeSec:i,endTimeSec:s,currentTime:n},{deltaT:h});d.visibleStartTimeSec!==void 0&&d.visibleEndTimeSec!==void 0&&o(d.visibleStartTimeSec,d.visibleEndTimeSec)},[t,e,i,s,n,o]),u=D.useCallback(h=>{if(t===void 0||e===void 0)return;const d=e-t,g=h,p=g+d;o(g,p)},[t,e,o]),f=D.useCallback((h,d)=>{if(t===void 0||e===void 0)return;const g=t+h*(e-t);r(g)},[t,e,r]);return{visibleStartTimeSec:t,visibleEndTimeSec:e,setVisibleTimeRange:o,zoomTimeseriesSelection:a,panTimeseriesSelection:l,panTimeseriesSelectionDeltaT:c,panTimeseriesSelectionVisibleStartTimeSec:u,setCurrentTimeFraction:f}},VD=()=>{const[t,e]=D.useState(!1),n=D.useMemo(()=>[{id:"only-show-selected",label:"Only Show Selected",tooltip:"Toggle visibility of only selected units",icon:t?"👁️":"👁️🗨️",isActive:t,onClick:()=>e(r=>!r)}],[t]);return{onlyShowSelected:t,customToolbarActions:n}},zW=({width:t,height:e,customActions:n})=>!n||n.length===0?null:R.jsx("div",{style:{width:t,height:e,backgroundColor:"#f8f9fa",borderTop:"1px solid #dee2e6",display:"flex",alignItems:"center",justifyContent:"flex-start",padding:"0 12px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif"},children:R.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:n.map(r=>r.component?R.jsx("div",{style:{display:"flex",alignItems:"center"},children:r.component},r.id):R.jsxs("button",{onClick:r.onClick,style:{padding:"4px 8px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:r.isActive?"#007bff":"#ffffff",color:r.isActive?"#ffffff":"#495057",cursor:r.onClick?"pointer":"default",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:r.tooltip||r.label,onMouseEnter:i=>{!r.isActive&&r.onClick&&(i.currentTarget.style.backgroundColor="#e9ecef")},onMouseLeave:i=>{!r.isActive&&r.onClick&&(i.currentTarget.style.backgroundColor="#ffffff")},children:[r.icon&&R.jsx("span",{children:r.icon}),r.label]},r.id))})}),$W=t=>{if(!t||!t.current)return;t.current.querySelectorAll("canvas").forEach(n=>{n.addEventListener("wheel",r=>{r.preventDefault()})})},VW=t=>{const e=Math.round(t*1e3),n=Math.floor(e/(1e3*60*60)),r=Math.floor(e%(1e3*60*60)/(1e3*60)),i=Math.floor(e%(1e3*60)/1e3),s=e%1e3;return`${n.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`},jW=({width:t,height:e,interactionMode:n,onInteractionModeChange:r,currentTime:i,onZoomToFit:s})=>{const{zoomTimeseriesSelection:o,panTimeseriesSelection:a}=sg(),l=D.useCallback(()=>{o("in",1.2)},[o]),c=D.useCallback(()=>{o("out",1.2)},[o]),u=D.useCallback(()=>{a("back",10)},[a]),f=D.useCallback(()=>{a("forward",10)},[a]),h=D.useCallback(d=>{r(d)},[r]);return R.jsxs("div",{style:{width:t,height:e,backgroundColor:"#f8f9fa",borderTop:"1px solid #dee2e6",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 12px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif"},children:[R.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[R.jsx("button",{onClick:()=>h("pan"),style:{padding:"4px 8px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:n==="pan"?"#007bff":"#ffffff",color:n==="pan"?"#ffffff":"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease"},title:"Pan mode: Drag to pan, wheel to zoom",children:"🖱️ Pan"}),R.jsx("button",{onClick:()=>h("select-zoom"),style:{padding:"4px 8px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:n==="select-zoom"?"#007bff":"#ffffff",color:n==="select-zoom"?"#ffffff":"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease"},title:"Select zoom mode: Drag to select region and zoom in",children:"🔍 Select"})]}),R.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[R.jsx("button",{onClick:u,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Pan left",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"⬅️"}),R.jsx("button",{onClick:c,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Zoom out",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"🔍➖"}),R.jsx("button",{onClick:l,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Zoom in",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"🔍➕"}),R.jsx("button",{onClick:f,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Pan right",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"➡️"}),R.jsx("div",{style:{width:"1px",height:"20px",backgroundColor:"#dee2e6",margin:"0 4px"}}),R.jsx("button",{onClick:s,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Reset zoom to show all data",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"🏠"})]}),R.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[R.jsx("span",{style:{color:"#6c757d",fontWeight:"500"},children:"Time:"}),R.jsx("span",{style:{padding:"4px 8px",backgroundColor:"#e9ecef",borderRadius:"4px",fontFamily:"Monaco, Consolas, monospace",fontSize:"12px",fontWeight:"600",color:"#495057",minWidth:"120px",textAlign:"center"},children:i!==void 0?VW(i):"--:--:--.---"})]})]})},HW=[{name:"1ms",secondsPerTick:.001,countPerLargerUnit:10,scale_appropriate_label:t=>`${t%1e3} ms`},{name:"10ms",secondsPerTick:.01,countPerLargerUnit:10,scale_appropriate_label:t=>`${t*10%1e3} ms`},{name:"100ms",secondsPerTick:.1,countPerLargerUnit:10,scale_appropriate_label:t=>`${t*100%1e3} ms`},{name:"1s",secondsPerTick:1,countPerLargerUnit:10,scale_appropriate_label:t=>`${t%60} s`},{name:"10s",secondsPerTick:10,countPerLargerUnit:6,scale_appropriate_label:t=>`${t*10%60} s`},{name:"1min",secondsPerTick:60,countPerLargerUnit:10,scale_appropriate_label:t=>`${t%60} min`},{name:"10min",secondsPerTick:60*10,countPerLargerUnit:6,scale_appropriate_label:t=>`${t*10%60} min`},{name:"1hr",secondsPerTick:60*60,countPerLargerUnit:6,scale_appropriate_label:t=>`${t%24} hr`},{name:"6hr",secondsPerTick:60*60*6,countPerLargerUnit:4,scale_appropriate_label:t=>`${t*6%24} hr`},{name:"1day",secondsPerTick:60*60*24,countPerLargerUnit:10,scale_appropriate_label:t=>`${t} day`},{name:"10day",secondsPerTick:60*60*24*10,countPerLargerUnit:1e4,scale_appropriate_label:t=>`${10*t} day`}],jD=(t,e,n,r)=>{if(e===void 0||n===void 0)return[];if(n<=e)return[];const i=[],s=t/(n-e);for(const o of HW){const a=s*o.secondsPerTick;if(a<=50)continue;const l=Math.ceil(e/o.secondsPerTick),c=Math.floor(n/o.secondsPerTick),u=a>200||c-l<5;for(let f=l;f<=c;f++){if(f%o.countPerLargerUnit===0)continue;const h=f*o.secondsPerTick;i.push({value:h,label:o.scale_appropriate_label(f),major:u,xPixelPosition:r(h)})}}return i},WW=(t,e,n,r)=>D.useMemo(()=>jD(t,e,n,r),[e,n,r,t]),XW=t=>{if(!t||typeof t=="function")return;const e=t.current,n=e&&e.getContext("2d");if(n)return n},qW={position:"absolute",left:0,top:0},HD=t=>{const{width:e,height:n,draw:r,drawData:i}=t,s=D.useRef(null);return D.useEffect(()=>{const o=XW(s);o&&o.canvas&&r(o,i)},[r,s,i]),R.jsx("canvas",{ref:s,width:e,height:n,style:qW})},WD=(t,e)=>{const{width:n,height:r,margins:i,timeTicks:s,gridlineOpts:o,yTickSet:a,yLabel:l}=e;t.clearRect(0,0,t.canvas.width,t.canvas.height);const c=r-i.bottom;YW(t,s,c,i.top,{hideGridlines:o?.hideX},e.hideTimeAxisLabels),t.strokeStyle="lightgray",$_(t,i.left,c,n-i.right,c),a&&KW(t,a,c,i.left,n-i.right,i.top,{hideGridlines:o?.hideY}),l&&ZW(t,l,i.left,i.bottom,i.top,t.canvas.height)},YW=(t,e,n,r,i,s)=>{const o=s||!1;if(!e||e.length===0)return;const a=2,l=n+(o?0:5);t.textAlign="center",t.textBaseline="top",e.forEach(c=>{t.strokeStyle=c.major?"gray":"lightgray";const u=i.hideGridlines?n:r;$_(t,c.xPixelPosition,l,c.xPixelPosition,u),o||(t.fillStyle=c.major?"black":"gray",t.fillText(c.label,c.xPixelPosition,l+a))})},KW=(t,e,n,r,i,s,o)=>{const l=r-5,c=l-2,{ticks:u}=e;t.fillStyle="black",t.textAlign="right",t.textBaseline="middle",u.forEach(f=>{if(!f.pixelValue)return;const h=f.pixelValue;t.strokeStyle=f.isMajor?"gray":"lightgray",t.fillStyle=f.isMajor?"black":"gray";const d=o.hideGridlines?r:i;$_(t,l,h,d,h),t.fillText(f.label,c,h)})},ZW=(t,e,n,r,i,s)=>{t.textAlign="center",t.textBaseline="middle",t.save(),t.translate(15,(s-r-i)/2+i),t.fillStyle="black",t.font="13px sans-serif",t.rotate(-Math.PI/2),t.fillText(e,0,0),t.restore()},$_=(t,e,n,r,i)=>{t.beginPath(),t.moveTo(e,n),t.lineTo(r,i),t.stroke()},GW={},QW=t=>{const{width:e,height:n}=t,r=D.useCallback(i=>{WD(i,t)},[t]);return R.jsx("span",{className:"TSV2AxesLayer",children:R.jsx(HD,{width:e,height:n,draw:r,drawData:GW})})},JW=(t,e)=>{const{margins:n,currentTimePixels:r,currentTimeIntervalPixels:i}=e;if(t.clearRect(0,0,t.canvas.width,t.canvas.height),i!==void 0){t.fillStyle="rgba(255, 225, 225, 0.4)",t.strokeStyle="rgba(150, 50, 50, 0.9)";const s=i[0],o=n.top,a=i[1]-i[0],l=t.canvas.height-n.bottom-n.top;t.fillRect(s,o,a,l),t.strokeRect(s,o,a,l)}if(r!==void 0&&i===void 0){t.fillStyle="rgba(255, 255, 0, 0.1)";const s=4;t.fillRect(r-s/2,n.top,s,t.canvas.height-n.bottom-n.top),t.strokeStyle="rgba(200, 200, 0, 0.4)",t.lineWidth=1,t.beginPath(),t.moveTo(r,n.top),t.lineTo(r,t.canvas.height-n.bottom),t.stroke()}},eX=t=>{const{width:e,height:n,timeRange:r,currentTimePixels:i,currentTimeIntervalPixels:s,margins:o}=t,a=D.useMemo(()=>({width:e,height:n,timeRange:r,currentTimePixels:i,currentTimeIntervalPixels:s,margins:o}),[e,n,r,i,s,o]);return R.jsx(HD,{width:e,height:n,draw:JW,drawData:a})},tX=({width:t,height:e,selectionRect:n})=>{if(!n)return null;const{startX:r,endX:i}=n,s=Math.abs(i-r),o=Math.min(r,i);return R.jsx("div",{style:{position:"absolute",top:0,left:0,width:t,height:e,pointerEvents:"none",zIndex:10},children:R.jsx("div",{style:{position:"absolute",left:o,top:0,width:s,height:e,backgroundColor:"rgba(0, 123, 255, 0.2)",border:"1px solid rgba(0, 123, 255, 0.6)",borderRadius:"2px"}})})},nX=t=>{const{pixelToTime:e,visibleStartTimeSec:n,setCurrentTime:r,onMouseDown:i,onMouseUp:s,onMouseMove:o,onMouseOut:a,onCanvasClick:l,interactionMode:c}=t,{panTimeseriesSelectionVisibleStartTimeSec:u,setVisibleTimeRange:f}=sg(),[h,d]=D.useState(!1),[g,p]=D.useState(void 0),[_,m]=D.useState(null),v=D.useRef({mouseDownAchorX:null,mouseDownAnchorTime:null,mouseDownAnchorVisibleStartTime:null,mouseDownAnchorPixelToTime:null,moved:!1,selectionStartX:null,selectionEndX:null}),y=D.useCallback(S=>{if(d(!0),!S.shiftKey&&!S.ctrlKey&&!S.altKey){const A=S.clientX-S.currentTarget.getBoundingClientRect().x;c==="select-zoom"?(v.current.selectionStartX=A,v.current.selectionEndX=A,m({startX:A,endX:A})):(v.current.mouseDownAchorX=A,v.current.mouseDownAnchorTime=e(A),v.current.mouseDownAnchorVisibleStartTime=n||null,v.current.mouseDownAnchorPixelToTime=e),v.current.moved=!1}else i&&i(S)},[e,i,n,c]),b=D.useCallback(S=>{if(!S.shiftKey&&!S.ctrlKey&&!S.altKey){const A=S.clientX-S.currentTarget.getBoundingClientRect().x;if(c==="select-zoom"&&v.current.selectionStartX!==null){const E=Math.min(v.current.selectionStartX,A),C=Math.max(v.current.selectionStartX,A);if(Math.abs(C-E)>5){const M=e(E),T=e(C);f(M,T)}else if(!v.current.moved){const M=e(A);if(r(M),l){const T=S.clientY-S.currentTarget.getBoundingClientRect().y;l(A,T)}}m(null),v.current.selectionStartX=null,v.current.selectionEndX=null}else if(v.current.mouseDownAchorX=null,v.current.mouseDownAnchorTime=null,v.current.mouseDownAnchorPixelToTime=null,!v.current.moved){const E=e(A);if(r(E),l){const C=S.clientY-S.currentTarget.getBoundingClientRect().y;l(A,C)}}}else s&&s(S)},[s,e,r,c,f,l]),w=D.useCallback(S=>{const A=S.clientX-S.currentTarget.getBoundingClientRect().x,E=e(A);if(p(E),!S.shiftKey&&!S.ctrlKey&&!S.altKey){if(c==="select-zoom"&&v.current.selectionStartX!==null)v.current.selectionEndX=A,m({startX:Math.min(v.current.selectionStartX,A),endX:Math.max(v.current.selectionStartX,A)}),v.current.moved=!0;else if(c==="pan"&&v.current.mouseDownAchorX!==null&&v.current.mouseDownAnchorPixelToTime!==null){const C=v.current.mouseDownAnchorPixelToTime(A),M=v.current.mouseDownAnchorTime,T=v.current.mouseDownAnchorVisibleStartTime;if(M!==null&&T!==null){const P=C-M,I=A-v.current.mouseDownAchorX;if(Math.abs(I)>2||Math.abs(P)>.01){const k=T-P;u(k),S.preventDefault(),S.stopPropagation(),v.current.moved=!0}}}}o&&o(S)},[e,o,c,u]),x=D.useCallback(S=>{p(void 0),d(!1),m(null),v.current.selectionStartX=null,v.current.selectionEndX=null,a&&a(S)},[a]);return{isViewClicked:h,hoverTime:g,selectionRect:_,handleMouseDown:y,handleMouseUp:b,handleMouseMove:w,handleMouseOut:x}},rX=({width:t,height:e,leftMargin:n,customToolbarActions:r,hideTimeAxisLabels:i,hideNavToolbar:s})=>{const o=r&&r.length>0,a=D.useMemo(()=>({left:n||60,right:20,top:10,bottom:i?10:30}),[n,i]);let l=0;s||(l+=40),o&&(l+=40);const c=t,u=e-l;return{margins:a,canvasWidth:c,canvasHeight:u}},iX=23,sX=60,oX=(t,e,n,r)=>{const i=Math.ceil((e-r)/n);return isNaN(i)||i<1?[]:Array(i).fill(0).map((s,o)=>r+o*n).filter(s=>s>t)},aX=(t,e)=>{let n=0;const r=Math.trunc(Math.log10(e));if(Math.trunc(Math.log10(t))!==r)return n;const i=Math.trunc(Math.log10(e-t));if(r<=i)return n;const s=i+1,o=Math.pow(10,-s),a=Math.trunc(e*o).toString(),l=Math.trunc(t*o).toString();for(const[c,u]of[...a].entries()){if(u!==l[c]){n=n*Math.pow(10,c-s);break}n=n*10+parseInt(u)}return n*Math.pow(10,s)},lX=(t,e)=>Math.floor(t*Math.pow(10,-(e+1)))*Math.pow(10,e+1),cX=(t,e,n)=>{const r=t-0,i=Math.trunc(r*Math.pow(10,-n)),s=i%10===0;return{label:Math.abs(n)>3?`${(i/10).toFixed(1)}e${n+1}`:`${Math.round(i*Math.pow(10,n)*1e9)/1e9}`,isMajor:s,dataValue:t}},uX=(t,e,n,r,i)=>{const s=oX(e,n,r,t).map(l=>Math.round(l*1e9)/1e9),o=aX(e,n);return s.map(l=>cX(l,o,i))},XD={ticks:[],datamin:0,datamax:0},fX=(t,e)=>{const n=Math.floor(Math.log10(t/e)),r=Math.pow(10,n),i=[1,2,5,10],o=i.map(a=>t/(r*a)).findIndex(a=>a<e);return o===3?{step:1,scale:n+1}:{step:i[o],scale:n}},qD=t=>{const{datamin:e,datamax:n,userSpecifiedZoom:r}=t;let{pixelHeight:i}=t;i<=1&&(i=1);const s=r??1;if(e===void 0||n===void 0||e===n)return XD;const o=e/s,a=n/s,l=a-o,c=i/sX,u=i/iX,f=fX(l,u),h=f.step*Math.pow(10,f.scale);if(l/h<c)return console.warn("Error: Unable to compute valid y-axis step size. Suppressing display."),XD;const d=lX(o,f.scale);return{ticks:uX(d,o,a,h,f.scale),datamin:o,datamax:a}},hX=t=>{const{datamin:e,datamax:n,userSpecifiedZoom:r}=t;let{pixelHeight:i}=t;return i<=1&&(i=1),D.useMemo(()=>qD({datamin:e,datamax:n,userSpecifiedZoom:r,pixelHeight:i}),[n,e,i,r])},YD=({width:t,height:e,onCanvasElement:n,gridlineOpts:r,onKeyDown:i,onMouseDown:s,onMouseMove:o,onMouseOut:a,onMouseUp:l,yAxisInfo:c,shiftZoom:u,requireClickToZoom:f,leftMargin:h,customToolbarActions:d,onCanvasClick:g,hideNavToolbar:p=!1,hideTimeAxisLabels:_=!1,drawContentForExport:m,setDrawForExport:v})=>{const{visibleStartTimeSec:y,visibleEndTimeSec:b,zoomTimeseriesSelection:w,panTimeseriesSelection:x,setVisibleTimeRange:S}=sg(),{currentTime:A,setCurrentTime:E,startTimeSec:C,endTimeSec:M}=ig(),T=D.useMemo(()=>[y,b],[y,b]),{margins:P,canvasWidth:I,canvasHeight:k}=rX({width:t,height:e,leftMargin:h,customToolbarActions:d,hideNavToolbar:p}),O=D.useMemo(()=>y===void 0||b===void 0?()=>0:b<=y?()=>0:K=>P.left+(K-y)/(b-y)*(I-P.left-P.right),[I,y,b,P]),L=D.useMemo(()=>y===void 0||b===void 0?()=>0:b<=y?()=>0:K=>y+(K-P.left)/(I-P.left-P.right)*(b-y),[I,y,b,P]),U=D.useMemo(()=>{const K=c?.yMin||0,te=c?.yMax||0;return te<=K?()=>0:de=>k-P.bottom-(de-K)/(te-K)*(k-P.top-P.bottom)},[c,k,P]),$=WW(I,y,b,O),J=hX({datamin:c?.yMin||0,datamax:c?.yMax||0,pixelHeight:k-P.left-P.right}),ne=D.useMemo(()=>({datamin:J.datamin,datamax:J.datamax,ticks:J.ticks.map(K=>({...K,pixelValue:U(K.dataValue)}))}),[J,U]),j=k,V=D.useMemo(()=>R.jsx(QW,{width:I,height:j,timeRange:T,margins:P,timeTicks:$,yTickSet:c?.showTicks?ne:void 0,yLabel:c?.yLabel,gridlineOpts:r,hideTimeAxisLabels:_}),[r,I,j,T,P,$,c?.showTicks,c?.yLabel,ne,_]),G=D.useMemo(()=>A!==void 0?O(A):void 0,[A,O]),z=D.useMemo(()=>R.jsx(eX,{width:I,height:j,timeRange:T,margins:P,currentTimePixels:G}),[I,j,T,P,G]),Q=D.useRef(null),[ee,ce]=D.useState("pan"),{isViewClicked:se,hoverTime:ue,selectionRect:be,handleMouseDown:le,handleMouseUp:ye,handleMouseMove:ve,handleMouseOut:Ie}=nX({pixelToTime:L,visibleStartTimeSec:y,setCurrentTime:E,onMouseDown:s,onMouseUp:l,onMouseMove:o,onMouseOut:a,onCanvasClick:g,interactionMode:ee});D.useEffect(()=>{(f===!1||se)&&$W(Q)},[f,se]);const Re=D.useCallback(K=>{if(u&&!K.shiftKey||K.deltaY===0||f!==!1&&!se)return;const te=-K.deltaY/100;w(te>0?"in":"out",1.2,ue)},[u,w,ue,f,se]),Oe=D.useCallback(K=>{K.key==="="?w("in"):K.key==="-"?w("out"):K.key==="ArrowRight"?x("forward"):K.key==="ArrowLeft"&&x("back"),i&&i(K)},[i,w,x]),Ne=D.useCallback(()=>{C!==void 0&&M!==void 0&&S(C,M)},[C,M,S]),Ye=D.useMemo(()=>R.jsx(tX,{width:I,height:j,selectionRect:be}),[I,j,be]),[Le,je]=D.useState(null);D.useEffect(()=>{Le&&n(Le,I,k,P)},[Le,I,k,P,n]),D.useEffect(()=>{if(!v)return;v(async te=>{if(!te||!P)return;const de=ge=>{const xe=c?.yMin||0,me=c?.yMax||0;return me<=xe?0:te.height-P.bottom-(ge-xe)/(me-xe)*(te.height-P.top-P.bottom)},oe=jD(te.width,y,b,O),we=qD({datamin:c?.yMin,datamax:c?.yMax,pixelHeight:te.height});for(const ge of we.ticks)ge.pixelValue=de(ge.dataValue);WD(te.context,{timeTicks:oe,margins:P,gridlineOpts:r,yTickSet:we,yLabel:c?.yLabel,width:te.width,height:te.height,hideTimeAxisLabels:_}),m&&await m(te.context,te.width,te.height,P,{exporting:!0})})},[m,v,P,y,b,O,T,r,c,_,U]);const Ee=D.useMemo(()=>R.jsxs("div",{style:{position:"relative",overflow:"hidden",width:I,height:j},onWheel:!f||se?Re:void 0,onMouseDown:le,onMouseUp:ye,onMouseMove:ve,onMouseOut:Ie,tabIndex:0,onKeyDown:Oe,children:[V,R.jsx("canvas",{style:{position:"absolute",width:I,height:j},ref:K=>je(K),width:I,height:j}),z,Ye]}),[V,z,Ye,I,j,Oe,Re,le,ye,ve,Ie,f,se]),B=D.useMemo(()=>R.jsx(jW,{width:t,height:40,interactionMode:ee,onInteractionModeChange:ce,currentTime:A,onZoomToFit:Ne}),[t,ee,ce,A,Ne]),H=D.useMemo(()=>R.jsx(zW,{width:t,height:40,customActions:d}),[t,d]);return R.jsxs("div",{className:"time-scroll-view-3",ref:Q,style:{position:"absolute",width:t,height:e,background:"white"},children:[Ee,!p&&R.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0},children:[B,H]})]})},KD=15,dX={hideX:!1,hideY:!0},pX={showTicks:!1,yMin:void 0,yMax:void 0},gX=({dataClient:t,width:e,height:n,setDrawForExport:r})=>{const{visibleStartTimeSec:i,visibleEndTimeSec:s}=sg(),{initializeTimeseriesSelection:o}=ig(),{selectedUnitIds:a,unitIdSelectionDispatch:l}=Vr(),[c,u]=D.useState(void 0),f=D.useRef(null),[h,d]=D.useState(null),[g,p]=D.useState(null),[_,m]=D.useState(!1),[v,y]=D.useState(null),[b,w]=D.useState(null),x=D.useMemo(()=>i===void 0||s===void 0?"raster":s-i>120?"heatmap":"raster",[i,s]),S=t.metadata.unitIds;D.useEffect(()=>{t.metadata&&o({startTimeSec:t.metadata.startTimeSec,endTimeSec:t.metadata.endTimeSec,initialVisibleStartTimeSec:t.metadata.startTimeSec,initialVisibleEndTimeSec:t.metadata.endTimeSec})},[o,t.metadata]),D.useEffect(()=>{let z=!1;const Q=async()=>{if(!(i===void 0||s===void 0))try{if(x==="raster"){const ee=await t.getDataForRange({startTimeSec:i,endTimeSec:s});if(z)return;p(ee),w(null)}else{const ee=t.getSpikeCountsForRange({startTimeSec:i,endTimeSec:s});if(z)return;w(ee),p(null)}y(null)}catch(ee){if(z)return;console.error("Error loading data:",ee),y(`Error loading data: ${ee}`)}};return m(!0),Q().finally(()=>{z||m(!1)}),()=>{z=!0}},[t,i,s,x]);const{onlyShowSelected:A,customToolbarActions:E}=VD(),[C,M]=D.useState(e),[T,P]=D.useState(n),[I,k]=D.useState(null),O=D.useMemo(()=>{const z=[];return A&&S.forEach((Q,ee)=>{a.has(Q)&&z.push(ee)}),z},[A,a,S]),L=D.useMemo(()=>O.map(z=>S[z]),[O,S]),U=D.useCallback(()=>{if(!I||!f.current||!h||!b||!t.metadata||i===void 0||s===void 0)return;if(h.clearRect(0,0,C,T),_&&(h.fillStyle="rgba(0, 0, 0, 0.02)",h.fillRect(0,0,C,T),h.fillStyle="black",h.font="16px Arial",h.textAlign="center",h.fillText("Loading...",C/2,T/2)),v){h.fillStyle="rgba(255, 0, 0, 0.1)",h.fillRect(0,0,C,T),h.fillStyle="red",h.font="14px Arial",h.textAlign="center",h.fillText(v,C/2,T/2);return}const Q=T-I.top-I.bottom,ee=C-I.left-I.right,ce=s-i;let se;if(A){let le=0;S.forEach((ye,ve)=>{a.has(ye)&&le++}),se=le}else S.forEach((le,ye)=>{}),se=S.length;const ue=Q/(se||1);h.save(),h.beginPath(),h.rect(I.left,I.top,ee,Q),h.clip();let be=1;if(b.counts.forEach(le=>{A?O.forEach(ye=>{const ve=le[ye];ve>be&&(be=ve)}):le.forEach(ye=>{ye>be&&(be=ye)})}),b.counts.forEach((le,ye)=>{const ve=b.binEdges[ye],Ie=b.binEdges[ye+1],Re=I.left+(ve-i)/ce*ee,Oe=I.left+(Ie-i)/ce*ee;if(A)for(let Ne=0;Ne<O.length;Ne++){const Ye=O[Ne],je=le[Ye]/be,Ee=I.top+(O.length-1-Ne)*ue,B=ZD(je);h.fillStyle=B,h.fillRect(Re,Ee,Oe-Re+.5,ue)}else le.forEach((Ne,Ye)=>{const Le=Ne/be,je=I.top+(S.length-1-Ye)*ue,Ee=ZD(Le);h.fillStyle=Ee,h.fillRect(Re,je,Oe-Re+.5,ue)})}),h.restore(),ue>=KD){h.globalAlpha=1;const le=A?L:S;le.forEach((ye,ve)=>{const Re=I.top+(le.length-1-ve)*ue+ue/2,Oe=_v(Nt(ye));h.fillStyle=Oe,h.font="12px Arial",h.textAlign="right",h.fillText(`Unit ${ye}`,I.left-5,Re)})}},[C,T,I,b,i,s,t.metadata,_,v,h,a,A,S,O,L]),$=D.useCallback(()=>{if(!I||!f.current||!h||!g||!t.metadata||i===void 0||s===void 0)return;if(h.clearRect(0,0,C,T),_&&(h.fillStyle="rgba(0, 0, 0, 0.02)",h.fillRect(0,0,C,T),h.fillStyle="black",h.font="16px Arial",h.textAlign="center",h.fillText("Loading...",C/2,T/2)),v){h.fillStyle="rgba(255, 0, 0, 0.1)",h.fillRect(0,0,C,T),h.fillStyle="red",h.font="14px Arial",h.textAlign="center",h.fillText(v,C/2,T/2);return}const Q=T-I.top-I.bottom,ee=C-I.left-I.right,ce=s-i,se=t.metadata.unitIds,ue={};let be;if(A){for(let ye=0;ye<O.length;ye++){const ve=O[ye];ue[ve]=ye}be=O.length}else se.forEach((ye,ve)=>{ue[ve]=ve}),be=se.length;const le=Q/(be||1);h.save(),h.beginPath(),h.rect(I.left,I.top,ee,Q),h.clip();for(let ye=0;ye<g.timestamps.length;ye++){const ve=g.timestamps[ye],Ie=ue[g.unitIndices[ye]];if(Ie===void 0)continue;const Re=se[g.unitIndices[ye]],Oe=I.top+(be-1-Ie)*le+le/2,Ne=_v(Nt(Re)),Ye=c===Re,Le=a.has(Re);h.strokeStyle=Ne,h.lineWidth=Ye||Le?2:1,h.globalAlpha=Le?1:Ye?.8:.6;const je=I.left+(ve-i)/ce*ee;h.beginPath(),h.moveTo(je,Oe-le*.4),h.lineTo(je,Oe+le*.4),h.stroke()}if(h.restore(),le>=KD){h.globalAlpha=1;const ye=A?L:se;ye.forEach((ve,Ie)=>{const Oe=I.top+(ye.length-1-Ie)*le+le/2,Ne=_v(Nt(ve));h.fillStyle=Ne,h.font="12px Arial",h.textAlign="right",h.fillText(`Unit ${ve}`,I.left-5,Oe)})}},[C,T,I,g,t.metadata,i,s,_,v,c,a,A,h,L,O]);D.useEffect(()=>{x==="heatmap"&&b?U():$()},[$,U,x,b]);const J=D.useCallback(()=>{},[]),ne=D.useCallback(z=>{if(!I||!t.metadata)return;const Q=t.metadata.unitIds,ee=Q.length,ce=1-(z.y-I.top)/(T-I.top-I.bottom),se=Math.round(ce*ee-.5);if(0<=se&&se<ee)return Q[se]},[T,I,t.metadata]),j=D.useCallback(z=>{const Q=z.currentTarget.getBoundingClientRect(),ee={x:z.clientX-Q.x,y:z.clientY-Q.y},ce=ne(ee);z.shiftKey||z.ctrlKey?l({type:"TOGGLE_UNIT",targetUnit:ce}):l({type:"UNIQUE_SELECT",targetUnit:ce})},[ne,l]),V=D.useCallback(z=>{const Q=z.currentTarget.getBoundingClientRect(),ee={x:z.clientX-Q.x,y:z.clientY-Q.y},ce=ne(ee);ce!==void 0&&u(ce)},[ne]),G=D.useCallback(()=>{u(void 0)},[]);return t.metadata?R.jsx(YD,{width:e,height:n,customToolbarActions:E,onCanvasElement:(z,Q,ee,ce)=>{f.current=z;const se=z?.getContext("2d");d(se),M(Q),P(ee),k(ce)},gridlineOpts:dX,onKeyDown:J,onMouseDown:j,onMouseMove:V,onMouseOut:G,yAxisInfo:pX,setDrawForExport:r}):R.jsx("div",{children:"Loading metadata..."})},ZD=t=>{if(t===0)return"rgb(255,255,255)";const e=Math.max(0,Math.min(1,.7*(1-t))),n=Math.round(e*255);return`rgb(${n}, ${n}, ${n})`};class V_{constructor(e,n,r,i,s,o){this.zarrGroup=e,this.metadata=n,this.referenceTimes=r,this.referenceIndices=i,this.counts2dArray=s,this.binEdges=o,this.zarrGroup=e}static async create(e){const n={startTimeSec:e.attrs.start_time_sec,endTimeSec:e.attrs.end_time_sec,unitIds:e.attrs.unit_ids||[],totalSpikes:e.attrs.total_spikes||0},r=await e.getDatasetData("reference_times",{}),i=await e.getDatasetData("reference_indices",{});if(!r||!i)throw new Error(`Reference arrays not found in Zarr group: ${e.path}`);const s=await e.getDatasetData("spike_counts_1sec",{}).catch(()=>{});if(!s)throw new Error(`Spike counts data not found in Zarr group: ${e.path}`);const o=Math.ceil(n.endTimeSec-n.startTimeSec),a=n.unitIds.length,l=Array(o);for(let f=0;f<o;f++){l[f]=Array(a);for(let h=0;h<a;h++){const d=f*a+h;l[f][h]=d<s.length?s[d]:0}}const c=Array(o+1);for(let f=0;f<=o;f++)c[f]=n.startTimeSec+f;return new V_(e,n,r,i,l,c)}async getDataForRange(e){const n=this.findStartIndex(this.referenceTimes,this.referenceIndices,e.startTimeSec),r=this.findEndIndex(this.referenceTimes,this.referenceIndices,e.endTimeSec);if(n>=r)return{timestamps:[],unitIndices:[]};const i=await this.zarrGroup.getDatasetData("timestamps",{slice:[[n,r]]}),s=await this.zarrGroup.getDatasetData("unit_indices",{slice:[[n,r]]});return{timestamps:Array.from(i),unitIndices:Array.from(s)}}findStartIndex(e,n,r){let i=0;for(;i+1<e.length&&e[i+1]<r;)i++;return n[i]}getSpikeCountsForRange(e){const{startTimeSec:n,endTimeSec:r}=e,i=Math.floor(n-this.metadata.startTimeSec),s=Math.ceil(r-this.metadata.startTimeSec);let o=1;for(;(s-i)/o>500;)o+=1;const a=this.counts2dArray.slice(i,s),l=this.binEdges.slice(i,s+1);if(o===1)return{binEdges:l,counts:a};{const c=[],u=[];for(let f=0;f<a.length;f+=o){const h=Array(this.metadata.unitIds.length).fill(0);for(let d=0;d<o;d++)if(f+d<a.length)for(let g=0;g<h.length;g++)h[g]+=a[f+d][g];c.push(h),u.push(l[f])}return l.length>0&&u.push(l[Math.min(l.length-1,u.length*o)]),{binEdges:u,counts:c}}}findEndIndex(e,n,r){let i=e.length-1;for(;i-1>=0&&e[i-1]>r;)i--;return n[i]}}const mX=({zarrGroup:t,contexts:e,width:n,height:r,setDrawForExport:i})=>{const s=yX(t);return s?R.jsx(GD,{context:e.timeseriesSelection,children:R.jsx(ui,{context:e.unitSelection,children:R.jsx(gX,{dataClient:s,width:n,height:r,setDrawForExport:i})})}):null},GD=({context:t,children:e})=>{const{state:n,dispatch:r}=Jp(t);return!r||!n?R.jsx(R.Fragment,{children:"Waiting for context..."}):R.jsx($D.Provider,{value:{timeseriesSelection:n,dispatch:r},children:e})},yX=t=>{const[e,n]=D.useState(null);return D.useEffect(()=>{let r=!0;return V_.create(t).then(i=>{r&&n(i)}),()=>{r=!1}},[t]),e},vX=({dataClient:t,width:e,height:n})=>{const{selectedUnitIds:r,unitIdSelectionDispatch:i}=Vr(),{initializeTimeseriesSelection:s,visibleStartTimeSec:o,visibleEndTimeSec:a}=ig(),[l,c]=D.useState(null),[u,f]=D.useState(null),[h,d]=D.useState(!1),[g,p]=D.useState(null),_=Qu,{onlyShowSelected:m,customToolbarActions:v}=VD(),[y,b]=D.useState(e),[w,x]=D.useState(n),[S,A]=D.useState(null),E=t.metadata;D.useEffect(()=>{E&&i({type:$o,newUnitOrder:si(E.unitIds)})},[E,i]),D.useEffect(()=>{E&&s({startTimeSec:E.startTimeSec,endTimeSec:E.endTimeSec,initialVisibleStartTimeSec:E.startTimeSec,initialVisibleEndTimeSec:E.endTimeSec})},[s,E]),D.useEffect(()=>{let T=!1;const P=async()=>{if(o!==void 0&&a!==void 0){let I=1e4;for(;;){const k=await t.getDataForRange({startTimeSec:o,endTimeSec:a},{maxNumEvents:I});if(T)return;if(k&&f(k),k.subsampleFactor>1){if(I===1e6)break;I=Math.max(I*3,k.timestamps.length*3),I>1e6&&(I=1e6)}else break}}};return d(!0),p(null),P().catch(I=>{T||p(`Failed to load data: ${I}`),p(`Failed to load data: ${I}`)}).finally(()=>{d(!1)}),()=>{T=!0}},[o,a,t]);const C=D.useMemo(()=>{if(!u||!E||u.amplitudes.length===0)return{yMin:0,yMax:10};let T=1/0,P=-1/0;for(let k=0;k<u.amplitudes.length;k++){const O=E.unitIds[u.unitIndices[k]];if(m?r.has(O):!0){const U=u.amplitudes[k];U<T&&(T=U),U>P&&(P=U)}}if(T===1/0)return{yMin:0,yMax:10};const I=(P-T)*.1;return{yMin:T-I,yMax:P+I}},[u,E,m,r]);D.useEffect(()=>{if(!l||!u||!E||!S||a===void 0||o===void 0)return;let T=!1;return(async()=>{if(T)return;if(l.clearRect(0,0,y,w),h&&(l.fillStyle="rgba(0, 0, 0, 0.1)",l.fillRect(0,0,y,w),l.fillStyle="black",l.font="16px Arial",l.textAlign="center",l.fillText("Loading...",y/2,w/2)),g){l.fillStyle="rgba(255, 0, 0, 0.1)",l.fillRect(0,0,y,w),l.fillStyle="red",l.font="14px Arial",l.textAlign="center",l.fillText(g,y/2,w/2);return}l.save(),l.beginPath(),l.rect(S.left,S.top,y-S.left-S.right,w-S.top-S.bottom),l.clip();const I=O=>S.left+(O-o)/(a-o)*(y-S.left-S.right),k=O=>w-S.bottom-(O-C.yMin)/(C.yMax-C.yMin)*(w-S.top-S.bottom);for(let O=0;O<u.timestamps.length;O++){const L=u.timestamps[O],U=u.amplitudes[O],$=E.unitIds[u.unitIndices[O]];if(L<o||L>a||!(m?r.has($):!0))continue;const ne=ci(Nt($)),V=r.has($)?1:.3;l.fillStyle=ne,l.globalAlpha=V;const G=I(L),z=k(U);l.beginPath(),l.arc(G,z,2,0,Math.PI*2),l.fill()}l.globalAlpha=1,u.subsampleFactor>1&&(l.fillStyle="#2196F3",l.font="12px Arial",l.textAlign="left",l.fillText(`Subsampled ${u.subsampleFactor}x`,S.left+10,S.top+20)),l.restore()})(),()=>{T=!0}},[l,u,E,o,a,y,w,S,C,r,m,h,g]);const M=D.useMemo(()=>({showTicks:!0,yMin:C.yMin,yMax:C.yMax,yLabel:"Amplitude"}),[C]);return E?R.jsx("div",{children:R.jsxs(Jo,{width:e,height:n,initialPosition:_,adjustable:!1,children:[R.jsx(Ju,{width:_,height:n}),R.jsx(YD,{width:e-_,height:n,onCanvasElement:(T,P,I,k)=>{if(!T)return;const O=T.getContext("2d");c(O),b(P),x(I),A(k)},yAxisInfo:M,customToolbarActions:v})]})}):R.jsx("div",{children:"Loading metadata..."})};class og{constructor(e,n,r={},i,s){this.zarrGroup=e,this.metadata=n,this.subsampleClients=r,this.referenceTimes=i,this.referenceIndices=s,this.zarrGroup=e}static async create(e){const n={startTimeSec:e.attrs.start_time_sec,endTimeSec:e.attrs.end_time_sec,unitIds:e.attrs.unit_ids||[],totalSpikes:e.attrs.total_spikes||0},r={},i=e.subgroups.find(a=>a.name==="subsampled_data"),s=await e.getDatasetData("reference_times",{}),o=await e.getDatasetData("reference_indices",{});if(!s||!o)throw new Error(`Reference arrays not found in Zarr group: ${e.path}`);if(i){const a=await e.getGroup(i.name);if(!a)throw new Error(`Failed to load subsampled_data group at ${i.name} in ${e.path}`);let l=4;for(;;){const c=a.subgroups.find(h=>h.name===`factor_${l}`);if(!c)break;const u=await a.getGroup(c.name);if(!u)throw console.warn(a.subgroups),new Error(`Failed to load subsampled group at ${c.name} in ${e.path}`);const f=await og.create(u);r[l]=f,l*=4}}return new og(e,n,r,s,o)}async getDataForRange(e,n){const r=this.findStartIndex(this.referenceTimes,this.referenceIndices,e.startTimeSec),i=this.findEndIndex(this.referenceTimes,this.referenceIndices,e.endTimeSec);if(r>=i)return{timestamps:[],unitIndices:[],amplitudes:[],subsampleFactor:1};if(n.maxNumEvents>0&&i-r>n.maxNumEvents){let c=4;for(;c*4 in this.subsampleClients&&(i-r)/c>n.maxNumEvents;)c*=4;if(c in this.subsampleClients){const f=await this.subsampleClients[c].getDataForRange(e,{maxNumEvents:0});return f.subsampleFactor=c,f}}const s=await this.zarrGroup.getDatasetData("timestamps",{slice:[[r,i]]}),o=await this.zarrGroup.getDatasetData("unit_indices",{slice:[[r,i]]}),a=await this.zarrGroup.getDatasetData("amplitudes",{slice:[[r,i]]});return{timestamps:Array.from(s),unitIndices:Array.from(o),amplitudes:Array.from(a),subsampleFactor:1}}findStartIndex(e,n,r){let i=0;for(;i+1<e.length&&e[i+1]<r;)i++;return n[i]}findEndIndex(e,n,r){let i=e.length-1;for(;i-1>=0&&e[i-1]>r;)i--;return n[i]}}const _X=({zarrGroup:t,contexts:e,width:n,height:r})=>{const i=bX(t);return i?R.jsx(GD,{context:e.timeseriesSelection,children:R.jsx(ui,{context:e.unitSelection,children:R.jsx(vX,{dataClient:i,width:n,height:r})})}):null},bX=t=>{const[e,n]=D.useState(null);return D.useEffect(()=>{let r=!0;return og.create(t).then(i=>{r&&n(i)}),()=>{r=!1}},[t]),e},xX=25,QD=2*Math.PI,wX={maxElectrodePixelRadius:xX},j_={},JD=2,SX=t=>{const{width:e,height:n,electrodes:r,units:i,disableAutoRotate:s,onlyShowSelected:o}=t,{selectedElectrodeIds:a}=ND(),{selectedUnitIds:l,unitIdSelectionDispatch:c}=Vr(),{affineTransform:u,handleWheel:f}=rf(e,n,{shift:!0,alt:!1}),h=D.useMemo(()=>new Set([...l]),[l]),d=i.filter(U=>o?h.has(U.unitId):!0).sort((U,$)=>h.has(U.unitId)&&!h.has($.unitId)?1:!h.has(U.unitId)&&h.has($.unitId)?-1:Nt(U.unitId)-Nt($.unitId)),g=t.maxElectrodePixelRadius||wX.maxElectrodePixelRadius,p=t.colors??ea,_=t.showLabels??!1,m=t.offsetLabels??!1,{convertedElectrodes:v,pixelRadius:y,transform:b}=D.useMemo(()=>rg(e,n,r,"geom",g,{disableAutoRotate:s}),[r,n,g,e,s]),w=Math.sqrt(nf(u)),x=D.useCallback((U,$)=>{const J=y*w,ne=v.map(j=>{const V=(a||[]).includes(j.e.id),G=!1,z=!1,Q=V?z?p.draggedSelected:G?p.selectedHover:p.selected:z?p.dragged:G?p.hover:p.base;return{...j,color:Q,textColor:V||G&&!z?p.textDark:p.textLight}});if(U.clearRect(0,0,U.canvas.width,U.canvas.height),U.strokeStyle=ea.border,v.forEach(j=>{const V=fi(u,{x:j.pixelX,y:j.pixelY});U.beginPath(),U.ellipse(V.x,V.y,J,J,0,0,QD),U.stroke()}),_){U.font=`${J}px Arial`,U.textAlign=m?"right":"center",U.textBaseline="middle";const j=m?1.4*J:0;ne.forEach(V=>{const G=fi(u,{x:V.pixelX,y:V.pixelY});U.fillStyle=m?p.textDark:V.textColor,U.fillText(`${V.e.label}`,G.x-j,G.y)})}},[p,m,v,y,a,_,u,w]),S=D.useMemo(()=>{const U={};for(const $ of i){const ne=$.xLocations.map((j,V)=>{const G=$.xLocations[V],z=$.yLocations[V];return Jd(b,[G,z])}).map(j=>fi(u,{x:j[0],y:j[1]}));U[$.unitId]=ne}return U},[u,b,i]),A=D.useCallback((U,$)=>{const J=JD;U.clearRect(0,0,U.canvas.width,U.canvas.height);const ne=(j,V)=>{U.fillStyle=V,U.strokeStyle="black";for(let G=0;G<j.length;G++){const{x:z,y:Q}=j[G];U.beginPath(),U.ellipse(z,Q,J,J,0,0,QD),U.fill(),U.stroke()}};for(const j of d){const V=S[j.unitId],G=l.size===0||l.has(j.unitId)?ci(Nt(j.unitId)):"rgb(220, 220, 220)";ne(V,G)}},[d,l,S]),E=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:x,drawData:j_}),[e,n,x]),C=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:A,drawData:j_}),[e,n,A]),M=D.useCallback((U,{ctrlKey:$})=>{const J=TX(u,U),ne=nf(u),j=JD/Math.sqrt(ne),V=[];for(const G of d){const z=S[G.unitId];for(const Q of z)if(Qd(eM([Q.x-j,Q.y-j,j*2,j*2]),eM(J))){V.push(G.unitId);break}}if($)for(const G of V)c({type:"TOGGLE_UNIT",targetUnit:G});else c({type:"SET_SELECTION",incomingSelectedUnitIds:V})},[c,u,d,S]),T=D.useCallback((U,{ctrlKey:$})=>{c({type:"SET_SELECTION",incomingSelectedUnitIds:[]})},[c]),{onMouseMove:P,onMouseDown:I,onMouseUp:k,paintDragSelectLayer:O}=Cu(e,n,M,T),L=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:O,drawData:j_}),[e,n,O]);return R.jsxs("div",{style:{width:e,height:n,position:"relative"},onMouseMove:P,onMouseUp:k,onMouseDown:I,onWheel:f,children:[E,C,L]})},eM=t=>({xmin:t[0],ymin:t[1],xmax:t[0]+t[2],ymax:t[1]+t[3]}),TX=(t,e)=>{const n=jl(t,{x:e[0],y:e[1]}),r=jl(t,{x:e[0]+e[2],y:e[1]+e[3]});return[n.x,n.y,r.x-n.x,r.y-n.y]},tM=10,AX=({data:t,width:e,height:n})=>{const{selectedUnitIds:r}=Vr();return R.jsx(Jo,{width:e,height:n,initialPosition:200,children:r.size>tM?R.jsxs("div",{children:["Not showing spike locations. Too many units selected (max ="," ",tM,")."]}):R.jsx(EX,{data:t,width:0,height:0,selectedUnitIds:r})})},EX=t=>{const{data:e,width:n,height:r}=t,[i,s]=D.useState({...ef,onlyShowSelected:!1}),o=30,a=Object.keys(e.channelLocations),l=TD(a,e.channelLocations),c=D.useMemo(()=>({width:n-20,height:r-o,top:0,position:"absolute"}),[n,r]);return R.jsxs("div",{children:[R.jsx("div",{style:c,children:R.jsx(SX,{width:n-20,height:r-o,electrodes:l,units:e.units,disableAutoRotate:e.disableAutoRotate,onlyShowSelected:i.onlyShowSelected})}),R.jsx("div",{style:{position:"absolute",top:r-o,height:o,overflow:"hidden"},children:R.jsx(tf,{options:i,setOptions:s})})]})},CX=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.x_range,d=t.attrs.y_range,g=t.attrs.channel_locations||{},p=t.attrs.hide_unit_selector,_=t.attrs.disable_auto_rotate,m=t.attrs.units||[],v=[];for(const b of m){const w=b.name,x=b.unit_id,S=await t.getDatasetData(`${w}/spike_times_sec`,{}),A=await t.getDatasetData(`${w}/x_locations`,{}),E=await t.getDatasetData(`${w}/y_locations`,{});if(u)return;v.push({unitId:x,spikeTimesSec:Array.from(S),xLocations:Array.from(A),yLocations:Array.from(E)})}if(u)return;const y={type:"SpikeLocations",channelLocations:g,units:v,xRange:h,yRange:d};p&&(y.hideUnitSelector=p),_&&(y.disableAutoRotate=_),s(y)}catch(h){console.error("Error loading spike locations data:",h),a(`Failed to load spike locations data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading spike locations data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(AX,{data:i,width:n,height:r})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No spike locations data available"})},DX=25,H_=2*Math.PI,MX={maxElectrodePixelRadius:DX},W_={},Wl=8,RX=()=>({selectedElectrodeIds:[]}),IX=t=>{const{width:e,height:n,electrodes:r,units:i,disableAutoRotate:s,onlyShowSelected:o}=t,{selectedElectrodeIds:a}=RX(),{selectedUnitIds:l,unitIdSelectionDispatch:c}=Vr(),{affineTransform:u,handleWheel:f}=rf(e,n,{shift:!0,alt:!1}),h=D.useMemo(()=>new Set([...l]),[l]),d=i.filter(L=>o?h.has(L.unitId):!0).sort((L,U)=>h.has(L.unitId)&&!h.has(U.unitId)?1:!h.has(L.unitId)&&h.has(U.unitId)?-1:Nt(L.unitId)-Nt(U.unitId)),g=t.maxElectrodePixelRadius||MX.maxElectrodePixelRadius,p=t.colors??ea,_=t.showLabels??!1,m=t.offsetLabels??!1,{convertedElectrodes:v,pixelRadius:y,transform:b}=D.useMemo(()=>rg(e,n,r,"geom",g,{disableAutoRotate:s}),[r,n,g,e,s]),w=Math.sqrt(nf(u)),x=D.useCallback((L,U)=>{const $=y*w,J=v.map(ne=>{const j=(a||[]).includes(ne.e.id),V=!1,G=!1,z=j?G?p.draggedSelected:V?p.selectedHover:p.selected:G?p.dragged:V?p.hover:p.base;return{...ne,color:z,textColor:j||V&&!G?p.textDark:p.textLight}});if(L.clearRect(0,0,L.canvas.width,L.canvas.height),J.forEach(ne=>{const j=fi(u,{x:ne.pixelX,y:ne.pixelY});L.fillStyle=ne.color,L.beginPath(),L.ellipse(j.x,j.y,$,$,0,0,H_),L.fill()}),L.strokeStyle=ea.border,v.forEach(ne=>{const j=fi(u,{x:ne.pixelX,y:ne.pixelY});L.beginPath(),L.ellipse(j.x,j.y,$,$,0,0,H_),L.stroke()}),_){L.font=`${$}px Arial`,L.textAlign=m?"right":"center",L.textBaseline="middle";const ne=m?1.4*$:0;J.forEach(j=>{const V=fi(u,{x:j.pixelX,y:j.pixelY});L.fillStyle=m?p.textDark:j.textColor,L.fillText(`${j.e.label}`,V.x-ne,V.y)})}},[p,m,v,y,a,_,u,w]),S=D.useCallback((L,U)=>{const $=Wl;L.clearRect(0,0,L.canvas.width,L.canvas.height);const J=(ne,j,V)=>{L.fillStyle=V,L.strokeStyle="black",L.beginPath(),L.ellipse(ne,j,$,$,0,0,H_),L.fill(),L.stroke()};for(const ne of d){const j=Jd(b,[ne.x,ne.y]),V=fi(u,{x:j[0],y:j[1]}),G=l.size===0||l.has(ne.unitId)?ci(Nt(ne.unitId)):"rgb(220, 220, 220)";J(V.x,V.y,G)}},[b,d,l,u]),A=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:x,drawData:W_}),[e,n,x]),E=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:S,drawData:W_}),[e,n,S]),C=D.useCallback((L,{ctrlKey:U})=>{const $=PX(u,L),J=nf(u),ne=Wl/Math.sqrt(J),j=[];for(const V of d){const G=Jd(b,[V.x,V.y]);Qd(ag([G[0]-ne,G[1]-ne,ne*2,ne*2]),ag($))&&(ag([G[0]-ne,G[1]-ne,ne*2,ne*2]),j.push(V.unitId))}if(U)for(const V of j)c({type:"TOGGLE_UNIT",targetUnit:V});else c({type:"SET_SELECTION",incomingSelectedUnitIds:j})},[b,c,d,u]),M=D.useCallback((L,{ctrlKey:U})=>{let $=!1;for(const J of d){const ne=Jd(b,[J.x,J.y]);Wz(L,ag([ne[0]-Wl,ne[1]-Wl,Wl*2,Wl*2]))&&($=!0,c(U?{type:"TOGGLE_UNIT",targetUnit:J.unitId}:{type:"SET_SELECTION",incomingSelectedUnitIds:[J.unitId]}))}$||c({type:"SET_SELECTION",incomingSelectedUnitIds:[]})},[b,c,d]),{onMouseMove:T,onMouseDown:P,onMouseUp:I,paintDragSelectLayer:k}=Cu(e,n,C,M),O=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:k,drawData:W_}),[e,n,k]);return e>0&&n>0?R.jsxs("div",{style:{width:e,height:n,position:"relative"},onMouseMove:T,onMouseUp:I,onMouseDown:P,onWheel:f,children:[A,E,O]}):R.jsx("div",{})},ag=t=>({xmin:t[0],ymin:t[1],xmax:t[0]+t[2],ymax:t[1]+t[3]}),PX=(t,e)=>{const n=jl(t,{x:e[0],y:e[1]}),r=jl(t,{x:e[0]+e[2],y:e[1]+e[3]});return[n.x,n.y,r.x-n.x,r.y-n.y]},OX=t=>{const{data:e,width:n,height:r}=t,[i,s]=D.useState({...ef,onlyShowSelected:!1}),o=30,a=Object.keys(e.channelLocations),l=TD(a,e.channelLocations),c=D.useMemo(()=>({width:n-20,height:r-o,top:0,position:"absolute"}),[n,r]);return R.jsxs("div",{children:[R.jsx("div",{style:c,children:R.jsx(IX,{width:n-20,height:r-o,electrodes:l,units:e.units,disableAutoRotate:e.disableAutoRotate,onlyShowSelected:i.onlyShowSelected})}),R.jsx("div",{style:{position:"absolute",top:r-o,height:o,overflow:"hidden"},children:R.jsx(tf,{options:i,setOptions:s})})]})},NX=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.disable_auto_rotate||!1,d=t.attrs.unit_ids,g=t.attrs.channel_locations,p=await t.getDatasetData("coords",{});if(!p||p.length===0)throw new Error("Empty coords data");const _=new Float32Array(p);if(_.length!==d.length*2)throw new Error(`Expected coords length ${d.length*2}, got ${_.length}`);const m=[];for(let v=0;v<d.length;v++)m.push({unitId:d[v],x:_[v*2],y:_[v*2+1]});if(u)return;s({type:"UnitLocations",channelLocations:g,units:m,disableAutoRotate:h})}catch(h){console.error("Error loading unit locations data:",h),a(`Failed to load unit locations data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading unit locations data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(OX,{data:i,width:n,height:r})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No unit locations data available"})},FX=({rows:t,columns:e,onDeleteRow:n=void 0,deleteRowLabel:r=void 0,onEditRow:i=void 0,editRowLabel:s=void 0,selectionMode:o="none",selectedRowKeys:a=[],onSelectedRowKeysChanged:l=void 0,selectionDisabled:c})=>{const u=D.useMemo(()=>{const m={};return a.forEach(v=>{m[v]=!0}),m},[a]),[f,h]=D.useState(null),d=D.useCallback(m=>{l&&(o==="single"?!(m in u)||!u[m]?l([m+""]):l([]):o==="multiple"&&l(Object.keys(u).filter(v=>v!=m&&u[v]).concat(u[m]?[]:[m.toString()])))},[l,o,u]),g=D.useCallback(m=>{h(m)},[]),p=D.useCallback((m,v)=>{v&&n&&n(m),h(null)},[n]),_=D.useCallback(m=>{i&&i(m)},[i]);return R.jsxs(oH,{className:"NiceTable",children:[R.jsx(bH,{children:R.jsxs(pD,{children:[R.jsx(Qp,{style:{width:0}},"_first"),e.map(m=>R.jsx(Qp,{children:m.element?m.element:R.jsx("span",{children:m.label})},m.key))]})}),R.jsx(fH,{children:t.map(m=>R.jsxs(pD,{children:[R.jsxs(Qp,{children:[n&&(f===m.key?R.jsx(kX,{title:r||"",onConfirmDeleteRow:p,rowKey:m.key}):R.jsx(BX,{title:r||"",onDeleteRow:g,rowKey:m.key})),i&&R.jsx(UX,{title:s||"",onEditRow:_,rowKey:m.key}),o!=="none"&&R.jsx(oD,{checked:u[m.key]||!1,onClick:()=>d(m.key),disabled:c})]}),e.map(v=>R.jsx(Qp,{children:R.jsx("span",{children:LX(m.columnValues[v.key])})},v.key))]},m.key))})]})},BX=({title:t,rowKey:e,onDeleteRow:n})=>{const r=D.useCallback(()=>{n&&n(e)},[n,e]);return R.jsx(Vl,{title:t,onClick:r,children:R.jsx(zE,{})})},kX=({title:t,rowKey:e,onConfirmDeleteRow:n})=>{const r=D.useCallback(()=>{n&&n(e,!0)},[n,e]),i=D.useCallback(()=>{n&&n(e,!1)},[n,e]);return R.jsxs("span",{children:["Confirm delete?",R.jsx(Vl,{title:t,onClick:r,children:R.jsx(zE,{})}),R.jsx(Vl,{title:"Cancel",onClick:i,children:R.jsx(w9,{})})]})},UX=({title:t,rowKey:e,onEditRow:n})=>R.jsx(Vl,{title:t,onClick:()=>n&&n(e),children:R.jsx(x9,{})}),LX=t=>t==0?t:t?typeof t=="object"?t.element?t.element:t.text||"":t:"",zX=({width:t,height:e})=>{const{selectedUnitMetrics:n,allUnitMetrics:r,unitMetricSelectionDispatch:i}=gv(),s=D.useMemo(()=>[{key:"metric",label:"Metric"}],[]),o=D.useMemo(()=>(r||[]).map(l=>({key:l,columnValues:{metric:l}})),[r]),a=D.useCallback(l=>{i({type:"selectUnitMetrics",unitMetrics:l})},[i]);return R.jsx("div",{style:{position:"absolute",width:t,height:e},children:R.jsx(FX,{rows:o,columns:s,selectedRowKeys:n,onSelectedRowKeysChanged:a,selectionMode:"multiple"})})},$X=(t,e)=>{t.clearRect(0,0,e.width,e.height);for(const n of e.pixelVerticalLines||[])t.strokeStyle=n.color,t.beginPath(),t.moveTo(n.x,e.margins.top-20),t.lineTo(n.x,e.height-e.margins.bottom),t.stroke();e.barBoxes.forEach(n=>{t.fillStyle=n.color,t.fillRect(n.x1,n.y1,n.x2-n.x1,n.y2-n.y1)}),e.xLabel&&(t.textBaseline="bottom",t.textAlign="center",t.fillStyle="black",t.fillText(e.xLabel,e.width/2,e.height-3));for(const n of e.pixelTicks||[])t.strokeStyle="black",t.beginPath(),t.moveTo(n.x,e.height-e.margins.bottom),t.lineTo(n.x,e.height-e.margins.bottom+6),t.stroke(),t.textBaseline="top",t.textAlign="center",t.fillStyle="black",t.fillText(n.label,n.x,e.height-e.margins.bottom+8)},VX=t=>R.jsx(qn,{width:t.width,height:t.height,draw:$X,drawData:t}),jX={},HX=({bars:t,range:e,ticks:n,verticalLines:r,xLabel:i,onSelectRect:s,width:o,height:a})=>{const{xMin:l,xMax:c}=D.useMemo(()=>e?{xMin:e.min,xMax:e.max}:t.length>0?{xMin:t[0].xStart,xMax:t[t.length-1].xEnd}:{xMin:0,xMax:1},[t,e]),u=D.useMemo(()=>Math.max(...t.map(S=>S.height)),[t]),{barBoxes:f,margins:h,pixelTicks:d,pixelVerticalLines:g}=D.useMemo(()=>{const S={left:3,right:3,top:5,bottom:3+(i?18:0)+(n?18:0)},A=o-S.left-S.right,E=a-S.top-S.bottom,C=t.map(P=>({key:P.key,x1:S.left+(P.xStart-l)/(c-l)*A,x2:S.left+(P.xEnd-l)/(c-l)*A,y1:S.top+E*(1-P.height/u),y2:S.top+E,tooltip:P.tooltip,color:P.color})),M=n?n.map(P=>({x:S.left+(P.x-l)/(c-l)*A,label:`${P.label}`})):void 0,T=r?r.map(P=>({x:S.left+(P.x-l)/(c-l)*A,color:P.color})):void 0;return{barBoxes:C,margins:S,pixelTicks:M,pixelVerticalLines:T}},[t,n,r,l,c,u,o,a,i]),p=D.useCallback((S,{ctrlKey:A,shiftKey:E})=>{const C=[],M={x:S[0],y:S[1],width:S[2],height:S[3]};for(const k of f)k.x1<=M.x+M.width&&k.x2>=M.x&&C.push(k.key);const T=o-h.left-h.right,P=(M.x-h.left)/T*(c-l)+l,I=(M.x+M.width-h.left)/T*(c-l)+l;s&&s(M,C,{ctrlKey:A,shiftKey:E,xMin:P,xMax:I})},[f,s,h.left,h.right,o,l,c]),_=D.useCallback(()=>{},[]),{onMouseMove:m,onMouseDown:v,onMouseUp:y,onMouseLeave:b,paintDragSelectLayer:w}=Cu(o,a,p,_),x=D.useMemo(()=>R.jsx(qn,{width:o,height:a,draw:w,drawData:jX}),[o,a,w]);return R.jsxs("div",{style:{width:o,height:a,position:"relative"},onMouseDown:v,onMouseMove:m,onMouseUp:y,onMouseLeave:b,children:[R.jsx(VX,{barBoxes:f,margins:h,pixelTicks:d,pixelVerticalLines:g,xLabel:i,width:o,height:a}),x]})},WX=(t,e)=>{const n=e-t;let r;n<=30?r=10:n<=120?r=20:n<=300?r=50:n<=600?r=100:n<=1e3?r=150:r=100;const i=[];let s=Math.ceil(t/r);for(;s*r<=e;)i.push(s*r),s++;return i},XX=({metric:t,metricRange:e,units:n,selectedUnitIds:r,setSelectedUnitIds:i,numBins:s,onZoomToRect:o,width:a,height:l})=>{const{bars:c,ticks:u,verticalLines:f}=D.useMemo(()=>{const d=n.map(m=>m.values[t.key]).filter(m=>m!==void 0).map(m=>m),g=n.filter(m=>r.has(m.unitId)).map(m=>m.values[t.key]).filter(m=>m!==void 0).map(m=>m),_=n.filter(m=>r.has(m.unitId)).map(m=>({unitId:m.unitId,value:m.values[t.key]})).filter(m=>m.value!==void 0).map(m=>m.unitId).map(m=>ci(Nt(m)));return qX(d,g,_,s||10)},[n,t,r,s]),h=D.useCallback((d,g,{ctrlKey:p,shiftKey:_,xMin:m,xMax:v})=>{if(_){o&&o({x:m,y:d.y,width:v-m,height:d.height});return}if(g.length===0)return;const y=[];for(const S of g){const A=c[S];y.push(A)}const b=Math.min(...y.map(S=>S.xStart)),w=Math.max(...y.map(S=>S.xEnd)),x=[];for(const S of n){const A=S.values[t.key];A!==void 0&&b<=A&&A<=w&&x.push(S.unitId)}i(p||_?[...new Set([...r,...x])]:x)},[c,t,r,i,n,o]);return R.jsx(HX,{width:a,height:l,bars:c,range:e,ticks:u,verticalLines:f,onSelectRect:h})},qX=(t,e,n,r)=>{if(t.length===0)return{bars:[],ticks:[],verticalLines:[]};let i=Math.min(...t),s=Math.max(...t);if(s<=i)return{bars:[],ticks:[],verticalLines:[]};i-=(s-i)/r/2,s+=(s-i)/r/2;const o=[];for(let f=0;f<r;f++)o.push(0);for(const f of t){const h=Math.min(Math.floor((f-i)/(s-i)*r),r-1);o[h]++}const a=[];for(let f=0;f<r;f++)a.push(0);for(const f of e){const h=Math.min(Math.floor((f-i)/(s-i)*r),r-1);a[h]++}const l=[];e.forEach((f,h)=>{l.push({x:f,color:n[h]})});const u=YX(i,s).map(f=>({x:f,label:`${f}`}));return{bars:[...o.map((f,h)=>({key:h,xStart:i+h*(s-i)/r,xEnd:i+(h+1)*(s-i)/r,height:f,tooltip:"",color:"gray"}))],ticks:u,verticalLines:l}},YX=(t,e)=>{const n=e-t;if(n<=0)return[];let r=1;for(;n*r<100;)r*=10;for(;n*r>=1e3;)r/=10;return WX(t*r,e*r).map(i=>i/r)},KX=(t,e)=>{t.clearRect(0,0,e.width,e.height),e.markers.forEach(n=>{const r=e.coord2Pixel({x:n.x,y:n.y});t.fillStyle=n.color,t.strokeStyle="black",t.beginPath(),t.ellipse(r.x,r.y,n.radius,n.radius,0,0,2*Math.PI),t.fill(),t.stroke()})},ZX=t=>R.jsx(qn,{width:t.width,height:t.height,draw:KX,drawData:t}),GX={},QX=({markers:t,xRange:e,yRange:n,onSelectRect:r,onClickPoint:i,width:s,height:o})=>{const{margins:a}=D.useMemo(()=>({margins:{left:20,right:20,top:20,bottom:20}}),[]),{xMin:l,xMax:c,yMin:u,yMax:f}=D.useMemo(()=>{let x,S,A,E;return e?(x=e.min,S=e.max):t.length>0?(x=Math.min(...t.map(C=>C.x)),S=Math.max(...t.map(C=>C.x))):(x=0,S=1),n?(A=n.min,E=n.max):t.length>0?(A=Math.min(...t.map(C=>C.y)),E=Math.max(...t.map(C=>C.y))):(A=0,E=1),{xMin:x,xMax:S,yMin:A,yMax:E}},[t,e,n]),{coord2Pixel:h,pixel2Coord:d}=D.useMemo(()=>{const x=s-a.left-a.right,S=o-a.top-a.bottom;return{coord2Pixel:C=>({x:a.left+(C.x-l)/(c-l)*x,y:a.top+(1-(C.y-u)/(f-u))*S}),pixel2Coord:C=>({x:l+(C.x-a.left)/x*(c-l),y:u+(1-(C.y-a.top)/S)*(f-u)})}},[s,o,a,l,c,u,f]),g=D.useCallback((x,{ctrlKey:S,shiftKey:A})=>{const E={x:x[0],y:x[1],width:x[2],height:x[3]},C=[];for(const T of t){const P=h({x:T.x,y:T.y}),I={xmin:P.x-T.radius,ymin:P.y-T.radius,xmax:P.x+T.radius,ymax:P.y+T.radius};Qd({xmin:E.x,xmax:E.x+E.width,ymin:E.y,ymax:E.y+E.height},I)&&C.push(T.key)}const M=JX(d,E);r&&r(M,C,{ctrlKey:S,shiftKey:A})},[r,d,t,h]),p=D.useCallback((x,{ctrlKey:S,shiftKey:A})=>{const E={x:x[0],y:x[1]},C={x:E.x,y:E.y,width:1,height:1};let M;for(const T of t){const P=h({x:T.x,y:T.y}),I={xmin:P.x-T.radius,ymin:P.y-T.radius,xmax:P.x+T.radius,ymax:P.y+T.radius};Qd({xmin:C.x,xmax:C.x+C.width,ymin:C.y,ymax:C.y+C.height},I)&&(M=T.key)}i&&i(d(E),M,{ctrlKey:S,shiftKey:A})},[h,t,i,d]),{onMouseMove:_,onMouseDown:m,onMouseUp:v,onMouseLeave:y,paintDragSelectLayer:b}=Cu(s,o,g,p),w=D.useMemo(()=>R.jsx(qn,{width:s,height:o,draw:b,drawData:GX}),[s,o,b]);return R.jsxs("div",{style:{width:s,height:o,position:"relative"},onMouseDown:m,onMouseMove:_,onMouseUp:v,onMouseLeave:y,children:[R.jsx(ZX,{markers:t,margins:a,coord2Pixel:h,width:s,height:o}),w]})},JX=(t,e)=>{const n=t({x:e.x,y:e.y}),r=t({x:e.x+e.width,y:e.y+e.height});return{x:Math.min(n.x,r.x),y:Math.min(n.y,r.y),width:Math.abs(r.x-n.x),height:Math.abs(r.y-n.y)}},eq=({metric1:t,metric2:e,metric1Range:n,metric2Range:r,units:i,selectedUnitIds:s,setSelectedUnitIds:o,onZoomToRect:a,width:l,height:c})=>{const f=D.useMemo(()=>{const g=[];for(const p of i){const _=p.values[t.key],m=p.values[e.key];_!==void 0&&m!==void 0&&g.push({key:p.unitId,x:_,y:m,color:s.has(p.unitId)?ci(Nt(p.unitId)):"lightgray",radius:6,tooltip:`Unit ${p.unitId}`})}return g},[i,t,e,s]),h=D.useCallback((g,p,{ctrlKey:_,shiftKey:m})=>{if(m){a&&a(g);return}let v=p;_&&(v=[...new Set([...p,...s])]),o(v)},[o,s,a]),d=D.useCallback((g,p,{ctrlKey:_,shiftKey:m})=>{let v;if(_||m){const y=new Set([...s]);p!==void 0&&(y.has(p)?y.delete(p):y.add(p)),v=[...y]}else p===void 0?v=[]:v=[p];o(v)},[o,s]);return R.jsx(QX,{width:l,height:c,markers:f,xRange:n,yRange:r,onSelectRect:h,onClickPoint:d})},tq=({type:t,metric1:e,metric2:n,metric1Range:r,metric2Range:i,units:s,selectedUnitIds:o,setSelectedUnitIds:a,numHistogramBins:l,onZoomToRect:c,width:u,height:f})=>{if(t==="histogram"){if(!e)throw Error("Unexpected: metric1 not defined");return R.jsx(XX,{metric:e,metricRange:r,units:s,selectedUnitIds:o,setSelectedUnitIds:a,numBins:l,onZoomToRect:c,width:u,height:f})}else if(t==="scatter"){if(!e)throw Error("Unexpected: metric1 not defined");if(!n)throw Error("Unexpected: metric2 not defined");return R.jsx(eq,{metric1:e,metric2:n,metric1Range:r,metric2Range:i,units:s,selectedUnitIds:o,setSelectedUnitIds:a,onZoomToRect:c,width:u,height:f})}else{if(t==="bottom-label")return R.jsx("div",{style:{width:u,textAlign:"center"},children:e?.label||R.jsx("span",{children:" "})});if(t==="left-label")return R.jsx("div",{style:{width:u,height:f,overflow:"hidden",writingMode:"vertical-lr",transform:"rotate(-180deg)",textAlign:"center"},children:e?.label||R.jsx("span",{children:" "})});throw Error(`Unexpected type: ${t}`)}},nq=({data:t,width:e,height:n})=>{const{units:r,metrics:i}=t,{selectedUnitIds:s,unitIdSelectionDispatch:o}=Vr(),{selectedUnitMetrics:a}=gv(),[l,c]=D.useState(1),[u,f]=D.useState(10),[h,d]=D.useState({}),g=D.useMemo(()=>r.sort((v,y)=>s.has(v.unitId)&&!s.has(y.unitId)?1:!s.has(v.unitId)&&s.has(y.unitId)?-1:Nt(v.unitId)-Nt(y.unitId)),[r,s]);D.useEffect(()=>{o({type:$o,newUnitOrder:si(g.map(v=>v.unitId))})},[g,o]);const p=D.useMemo(()=>{const v=a.length===0?[{type:"text",content:"Box size",title:"Set box size"},{type:"button",callback:()=>c(w=>w*1.3),title:"Increase box size",icon:R.jsx(sp,{})},{type:"button",callback:()=>c(w=>w/1.3),title:"Decrease box size",icon:R.jsx(ip,{})}]:[],y=[{type:"text",content:"# bins",title:""},{type:"button",callback:()=>f(w=>w+5),title:"Increase num. histogram bins",icon:R.jsx(sp,{})},{type:"button",callback:()=>f(w=>Math.max(5,w-5)),title:"Decrease num. histogram bins",icon:R.jsx(ip,{})}],b={type:"button",callback:()=>d({}),title:"Reset zoom",text:"reset"};return[...v,{type:"divider"},...y,{type:"divider"},b]},[a.length]),_=Qu,m=D.useMemo(()=>{const v=y=>{o({type:"SET_SELECTION",incomingSelectedUnitIds:y})};if(a.length===0)return i.map(y=>{const b={type:"histogram",metric1:y,metric2:y,metric1Range:h[y.key],metric2Range:h[y.key],units:g,width:400*l,height:400*l,numHistogramBins:u,selectedUnitIds:s,setSelectedUnitIds:v,onZoomToRect:x=>{d({...h,[y.key]:{min:x.x,max:x.x+x.width}})}};return{key:y.key,label:y.label,unitId:"",labelColor:"black",props:b}});{const{plotWidth:w,plotHeight:x}=LD(e-_-30-10,n-30-10,a.length),S=[];for(const A of a){const E=i.filter(C=>C.key===A)[0];{const C={type:"left-label",metric1:E,metric2:E,units:g,numHistogramBins:u,width:30,height:x,selectedUnitIds:s,setSelectedUnitIds:v};S.push({key:`left-label-${A}`,label:void 0,unitId:"",labelColor:"black",props:C,hideBorderColor:!0})}for(const C of a){const M=i.filter(T=>T.key===C)[0];if(E&&M){const T={type:A===C?"histogram":"scatter",metric1:M,metric2:E,metric1Range:h[M.key],metric2Range:h[E.key],units:g,numHistogramBins:u,width:w,height:x,selectedUnitIds:s,setSelectedUnitIds:v,onZoomToRect:P=>{d(A!==C?{...h,[M.key]:{min:P.x,max:P.x+P.width},[E.key]:{min:P.y,max:P.y+P.height}}:{...h,[E.key]:{min:P.x,max:P.x+P.width}})}};S.push({key:`${C}-${A}`,label:T.type==="histogram"?A:void 0,unitId:"",labelColor:"black",props:T})}}}{const A={type:"bottom-label",metric1:void 0,metric2:void 0,units:g,numHistogramBins:u,width:30,height:30,selectedUnitIds:s,setSelectedUnitIds:v};S.push({key:"left-bottom-label",label:void 0,unitId:"",labelColor:"black",props:A,hideBorderColor:!0})}for(const A of a){const E=i.filter(M=>M.key===A)[0],C={type:"bottom-label",metric1:E,metric2:E,units:g,numHistogramBins:u,width:w,height:30,selectedUnitIds:s,setSelectedUnitIds:v};S.push({key:`bottom-label-${A}`,label:void 0,unitId:"",labelColor:"black",props:C,hideBorderColor:!0})}return S}},[i,s,g,l,a,u,e,n,o,h,_]);return R.jsxs(Jo,{width:e,height:n,initialPosition:_,adjustable:!1,children:[R.jsx(Ju,{width:_,height:n,customActions:p}),R.jsx(tp,{width:0,height:0,disableScroll:a.length>0,children:R.jsx(ep,{plots:m,plotComponent:tq,numPlotsPerRow:a.length===0?void 0:a.length+1})})]})},rq=({data:t,width:e,height:n})=>{const{metrics:r}=t,{unitMetricSelectionDispatch:i}=gv();return D.useEffect(()=>{i({type:"initialize",unitMetrics:r.map(s=>s.key)})},[r,i]),R.jsxs(Jo,{width:e,height:n,initialPosition:200,adjustable:!0,children:[R.jsx(zX,{width:0,height:0}),R.jsx(nq,{data:t,width:0,height:0})]})},iq=t=>vd(t,{key:yd,label:yd,dtype:yd}),sq=t=>vd(t,{unitId:EB([AB,yd]),values:()=>!0}),oq=t=>vd(t,{type:CB("UnitMetricsGraph"),metrics:_3(iq),units:_3(sq)}),aq=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.metrics||[],d=await t.getDatasetData("units_data",{});if(!d||d.length===0)throw new Error("Empty units data");const g=new Uint8Array(d),p=new TextDecoder("utf-8").decode(g),_=JSON.parse(p);if(u)return;const m={type:"UnitMetricsGraph",metrics:h,units:_.map(v=>({unitId:v.unit_id,values:v.values}))};if(!oq(m))throw new Error("Invalid view data structure");s(m)}catch(h){console.error("Error loading unit metrics graph data:",h),a(`Failed to load unit metrics graph data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading unit metrics data..."}):i?R.jsx(lq,{context:e.unitMetricSelection,children:R.jsx(ui,{context:e.unitSelection,children:R.jsx(rq,{data:i,width:n,height:r})})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No unit metrics data available"})},lq=({context:t,children:e})=>{const{state:n,dispatch:r}=Jp(t);return!r||!n?R.jsx(R.Fragment,{children:"Waiting for unit metric selection context..."}):R.jsx(o3.Provider,{value:{unitMetricSelection:n,unitMetricSelectionDispatch:r},children:e})},cq=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.unit_ids||[],d=t.attrs.similarity_scores||[],g=t.attrs.range;if(u)return;const p={type:"UnitSimilarityMatrix",unitIds:h,similarityScores:d};g&&(p.range=g),s(p)}catch(h){console.error("Error loading unit similarity matrix data:",h),a(`Failed to load unit similarity matrix data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading unit similarity matrix data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(oW,{data:i,width:n,height:r})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No unit similarity matrix data available"})};function lg(t,e){if(!t)throw new Error(e||"loader assertion failed.")}const X_=!!(typeof process!="object"||String(process)!=="[object process]"||process.browser),nM=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version);nM&&parseFloat(nM[1]);const rM=globalThis,iM=globalThis.process||{},uq=globalThis.navigator||{};function sM(t){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;const n=typeof navigator<"u"&&navigator.userAgent;return!!(n&&n.indexOf("Electron")>=0)}function na(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||sM()}function fq(t){return na()?sM()?"Electron":(uq.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown":"Node"}const oM="4.1.0";function hq(t){try{const e=window[t],n="__storage_test__";return e.setItem(n,n),e.removeItem(n),e}catch{return null}}class dq{constructor(e,n,r="sessionStorage"){this.storage=hq(r),this.id=e,this.config=n,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){const n=JSON.stringify(this.config);this.storage.setItem(this.id,n)}}_loadConfiguration(){let e={};if(this.storage){const n=this.storage.getItem(this.id);e=n?JSON.parse(n):{}}return Object.assign(this.config,e),this}}function pq(t){let e;return t<10?e=`${t.toFixed(2)}ms`:t<100?e=`${t.toFixed(1)}ms`:t<1e3?e=`${t.toFixed(0)}ms`:e=`${(t/1e3).toFixed(2)}s`,e}function gq(t,e=8){const n=Math.max(e-t.length,0);return`${" ".repeat(n)}${t}`}var cg;(function(t){t[t.BLACK=30]="BLACK",t[t.RED=31]="RED",t[t.GREEN=32]="GREEN",t[t.YELLOW=33]="YELLOW",t[t.BLUE=34]="BLUE",t[t.MAGENTA=35]="MAGENTA",t[t.CYAN=36]="CYAN",t[t.WHITE=37]="WHITE",t[t.BRIGHT_BLACK=90]="BRIGHT_BLACK",t[t.BRIGHT_RED=91]="BRIGHT_RED",t[t.BRIGHT_GREEN=92]="BRIGHT_GREEN",t[t.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",t[t.BRIGHT_BLUE=94]="BRIGHT_BLUE",t[t.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",t[t.BRIGHT_CYAN=96]="BRIGHT_CYAN",t[t.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(cg||(cg={}));const mq=10;function aM(t){return typeof t!="string"?t:(t=t.toUpperCase(),cg[t]||cg.WHITE)}function yq(t,e,n){return!na&&typeof t=="string"&&(e&&(t=`\x1B[${aM(e)}m${t}\x1B[39m`),n&&(t=`\x1B[${aM(n)+mq}m${t}\x1B[49m`)),t}function vq(t,e=["constructor"]){const n=Object.getPrototypeOf(t),r=Object.getOwnPropertyNames(n),i=t;for(const s of r){const o=i[s];typeof o=="function"&&(e.find(a=>s===a)||(i[s]=o.bind(t)))}}function q_(t,e){if(!t)throw new Error("Assertion failed")}function Xl(){let t;if(na()&&rM.performance)t=rM?.performance?.now?.();else if("hrtime"in iM){const e=iM?.hrtime?.();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}const ql={debug:na()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},_q={enabled:!0,level:0};function Yl(){}const lM={},cM={once:!0};class of{constructor({id:e}={id:""}){this.VERSION=oM,this._startTs=Xl(),this._deltaTs=Xl(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new dq(`__probe-${this.id}__`,_q),this.timeStamp(`${this.id} started`),vq(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Xl()-this._startTs).toPrecision(10))}getDelta(){return Number((Xl()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._storage.setConfiguration({enabled:e}),this}setLevel(e){return this._storage.setConfiguration({level:e}),this}get(e){return this._storage.config[e]}set(e,n){this._storage.setConfiguration({[e]:n})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,n){if(!e)throw new Error(n||"Assertion failed")}warn(e){return this._getLogFunction(0,e,ql.warn,arguments,cM)}error(e){return this._getLogFunction(0,e,ql.error,arguments)}deprecated(e,n){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${n}\` instead`)}removed(e,n){return this.error(`\`${e}\` has been removed. Use \`${n}\` instead`)}probe(e,n){return this._getLogFunction(e,n,ql.log,arguments,{time:!0,once:!0})}log(e,n){return this._getLogFunction(e,n,ql.debug,arguments)}info(e,n){return this._getLogFunction(e,n,console.info,arguments)}once(e,n){return this._getLogFunction(e,n,ql.debug||ql.info,arguments,cM)}table(e,n,r){return n?this._getLogFunction(e,n,console.table||Yl,r&&[r],{tag:xq(n)}):Yl}time(e,n){return this._getLogFunction(e,n,console.time?console.time:console.info)}timeEnd(e,n){return this._getLogFunction(e,n,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,n){return this._getLogFunction(e,n,console.timeStamp||Yl)}group(e,n,r={collapsed:!1}){const i=fM({logLevel:e,message:n,opts:r}),{collapsed:s}=r;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}groupCollapsed(e,n,r={}){return this.group(e,n,Object.assign({},r,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||Yl)}withGroup(e,n,r){this.group(e,n)();try{r()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=uM(e)}_getLogFunction(e,n,r,i,s){if(this._shouldLog(e)){s=fM({logLevel:e,message:n,args:i,opts:s}),r=r||s.method,q_(r),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=Xl();const o=s.tag||s.message;if(s.once&&o)if(!lM[o])lM[o]=Xl();else return Yl;return n=bq(this.id,s.message,s),r.bind(console,n,...s.args)}return Yl}}of.VERSION=oM;function uM(t){if(!t)return 0;let e;switch(typeof t){case"number":e=t;break;case"object":e=t.logLevel||t.priority||0;break;default:return 0}return q_(Number.isFinite(e)&&e>=0),e}function fM(t){const{logLevel:e,message:n}=t;t.logLevel=uM(e);const r=t.args?Array.from(t.args):[];for(;r.length&&r.shift()!==n;);switch(typeof e){case"string":case"function":n!==void 0&&r.unshift(n),t.message=e;break;case"object":Object.assign(t,e);break}typeof t.message=="function"&&(t.message=t.message());const i=typeof t.message;return q_(i==="string"||i==="object"),Object.assign(t,{args:r},t.opts)}function bq(t,e,n){if(typeof e=="string"){const r=n.time?gq(pq(n.total)):"";e=n.time?`${t}: ${r} ${e}`:`${t}: ${e}`,e=yq(e,n.color,n.background)}return e}function xq(t){for(const e in t)for(const n in t[e])return n||"untitled";return"empty"}const Y_="4.3.3",wq=Y_[0]>="0"&&Y_[0]<="9"?`v${Y_}`:"";function Sq(){const t=new of({id:"loaders.gl"});return globalThis.loaders=globalThis.loaders||{},globalThis.loaders.log=t,globalThis.loaders.version=wq,globalThis.probe=globalThis.probe||{},globalThis.probe.loaders=t,t}const Tq=Sq();function Aq(t,e){return hM(t||{},e)}function hM(t,e,n=0){if(n>3)return e;const r={...t};for(const[i,s]of Object.entries(e))s&&typeof s=="object"&&!Array.isArray(s)?r[i]=hM(r[i]||{},e[i],n+1):r[i]=e[i];return r}const Eq="latest";function Cq(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.3.3"),globalThis._loadersgl_.version}const Dq=Cq();function oo(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}const ra=typeof process!="object"||String(process)!=="[object process]"||process.browser,Mq=typeof window<"u"&&typeof window.orientation<"u",dM=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version);dM&&parseFloat(dM[1]);class Rq{name;workerThread;isRunning=!0;result;_resolve=()=>{};_reject=()=>{};constructor(e,n){this.name=e,this.workerThread=n,this.result=new Promise((r,i)=>{this._resolve=r,this._reject=i})}postMessage(e,n){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:n})}done(e){oo(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){oo(this.isRunning),this.isRunning=!1,this._reject(e)}}class K_{terminate(){}}const Z_=new Map;function Iq(t){oo(t.source&&!t.url||!t.source&&t.url);let e=Z_.get(t.source||t.url);return e||(t.url&&(e=Pq(t.url),Z_.set(t.url,e)),t.source&&(e=pM(t.source),Z_.set(t.source,e))),oo(e),e}function Pq(t){if(!t.startsWith("http"))return t;const e=Oq(t);return pM(e)}function pM(t){const e=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(e)}function Oq(t){return`try {
|
|
191
|
+
Action: ${e.type}`),e.type==="SET_CURATION")return e.curation;if(e.type==="CLOSE_CURATION")return{...t,isClosed:!0};if(e.type==="REOPEN_CURATION")return{...t,isClosed:!1};if(e.type==="ADD_UNIT_LABEL"){const n=typeof e.unitId=="object"?e.unitId:[e.unitId],r={...t.labelsByUnit||{}};let i=!1;for(const s of n){const o=r[s+""]||[];o.includes(e.label)||(i=!0,r[s+""]=[...o,e.label].sort())}return i?{...t,labelsByUnit:r}:t}else if(e.type==="TOGGLE_UNIT_LABEL"){const n=typeof e.unitId=="object"?e.unitId:[e.unitId];let r=!0;for(const i of n)((t.labelsByUnit||{})[i+""]||[]).includes(e.label)||(r=!1);return r?eg(t,{type:"REMOVE_UNIT_LABEL",unitId:e.unitId,label:e.label}):eg(t,{type:"ADD_UNIT_LABEL",unitId:e.unitId,label:e.label})}else if(e.type==="REMOVE_UNIT_LABEL"){const n=typeof e.unitId=="object"?e.unitId:[e.unitId],r={...t.labelsByUnit||{}};let i=!1;for(const s of n){const o=r[s+""]||[];o.includes(e.label)&&(i=!0,r[s+""]=o.filter(a=>a!==e.label))}return i?{...t,labelsByUnit:r}:t}else{if(e.type==="MERGE_UNITS")return{...t,mergeGroups:vD([...t.mergeGroups||[],e.unitIds])};if(e.type==="UNMERGE_UNITS")return{...t,mergeGroups:vD((t.mergeGroups||[]).map(n=>n.filter(r=>!e.unitIds.includes(r))))};if(e.type==="SET_LABEL_CHOICES")return{...t,labelChoices:e.labelChoices}}return t},HH={sortingCuration:jH,sortingCurationDispatch:t=>{console.warn("No sortingCurationDispatch function provided.")},curating:!1},mD=ln.createContext(HH),yD=()=>{const t=D.useContext(mD);if(!t)throw Error("useSortingCuration must be used within a SortingCurationContext.Provider");return t},WH=(t,e)=>t.filter(n=>e.includes(n)),XH=(t,e)=>[...t,...e.filter(n=>!t.includes(n))].sort(),vD=t=>{const e=t.map(r=>[...r]);let n=!0;for(;n;){n=!1;for(let r=0;r<e.length;r++){const i=e[r];for(let s=r+1;s<e.length;s++){const o=e[s];WH(i,o).length>0&&(e[r]=XH(i,o),e[s]=[],n=!0)}}}return e.filter(r=>r.length>=2)},_D=({data:t,width:e,height:n})=>{const[r,i]=D.useState({...ef,onlyShowSelected:!1}),{selectedUnitIds:s,currentUnitId:o,orderedUnitIds:a,visibleUnitIds:l,primarySortRule:c,checkboxClickHandlerGenerator:u,unitIdSelectionDispatch:f}=Vr(),{sortingCuration:h}=yD(),d=D.useMemo(()=>r.onlyShowSelected?l?l.filter(w=>s.has(w)):[...s]:l,[l,s,r.onlyShowSelected]),g=D.useMemo(()=>{const w=[];return w.push({columnName:"_unitId",label:"Unit",tooltip:"Unit ID",sort:(x,S)=>Nt(x)-Nt(S),dataElement:x=>R.jsx(zH,{unitId:x.unitId,mergeGroup:x.mergeGroup}),calculating:!1}),h&&w.push({columnName:"_labels",label:"Labels",tooltip:"Curation labels",sort:(x,S)=>x<S?-1:x>S?1:0,dataElement:x=>R.jsx("span",{children:x.join(", ")}),calculating:!1}),t.similarityScores&&w.push({columnName:"_similarity",label:"Similarity",tooltip:"Similarity with current unit",sort:(x,S)=>{if(x.unitId===o)return 1;if(S.unitId===o)return-1;const A=x.score,E=S.score;return A===void 0&&E!==void 0?-1:A!==void 0&&E===void 0?1:A===void 0&&E===void 0?0:A!==void 0&&E!==void 0?A<E?-1:A>E?1:0:0},dataElement:x=>R.jsx("span",{children:x}),calculating:!1,onlyAllowDescendingSort:!0}),t.columns.filter(x=>x.key!=="unitId").forEach(x=>{w.push({columnName:x.key,label:x.label,tooltip:x.label,sort:x.dtype==="str"?(S,A)=>S<A?-1:S>A?1:0:x.dtype==="int"?(S,A)=>S-A:x.dtype=="bool"?(S,A)=>(S?1:0)-(A?1:0):x.dtype==="float"?(S,A)=>S-A:(S,A)=>S-A,dataElement:S=>R.jsx("span",{children:S}),calculating:!1})}),w},[t.columns,o,h,t.similarityScores]),p=D.useMemo(()=>{for(let x=0;x<0;x++)a.push("never-added");const w={};if(t.similarityScores&&o!==void 0)for(const x of t.similarityScores)x.unitId1===o?w[x.unitId2]=x.similarity:x.unitId2===o&&(w[x.unitId1]=x.similarity);return t.rows.map(x=>{const S=(h?.labelsByUnit||{})[`${x.unitId}`]||[],A={value:{unitId:x.unitId,mergeGroup:$H(x.unitId,h)},sortValue:x.unitId},E=w[x.unitId],C={_unitId:A,_labels:{value:S,sortValue:S.join(", ")},_similarity:{value:E!==void 0?E.toFixed(3):void 0,sortValue:{unitId:x.unitId,score:E}}};for(const M of t.columns){const T=`${x.values[M.key]!==void 0?x.values[M.key]:""}`;C[M.key]={value:T,sortValue:x.values[M.key]}}return{rowId:x.unitId,data:C,checkboxFn:u(x.unitId)}})},[t.rows,t.columns,o,t.similarityScores,h,u,a]);D.useEffect(()=>{f({type:$o,newUnitOrder:si(p.map(w=>w.rowId))})},[p,f]);const _=D.useMemo(()=>{const w=new Map;return p.forEach(x=>w.set(x.rowId,x)),w},[p]),m=30,v=D.useMemo(()=>({width:e-20,height:n-m,top:0,position:"relative",overflowY:"auto"}),[e,n]),y=D.useCallback(w=>{if(w.ctrlKey)return w.key==="ArrowDown"?f({type:u3}):w.key==="ArrowUp"?f({type:f3}):w.key==="Home"?f({type:h3}):w.key==="End"&&f({type:d3}),!1},[f]),b=D.useCallback(()=>{f({type:"REDISTRIBUTE_UNIT_COLORS"})},[f]);return R.jsxs("div",{children:[R.jsx("div",{style:v,onKeyDown:y,children:R.jsx(VH,{columns:g,rows:_,orderedUnitIds:a,visibleUnitIds:d,selectedUnitIds:s,currentUnitId:o,selectionDispatch:f,primarySortRule:c})}),R.jsx("div",{style:{position:"absolute",top:n-m,height:m,overflow:"hidden"},children:R.jsx(tf,{options:r,setOptions:i,onRedistributeUnitColors:b})})]})},qH=({defaultLabelOptions:t,width:e,height:n})=>{const{selectedUnitIdsArray:r}=Vr(),{sortingCuration:i,sortingCurationDispatch:s,curating:o}=yD(),{labelChoices:a=[],labelsByUnit:l={},mergeGroups:c=[],isClosed:u=!1}=i,[f,h]=D.useState(""),[d,g]=D.useState(!1),p=D.useMemo(()=>a.length===0&&t.length>0&&o?(s({type:"SET_LABEL_CHOICES",labelChoices:t}),t):a,[a,t,s,o]);D.useEffect(()=>{},[p]);const _=D.useCallback(V=>{if(r.length===0)return"none";const G=r.filter(z=>(l[z.toString()]||[]).includes(V));return G.length===0?"none":G.length===r.length?"full":"partial"},[r,l]),m=D.useCallback(V=>{o&&(r.length===0||u||s({type:"TOGGLE_UNIT_LABEL",unitId:r,label:V}))},[r,u,s,o]),v=D.useCallback(()=>{if(!o)return;const V=f.trim();V&&!p.includes(V)&&(s({type:"SET_LABEL_CHOICES",labelChoices:[...p,V]}),h(""))},[f,p,s,o]),y=D.useCallback(V=>Object.values(l).some(G=>G.includes(V)),[l]),b=D.useCallback(V=>{o&&(y(V)||s({type:"SET_LABEL_CHOICES",labelChoices:p.filter(G=>G!==V)}))},[p,s,y,o]),w=D.useCallback(V=>c.find(G=>G.includes(V)),[c]),x=D.useMemo(()=>{if(r.length===0)return{canMerge:!1,canUnmerge:!1,groupsInvolved:[],unmergedUnits:[]};const V=new Set,G=[];r.forEach(ee=>{const ce=w(ee);ce?V.add(ce):G.push(ee)});const z=r.length>=2,Q=V.size>0;return{canMerge:z,canUnmerge:Q,groupsInvolved:Array.from(V),unmergedUnits:G}},[r,w]),S=D.useCallback(()=>{o&&(r.length<2||u||s({type:"MERGE_UNITS",unitIds:r}))},[r,u,s,o]),A=D.useCallback(()=>{o&&(r.length===0||u||s({type:"UNMERGE_UNITS",unitIds:r}))},[r,u,s,o]),E=D.useCallback(()=>{o&&s(u?{type:"REOPEN_CURATION"}:{type:"CLOSE_CURATION"})},[u,s,o]),C=D.useMemo(()=>r.length===0?"No units selected":r.length<=5?`Units: ${r.join(", ")}`:`${r.length} units selected`,[r]),M={width:e,height:n,padding:"8px",fontSize:"12px",fontFamily:"Arial, sans-serif",border:"1px solid #ddd",borderRadius:"4px",backgroundColor:"#fafafa",overflow:"auto",display:"flex",flexDirection:"column",gap:"8px"},T={marginBottom:"6px"},P={fontWeight:"bold",marginBottom:"4px",fontSize:"11px",color:"#333"},I={display:"inline-flex",alignItems:"center",padding:"2px 6px",margin:"2px",backgroundColor:"#e0e0e0",borderRadius:"12px",fontSize:"10px",border:"1px solid #ccc"},k={marginLeft:"4px",cursor:"pointer",color:"#666",fontWeight:"bold"},O={padding:"2px 4px",fontSize:"10px",border:"1px solid #ccc",borderRadius:"2px",marginRight:"4px",flex:1},L={padding:"2px 6px",fontSize:"10px",border:"1px solid #ccc",borderRadius:"2px",backgroundColor:"#f0f0f0",cursor:"pointer"},U={display:"inline-flex",alignItems:"center",margin:"2px 8px 2px 0",cursor:r.length>0&&!u?"pointer":"default",opacity:r.length>0&&!u?1:.5},$={...T,textAlign:"center"},J={...L,backgroundColor:u?"#f8d7da":"#d4edda",borderColor:u?"#f5c6cb":"#c3e6cb",color:u?"#721c24":"#155724"},ne={display:"flex",alignItems:"center",cursor:"pointer",fontSize:"11px",fontWeight:"bold",color:"#333",marginBottom:"4px"},j={marginRight:"4px",fontSize:"10px",transform:d?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s"};return R.jsxs("div",{style:M,children:[R.jsxs("div",{style:T,children:[R.jsx("div",{style:P,children:"Selected Units"}),R.jsx("div",{style:{fontSize:"10px",color:"#666"},children:C})]}),R.jsxs("div",{style:T,children:[R.jsx("div",{style:P,children:"Label Assignment"}),p.map(V=>{const G=_(V);return R.jsxs("div",{style:U,onClick:o?()=>m(V):void 0,children:[R.jsx("input",{type:"checkbox",checked:G==="full",ref:z=>{z&&(z.indeterminate=G==="partial")},onChange:()=>{},style:{marginRight:"4px"},disabled:r.length===0||u}),R.jsx("span",{style:{fontSize:"10px"},children:V})]},V)}),r.length===0&&R.jsx("div",{style:{fontSize:"10px",color:"#999",fontStyle:"italic"},children:"Select units to assign labels"})]}),R.jsxs("div",{style:T,children:[R.jsx("div",{style:P,children:"Unit Merging"}),r.length>0&&x.groupsInvolved.length>0&&R.jsxs("div",{style:{marginBottom:"6px"},children:[R.jsx("div",{style:{fontSize:"10px",color:"#666",marginBottom:"2px"},children:"Merge groups involving selected units:"}),x.groupsInvolved.map((V,G)=>{const z={...I,backgroundColor:"#e3f2fd",borderColor:"#90caf9",color:"#1565c0"};return R.jsx("span",{style:z,children:V.join(", ")},G)})]}),R.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center",flexWrap:"wrap"},children:[R.jsx("button",{onClick:o?S:void 0,style:{...L,backgroundColor:x.canMerge&&!u?"#d4edda":"#f8f9fa",borderColor:x.canMerge&&!u?"#c3e6cb":"#dee2e6",color:x.canMerge&&!u?"#155724":"#6c757d",cursor:x.canMerge&&!u?"pointer":"default"},disabled:!x.canMerge||u,title:u?"Cannot merge when curation is closed":r.length<2?"Select 2 or more units to merge":"Merge selected units",children:"Merge Selected"}),R.jsx("button",{onClick:o?A:void 0,style:{...L,backgroundColor:x.canUnmerge&&!u?"#fff3cd":"#f8f9fa",borderColor:x.canUnmerge&&!u?"#ffeaa7":"#dee2e6",color:x.canUnmerge&&!u?"#856404":"#6c757d",cursor:x.canUnmerge&&!u?"pointer":"default"},disabled:!x.canUnmerge||u,title:u?"Cannot unmerge when curation is closed":x.canUnmerge?"Unmerge selected units":"Select units that are part of merge groups to unmerge",children:"Unmerge Selected"})]}),r.length>0&&R.jsxs("div",{style:{fontSize:"10px",color:"#666",marginTop:"4px"},children:[x.groupsInvolved.length>0&&R.jsxs("div",{children:["Selected units in"," ",x.groupsInvolved.length," merge group(s)"]}),x.unmergedUnits.length>0&&R.jsxs("div",{children:[x.unmergedUnits.length," unmerged unit(s) selected"]})]}),r.length===0&&R.jsx("div",{style:{fontSize:"10px",color:"#999",fontStyle:"italic",marginTop:"4px"},children:"Select units to merge or unmerge"})]}),R.jsxs("div",{style:T,children:[R.jsxs("div",{style:ne,onClick:()=>g(!d),children:[R.jsx("span",{style:j,children:"▶"}),"Manage Label Choices"]}),d&&R.jsxs("div",{children:[R.jsx("div",{style:{marginBottom:"4px"},children:p.map(V=>{const G=y(V);return R.jsxs("span",{style:I,children:[V,!u&&!G&&R.jsx("span",{style:k,onClick:o?()=>b(V):void 0,title:"Remove label choice",children:"×"})]},V)})}),!u&&R.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[R.jsx("input",{type:"text",value:f,onChange:V=>h(V.target.value),onKeyPress:V=>V.key==="Enter"&&o&&v(),placeholder:"Add label...",style:O}),R.jsx("button",{onClick:o?v:void 0,style:L,disabled:!f.trim(),children:"Add"})]})]})]}),R.jsxs("div",{style:$,children:[R.jsx("button",{onClick:o?E:void 0,style:J,children:u?"Reopen Curation":"Finalize Curation"}),R.jsxs("div",{style:{fontSize:"10px",color:"#666",marginTop:"2px"},children:["Status: ",u?"Closed":"Open"]})]})]})},YH=({zarrGroup:t,contexts:e,width:n,height:r})=>R.jsx(ui,{context:e.unitSelection,children:R.jsx(bD,{contexts:e,editable:!0,children:R.jsx(KH,{zarrGroup:t,contexts:e,width:n,height:r})})}),KH=({zarrGroup:t,width:e,height:n})=>{const r=t.attrs.default_label_options||[];return R.jsx(qH,{defaultLabelOptions:r,width:e,height:n})},bD=({contexts:t,children:e,editable:n})=>{const{annotations:r,setAnnotation:i}=UH(t,"/",n),s=D.useMemo(()=>{try{return JSON.parse(r?.sorting_curation||"{}")}catch(a){return console.error("Error parsing sorting_curation:",a),{}}},[r]),o=D.useMemo(()=>a=>{if(!i)return;const l=eg(s,a);i("sorting_curation",JSON.stringify(l))},[i,s]);return R.jsx(mD.Provider,{value:{sortingCuration:s,sortingCurationDispatch:o,curating:!!i},children:e})},ZH=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.columns||[],d=await t.getDatasetData("rows_data",{});if(!d||d.length===0)throw new Error("Empty rows data");const g=new Uint8Array(d),p=new TextDecoder("utf-8").decode(g),_=JSON.parse(p);let m;try{const v=await t.getDatasetData("similarity_scores_data",{});if(v&&v.length>0){const y=new Uint8Array(v),b=new TextDecoder("utf-8").decode(y);m=JSON.parse(b)}}catch(v){console.warn("No similarity scores data found: "+v)}if(u)return;s({type:"UnitsTable",columns:h,rows:_,similarityScores:m})}catch(h){console.error("Error loading units table data:",h),a(`Failed to load units table data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading units table data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(bD,{contexts:e,editable:!1,children:R.jsx(_D,{data:i,width:n,height:r})})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No units table data available"})},GH=t=>{const{ampScaleFactor:e,setAmpScaleFactor:n}=t,r=()=>{n(e*1.2)},i=()=>{n(e/1.2)},s=()=>{n(1)};return[{type:"button",callback:r,title:"Scale amplitude up [shift + mouse-wheel]",icon:R.jsx(b9,{}),keyCode:38},{type:"button",callback:s,title:"Reset scale amplitude",icon:R.jsx($E,{})},{type:"button",callback:i,title:"Scale amplitude down [shift + mouse-wheel]",icon:R.jsx(y9,{}),keyCode:40}]},xD={forward:[[1,0,0],[0,1,0]],inverse:[[1,0,0],[0,1,0]]},fi=(t,e)=>({x:e.x*t.forward[0][0]+e.y*t.forward[0][1]+t.forward[0][2],y:e.x*t.forward[1][0]+e.y*t.forward[1][1]+t.forward[1][2]}),jl=(t,e)=>({x:e.x*t.inverse[0][0]+e.y*t.inverse[0][1]+t.inverse[0][2],y:e.x*t.inverse[1][0]+e.y*t.inverse[1][1]+t.inverse[1][2]}),QH=(t,e)=>({forward:wD(t.forward,e.forward),inverse:wD(e.inverse,t.inverse)}),JH=t=>({forward:[...t.map(e=>[...e])],inverse:tW(t)}),eW=t=>({forward:t.inverse,inverse:t.forward}),nf=t=>t.forward[0][0]*t.forward[1][1]-t.forward[0][1]*t.forward[1][0],wD=(t,e)=>[[t[0][0]*e[0][0]+t[0][1]*e[1][0],t[0][0]*e[0][1]+t[0][1]*e[1][1],t[0][0]*e[0][2]+t[0][1]*e[1][2]+t[0][2]],[t[1][0]*e[0][0]+t[1][1]*e[1][0],t[1][0]*e[0][1]+t[1][1]*e[1][1],t[1][0]*e[0][2]+t[1][1]*e[1][2]+t[1][2]]],tW=t=>{const e=[[t[0][0],t[0][1]],[t[1][0],t[1][1]]],n=[t[0][2],t[1][2]],r=e[0][0]*e[1][1]-e[0][1]*e[1][0],i=[[e[1][1]/r,-e[0][1]/r],[-e[1][0]/r,e[0][0]/r]],s=[i[0][0]*n[0]+i[0][1]*n[1],i[1][0]*n[0]+i[1][1]*n[1]];return[[i[0][0],i[0][1],-s[0]],[i[1][0],i[1][1],-s[1]]]},nW={paddingLeft:6,paddingRight:6,paddingTop:0,paddingBottom:0},rW=({hoveredInfo:t,onSelectSimilarUnits:e})=>R.jsxs("span",{children:[e&&R.jsx(Vl,{style:nW,onClick:e,title:"Select similar units",children:"all"}),t?R.jsxs("span",{children:["Units ",t.unitId1,"/",t.unitId2," |"," ",t.value!==void 0?`value: ${t.value}`:""]}):R.jsx("span",{})]}),rf=(t,e,n={})=>{const r=n.shift!==void 0?n.shift:!0,i=n.shift!==void 0?n.alt:!1,[s,o]=D.useState(xD),a=D.useCallback(l=>{if(r&&!l.shiftKey||!r&&l.shiftKey||i&&!l.altKey||!i&&l.altKey)return;const c=l.currentTarget.getBoundingClientRect(),u={x:l.clientX-c.x,y:l.clientY-c.y},f=l.deltaY,h=1.3;let d=JH([[h,0,(1-h)*u.x],[0,h,(1-h)*u.y]]);f>0&&(d=eW(d));let g=QH(d,s);const p=fi(g,{x:0,y:0}),_=fi(g,{x:t,y:e});return 0<=p.x&&p.x<t&&0<=p.y&&p.y<e&&0<=_.x&&_.x<t&&0<=_.y&&_.y<e&&(g=xD),o(g),!1},[s,e,t,r,i]);return{affineTransform:s,handleWheel:a}},iW=({unitIds1:t,unitIds2:e,selectedUnitIds:n,onSetSelectedUnitIds:r,matrix:i,range:s,setHoveredInfo:o,width:a,height:l})=>{const c=Math.min(a,l),u=(a-c)/2,f=(l-c)/2,{affineTransform:h,handleWheel:d}=rf(a,l,{shift:!0,alt:!1}),g=D.useMemo(()=>b=>fi(h,{x:u+b.i1/t.length*c,y:f+b.i2/e.length*c}),[t.length,e.length,c,u,f,h]),p=D.useMemo(()=>b=>{const w=jl(h,b),x=Math.floor((w.x-u)/c*t.length),S=Math.floor((w.y-f)/c*e.length);return 0<=x&&x<t.length&&0<=S&&S<e.length?{i1:x,i2:S}:void 0},[t.length,e.length,c,u,f,h]),_=D.useCallback(b=>{b.clearRect(0,0,a,l),b.fillStyle="rgb(100, 100, 80)";const w=g({i1:0,i2:0}),x=g({i1:t.length,i2:e.length});b.fillRect(w.x,w.y,x.x-w.x,x.y-w.y),t.forEach((S,A)=>{e.forEach((E,C)=>{const{x:M,y:T}=g({i1:A,i2:C}),{x:P,y:I}=g({i1:A+1,i2:C+1}),k=SD(i[A][C],s,!1);b.fillStyle=k;const O=P-M>=10?3:P-M>=6?2:P-M>=4?1:0;if(b.fillRect(M,T,P-M-O,I-T-O),n.has(S)&&n.has(E)){const L=SD(i[A][C],s,!0);b.strokeStyle=L,b.lineWidth=O,b.strokeRect(M,T,P-M-O,I-T-O)}})})},[g,i,t,e,n,a,l,s]),m=D.useCallback(b=>{const w=b.currentTarget.getBoundingClientRect(),x={x:b.clientX-w.x,y:b.clientY-w.y},S=p(x);S&&r([t[S.i1],e[S.i2]])},[r,t,e,p]),v=D.useCallback(b=>{const w=b.currentTarget.getBoundingClientRect(),x={x:b.clientX-w.x,y:b.clientY-w.y},S=p(x);o(S?{unitId1:t[S.i1],unitId2:e[S.i2],value:i[S.i1][S.i2]}:void 0)},[p,i,o,t,e]),y=D.useCallback(()=>{o(void 0)},[o]);return R.jsx("div",{style:{width:a,height:l,position:"relative"},onMouseDown:m,onWheel:d,onMouseMove:v,onMouseLeave:y,children:R.jsx(qn,{width:a,height:l,draw:_,drawData:null})})},SD=(t,e,n)=>{if(isNaN(t))return n?"rgb(0, 0, 255)":"rgb(50, 20, 0)";const r=Math.min(255,Math.max(0,Math.floor((t-e[0])/(e[1]-e[0])*255))),i=Math.min(255,Math.max(0,255-r-30));return n?`rgb(${i}, ${i}, 255)`:`rgb(${r}, ${r}, ${r})`},sW=[0,1],oW=({data:t,width:e,height:n})=>{const{selectedUnitIds:r,visibleUnitIds:i,unitIdSelectionDispatch:s}=Vr(),[o,a]=D.useState(void 0);D.useEffect(()=>{s({type:$o,newUnitOrder:si(t.unitIds)})},[t.unitIds,s]);const l=D.useMemo(()=>t.unitIds.filter(g=>!i||i.includes(g)),[t.unitIds,i]),c=D.useMemo(()=>{const g={};return l.forEach((p,_)=>{g[p]=_}),g},[l]),u=D.useMemo(()=>{const g=[];l.forEach(()=>{const p=[];l.forEach(()=>{p.push(NaN)}),g.push(p)});for(const p of t.similarityScores){const _=c[p.unitId1],m=c[p.unitId2];g[_][m]=p.similarity}return g},[c,l,t.similarityScores]),f=D.useCallback(g=>{s({type:"SET_SELECTION",incomingSelectedUnitIds:g})},[s]),h=D.useCallback(()=>{const g=[...r][0];if(!g)return;const p=c[g],_=[];for(let v=0;v<l.length;v++)if(v!==p){const y=u[p][v];isNaN(y)||_.push({id:l[v],similarity:y})}_.sort((v,y)=>y.similarity-v.similarity);const m=[g,..._.slice(0,4).map(v=>v.id)];s({type:"SET_SELECTION",incomingSelectedUnitIds:m})},[c,r,u,s,l]),d=20;return R.jsxs("div",{children:[R.jsx("div",{style:{position:"absolute",height:n-d,width:e},children:R.jsx(iW,{unitIds1:l,unitIds2:l,selectedUnitIds:r,onSetSelectedUnitIds:f,matrix:u,range:t.range||sW,setHoveredInfo:a,width:e,height:n-d})}),R.jsx("div",{style:{position:"absolute",top:n-d,height:d,width:e},children:R.jsx(rW,{hoveredInfo:o,onSelectSimilarUnits:r.size===1?h:void 0})})]})},ea={border:"rgb(30, 30, 30)",base:"rgb(0, 0, 255)",selected:"rgb(50, 200, 50)",hover:"rgb(128, 128, 255)",selectedHover:"rgb(200, 200, 196)",dragged:"rgb(0, 0, 196)",draggedSelected:"rgb(180, 180, 150)",dragRect:"rgba(196, 196, 196, 0.5)",textLight:"rgb(228, 228, 228)",textDark:"rgb(32, 32, 32)"},aW=2*Math.PI,lW=(t,e)=>{const{layoutMode:n,affineTransform:r}=e;if(t.save(),r){const i=r.forward;t.transform(i[0][0],i[1][0],i[0][1],i[1][1],i[0][2],i[1][2])}n==="geom"?uW(t,e):cW(t,e),t.restore()},cW=(t,e)=>{const{pixelElectrodes:n,pixelRadius:r,showLabels:i,xMargin:s}=e,o=r>5&&i,a=e.colors??ea,l=o?2*r:0;t.clearRect(0,0,t.canvas.width,t.canvas.height);const c=s+l,u=t.canvas.width-s;if(t.beginPath(),n.forEach(f=>{t.moveTo(c,f.pixelY),t.lineTo(u,f.pixelY)}),t.strokeStyle=a.border,t.stroke(),o){const f=c-.5*r;t.font=`${r-3}px Arial`,t.fillStyle=a.textDark,t.textAlign="right",t.textBaseline="middle",n.forEach(h=>{t.fillText(`${h.e.label}`,f,h.pixelY)})}},uW=(t,e)=>{const{pixelElectrodes:n,selectedElectrodeIds:r,hoveredElectrodeId:i,draggedElectrodeIds:s,pixelRadius:o,showLabels:a,offsetLabels:l}=e,c=o>5&&a,u=e.colors??ea,f=n.map(h=>{const d=r.includes(h.e.id),g=(i??-1)===h.e.id,p=s.includes(h.e.id),_=d?p?u.draggedSelected:g?u.selectedHover:u.selected:p?u.dragged:g?u.hover:u.base;return{...h,color:_,textColor:d||g&&!p?u.textDark:u.textLight}});if(t.clearRect(0,0,t.canvas.width,t.canvas.height),f.forEach(h=>{t.fillStyle=h.color,t.beginPath(),t.ellipse(h.pixelX,h.pixelY,o,o,0,0,aW),t.fill()}),c){t.font=`${o}px Arial`,t.textAlign=l?"right":"center",t.textBaseline="middle";const h=l?1.4*o:0;f.forEach(d=>{t.fillStyle=l?u.textDark:d.textColor,t.fillText(`${d.e.label}`,d.pixelX-h,d.pixelY)})}},tg=t=>t.reduce((e,n)=>e<=n?e:n,1/0),ng=t=>t.reduce((e,n)=>e>=n?e:n,-1/0),Hl=10,sf=10,TD=(t,e)=>{const n=e||{};return e&&(Object.keys(n).length!==t.length||t.some(i=>!n[`${i}`]))?(console.warn("Attempt to compute electrode locations with mismatched lists. Skipping..."),[]):t.map(i=>{const s=n[`${i}`]||[i,0];return{id:i,label:`${i}`,x:s[0],y:s[1]}})},AD=new Map,ED=t=>{const e=JSON.stringify(t),n=AD.get(e);if(n!==void 0)return n;let r=Number.MAX_VALUE;t.forEach(s=>{t.forEach(o=>{const a=CE([s.x-o.x,s.y-o.y]);a!==0&&(r=Math.min(r,a))})});const i=.45*r;return AD.set(e,i),i},CD=(t,e)=>({xmin:tg(t.map(n=>n.x))-e,xmax:ng(t.map(n=>n.x))+e,ymin:tg(t.map(n=>n.y))-e,ymax:ng(t.map(n=>n.y))+e}),fW=t=>{const e=ED(t),n=CD(t,e),r=Gd(n),i=DE(n),s={x:r/2+n.xmin,y:i/2+n.ymin};return{boxAspect:r/i,boxCenter:s}},hW=t=>{const e={xmin:tg(t.map(n=>n.x)),xmax:ng(t.map(n=>n.x)),ymin:tg(t.map(n=>n.y)),ymax:ng(t.map(n=>n.y))};return e.xmin===e.xmax&&e.ymin===e.ymax?t.map((n,r)=>({...n,x:r,y:0})):t},dW=(t,e)=>t9(n=>{const r=Hl+n[0]*(t-2*Hl),i=sf+n[1]*(e-2*sf);return[r,i]}),pW=(t,e)=>{const n=t.map((s,o)=>({e:s,ind:o})).sort((s,o)=>-s.e.y+o.e.y).map(s=>s.ind),r=[];for(let s=0;s<t.length;s++)r.push([0,0]);for(let s=0;s<n.length;s++){const o=n[s];r[o]=[.5,(.5+s)/(1+t.length)]}const i=Qv(e,r);return t.map((s,o)=>{const[a,l]=i[o];return{e:s,pixelX:a,pixelY:l}})},gW=(t,e,n,r,i)=>{const s=t-Hl*2,o=e-sf*2,a=Gd(i),l=DE(i);return Pz(s/a,o/l,r/n)},mW=(t,e,n,r)=>{const i=Gd(r),s=(t-i*n)/2,o=[n,0,s-r.xmin*n],a=[0,-n,(e+n*(r.ymin+r.ymax))/2];return[o,a,[0,0,1]]},yW=(t,e,n,r={})=>{const i=(t-Hl*2)/(e-sf*2),s=hW(n),{boxAspect:o}=fW(s);return r.disableAutoRotate||o===1||i===1||o>1==i>1?{electrodes:n,rotated:!1}:{electrodes:n.map(a=>({...a,x:a.y,y:-a.x})),rotated:!0}},vW=(t,e)=>{const n=t.map(i=>[i.x,i.y]),r=Qv(e,n);return t.map((i,s)=>{const[o,a]=r[s];return{e:i,pixelX:o,pixelY:a}})},DD=(t,e,n)=>{for(const r of t)if(CE([r.pixelX-n[0],r.pixelY-n[1]])<e)return r.e.id},MD=(t,e,n)=>{const r=e.xmin-n,i=e.xmax+n,s=e.ymin-n,o=e.ymax+n;return t.filter(a=>a.pixelX>r&&a.pixelX<i&&a.pixelY>s&&a.pixelY<o).map(a=>a.e.id)},rg=(t,e,n,r="geom",i=PD,s)=>{if(r==="vertical"){const p=dW(t,e),_=pW(n,p),m=(e-2*sf)/(1+n.length);return{transform:p,convertedElectrodes:_,pixelRadius:m}}const{electrodes:o,rotated:a}=yW(t,e,n,{disableAutoRotate:s.disableAutoRotate}),l=ED(o),c=CD(o,l),u=gW(t,e,l,i,c),f=l*u;let h=mW(t,e,u,c);const d=(t-Gd(c)*u)/2,g=vW(o,h);return a&&(h=[[-h[0][1],h[0][0],h[0][2]],[-h[1][1],h[1][0],h[1][2]],[-h[2][1],h[2][0],h[2][2]]]),{transform:h,convertedElectrodes:g,pixelRadius:f,xMargin:d}},RD={isActive:!1},_W=(t,e)=>{if(e.type==="INITIALIZE"){const{width:n,height:r,electrodes:i,layoutMode:s,maxElectrodePixelRadius:o}=e,{convertedElectrodes:a,pixelRadius:l,xMargin:c}=rg(n,r,i,s,o,{disableAutoRotate:e.disableAutoRotate});return{...t,convertedElectrodes:a,pixelRadius:l,draggedElectrodeIds:[],hoveredElectrodeId:void 0,dragState:RD,xMarginWidth:c??Hl}}else if(e.type==="DRAGUPDATE"){const n=Kz(t.dragState,e.dragAction);if(!n.isActive&&n.dragRect){const r=RE(n.dragRect),i=MD(t.convertedElectrodes,r,t.pixelRadius),s=e.dragAction.shift?[...i,...e.selectedElectrodeIds||[]]:i;return{...t,draggedElectrodeIds:[],hoveredElectrodeId:void 0,pendingSelectedElectrodeIds:s,dragState:RD}}else if(n.dragRect){const r=RE(n.dragRect),i=MD(t.convertedElectrodes,r,t.pixelRadius);return i.length===t.draggedElectrodeIds.length&&i.filter(s=>!t.draggedElectrodeIds.includes(s)).length===0?{...t,hoveredElectrodeId:void 0,dragState:n}:{...t,hoveredElectrodeId:void 0,draggedElectrodeIds:i,dragState:n}}else return{...t,dragState:n}}else if(e.type==="UPDATEHOVER"){const n=DD(t.convertedElectrodes,t.pixelRadius,e.point);return n===t.hoveredElectrodeId?t:{...t,hoveredElectrodeId:n}}else if(e.type==="UPDATECLICK"){const n=DD(t.convertedElectrodes,t.pixelRadius,e.point);if(n===void 0)return!(e.shift||e.ctrl)&&e.selectedElectrodeIds.length>0?{...t,pendingSelectedElectrodeIds:[]}:t;const r=e.ctrl?e.selectedElectrodeIds.includes(n)?e.selectedElectrodeIds.filter(i=>i!==n):[...e.selectedElectrodeIds,n]:e.shift?[...e.selectedElectrodeIds,n]:[n];return{...t,hoveredElectrodeId:void 0,pendingSelectedElectrodeIds:r}}else return console.log("Error: unrecognized verb in electrode geometry reducer."),t},ID=!1,PD=25,OD={showLabels:!0,maxElectrodePixelRadius:PD},bW=t=>{const e=t.currentTarget.getBoundingClientRect();return[t.clientX-e.x,t.clientY-e.y]},ND=()=>({selectedElectrodeIds:[],setSelectedElectrodeIds:t=>{}}),FD=t=>{const{width:e,height:n,electrodes:r,disableAutoRotate:i,affineTransform:s}=t,{selectedElectrodeIds:o,setSelectedElectrodeIds:a}=ND(),l=t.disableSelection??!1,c=t.offsetLabels??!1,u=t.colors??ea,f=t.layoutMode??"geom",h=t.maxElectrodePixelRadius||OD.maxElectrodePixelRadius,[d,g]=D.useReducer(_W,{convertedElectrodes:[],pixelRadius:-1,draggedElectrodeIds:[],pendingSelectedElectrodeIds:o||[],dragState:{isActive:!1},xMarginWidth:-1}),{affineTransform:p,handleWheel:_}=rf(e,n,{shift:!0,alt:!1}),m=D.useMemo(()=>{const C=d.convertedElectrodes.map(M=>{const T=fi(p,{x:M.pixelX,y:M.pixelY});return{...M,pixelX:T.x,pixelY:T.y}});return{...d,convertedElectrodes:C,pixelRadius:d.pixelRadius*Math.sqrt(nf(p))}},[p,d]),v=D.useMemo(()=>C=>{const M=bW(C),T=jl(p,{x:M[0],y:M[1]});return[T.x,T.y]},[p]);D.useEffect(()=>{g({type:"INITIALIZE",electrodes:r,width:e,height:n,maxElectrodePixelRadius:h,layoutMode:f,disableAutoRotate:i})},[e,n,r,f,h,i]),D.useEffect(()=>{a(d.pendingSelectedElectrodeIds)},[a,d.pendingSelectedElectrodeIds]);const y=D.useRef(null),b=D.useRef(0),w=l||R.jsx(e9,{width:e,height:n,newState:d.dragState}),x=D.useCallback(C=>{if(!Gz(C,{nextDragStateUpdate:y,nextFrame:b,reducer:g,reducerOtherProps:{type:"DRAGUPDATE"}})){const T=v(C);g({type:"UPDATEHOVER",point:T})}},[v]),S=D.useCallback(C=>{Qz(C,{nextDragStateUpdate:y,reducer:g,reducerOtherProps:{type:"DRAGUPDATE"}})},[]),A=D.useCallback(C=>{if(d.dragState.isActive)Jz(C,{nextDragStateUpdate:y,reducer:g,reducerOtherProps:{type:"DRAGUPDATE",selectedElectrodeIds:o}});else{const M=v(C);g({type:"UPDATECLICK",point:M,shift:C.shiftKey,ctrl:C.ctrlKey,selectedElectrodeIds:o||[]})}},[d.dragState.isActive,o,v]),E=D.useMemo(()=>{const C={pixelElectrodes:m.convertedElectrodes,selectedElectrodeIds:o||[],hoveredElectrodeId:d.hoveredElectrodeId,draggedElectrodeIds:d.draggedElectrodeIds,pixelRadius:m.pixelRadius,showLabels:t.showLabels??OD.showLabels,offsetLabels:c,layoutMode:t.layoutMode??"geom",xMargin:d.xMarginWidth,colors:u,affineTransform:s};return R.jsx(qn,{width:e,height:n,draw:lW,drawData:C})},[e,n,m.convertedElectrodes,o,d.hoveredElectrodeId,d.draggedElectrodeIds,m.pixelRadius,t.showLabels,c,t.layoutMode,d.xMarginWidth,u,s]);return D.useMemo(()=>ID,[d.convertedElectrodes,o,d.hoveredElectrodeId,d.draggedElectrodeIds,d.pixelRadius,t.showLabels,c,t.layoutMode,d.xMarginWidth,e,n,u]),R.jsxs("div",{style:{width:e,height:n,position:"relative"},onMouseMove:x,onMouseUp:A,onMouseDown:S,onWheel:_,children:[w,ID,E]})},xW=t=>1/t,ta=(t,e,n,r,i)=>{const s=[];return n.forEach((o,a)=>{for(const l of e){const c=l.electrodeIndices.indexOf(a);if(c>=0){let u;const f=l.waveformStdDev,h=l.waveformPercentiles;if(r==="normal"?u=l.waveform.map(d=>d[c]):r==="lower"?u=f?l.waveform.map((d,g)=>d[c]-f[g][c]):void 0:r==="upper"?u=f?l.waveform.map((d,g)=>d[c]+f[g][c]):void 0:r==="percentile1"?(console.log("--- computing ww for percentile1",l.waveform,h),u=h?l.waveform.map((d,g)=>h[0][g][c]):void 0):r==="percentile2"?(console.log("--- computing ww for percentile2"),u=h?l.waveform.map((d,g)=>h[1][g][c]):void 0):r==="percentile3"?(console.log("--- computing ww for percentile3"),u=h&&2<h.length?l.waveform.map((d,g)=>h[2][g][c]):void 0):r==="percentile4"&&(u=h&&3<h.length?l.waveform.map((d,g)=>h[3][g][c]):void 0),u){const d=u.map((p,_)=>[(u?.length||0)/2+(_-(u?.length||0)/2)*i,p]),g=Qv(t,d);s.push({pointsInPaintBox:g,offsetFromParentCenter:[o.pixelX,o.pixelY],color:l.waveformColors.base})}}}}),s},wW=(t,e)=>{const{pixelSpacePaths:n,pixelSpacePathsLower:r,pixelSpacePathsUpper:i,pixelSpacePathsPercentile1:s,pixelSpacePathsPercentile2:o,pixelSpacePathsPercentile3:a,pixelSpacePathsPercentile4:l,xMargin:c,waveformWidth:u,affineTransform:f,useUnitColors:h}=e;if(!n||n.length===0)return;if(t.resetTransform(),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.save(),f){const v=f.forward;t.transform(v[0][0],v[1][0],v[0][1],v[1][1],v[0][2],v[1][2])}t.translate(c,0);const d=t.getTransform();r&&i&&r.forEach((v,y)=>{const b=r[y],w=i[y];t.fillStyle="#dddddd",t.strokeStyle="#bbbbbb",t.lineWidth=1,t.translate(b.offsetFromParentCenter[0],b.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(b.pointsInPaintBox[0][0],b.pointsInPaintBox[0][1]);for(let x=0;x<b.pointsInPaintBox.length;x++)t.lineTo(b.pointsInPaintBox[x][0],b.pointsInPaintBox[x][1]);for(let x=w.pointsInPaintBox.length-1;x>=0;x--)t.lineTo(w.pointsInPaintBox[x][0],w.pointsInPaintBox[x][1]);t.fill(),t.stroke(),t.setTransform(d)});let g,p,_,m;s&&o&&a&&l?(g=s,p=o,_=a,m=l):s&&o&&!a&&!l?(g=void 0,p=s,_=o,m=void 0):(g=void 0,p=void 0,_=void 0,m=void 0),g&&g.length>0&&m&&m.length>0&&g.forEach((v,y)=>{if(!g||!m)throw Error("unexpected");const b=g[y],w=m[y];t.fillStyle="#dddddd",t.strokeStyle="#dddddd",t.lineWidth=1,t.translate(b.offsetFromParentCenter[0],b.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(b.pointsInPaintBox[0][0],b.pointsInPaintBox[0][1]);for(let x=0;x<b.pointsInPaintBox.length;x++)t.lineTo(b.pointsInPaintBox[x][0],b.pointsInPaintBox[x][1]);for(let x=w.pointsInPaintBox.length-1;x>=0;x--)t.lineTo(w.pointsInPaintBox[x][0],w.pointsInPaintBox[x][1]);t.fill(),t.stroke(),t.setTransform(d)}),p&&p.length>0&&p.length>0&&_&&_.length>0&&p.forEach((v,y)=>{if(!p||!_)throw Error("unexpected");const b=p[y],w=_[y];t.fillStyle="#bbbbbb",t.strokeStyle="#bbbbbb",t.lineWidth=1,t.translate(b.offsetFromParentCenter[0],b.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(b.pointsInPaintBox[0][0],b.pointsInPaintBox[0][1]);for(let x=0;x<b.pointsInPaintBox.length;x++)t.lineTo(b.pointsInPaintBox[x][0],b.pointsInPaintBox[x][1]);for(let x=w.pointsInPaintBox.length-1;x>=0;x--)t.lineTo(w.pointsInPaintBox[x][0],w.pointsInPaintBox[x][1]);t.fill(),t.stroke(),t.setTransform(d)}),n.forEach(v=>{t.strokeStyle=h?v.color:"black",t.lineWidth=u,t.translate(v.offsetFromParentCenter[0],v.offsetFromParentCenter[1]),t.beginPath(),t.moveTo(v.pointsInPaintBox[0][0],v.pointsInPaintBox[0][1]),v.pointsInPaintBox.forEach(y=>{t.lineTo(y[0],y[1])}),t.stroke(),t.setTransform(d)}),t.restore()},SW=t=>{const{electrodes:e,waveforms:n,oneElectrodeHeight:r,oneElectrodeWidth:i,yScale:s,horizontalStretchFactor:o,width:a,height:l,layoutMode:c,waveformWidth:u,affineTransform:f,useUnitColors:h}=t;return D.useMemo(()=>{const g=n.length>0?n[0].waveform.length:0,p=i/g,_=-i*(.5+1/g),m=s*r/2,v=Ze([[p,0,_],[0,-m,0],[0,0,1]]).toArray(),y=ta(v,n,e,"normal",o),b=ta(v,n,e,"lower",o),w=ta(v,n,e,"upper",o);let x=ta(v,n,e,"percentile1",o),S=ta(v,n,e,"percentile2",o),A=ta(v,n,e,"percentile3",o),E=ta(v,n,e,"percentile4",o);x&&x.length===0&&(x=void 0),S&&S.length===0&&(S=void 0),A&&A.length===0&&(A=void 0),E&&E.length===0&&(E=void 0);const C=c==="vertical"?(a-i)/2:0,M={pixelSpacePaths:y,pixelSpacePathsLower:b,pixelSpacePathsUpper:w,pixelSpacePathsPercentile1:x,pixelSpacePathsPercentile2:S,pixelSpacePathsPercentile3:A,pixelSpacePathsPercentile4:E,xMargin:C,waveformWidth:u,affineTransform:f,useUnitColors:h};return R.jsx(qn,{width:a,height:l,draw:wW,drawData:M})},[n,e,s,a,l,i,r,c,u,f,o,h])},TW={colors:{border:"rgb(120, 100, 120)",base:"rgb(240, 240, 240)",selected:"rgb(196, 196, 128)",hover:"rgb(128, 128, 255)",selectedHover:"rgb(200, 200, 196)",dragged:"rgb(0, 0, 196)",draggedSelected:"rgb(180, 180, 150)",dragRect:"rgba(196, 196, 196, 0.5)",textLight:"rgb(162, 162, 162)",textDark:"rgb(32, 150, 150)"}},AW=t=>{const e=t.colors??TW.colors,{electrodes:n,waveforms:r,ampScaleFactor:i,horizontalStretchFactor:s,layoutMode:o,hideElectrodes:a,width:l,height:c,showChannelIds:u,useUnitColors:f,waveformWidth:h,disableAutoRotate:d}=t,g=1e3,{handleWheel:p,affineTransform:_}=rf(l,c,{shift:!0,alt:!0}),m=D.useMemo(()=>R.jsx(FD,{electrodes:n,width:l,height:c,layoutMode:o,colors:e,showLabels:u,maxElectrodePixelRadius:g,disableSelection:!0,disableAutoRotate:d,affineTransform:_}),[n,l,c,o,e,u,d,_]),{convertedElectrodes:v,pixelRadius:y,xMargin:b}=rg(l,c,n,o,g,{disableAutoRotate:d}),w=b||Hl,x=D.useMemo(()=>xW(t.peakAmplitude),[t.peakAmplitude]),S=D.useMemo(()=>i*x,[i,x]),A=o==="geom"?y*2:c/n.length,E=o==="geom"?y*2:l-w-(u?2*y:0),C=R.jsx(SW,{electrodes:v,waveforms:r,oneElectrodeHeight:A,oneElectrodeWidth:E,horizontalStretchFactor:s,yScale:S,width:l,height:c,layoutMode:o,waveformWidth:h,affineTransform:_,useUnitColors:f});return R.jsxs("div",{style:{width:l,height:c,position:"relative"},onWheel:p,children:[!a&&m,C]})},EW=({allChannelIds:t,channelIds:e,units:n,layoutMode:r,hideElectrodes:i,channelLocations:s,samplingFrequency:o,peakAmplitude:a,ampScaleFactor:l,horizontalStretchFactor:c,showChannelIds:u,useUnitColors:f,showReferenceProbe:h,disableAutoRotate:d,width:g,height:p})=>{const _=D.useMemo(()=>{const w=s||{};return e.map(x=>({id:x,label:`${x}`,x:w[`${x}`]!==void 0?w[`${x}`][0]:Nt(x),y:w[`${x}`]!==void 0?w[`${x}`][1]:0}))},[e,s]),m=D.useMemo(()=>{const w=s||{};return t.map(x=>({id:x,label:`${x}`,x:w[`${x}`]!==void 0?w[`${x}`][0]:Nt(x),y:w[`${x}`]!==void 0?w[`${x}`][1]:0}))},[t,s]),v=g/4,y=D.useMemo(()=>n.map(w=>{const x={base:w.waveformColor},S=[];for(const A of w.channelIds)S.push(_.map(E=>E.id).indexOf(A));return{electrodeIndices:S,waveform:w.waveform,waveformStdDev:w.waveformStdDev,waveformPercentiles:w.waveformPercentiles,waveformColors:x}}),[_,n]),b=R.jsx(AW,{waveforms:y,electrodes:_,ampScaleFactor:l,horizontalStretchFactor:c,layoutMode:s?r:"vertical",hideElectrodes:i,width:h?g-v:g,height:p,showLabels:!0,peakAmplitude:a,samplingFrequency:o,showChannelIds:u,useUnitColors:f,waveformWidth:2,disableAutoRotate:d});return h?R.jsxs("div",{style:{position:"relative",width:g,height:p},children:[R.jsx("div",{style:{position:"absolute",left:0,top:0,width:v,height:p},children:R.jsx(FD,{electrodes:m,disableSelection:!1,width:v,height:p})}),R.jsx("div",{style:{position:"absolute",left:v,top:0,width:g-v,height:p},children:b})]}):b},CW=({data:t,width:e,height:n})=>{const r=D.useMemo(()=>{const z=[];for(const Q of t.averageWaveforms)for(const ee of Q.channelIds)z.includes(ee)||z.push(ee);return si(z)},[t.averageWaveforms]),[i,s]=D.useState({...ef,onlyShowSelected:!1}),{selectedUnitIds:o,currentUnitId:a,orderedUnitIds:l,plotClickHandlerGenerator:c,unitIdSelectionDispatch:u}=Vr(),[f,h]=D.useState(1),[d,g]=D.useState("geom"),[p,_]=D.useState(!0),[m,v]=D.useState(!1),[y,b]=D.useState(t.showReferenceProbe||!1),[w,x]=D.useState(!1),[S,A]=D.useState(1),[E,C]=D.useState(!0),[M,T]=D.useState(!0);D.useEffect(()=>{u({type:$o,newUnitOrder:si(t.averageWaveforms.map(z=>z.unitId))})},[t.averageWaveforms,u]);const[P,I]=D.useState(2),k=D.useMemo(()=>{let z=0;return t.averageWaveforms.forEach(Q=>{Q.waveform.forEach(ee=>{ee.forEach(ce=>{const se=Math.abs(ce);se>z&&(z=se)})})}),z},[t.averageWaveforms]),O=D.useMemo(()=>t.averageWaveforms.filter(z=>i.onlyShowSelected?o.has(z.unitId):!0).map(z=>{const Q=[{channelIds:z.channelIds,waveform:MW(z.waveform),waveformStdDev:p&&!w?z.waveformStdDev:void 0,waveformPercentiles:p&&!w&&z.waveformPercentiles?RW(z.waveformPercentiles,z.waveform):void 0,waveformColor:ci(Nt(z.unitId))}],ee={allChannelIds:r,channelIds:z.channelIds,units:Q,layoutMode:d,hideElectrodes:E,channelLocations:t.channelLocations,samplingFrequency:t.samplingFrequency,peakAmplitude:k,ampScaleFactor:f,horizontalStretchFactor:S,showChannelIds:m,useUnitColors:M,width:120*P+(y?120*P/4:0),height:120*P,showReferenceProbe:y,disableAutoRotate:!0};return{unitId:z.unitId,key:z.unitId,label:`Unit ${z.unitId}`,labelColor:ci(Nt(z.unitId)),clickHandler:i.onlyShowSelected?void 0:c(z.unitId),props:ee}}),[t.averageWaveforms,t.channelLocations,t.samplingFrequency,r,k,d,f,c,i.onlyShowSelected,o,P,p,m,y,w,S,E,M]),L=D.useMemo(()=>l?l.map(z=>O.filter(Q=>Q.unitId===z)[0]).filter(z=>z!==void 0):O,[O,l]),U=D.useMemo(()=>w?DW(L):L,[L,w]),$=D.useMemo(()=>[{type:"button",callback:()=>{A(z=>z*1.1)},title:"Increase horizontal stretch [alt + mouse-wheel]",icon:R.jsx(_9,{})},{type:"button",callback:()=>{A(1)},title:"Reset scale amplitude",icon:R.jsx($E,{})},{type:"button",callback:()=>{A(z=>z/1.1)},title:"Decrease horizontal stretch [alt + mouse-wheel]",icon:R.jsx(v9,{})}],[]),J=D.useMemo(()=>{const z=GH({ampScaleFactor:f,setAmpScaleFactor:h}),Q={type:"toggle",subtype:"checkbox",callback:()=>g(ve=>ve==="geom"?"vertical":"geom"),title:"Show electrode geometry",selected:d==="geom"},ee={type:"toggle",subtype:"checkbox",callback:()=>C(ve=>!ve),title:"Show electrodes",selected:!E},ce=[{type:"button",callback:()=>I(ve=>ve*1.3),title:"Increase box size",icon:R.jsx(sp,{})},{type:"button",callback:()=>I(ve=>ve/1.3),title:"Decrease box size",icon:R.jsx(ip,{})}],se={type:"toggle",subtype:"checkbox",callback:()=>_(ve=>!ve),title:"Show waveform stdev",selected:p===!0},ue={type:"toggle",subtype:"checkbox",callback:()=>v(ve=>!ve),title:"Show channel IDs",selected:m===!0},be={type:"toggle",subtype:"checkbox",callback:()=>b(ve=>!ve),title:"Show reference probes",selected:y===!0},le={type:"toggle",subtype:"checkbox",callback:()=>x(ve=>!ve),title:"Show overlapping",selected:w===!0},ye={type:"toggle",subtype:"checkbox",callback:()=>T(ve=>!ve),title:"Use unit colors",selected:M===!0};return[{type:"divider"},...ce,{type:"divider"},...z,{type:"divider"},...$,{type:"divider"},Q,ee,{type:"divider"},se,{type:"divider"},ue,{type:"divider"},be,{type:"divider"},le,{type:"divider"},ye]},[d,f,p,m,w,y,$,E,M]),ne=D.useCallback(z=>{z.shiftKey&&!z.altKey?z.deltaY<0?h(Q=>Q*1.3):h(Q=>Q/1.3):z.altKey&&!z.shiftKey&&(z.deltaY<0?A(Q=>Q*1.1):A(Q=>Q/1.1))},[]),j=30,V=D.useCallback(z=>{z&&z.addEventListener("wheel",Q=>{(Q.shiftKey||Q.altKey)&&Q.preventDefault()})},[]),G=Qu;return R.jsxs("div",{ref:z=>V(z),onWheel:ne,children:[R.jsxs(Jo,{width:e,height:n-j,initialPosition:G,adjustable:!1,children:[R.jsx(Ju,{width:G,height:n,customActions:J}),R.jsx(tp,{width:0,height:0,children:R.jsx(ep,{plots:U,plotComponent:EW,selectedPlotKeys:i.onlyShowSelected?void 0:o,currentPlotKey:a})})]}),R.jsx("div",{style:{position:"absolute",top:n-j,height:j,overflow:"hidden"},children:R.jsx(tf,{options:i,setOptions:s})})]})},DW=t=>{if(t.length===0)return t;const e={...t[0],props:{...t[0].props}},n=e.props;e.key="overlapping",e.label="Overlapping",e.labelColor="black",e.unitId="overlapping",n.height*=3;const r=new Set;for(const s of t)for(const o of s.props.channelIds)r.add(o);const i=si([...r]);return n.channelIds=i,n.units=t.map(s=>s.props.units[0]),[e]},MW=t=>t.map(n=>{const r=BD(n);return n.map(i=>i-r)}),RW=(t,e)=>{const n=e[0].length,r=[];for(let s=0;s<n;s++){const o=e.map(a=>a[s]);r.push(BD(o))}const i=[];for(let s=0;s<t.length;s++){const o=[];for(let a=0;a<t[s].length;a++){const l=[];for(let c=0;c<n;c++)l.push(t[s][a][c]-r[c]);o.push(l)}i.push(o)}return i},BD=t=>t.length>0?Hz(t):0,IW=t=>R.jsx(ui,{context:t.contexts.unitSelection,children:R.jsx(PW,{...t})}),PW=({zarrGroup:t,width:e,height:n})=>{const[r,i]=D.useState(null);return D.useEffect(()=>{let s=!1;return(async()=>{const a=[],l=t.attrs.num_average_waveforms||0,c=t.attrs.average_waveforms,u=c.length;u!==l&&console.warn(`numUnits (${u}) !== numAverageWaveforms (${l})`);for(let h=0;h<l;h++){const d=`waveform_${h}`,g=await t.getGroup(d);if(!g){console.warn(`No group for ${d}`);continue}if(g.datasets.find(w=>w.name==="waveform")===void 0){console.warn(`No waveform dataset for ${d}`);continue}const p=await t.getDataset(`${d}/waveform`);if(!p){console.warn(`Could not load waveform dataset for ${d}`);continue}const _=p.shape,m=await t.getDatasetData(`${d}/waveform`,{});let v;g.datasets.find(w=>w.name==="waveform_std_dev")===void 0?v=void 0:v=await t.getDatasetData(`${d}/waveform_std_dev`,{});let y,b;if(g.datasets.find(w=>w.name==="waveform_percentiles")===void 0)y=void 0;else{const w=await t.getDataset(`${d}/waveform_percentiles`);w?(y=await t.getDatasetData(`${d}/waveform_percentiles`,{}),b=w.shape[0]):(console.warn(`Could not load waveform_percentiles dataset for ${d}`),y=void 0)}if(m){const w=c.find(x=>x.name===d);w&&a.push({unitId:w.unit_id,channelIds:w.channel_ids,waveform:kD(m,_),waveformStdDev:v?kD(v,_):void 0,waveformPercentiles:y&&b?OW(y,[b,_[0],_[1]]):void 0})}}const f=t.attrs.channel_locations;s||i({type:"AverageWaveforms",averageWaveforms:a,channelLocations:f})})(),()=>{s=!0}},[t]),r?R.jsx(CW,{data:r,width:e,height:n}):R.jsx("div",{children:"Loading..."})},kD=(t,e)=>{if(e.length!==2)throw Error("shape.length should be 2");const[n,r]=e;if(t.length!==n*r)throw Error(`data.length does not match shape. Expected ${n*r}, got ${t.length}`);const i=[];for(let s=0;s<n;s++){const o=[];for(let a=0;a<r;a++)o.push(t[s*r+a]);i.push(o)}return i},OW=(t,e)=>{if(e.length!==3)throw Error("shape.length should be 3");const[n,r,i]=e;if(t.length!==n*r*i)throw Error(`data.length does not match shape. Expected ${n*r*i}, got ${t.length}`);const s=[];for(let o=0;o<n;o++){const a=[];for(let l=0;l<r;l++){const c=[];for(let u=0;u<i;u++)c.push(t[o*r*i+l*i+u]);a.push(c)}s.push(a)}return s},UD=20,NW=({data:t,width:e,height:n})=>{const[r,i]=D.useState(!1),{selectedUnitIds:s}=Vr(),o=D.useMemo(()=>si([...s]),[s]),a=t.hideUnitSelector,l=D.useMemo(()=>{const m=t.crossCorrelograms.filter(y=>o.includes(y.unitId1)&&o.includes(y.unitId2)),v=[];for(const y of o)for(const b of o){const w=m.filter(x=>x.unitId1===y&&x.unitId2===b)[0];w?v.push(w):v.push(void 0)}return v},[t.crossCorrelograms,o]),c=a?0:100,u=Qu,f=e-c-u,h=n,d=D.useMemo(()=>{const m=o.length,{plotWidth:v,plotHeight:y}=LD(f,h,m);return l.map((b,w)=>({key:`${w}`,unitId:b?b.unitId1:0,label:b?v>80?`Unit ${b.unitId1}/${b.unitId2}`:`${b.unitId1}/${b.unitId2}`:"",labelColor:"black",clickHandler:void 0,props:{binEdgesSec:b?b.binEdgesSec:void 0,binCounts:b?b.binCounts:void 0,color:b?.unitId1===b?.unitId2?ci(Nt(b?.unitId1)):"gray",width:v,height:y,hideXAxis:!r}}))},[l,f,h,o,r]),g=D.useMemo(()=>[{type:"toggle",subtype:"checkbox",callback:()=>i(v=>!v),title:"Show X Axis",selected:r===!0}],[r]),p=D.useMemo(()=>{const m=new Set;t.crossCorrelograms.forEach(y=>{m.add(y.unitId1),m.add(y.unitId2)});const v=si(Array.from(m));return{type:"UnitsTable",columns:[],rows:v.map(y=>({unitId:y,values:{}}))}},[t.crossCorrelograms]),_=R.jsxs(Jo,{width:e-c,height:n,initialPosition:u,adjustable:!1,children:[R.jsx(Ju,{width:u,height:n,customActions:g}),R.jsx(tp,{width:0,height:0,disableScroll:!0,children:o.length>UD?R.jsxs("div",{children:["Not showing cross-correlogram matrix. Too many units selected (max ="," ",UD,")."]}):o.length===0?R.jsx("div",{children:"Select one or more units to view cross-correlograms."}):R.jsx(ep,{plots:d,plotComponent:gD,selectedPlotKeys:void 0,numPlotsPerRow:o.length})})]});return a?_:R.jsxs("div",{style:{position:"relative",width:e,height:n},children:[R.jsx("div",{style:{position:"absolute",left:0,top:0,width:c,height:n,borderRight:"1px solid #ccc",boxSizing:"border-box",padding:10,backgroundColor:"#f9f9f9"},children:R.jsx(_D,{data:p,width:c,height:n})}),R.jsx("div",{style:{position:"absolute",left:c,top:0,width:e-c,height:n},children:_})]})},LD=(t,e,n)=>{const r=Math.min((t-30-(n-1)*7)/n,(e-30-(n-1)*7)/n);return{plotWidth:r,plotHeight:r}},FW=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null);return D.useEffect(()=>{let o=!1;return(async()=>{const l=[],c=t.attrs.num_cross_correlograms||0;if(c===0){o||s({type:"CrossCorrelograms",crossCorrelograms:[],hideUnitSelector:t.attrs.hide_unit_selector||!1});return}const u=await t.getDatasetData("bin_edges_sec",{}),f=await t.getDatasetData("bin_counts",{});if(!u||!f){console.error("Failed to load cross-correlograms data");return}const h=Array.from(u),d=new Int32Array(f),g=h.length-1,p=t.attrs.cross_correlograms;for(let m=0;m<c;m++){const v=p[m],y=m*g,b=Array.from(d.slice(y,y+g));l.push({unitId1:v.unit_id1,unitId2:v.unit_id2,binEdgesSec:h,binCounts:b})}const _=t.attrs.hide_unit_selector||!1;o||s({type:"CrossCorrelograms",crossCorrelograms:l,hideUnitSelector:_})})(),()=>{o=!0}},[t]),i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(NW,{data:i,width:n,height:r})}):R.jsx("div",{children:"Loading..."})},BW=1.4,kW=(t,e,n,r)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: * Attempt to call zoomTime() with uninitialized state ${t}.`),{visibleStartTimeSec:t.visibleStartTimeSec,visibleEndTimeSec:t.visibleEndTimeSec};const i=t.endTimeSec-t.startTimeSec,s=t.visibleEndTimeSec-t.visibleStartTimeSec;if(s===i&&e==="out")return{visibleStartTimeSec:t.startTimeSec,visibleEndTimeSec:t.endTimeSec};let o=n??BW;o=e==="in"?1/o:o;const a=Math.min(s*o,i);if(a>=i)return{...t,visibleStartTimeSec:t.startTimeSec,visibleEndTimeSec:t.endTimeSec};const l=r!==void 0?r:t.currentTime??t.visibleStartTimeSec+s/2,c=(l-t.visibleStartTimeSec)/s;let u=Math.max(l-c*a,t.startTimeSec);const f=Math.min(u+a,t.endTimeSec);return u=f-a,{visibleStartTimeSec:u,visibleEndTimeSec:f}},zD=(t,e)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: Attempt to call panTime() with uninitialized state ${t}.`),t;const n=t.visibleEndTimeSec-t.visibleStartTimeSec;let r=t.visibleStartTimeSec,i=t.visibleEndTimeSec;if(e>0)i=Math.min(t.visibleEndTimeSec+e,t.endTimeSec),r=Math.max(i-n,t.startTimeSec);else if(e<0)r=Math.max(t.visibleStartTimeSec+e,t.startTimeSec),i=Math.min(r+n,t.endTimeSec);else return t;const o=!0?t.currentTime:void 0;return r===t.visibleStartTimeSec&&i===t.visibleEndTimeSec?t:{...t,visibleStartTimeSec:r,visibleEndTimeSec:i,currentTimeSec:o}},UW=(t,e)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: * Attempt to call panTime() with uninitialized state ${t}.`),{visibleStartTimeSec:t.visibleStartTimeSec,visibleEndTimeSec:t.visibleEndTimeSec};const n=t.visibleEndTimeSec-t.visibleStartTimeSec,r=e.panAmountPct/100*n*(e.type==="back"?-1:1);return zD(t,r)},LW=(t,e)=>{if(t.visibleStartTimeSec===void 0||t.visibleEndTimeSec===void 0||t.startTimeSec===void 0||t.endTimeSec===void 0)return console.warn(`WARNING: Attempt to call panTime() with uninitialized state ${t}.`),t;const n=e.deltaT;return zD(t,n)},$D=ln.createContext(void 0),ig=()=>{const t=D.useContext($D);if(!t)throw new Error("useTimeseriesSelection must be used within a TimeseriesSelectionContext");const e=t.dispatch,n=D.useCallback(a=>{e({type:"initializeTimeseries",startTimeSec:a.startTimeSec,endTimeSec:a.endTimeSec,initialVisibleStartTimeSec:a.initialVisibleStartTimeSec,initialVisibleEndTimeSec:a.initialVisibleEndTimeSec})},[e]),r=D.useCallback((a,l)=>{e({type:"setVisibleTimeRange",visibleStartTimeSec:a,visibleEndTimeSec:l})},[e]),i=D.useCallback((a,l)=>{e({type:"setCurrentTime",currentTime:a,ensureVisible:l?.ensureVisible})},[e]),s=D.useCallback(a=>{e({type:"zoomVisibleTimeRange",factor:a})},[e]),o=D.useCallback(a=>{e({type:"translateVisibleTimeRangeFrac",frac:a})},[e]);if(t===void 0)throw new Error("useTimeseriesSelection must be used within a TimeseriesSelectionContext.Provider");return{initializeTimeseriesSelection:n,setVisibleTimeRange:r,setCurrentTime:i,zoomVisibleTimeRange:s,translateVisibleTimeRangeFrac:o,timeseriesSelection:t.timeseriesSelection,startTimeSec:t.timeseriesSelection.startTimeSec,endTimeSec:t.timeseriesSelection.endTimeSec,visibleStartTimeSec:t.timeseriesSelection.visibleStartTimeSec,visibleEndTimeSec:t.timeseriesSelection.visibleEndTimeSec,currentTime:t.timeseriesSelection.currentTime}},sg=()=>{const{visibleStartTimeSec:t,visibleEndTimeSec:e,currentTime:n,setCurrentTime:r,startTimeSec:i,endTimeSec:s,setVisibleTimeRange:o}=ig(),a=D.useCallback((h,d,g)=>{const p=kW({visibleStartTimeSec:t,visibleEndTimeSec:e,currentTime:n,startTimeSec:i,endTimeSec:s},h,d,g);p.visibleStartTimeSec!==void 0&&p.visibleEndTimeSec!==void 0&&o(p.visibleStartTimeSec,p.visibleEndTimeSec)},[t,e,n,i,s,o]),l=D.useCallback((h,d)=>{const g=UW({visibleStartTimeSec:t,visibleEndTimeSec:e,startTimeSec:i,endTimeSec:s,currentTime:n},{type:h,panAmountPct:d??10});g.visibleStartTimeSec!==void 0&&g.visibleEndTimeSec!==void 0&&o(g.visibleStartTimeSec,g.visibleEndTimeSec)},[t,e,i,s,n,o]),c=D.useCallback(h=>{const d=LW({visibleStartTimeSec:t,visibleEndTimeSec:e,startTimeSec:i,endTimeSec:s,currentTime:n},{deltaT:h});d.visibleStartTimeSec!==void 0&&d.visibleEndTimeSec!==void 0&&o(d.visibleStartTimeSec,d.visibleEndTimeSec)},[t,e,i,s,n,o]),u=D.useCallback(h=>{if(t===void 0||e===void 0)return;const d=e-t,g=h,p=g+d;o(g,p)},[t,e,o]),f=D.useCallback((h,d)=>{if(t===void 0||e===void 0)return;const g=t+h*(e-t);r(g)},[t,e,r]);return{visibleStartTimeSec:t,visibleEndTimeSec:e,setVisibleTimeRange:o,zoomTimeseriesSelection:a,panTimeseriesSelection:l,panTimeseriesSelectionDeltaT:c,panTimeseriesSelectionVisibleStartTimeSec:u,setCurrentTimeFraction:f}},VD=()=>{const[t,e]=D.useState(!1),n=D.useMemo(()=>[{id:"only-show-selected",label:"Only Show Selected",tooltip:"Toggle visibility of only selected units",icon:t?"👁️":"👁️🗨️",isActive:t,onClick:()=>e(r=>!r)}],[t]);return{onlyShowSelected:t,customToolbarActions:n}},zW=({width:t,height:e,customActions:n})=>!n||n.length===0?null:R.jsx("div",{style:{width:t,height:e,backgroundColor:"#f8f9fa",borderTop:"1px solid #dee2e6",display:"flex",alignItems:"center",justifyContent:"flex-start",padding:"0 12px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif"},children:R.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:n.map(r=>r.component?R.jsx("div",{style:{display:"flex",alignItems:"center"},children:r.component},r.id):R.jsxs("button",{onClick:r.onClick,style:{padding:"4px 8px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:r.isActive?"#007bff":"#ffffff",color:r.isActive?"#ffffff":"#495057",cursor:r.onClick?"pointer":"default",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:r.tooltip||r.label,onMouseEnter:i=>{!r.isActive&&r.onClick&&(i.currentTarget.style.backgroundColor="#e9ecef")},onMouseLeave:i=>{!r.isActive&&r.onClick&&(i.currentTarget.style.backgroundColor="#ffffff")},children:[r.icon&&R.jsx("span",{children:r.icon}),r.label]},r.id))})}),$W=t=>{if(!t||!t.current)return;t.current.querySelectorAll("canvas").forEach(n=>{n.addEventListener("wheel",r=>{r.preventDefault()})})},VW=t=>{const e=Math.round(t*1e3),n=Math.floor(e/(1e3*60*60)),r=Math.floor(e%(1e3*60*60)/(1e3*60)),i=Math.floor(e%(1e3*60)/1e3),s=e%1e3;return`${n.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`},jW=({width:t,height:e,interactionMode:n,onInteractionModeChange:r,currentTime:i,onZoomToFit:s})=>{const{zoomTimeseriesSelection:o,panTimeseriesSelection:a}=sg(),l=D.useCallback(()=>{o("in",1.2)},[o]),c=D.useCallback(()=>{o("out",1.2)},[o]),u=D.useCallback(()=>{a("back",10)},[a]),f=D.useCallback(()=>{a("forward",10)},[a]),h=D.useCallback(d=>{r(d)},[r]);return R.jsxs("div",{style:{width:t,height:e,backgroundColor:"#f8f9fa",borderTop:"1px solid #dee2e6",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 12px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif"},children:[R.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[R.jsx("button",{onClick:()=>h("pan"),style:{padding:"4px 8px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:n==="pan"?"#007bff":"#ffffff",color:n==="pan"?"#ffffff":"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease"},title:"Pan mode: Drag to pan, wheel to zoom",children:"🖱️ Pan"}),R.jsx("button",{onClick:()=>h("select-zoom"),style:{padding:"4px 8px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:n==="select-zoom"?"#007bff":"#ffffff",color:n==="select-zoom"?"#ffffff":"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease"},title:"Select zoom mode: Drag to select region and zoom in",children:"🔍 Select"})]}),R.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[R.jsx("button",{onClick:u,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Pan left",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"⬅️"}),R.jsx("button",{onClick:c,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Zoom out",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"🔍➖"}),R.jsx("button",{onClick:l,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Zoom in",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"🔍➕"}),R.jsx("button",{onClick:f,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Pan right",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"➡️"}),R.jsx("div",{style:{width:"1px",height:"20px",backgroundColor:"#dee2e6",margin:"0 4px"}}),R.jsx("button",{onClick:s,style:{padding:"6px 10px",border:"1px solid #ced4da",borderRadius:"4px",backgroundColor:"#ffffff",color:"#495057",cursor:"pointer",fontSize:"12px",fontWeight:"500",transition:"all 0.15s ease",display:"flex",alignItems:"center",gap:"4px"},title:"Reset zoom to show all data",onMouseEnter:d=>{d.currentTarget.style.backgroundColor="#e9ecef"},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ffffff"},children:"🏠"})]}),R.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[R.jsx("span",{style:{color:"#6c757d",fontWeight:"500"},children:"Time:"}),R.jsx("span",{style:{padding:"4px 8px",backgroundColor:"#e9ecef",borderRadius:"4px",fontFamily:"Monaco, Consolas, monospace",fontSize:"12px",fontWeight:"600",color:"#495057",minWidth:"120px",textAlign:"center"},children:i!==void 0?VW(i):"--:--:--.---"})]})]})},HW=[{name:"1ms",secondsPerTick:.001,countPerLargerUnit:10,scale_appropriate_label:t=>`${t%1e3} ms`},{name:"10ms",secondsPerTick:.01,countPerLargerUnit:10,scale_appropriate_label:t=>`${t*10%1e3} ms`},{name:"100ms",secondsPerTick:.1,countPerLargerUnit:10,scale_appropriate_label:t=>`${t*100%1e3} ms`},{name:"1s",secondsPerTick:1,countPerLargerUnit:10,scale_appropriate_label:t=>`${t%60} s`},{name:"10s",secondsPerTick:10,countPerLargerUnit:6,scale_appropriate_label:t=>`${t*10%60} s`},{name:"1min",secondsPerTick:60,countPerLargerUnit:10,scale_appropriate_label:t=>`${t%60} min`},{name:"10min",secondsPerTick:60*10,countPerLargerUnit:6,scale_appropriate_label:t=>`${t*10%60} min`},{name:"1hr",secondsPerTick:60*60,countPerLargerUnit:6,scale_appropriate_label:t=>`${t%24} hr`},{name:"6hr",secondsPerTick:60*60*6,countPerLargerUnit:4,scale_appropriate_label:t=>`${t*6%24} hr`},{name:"1day",secondsPerTick:60*60*24,countPerLargerUnit:10,scale_appropriate_label:t=>`${t} day`},{name:"10day",secondsPerTick:60*60*24*10,countPerLargerUnit:1e4,scale_appropriate_label:t=>`${10*t} day`}],jD=(t,e,n,r)=>{if(e===void 0||n===void 0)return[];if(n<=e)return[];const i=[],s=t/(n-e);for(const o of HW){const a=s*o.secondsPerTick;if(a<=50)continue;const l=Math.ceil(e/o.secondsPerTick),c=Math.floor(n/o.secondsPerTick),u=a>200||c-l<5;for(let f=l;f<=c;f++){if(f%o.countPerLargerUnit===0)continue;const h=f*o.secondsPerTick;i.push({value:h,label:o.scale_appropriate_label(f),major:u,xPixelPosition:r(h)})}}return i},WW=(t,e,n,r)=>D.useMemo(()=>jD(t,e,n,r),[e,n,r,t]),XW=t=>{if(!t||typeof t=="function")return;const e=t.current,n=e&&e.getContext("2d");if(n)return n},qW={position:"absolute",left:0,top:0},HD=t=>{const{width:e,height:n,draw:r,drawData:i}=t,s=D.useRef(null);return D.useEffect(()=>{const o=XW(s);o&&o.canvas&&r(o,i)},[r,s,i]),R.jsx("canvas",{ref:s,width:e,height:n,style:qW})},WD=(t,e)=>{const{width:n,height:r,margins:i,timeTicks:s,gridlineOpts:o,yTickSet:a,yLabel:l}=e;t.clearRect(0,0,t.canvas.width,t.canvas.height);const c=r-i.bottom;YW(t,s,c,i.top,{hideGridlines:o?.hideX},e.hideTimeAxisLabels),t.strokeStyle="lightgray",$_(t,i.left,c,n-i.right,c),a&&KW(t,a,c,i.left,n-i.right,i.top,{hideGridlines:o?.hideY}),l&&ZW(t,l,i.left,i.bottom,i.top,t.canvas.height)},YW=(t,e,n,r,i,s)=>{const o=s||!1;if(!e||e.length===0)return;const a=2,l=n+(o?0:5);t.textAlign="center",t.textBaseline="top",e.forEach(c=>{t.strokeStyle=c.major?"gray":"lightgray";const u=i.hideGridlines?n:r;$_(t,c.xPixelPosition,l,c.xPixelPosition,u),o||(t.fillStyle=c.major?"black":"gray",t.fillText(c.label,c.xPixelPosition,l+a))})},KW=(t,e,n,r,i,s,o)=>{const l=r-5,c=l-2,{ticks:u}=e;t.fillStyle="black",t.textAlign="right",t.textBaseline="middle",u.forEach(f=>{if(!f.pixelValue)return;const h=f.pixelValue;t.strokeStyle=f.isMajor?"gray":"lightgray",t.fillStyle=f.isMajor?"black":"gray";const d=o.hideGridlines?r:i;$_(t,l,h,d,h),t.fillText(f.label,c,h)})},ZW=(t,e,n,r,i,s)=>{t.textAlign="center",t.textBaseline="middle",t.save(),t.translate(15,(s-r-i)/2+i),t.fillStyle="black",t.font="13px sans-serif",t.rotate(-Math.PI/2),t.fillText(e,0,0),t.restore()},$_=(t,e,n,r,i)=>{t.beginPath(),t.moveTo(e,n),t.lineTo(r,i),t.stroke()},GW={},QW=t=>{const{width:e,height:n}=t,r=D.useCallback(i=>{WD(i,t)},[t]);return R.jsx("span",{className:"TSV2AxesLayer",children:R.jsx(HD,{width:e,height:n,draw:r,drawData:GW})})},JW=(t,e)=>{const{margins:n,currentTimePixels:r,currentTimeIntervalPixels:i}=e;if(t.clearRect(0,0,t.canvas.width,t.canvas.height),i!==void 0){t.fillStyle="rgba(255, 225, 225, 0.4)",t.strokeStyle="rgba(150, 50, 50, 0.9)";const s=i[0],o=n.top,a=i[1]-i[0],l=t.canvas.height-n.bottom-n.top;t.fillRect(s,o,a,l),t.strokeRect(s,o,a,l)}if(r!==void 0&&i===void 0){t.fillStyle="rgba(255, 255, 0, 0.1)";const s=4;t.fillRect(r-s/2,n.top,s,t.canvas.height-n.bottom-n.top),t.strokeStyle="rgba(200, 200, 0, 0.4)",t.lineWidth=1,t.beginPath(),t.moveTo(r,n.top),t.lineTo(r,t.canvas.height-n.bottom),t.stroke()}},eX=t=>{const{width:e,height:n,timeRange:r,currentTimePixels:i,currentTimeIntervalPixels:s,margins:o}=t,a=D.useMemo(()=>({width:e,height:n,timeRange:r,currentTimePixels:i,currentTimeIntervalPixels:s,margins:o}),[e,n,r,i,s,o]);return R.jsx(HD,{width:e,height:n,draw:JW,drawData:a})},tX=({width:t,height:e,selectionRect:n})=>{if(!n)return null;const{startX:r,endX:i}=n,s=Math.abs(i-r),o=Math.min(r,i);return R.jsx("div",{style:{position:"absolute",top:0,left:0,width:t,height:e,pointerEvents:"none",zIndex:10},children:R.jsx("div",{style:{position:"absolute",left:o,top:0,width:s,height:e,backgroundColor:"rgba(0, 123, 255, 0.2)",border:"1px solid rgba(0, 123, 255, 0.6)",borderRadius:"2px"}})})},nX=t=>{const{pixelToTime:e,visibleStartTimeSec:n,setCurrentTime:r,onMouseDown:i,onMouseUp:s,onMouseMove:o,onMouseOut:a,onCanvasClick:l,interactionMode:c}=t,{panTimeseriesSelectionVisibleStartTimeSec:u,setVisibleTimeRange:f}=sg(),[h,d]=D.useState(!1),[g,p]=D.useState(void 0),[_,m]=D.useState(null),v=D.useRef({mouseDownAchorX:null,mouseDownAnchorTime:null,mouseDownAnchorVisibleStartTime:null,mouseDownAnchorPixelToTime:null,moved:!1,selectionStartX:null,selectionEndX:null}),y=D.useCallback(S=>{if(d(!0),!S.shiftKey&&!S.ctrlKey&&!S.altKey){const A=S.clientX-S.currentTarget.getBoundingClientRect().x;c==="select-zoom"?(v.current.selectionStartX=A,v.current.selectionEndX=A,m({startX:A,endX:A})):(v.current.mouseDownAchorX=A,v.current.mouseDownAnchorTime=e(A),v.current.mouseDownAnchorVisibleStartTime=n||null,v.current.mouseDownAnchorPixelToTime=e),v.current.moved=!1}else i&&i(S)},[e,i,n,c]),b=D.useCallback(S=>{if(!S.shiftKey&&!S.ctrlKey&&!S.altKey){const A=S.clientX-S.currentTarget.getBoundingClientRect().x;if(c==="select-zoom"&&v.current.selectionStartX!==null){const E=Math.min(v.current.selectionStartX,A),C=Math.max(v.current.selectionStartX,A);if(Math.abs(C-E)>5){const M=e(E),T=e(C);f(M,T)}else if(!v.current.moved){const M=e(A);if(r(M),l){const T=S.clientY-S.currentTarget.getBoundingClientRect().y;l(A,T)}}m(null),v.current.selectionStartX=null,v.current.selectionEndX=null}else if(v.current.mouseDownAchorX=null,v.current.mouseDownAnchorTime=null,v.current.mouseDownAnchorPixelToTime=null,!v.current.moved){const E=e(A);if(r(E),l){const C=S.clientY-S.currentTarget.getBoundingClientRect().y;l(A,C)}}}else s&&s(S)},[s,e,r,c,f,l]),w=D.useCallback(S=>{const A=S.clientX-S.currentTarget.getBoundingClientRect().x,E=e(A);if(p(E),!S.shiftKey&&!S.ctrlKey&&!S.altKey){if(c==="select-zoom"&&v.current.selectionStartX!==null)v.current.selectionEndX=A,m({startX:Math.min(v.current.selectionStartX,A),endX:Math.max(v.current.selectionStartX,A)}),v.current.moved=!0;else if(c==="pan"&&v.current.mouseDownAchorX!==null&&v.current.mouseDownAnchorPixelToTime!==null){const C=v.current.mouseDownAnchorPixelToTime(A),M=v.current.mouseDownAnchorTime,T=v.current.mouseDownAnchorVisibleStartTime;if(M!==null&&T!==null){const P=C-M,I=A-v.current.mouseDownAchorX;if(Math.abs(I)>2||Math.abs(P)>.01){const k=T-P;u(k),S.preventDefault(),S.stopPropagation(),v.current.moved=!0}}}}o&&o(S)},[e,o,c,u]),x=D.useCallback(S=>{p(void 0),d(!1),m(null),v.current.selectionStartX=null,v.current.selectionEndX=null,a&&a(S)},[a]);return{isViewClicked:h,hoverTime:g,selectionRect:_,handleMouseDown:y,handleMouseUp:b,handleMouseMove:w,handleMouseOut:x}},rX=({width:t,height:e,leftMargin:n,customToolbarActions:r,hideTimeAxisLabels:i,hideNavToolbar:s})=>{const o=r&&r.length>0,a=D.useMemo(()=>({left:n||60,right:20,top:10,bottom:i?10:30}),[n,i]);let l=0;s||(l+=40),o&&(l+=40);const c=t,u=e-l;return{margins:a,canvasWidth:c,canvasHeight:u}},iX=23,sX=60,oX=(t,e,n,r)=>{const i=Math.ceil((e-r)/n);return isNaN(i)||i<1?[]:Array(i).fill(0).map((s,o)=>r+o*n).filter(s=>s>t)},aX=(t,e)=>{let n=0;const r=Math.trunc(Math.log10(e));if(Math.trunc(Math.log10(t))!==r)return n;const i=Math.trunc(Math.log10(e-t));if(r<=i)return n;const s=i+1,o=Math.pow(10,-s),a=Math.trunc(e*o).toString(),l=Math.trunc(t*o).toString();for(const[c,u]of[...a].entries()){if(u!==l[c]){n=n*Math.pow(10,c-s);break}n=n*10+parseInt(u)}return n*Math.pow(10,s)},lX=(t,e)=>Math.floor(t*Math.pow(10,-(e+1)))*Math.pow(10,e+1),cX=(t,e,n)=>{const r=t-0,i=Math.trunc(r*Math.pow(10,-n)),s=i%10===0;return{label:Math.abs(n)>3?`${(i/10).toFixed(1)}e${n+1}`:`${Math.round(i*Math.pow(10,n)*1e9)/1e9}`,isMajor:s,dataValue:t}},uX=(t,e,n,r,i)=>{const s=oX(e,n,r,t).map(l=>Math.round(l*1e9)/1e9),o=aX(e,n);return s.map(l=>cX(l,o,i))},XD={ticks:[],datamin:0,datamax:0},fX=(t,e)=>{const n=Math.floor(Math.log10(t/e)),r=Math.pow(10,n),i=[1,2,5,10],o=i.map(a=>t/(r*a)).findIndex(a=>a<e);return o===3?{step:1,scale:n+1}:{step:i[o],scale:n}},qD=t=>{const{datamin:e,datamax:n,userSpecifiedZoom:r}=t;let{pixelHeight:i}=t;i<=1&&(i=1);const s=r??1;if(e===void 0||n===void 0||e===n)return XD;const o=e/s,a=n/s,l=a-o,c=i/sX,u=i/iX,f=fX(l,u),h=f.step*Math.pow(10,f.scale);if(l/h<c)return console.warn("Error: Unable to compute valid y-axis step size. Suppressing display."),XD;const d=lX(o,f.scale);return{ticks:uX(d,o,a,h,f.scale),datamin:o,datamax:a}},hX=t=>{const{datamin:e,datamax:n,userSpecifiedZoom:r}=t;let{pixelHeight:i}=t;return i<=1&&(i=1),D.useMemo(()=>qD({datamin:e,datamax:n,userSpecifiedZoom:r,pixelHeight:i}),[n,e,i,r])},YD=({width:t,height:e,onCanvasElement:n,gridlineOpts:r,onKeyDown:i,onMouseDown:s,onMouseMove:o,onMouseOut:a,onMouseUp:l,yAxisInfo:c,shiftZoom:u,requireClickToZoom:f,leftMargin:h,customToolbarActions:d,onCanvasClick:g,hideNavToolbar:p=!1,hideTimeAxisLabels:_=!1,drawContentForExport:m,setDrawForExport:v})=>{const{visibleStartTimeSec:y,visibleEndTimeSec:b,zoomTimeseriesSelection:w,panTimeseriesSelection:x,setVisibleTimeRange:S}=sg(),{currentTime:A,setCurrentTime:E,startTimeSec:C,endTimeSec:M}=ig(),T=D.useMemo(()=>[y,b],[y,b]),{margins:P,canvasWidth:I,canvasHeight:k}=rX({width:t,height:e,leftMargin:h,customToolbarActions:d,hideNavToolbar:p}),O=D.useMemo(()=>y===void 0||b===void 0?()=>0:b<=y?()=>0:K=>P.left+(K-y)/(b-y)*(I-P.left-P.right),[I,y,b,P]),L=D.useMemo(()=>y===void 0||b===void 0?()=>0:b<=y?()=>0:K=>y+(K-P.left)/(I-P.left-P.right)*(b-y),[I,y,b,P]),U=D.useMemo(()=>{const K=c?.yMin||0,te=c?.yMax||0;return te<=K?()=>0:de=>k-P.bottom-(de-K)/(te-K)*(k-P.top-P.bottom)},[c,k,P]),$=WW(I,y,b,O),J=hX({datamin:c?.yMin||0,datamax:c?.yMax||0,pixelHeight:k-P.left-P.right}),ne=D.useMemo(()=>({datamin:J.datamin,datamax:J.datamax,ticks:J.ticks.map(K=>({...K,pixelValue:U(K.dataValue)}))}),[J,U]),j=k,V=D.useMemo(()=>R.jsx(QW,{width:I,height:j,timeRange:T,margins:P,timeTicks:$,yTickSet:c?.showTicks?ne:void 0,yLabel:c?.yLabel,gridlineOpts:r,hideTimeAxisLabels:_}),[r,I,j,T,P,$,c?.showTicks,c?.yLabel,ne,_]),G=D.useMemo(()=>A!==void 0?O(A):void 0,[A,O]),z=D.useMemo(()=>R.jsx(eX,{width:I,height:j,timeRange:T,margins:P,currentTimePixels:G}),[I,j,T,P,G]),Q=D.useRef(null),[ee,ce]=D.useState("pan"),{isViewClicked:se,hoverTime:ue,selectionRect:be,handleMouseDown:le,handleMouseUp:ye,handleMouseMove:ve,handleMouseOut:Ie}=nX({pixelToTime:L,visibleStartTimeSec:y,setCurrentTime:E,onMouseDown:s,onMouseUp:l,onMouseMove:o,onMouseOut:a,onCanvasClick:g,interactionMode:ee});D.useEffect(()=>{(f===!1||se)&&$W(Q)},[f,se]);const Re=D.useCallback(K=>{if(u&&!K.shiftKey||K.deltaY===0||f!==!1&&!se)return;const te=-K.deltaY/100;w(te>0?"in":"out",1.2,ue)},[u,w,ue,f,se]),Oe=D.useCallback(K=>{K.key==="="?w("in"):K.key==="-"?w("out"):K.key==="ArrowRight"?x("forward"):K.key==="ArrowLeft"&&x("back"),i&&i(K)},[i,w,x]),Ne=D.useCallback(()=>{C!==void 0&&M!==void 0&&S(C,M)},[C,M,S]),Ye=D.useMemo(()=>R.jsx(tX,{width:I,height:j,selectionRect:be}),[I,j,be]),[Le,je]=D.useState(null);D.useEffect(()=>{Le&&n(Le,I,k,P)},[Le,I,k,P,n]),D.useEffect(()=>{if(!v)return;v(async te=>{if(!te||!P)return;const de=ge=>{const xe=c?.yMin||0,me=c?.yMax||0;return me<=xe?0:te.height-P.bottom-(ge-xe)/(me-xe)*(te.height-P.top-P.bottom)},oe=jD(te.width,y,b,O),we=qD({datamin:c?.yMin,datamax:c?.yMax,pixelHeight:te.height});for(const ge of we.ticks)ge.pixelValue=de(ge.dataValue);WD(te.context,{timeTicks:oe,margins:P,gridlineOpts:r,yTickSet:we,yLabel:c?.yLabel,width:te.width,height:te.height,hideTimeAxisLabels:_}),m&&await m(te.context,te.width,te.height,P,{exporting:!0})})},[m,v,P,y,b,O,T,r,c,_,U]);const Ee=D.useMemo(()=>R.jsxs("div",{style:{position:"relative",overflow:"hidden",width:I,height:j},onWheel:!f||se?Re:void 0,onMouseDown:le,onMouseUp:ye,onMouseMove:ve,onMouseOut:Ie,tabIndex:0,onKeyDown:Oe,children:[V,R.jsx("canvas",{style:{position:"absolute",width:I,height:j},ref:K=>je(K),width:I,height:j}),z,Ye]}),[V,z,Ye,I,j,Oe,Re,le,ye,ve,Ie,f,se]),B=D.useMemo(()=>R.jsx(jW,{width:t,height:40,interactionMode:ee,onInteractionModeChange:ce,currentTime:A,onZoomToFit:Ne}),[t,ee,ce,A,Ne]),H=D.useMemo(()=>R.jsx(zW,{width:t,height:40,customActions:d}),[t,d]);return R.jsxs("div",{className:"time-scroll-view-3",ref:Q,style:{position:"absolute",width:t,height:e,background:"white"},children:[Ee,!p&&R.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0},children:[B,H]})]})},KD=15,dX={hideX:!1,hideY:!0},pX={showTicks:!1,yMin:void 0,yMax:void 0},gX=({dataClient:t,width:e,height:n,setDrawForExport:r})=>{const{visibleStartTimeSec:i,visibleEndTimeSec:s}=sg(),{initializeTimeseriesSelection:o}=ig(),{selectedUnitIds:a,unitIdSelectionDispatch:l}=Vr(),[c,u]=D.useState(void 0),f=D.useRef(null),[h,d]=D.useState(null),[g,p]=D.useState(null),[_,m]=D.useState(!1),[v,y]=D.useState(null),[b,w]=D.useState(null),x=D.useMemo(()=>i===void 0||s===void 0?"raster":s-i>120?"heatmap":"raster",[i,s]),S=t.metadata.unitIds;D.useEffect(()=>{t.metadata&&o({startTimeSec:t.metadata.startTimeSec,endTimeSec:t.metadata.endTimeSec,initialVisibleStartTimeSec:t.metadata.startTimeSec,initialVisibleEndTimeSec:t.metadata.endTimeSec})},[o,t.metadata]),D.useEffect(()=>{let z=!1;const Q=async()=>{if(!(i===void 0||s===void 0))try{if(x==="raster"){const ee=await t.getDataForRange({startTimeSec:i,endTimeSec:s});if(z)return;p(ee),w(null)}else{const ee=t.getSpikeCountsForRange({startTimeSec:i,endTimeSec:s});if(z)return;w(ee),p(null)}y(null)}catch(ee){if(z)return;console.error("Error loading data:",ee),y(`Error loading data: ${ee}`)}};return m(!0),Q().finally(()=>{z||m(!1)}),()=>{z=!0}},[t,i,s,x]);const{onlyShowSelected:A,customToolbarActions:E}=VD(),[C,M]=D.useState(e),[T,P]=D.useState(n),[I,k]=D.useState(null),O=D.useMemo(()=>{const z=[];return A&&S.forEach((Q,ee)=>{a.has(Q)&&z.push(ee)}),z},[A,a,S]),L=D.useMemo(()=>O.map(z=>S[z]),[O,S]),U=D.useCallback(()=>{if(!I||!f.current||!h||!b||!t.metadata||i===void 0||s===void 0)return;if(h.clearRect(0,0,C,T),_&&(h.fillStyle="rgba(0, 0, 0, 0.02)",h.fillRect(0,0,C,T),h.fillStyle="black",h.font="16px Arial",h.textAlign="center",h.fillText("Loading...",C/2,T/2)),v){h.fillStyle="rgba(255, 0, 0, 0.1)",h.fillRect(0,0,C,T),h.fillStyle="red",h.font="14px Arial",h.textAlign="center",h.fillText(v,C/2,T/2);return}const Q=T-I.top-I.bottom,ee=C-I.left-I.right,ce=s-i;let se;if(A){let le=0;S.forEach((ye,ve)=>{a.has(ye)&&le++}),se=le}else S.forEach((le,ye)=>{}),se=S.length;const ue=Q/(se||1);h.save(),h.beginPath(),h.rect(I.left,I.top,ee,Q),h.clip();let be=1;if(b.counts.forEach(le=>{A?O.forEach(ye=>{const ve=le[ye];ve>be&&(be=ve)}):le.forEach(ye=>{ye>be&&(be=ye)})}),b.counts.forEach((le,ye)=>{const ve=b.binEdges[ye],Ie=b.binEdges[ye+1],Re=I.left+(ve-i)/ce*ee,Oe=I.left+(Ie-i)/ce*ee;if(A)for(let Ne=0;Ne<O.length;Ne++){const Ye=O[Ne],je=le[Ye]/be,Ee=I.top+(O.length-1-Ne)*ue,B=ZD(je);h.fillStyle=B,h.fillRect(Re,Ee,Oe-Re+.5,ue)}else le.forEach((Ne,Ye)=>{const Le=Ne/be,je=I.top+(S.length-1-Ye)*ue,Ee=ZD(Le);h.fillStyle=Ee,h.fillRect(Re,je,Oe-Re+.5,ue)})}),h.restore(),ue>=KD){h.globalAlpha=1;const le=A?L:S;le.forEach((ye,ve)=>{const Re=I.top+(le.length-1-ve)*ue+ue/2,Oe=_v(Nt(ye));h.fillStyle=Oe,h.font="12px Arial",h.textAlign="right",h.fillText(`Unit ${ye}`,I.left-5,Re)})}},[C,T,I,b,i,s,t.metadata,_,v,h,a,A,S,O,L]),$=D.useCallback(()=>{if(!I||!f.current||!h||!g||!t.metadata||i===void 0||s===void 0)return;if(h.clearRect(0,0,C,T),_&&(h.fillStyle="rgba(0, 0, 0, 0.02)",h.fillRect(0,0,C,T),h.fillStyle="black",h.font="16px Arial",h.textAlign="center",h.fillText("Loading...",C/2,T/2)),v){h.fillStyle="rgba(255, 0, 0, 0.1)",h.fillRect(0,0,C,T),h.fillStyle="red",h.font="14px Arial",h.textAlign="center",h.fillText(v,C/2,T/2);return}const Q=T-I.top-I.bottom,ee=C-I.left-I.right,ce=s-i,se=t.metadata.unitIds,ue={};let be;if(A){for(let ye=0;ye<O.length;ye++){const ve=O[ye];ue[ve]=ye}be=O.length}else se.forEach((ye,ve)=>{ue[ve]=ve}),be=se.length;const le=Q/(be||1);h.save(),h.beginPath(),h.rect(I.left,I.top,ee,Q),h.clip();for(let ye=0;ye<g.timestamps.length;ye++){const ve=g.timestamps[ye],Ie=ue[g.unitIndices[ye]];if(Ie===void 0)continue;const Re=se[g.unitIndices[ye]],Oe=I.top+(be-1-Ie)*le+le/2,Ne=_v(Nt(Re)),Ye=c===Re,Le=a.has(Re);h.strokeStyle=Ne,h.lineWidth=Ye||Le?2:1,h.globalAlpha=Le?1:Ye?.8:.6;const je=I.left+(ve-i)/ce*ee;h.beginPath(),h.moveTo(je,Oe-le*.4),h.lineTo(je,Oe+le*.4),h.stroke()}if(h.restore(),le>=KD){h.globalAlpha=1;const ye=A?L:se;ye.forEach((ve,Ie)=>{const Oe=I.top+(ye.length-1-Ie)*le+le/2,Ne=_v(Nt(ve));h.fillStyle=Ne,h.font="12px Arial",h.textAlign="right",h.fillText(`Unit ${ve}`,I.left-5,Oe)})}},[C,T,I,g,t.metadata,i,s,_,v,c,a,A,h,L,O]);D.useEffect(()=>{x==="heatmap"&&b?U():$()},[$,U,x,b]);const J=D.useCallback(()=>{},[]),ne=D.useCallback(z=>{if(!I||!t.metadata)return;const Q=t.metadata.unitIds,ee=Q.length,ce=1-(z.y-I.top)/(T-I.top-I.bottom),se=Math.round(ce*ee-.5);if(0<=se&&se<ee)return Q[se]},[T,I,t.metadata]),j=D.useCallback(z=>{const Q=z.currentTarget.getBoundingClientRect(),ee={x:z.clientX-Q.x,y:z.clientY-Q.y},ce=ne(ee);z.shiftKey||z.ctrlKey?l({type:"TOGGLE_UNIT",targetUnit:ce}):l({type:"UNIQUE_SELECT",targetUnit:ce})},[ne,l]),V=D.useCallback(z=>{const Q=z.currentTarget.getBoundingClientRect(),ee={x:z.clientX-Q.x,y:z.clientY-Q.y},ce=ne(ee);ce!==void 0&&u(ce)},[ne]),G=D.useCallback(()=>{u(void 0)},[]);return t.metadata?R.jsx(YD,{width:e,height:n,customToolbarActions:E,onCanvasElement:(z,Q,ee,ce)=>{f.current=z;const se=z?.getContext("2d");d(se),M(Q),P(ee),k(ce)},gridlineOpts:dX,onKeyDown:J,onMouseDown:j,onMouseMove:V,onMouseOut:G,yAxisInfo:pX,setDrawForExport:r}):R.jsx("div",{children:"Loading metadata..."})},ZD=t=>{if(t===0)return"rgb(255,255,255)";const e=Math.max(0,Math.min(1,.7*(1-t))),n=Math.round(e*255);return`rgb(${n}, ${n}, ${n})`};class V_{constructor(e,n,r,i,s,o){this.zarrGroup=e,this.metadata=n,this.referenceTimes=r,this.referenceIndices=i,this.counts2dArray=s,this.binEdges=o,this.zarrGroup=e}static async create(e){const n={startTimeSec:e.attrs.start_time_sec,endTimeSec:e.attrs.end_time_sec,unitIds:e.attrs.unit_ids||[],totalSpikes:e.attrs.total_spikes||0},r=await e.getDatasetData("reference_times",{}),i=await e.getDatasetData("reference_indices",{});if(!r||!i)throw new Error(`Reference arrays not found in Zarr group: ${e.path}`);const s=await e.getDatasetData("spike_counts_1sec",{}).catch(()=>{});if(!s)throw new Error(`Spike counts data not found in Zarr group: ${e.path}`);const o=Math.ceil(n.endTimeSec-n.startTimeSec),a=n.unitIds.length,l=Array(o);for(let f=0;f<o;f++){l[f]=Array(a);for(let h=0;h<a;h++){const d=f*a+h;l[f][h]=d<s.length?s[d]:0}}const c=Array(o+1);for(let f=0;f<=o;f++)c[f]=n.startTimeSec+f;return new V_(e,n,r,i,l,c)}async getDataForRange(e){const n=this.findStartIndex(this.referenceTimes,this.referenceIndices,e.startTimeSec),r=this.findEndIndex(this.referenceTimes,this.referenceIndices,e.endTimeSec);if(n>=r)return{timestamps:[],unitIndices:[]};const i=await this.zarrGroup.getDatasetData("timestamps",{slice:[[n,r]]}),s=await this.zarrGroup.getDatasetData("unit_indices",{slice:[[n,r]]});return{timestamps:Array.from(i),unitIndices:Array.from(s)}}findStartIndex(e,n,r){let i=0;for(;i+1<e.length&&e[i+1]<r;)i++;return n[i]}getSpikeCountsForRange(e){const{startTimeSec:n,endTimeSec:r}=e,i=Math.floor(n-this.metadata.startTimeSec),s=Math.ceil(r-this.metadata.startTimeSec);let o=1;for(;(s-i)/o>500;)o+=1;const a=this.counts2dArray.slice(i,s),l=this.binEdges.slice(i,s+1);if(o===1)return{binEdges:l,counts:a};{const c=[],u=[];for(let f=0;f<a.length;f+=o){const h=Array(this.metadata.unitIds.length).fill(0);for(let d=0;d<o;d++)if(f+d<a.length)for(let g=0;g<h.length;g++)h[g]+=a[f+d][g];c.push(h),u.push(l[f])}return l.length>0&&u.push(l[Math.min(l.length-1,u.length*o)]),{binEdges:u,counts:c}}}findEndIndex(e,n,r){let i=e.length-1;for(;i-1>=0&&e[i-1]>r;)i--;return n[i]}}const mX=({zarrGroup:t,contexts:e,width:n,height:r,setDrawForExport:i})=>{const s=yX(t);return s?R.jsx(GD,{context:e.timeseriesSelection,children:R.jsx(ui,{context:e.unitSelection,children:R.jsx(gX,{dataClient:s,width:n,height:r,setDrawForExport:i})})}):null},GD=({context:t,children:e})=>{const{state:n,dispatch:r}=Jp(t);return!r||!n?R.jsx(R.Fragment,{children:"Waiting for context..."}):R.jsx($D.Provider,{value:{timeseriesSelection:n,dispatch:r},children:e})},yX=t=>{const[e,n]=D.useState(null);return D.useEffect(()=>{let r=!0;return V_.create(t).then(i=>{r&&n(i)}),()=>{r=!1}},[t]),e},vX=({dataClient:t,width:e,height:n})=>{const{selectedUnitIds:r,unitIdSelectionDispatch:i}=Vr(),{initializeTimeseriesSelection:s,visibleStartTimeSec:o,visibleEndTimeSec:a}=ig(),[l,c]=D.useState(null),[u,f]=D.useState(null),[h,d]=D.useState(!1),[g,p]=D.useState(null),_=Qu,{onlyShowSelected:m,customToolbarActions:v}=VD(),[y,b]=D.useState(e),[w,x]=D.useState(n),[S,A]=D.useState(null),E=t.metadata;D.useEffect(()=>{E&&i({type:$o,newUnitOrder:si(E.unitIds)})},[E,i]),D.useEffect(()=>{E&&s({startTimeSec:E.startTimeSec,endTimeSec:E.endTimeSec,initialVisibleStartTimeSec:E.startTimeSec,initialVisibleEndTimeSec:E.endTimeSec})},[s,E]),D.useEffect(()=>{let T=!1;const P=async()=>{if(o!==void 0&&a!==void 0){let I=1e4;for(;;){const k=await t.getDataForRange({startTimeSec:o,endTimeSec:a},{maxNumEvents:I});if(T)return;if(k&&f(k),k.subsampleFactor>1){if(I===1e6)break;I=Math.max(I*3,k.timestamps.length*3),I>1e6&&(I=1e6)}else break}}};return d(!0),p(null),P().catch(I=>{T||p(`Failed to load data: ${I}`),p(`Failed to load data: ${I}`)}).finally(()=>{d(!1)}),()=>{T=!0}},[o,a,t]);const C=D.useMemo(()=>{if(!u||!E||u.amplitudes.length===0)return{yMin:0,yMax:10};let T=1/0,P=-1/0;for(let k=0;k<u.amplitudes.length;k++){const O=E.unitIds[u.unitIndices[k]];if(m?r.has(O):!0){const U=u.amplitudes[k];U<T&&(T=U),U>P&&(P=U)}}if(T===1/0)return{yMin:0,yMax:10};const I=(P-T)*.1;return{yMin:T-I,yMax:P+I}},[u,E,m,r]);D.useEffect(()=>{if(!l||!u||!E||!S||a===void 0||o===void 0)return;let T=!1;return(async()=>{if(T)return;if(l.clearRect(0,0,y,w),h&&(l.fillStyle="rgba(0, 0, 0, 0.1)",l.fillRect(0,0,y,w),l.fillStyle="black",l.font="16px Arial",l.textAlign="center",l.fillText("Loading...",y/2,w/2)),g){l.fillStyle="rgba(255, 0, 0, 0.1)",l.fillRect(0,0,y,w),l.fillStyle="red",l.font="14px Arial",l.textAlign="center",l.fillText(g,y/2,w/2);return}l.save(),l.beginPath(),l.rect(S.left,S.top,y-S.left-S.right,w-S.top-S.bottom),l.clip();const I=O=>S.left+(O-o)/(a-o)*(y-S.left-S.right),k=O=>w-S.bottom-(O-C.yMin)/(C.yMax-C.yMin)*(w-S.top-S.bottom);for(let O=0;O<u.timestamps.length;O++){const L=u.timestamps[O],U=u.amplitudes[O],$=E.unitIds[u.unitIndices[O]];if(L<o||L>a||!(m?r.has($):!0))continue;const ne=ci(Nt($)),V=r.has($)?1:.3;l.fillStyle=ne,l.globalAlpha=V;const G=I(L),z=k(U);l.beginPath(),l.arc(G,z,2,0,Math.PI*2),l.fill()}l.globalAlpha=1,u.subsampleFactor>1&&(l.fillStyle="#2196F3",l.font="12px Arial",l.textAlign="left",l.fillText(`Subsampled ${u.subsampleFactor}x`,S.left+10,S.top+20)),l.restore()})(),()=>{T=!0}},[l,u,E,o,a,y,w,S,C,r,m,h,g]);const M=D.useMemo(()=>({showTicks:!0,yMin:C.yMin,yMax:C.yMax,yLabel:"Amplitude"}),[C]);return E?R.jsx("div",{children:R.jsxs(Jo,{width:e,height:n,initialPosition:_,adjustable:!1,children:[R.jsx(Ju,{width:_,height:n}),R.jsx(YD,{width:e-_,height:n,onCanvasElement:(T,P,I,k)=>{if(!T)return;const O=T.getContext("2d");c(O),b(P),x(I),A(k)},yAxisInfo:M,customToolbarActions:v})]})}):R.jsx("div",{children:"Loading metadata..."})};class og{constructor(e,n,r={},i,s){this.zarrGroup=e,this.metadata=n,this.subsampleClients=r,this.referenceTimes=i,this.referenceIndices=s,this.zarrGroup=e}static async create(e){const n={startTimeSec:e.attrs.start_time_sec,endTimeSec:e.attrs.end_time_sec,unitIds:e.attrs.unit_ids||[],totalSpikes:e.attrs.total_spikes||0},r={},i=e.subgroups.find(a=>a.name==="subsampled_data"),s=await e.getDatasetData("reference_times",{}),o=await e.getDatasetData("reference_indices",{});if(!s||!o)throw new Error(`Reference arrays not found in Zarr group: ${e.path}`);if(i){const a=await e.getGroup(i.name);if(!a)throw new Error(`Failed to load subsampled_data group at ${i.name} in ${e.path}`);let l=4;for(;;){const c=a.subgroups.find(h=>h.name===`factor_${l}`);if(!c)break;const u=await a.getGroup(c.name);if(!u)throw console.warn(a.subgroups),new Error(`Failed to load subsampled group at ${c.name} in ${e.path}`);const f=await og.create(u);r[l]=f,l*=4}}return new og(e,n,r,s,o)}async getDataForRange(e,n){const r=this.findStartIndex(this.referenceTimes,this.referenceIndices,e.startTimeSec),i=this.findEndIndex(this.referenceTimes,this.referenceIndices,e.endTimeSec);if(r>=i)return{timestamps:[],unitIndices:[],amplitudes:[],subsampleFactor:1};if(n.maxNumEvents>0&&i-r>n.maxNumEvents){let c=4;for(;c*4 in this.subsampleClients&&(i-r)/c>n.maxNumEvents;)c*=4;if(c in this.subsampleClients){const f=await this.subsampleClients[c].getDataForRange(e,{maxNumEvents:0});return f.subsampleFactor=c,f}}const s=await this.zarrGroup.getDatasetData("timestamps",{slice:[[r,i]]}),o=await this.zarrGroup.getDatasetData("unit_indices",{slice:[[r,i]]}),a=await this.zarrGroup.getDatasetData("amplitudes",{slice:[[r,i]]});return{timestamps:Array.from(s),unitIndices:Array.from(o),amplitudes:Array.from(a),subsampleFactor:1}}findStartIndex(e,n,r){let i=0;for(;i+1<e.length&&e[i+1]<r;)i++;return n[i]}findEndIndex(e,n,r){let i=e.length-1;for(;i-1>=0&&e[i-1]>r;)i--;return n[i]}}const _X=({zarrGroup:t,contexts:e,width:n,height:r})=>{const i=bX(t);return i?R.jsx(GD,{context:e.timeseriesSelection,children:R.jsx(ui,{context:e.unitSelection,children:R.jsx(vX,{dataClient:i,width:n,height:r})})}):null},bX=t=>{const[e,n]=D.useState(null);return D.useEffect(()=>{let r=!0;return og.create(t).then(i=>{r&&n(i)}),()=>{r=!1}},[t]),e},xX=25,QD=2*Math.PI,wX={maxElectrodePixelRadius:xX},j_={},JD=2,SX=t=>{const{width:e,height:n,electrodes:r,units:i,disableAutoRotate:s,onlyShowSelected:o}=t,{selectedElectrodeIds:a}=ND(),{selectedUnitIds:l,unitIdSelectionDispatch:c}=Vr(),{affineTransform:u,handleWheel:f}=rf(e,n,{shift:!0,alt:!1}),h=D.useMemo(()=>new Set([...l]),[l]),d=i.filter(U=>o?h.has(U.unitId):!0).sort((U,$)=>h.has(U.unitId)&&!h.has($.unitId)?1:!h.has(U.unitId)&&h.has($.unitId)?-1:Nt(U.unitId)-Nt($.unitId)),g=t.maxElectrodePixelRadius||wX.maxElectrodePixelRadius,p=t.colors??ea,_=t.showLabels??!1,m=t.offsetLabels??!1,{convertedElectrodes:v,pixelRadius:y,transform:b}=D.useMemo(()=>rg(e,n,r,"geom",g,{disableAutoRotate:s}),[r,n,g,e,s]),w=Math.sqrt(nf(u)),x=D.useCallback((U,$)=>{const J=y*w,ne=v.map(j=>{const V=(a||[]).includes(j.e.id),G=!1,z=!1,Q=V?z?p.draggedSelected:G?p.selectedHover:p.selected:z?p.dragged:G?p.hover:p.base;return{...j,color:Q,textColor:V||G&&!z?p.textDark:p.textLight}});if(U.clearRect(0,0,U.canvas.width,U.canvas.height),U.strokeStyle=ea.border,v.forEach(j=>{const V=fi(u,{x:j.pixelX,y:j.pixelY});U.beginPath(),U.ellipse(V.x,V.y,J,J,0,0,QD),U.stroke()}),_){U.font=`${J}px Arial`,U.textAlign=m?"right":"center",U.textBaseline="middle";const j=m?1.4*J:0;ne.forEach(V=>{const G=fi(u,{x:V.pixelX,y:V.pixelY});U.fillStyle=m?p.textDark:V.textColor,U.fillText(`${V.e.label}`,G.x-j,G.y)})}},[p,m,v,y,a,_,u,w]),S=D.useMemo(()=>{const U={};for(const $ of i){const ne=$.xLocations.map((j,V)=>{const G=$.xLocations[V],z=$.yLocations[V];return Jd(b,[G,z])}).map(j=>fi(u,{x:j[0],y:j[1]}));U[$.unitId]=ne}return U},[u,b,i]),A=D.useCallback((U,$)=>{const J=JD;U.clearRect(0,0,U.canvas.width,U.canvas.height);const ne=(j,V)=>{U.fillStyle=V,U.strokeStyle="black";for(let G=0;G<j.length;G++){const{x:z,y:Q}=j[G];U.beginPath(),U.ellipse(z,Q,J,J,0,0,QD),U.fill(),U.stroke()}};for(const j of d){const V=S[j.unitId],G=l.size===0||l.has(j.unitId)?ci(Nt(j.unitId)):"rgb(220, 220, 220)";ne(V,G)}},[d,l,S]),E=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:x,drawData:j_}),[e,n,x]),C=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:A,drawData:j_}),[e,n,A]),M=D.useCallback((U,{ctrlKey:$})=>{const J=TX(u,U),ne=nf(u),j=JD/Math.sqrt(ne),V=[];for(const G of d){const z=S[G.unitId];for(const Q of z)if(Qd(eM([Q.x-j,Q.y-j,j*2,j*2]),eM(J))){V.push(G.unitId);break}}if($)for(const G of V)c({type:"TOGGLE_UNIT",targetUnit:G});else c({type:"SET_SELECTION",incomingSelectedUnitIds:V})},[c,u,d,S]),T=D.useCallback((U,{ctrlKey:$})=>{c({type:"SET_SELECTION",incomingSelectedUnitIds:[]})},[c]),{onMouseMove:P,onMouseDown:I,onMouseUp:k,paintDragSelectLayer:O}=Cu(e,n,M,T),L=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:O,drawData:j_}),[e,n,O]);return R.jsxs("div",{style:{width:e,height:n,position:"relative"},onMouseMove:P,onMouseUp:k,onMouseDown:I,onWheel:f,children:[E,C,L]})},eM=t=>({xmin:t[0],ymin:t[1],xmax:t[0]+t[2],ymax:t[1]+t[3]}),TX=(t,e)=>{const n=jl(t,{x:e[0],y:e[1]}),r=jl(t,{x:e[0]+e[2],y:e[1]+e[3]});return[n.x,n.y,r.x-n.x,r.y-n.y]},tM=10,AX=({data:t,width:e,height:n})=>{const{selectedUnitIds:r}=Vr();return R.jsx(Jo,{width:e,height:n,initialPosition:200,children:r.size>tM?R.jsxs("div",{children:["Not showing spike locations. Too many units selected (max ="," ",tM,")."]}):R.jsx(EX,{data:t,width:0,height:0,selectedUnitIds:r})})},EX=t=>{const{data:e,width:n,height:r}=t,[i,s]=D.useState({...ef,onlyShowSelected:!1}),o=30,a=Object.keys(e.channelLocations),l=TD(a,e.channelLocations),c=D.useMemo(()=>({width:n-20,height:r-o,top:0,position:"absolute"}),[n,r]);return R.jsxs("div",{children:[R.jsx("div",{style:c,children:R.jsx(SX,{width:n-20,height:r-o,electrodes:l,units:e.units,disableAutoRotate:e.disableAutoRotate,onlyShowSelected:i.onlyShowSelected})}),R.jsx("div",{style:{position:"absolute",top:r-o,height:o,overflow:"hidden"},children:R.jsx(tf,{options:i,setOptions:s})})]})},CX=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.x_range,d=t.attrs.y_range,g=t.attrs.channel_locations||{},p=t.attrs.hide_unit_selector,_=t.attrs.disable_auto_rotate,m=t.attrs.units||[],v=[];for(const b of m){const w=b.name,x=b.unit_id,S=await t.getDatasetData(`${w}/spike_times_sec`,{}),A=await t.getDatasetData(`${w}/x_locations`,{}),E=await t.getDatasetData(`${w}/y_locations`,{});if(u)return;v.push({unitId:x,spikeTimesSec:Array.from(S),xLocations:Array.from(A),yLocations:Array.from(E)})}if(u)return;const y={type:"SpikeLocations",channelLocations:g,units:v,xRange:h,yRange:d};p&&(y.hideUnitSelector=p),_&&(y.disableAutoRotate=_),s(y)}catch(h){console.error("Error loading spike locations data:",h),a(`Failed to load spike locations data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading spike locations data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(AX,{data:i,width:n,height:r})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No spike locations data available"})},DX=25,H_=2*Math.PI,MX={maxElectrodePixelRadius:DX},W_={},Wl=8,RX=()=>({selectedElectrodeIds:[]}),IX=t=>{const{width:e,height:n,electrodes:r,units:i,disableAutoRotate:s,onlyShowSelected:o}=t,{selectedElectrodeIds:a}=RX(),{selectedUnitIds:l,unitIdSelectionDispatch:c}=Vr(),{affineTransform:u,handleWheel:f}=rf(e,n,{shift:!0,alt:!1}),h=D.useMemo(()=>new Set([...l]),[l]),d=i.filter(L=>o?h.has(L.unitId):!0).sort((L,U)=>h.has(L.unitId)&&!h.has(U.unitId)?1:!h.has(L.unitId)&&h.has(U.unitId)?-1:Nt(L.unitId)-Nt(U.unitId)),g=t.maxElectrodePixelRadius||MX.maxElectrodePixelRadius,p=t.colors??ea,_=t.showLabels??!1,m=t.offsetLabels??!1,{convertedElectrodes:v,pixelRadius:y,transform:b}=D.useMemo(()=>rg(e,n,r,"geom",g,{disableAutoRotate:s}),[r,n,g,e,s]),w=Math.sqrt(nf(u)),x=D.useCallback((L,U)=>{const $=y*w,J=v.map(ne=>{const j=(a||[]).includes(ne.e.id),V=!1,G=!1,z=j?G?p.draggedSelected:V?p.selectedHover:p.selected:G?p.dragged:V?p.hover:p.base;return{...ne,color:z,textColor:j||V&&!G?p.textDark:p.textLight}});if(L.clearRect(0,0,L.canvas.width,L.canvas.height),J.forEach(ne=>{const j=fi(u,{x:ne.pixelX,y:ne.pixelY});L.fillStyle=ne.color,L.beginPath(),L.ellipse(j.x,j.y,$,$,0,0,H_),L.fill()}),L.strokeStyle=ea.border,v.forEach(ne=>{const j=fi(u,{x:ne.pixelX,y:ne.pixelY});L.beginPath(),L.ellipse(j.x,j.y,$,$,0,0,H_),L.stroke()}),_){L.font=`${$}px Arial`,L.textAlign=m?"right":"center",L.textBaseline="middle";const ne=m?1.4*$:0;J.forEach(j=>{const V=fi(u,{x:j.pixelX,y:j.pixelY});L.fillStyle=m?p.textDark:j.textColor,L.fillText(`${j.e.label}`,V.x-ne,V.y)})}},[p,m,v,y,a,_,u,w]),S=D.useCallback((L,U)=>{const $=Wl;L.clearRect(0,0,L.canvas.width,L.canvas.height);const J=(ne,j,V)=>{L.fillStyle=V,L.strokeStyle="black",L.beginPath(),L.ellipse(ne,j,$,$,0,0,H_),L.fill(),L.stroke()};for(const ne of d){const j=Jd(b,[ne.x,ne.y]),V=fi(u,{x:j[0],y:j[1]}),G=l.size===0||l.has(ne.unitId)?ci(Nt(ne.unitId)):"rgb(220, 220, 220)";J(V.x,V.y,G)}},[b,d,l,u]),A=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:x,drawData:W_}),[e,n,x]),E=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:S,drawData:W_}),[e,n,S]),C=D.useCallback((L,{ctrlKey:U})=>{const $=PX(u,L),J=nf(u),ne=Wl/Math.sqrt(J),j=[];for(const V of d){const G=Jd(b,[V.x,V.y]);Qd(ag([G[0]-ne,G[1]-ne,ne*2,ne*2]),ag($))&&(ag([G[0]-ne,G[1]-ne,ne*2,ne*2]),j.push(V.unitId))}if(U)for(const V of j)c({type:"TOGGLE_UNIT",targetUnit:V});else c({type:"SET_SELECTION",incomingSelectedUnitIds:j})},[b,c,d,u]),M=D.useCallback((L,{ctrlKey:U})=>{let $=!1;for(const J of d){const ne=Jd(b,[J.x,J.y]);Wz(L,ag([ne[0]-Wl,ne[1]-Wl,Wl*2,Wl*2]))&&($=!0,c(U?{type:"TOGGLE_UNIT",targetUnit:J.unitId}:{type:"SET_SELECTION",incomingSelectedUnitIds:[J.unitId]}))}$||c({type:"SET_SELECTION",incomingSelectedUnitIds:[]})},[b,c,d]),{onMouseMove:T,onMouseDown:P,onMouseUp:I,paintDragSelectLayer:k}=Cu(e,n,C,M),O=D.useMemo(()=>R.jsx(qn,{width:e,height:n,draw:k,drawData:W_}),[e,n,k]);return e>0&&n>0?R.jsxs("div",{style:{width:e,height:n,position:"relative"},onMouseMove:T,onMouseUp:I,onMouseDown:P,onWheel:f,children:[A,E,O]}):R.jsx("div",{})},ag=t=>({xmin:t[0],ymin:t[1],xmax:t[0]+t[2],ymax:t[1]+t[3]}),PX=(t,e)=>{const n=jl(t,{x:e[0],y:e[1]}),r=jl(t,{x:e[0]+e[2],y:e[1]+e[3]});return[n.x,n.y,r.x-n.x,r.y-n.y]},OX=t=>{const{data:e,width:n,height:r}=t,[i,s]=D.useState({...ef,onlyShowSelected:!1}),o=30,a=Object.keys(e.channelLocations),l=TD(a,e.channelLocations),c=D.useMemo(()=>({width:n-20,height:r-o,top:0,position:"absolute"}),[n,r]);return R.jsxs("div",{children:[R.jsx("div",{style:c,children:R.jsx(IX,{width:n-20,height:r-o,electrodes:l,units:e.units,disableAutoRotate:e.disableAutoRotate,onlyShowSelected:i.onlyShowSelected})}),R.jsx("div",{style:{position:"absolute",top:r-o,height:o,overflow:"hidden"},children:R.jsx(tf,{options:i,setOptions:s})})]})},NX=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.disable_auto_rotate||!1,d=t.attrs.unit_ids,g=t.attrs.channel_locations,p=await t.getDatasetData("coords",{});if(!p||p.length===0)throw new Error("Empty coords data");const _=new Float32Array(p);if(_.length!==d.length*2)throw new Error(`Expected coords length ${d.length*2}, got ${_.length}`);const m=[];for(let v=0;v<d.length;v++)m.push({unitId:d[v],x:_[v*2],y:_[v*2+1]});if(u)return;s({type:"UnitLocations",channelLocations:g,units:m,disableAutoRotate:h})}catch(h){console.error("Error loading unit locations data:",h),a(`Failed to load unit locations data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading unit locations data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(OX,{data:i,width:n,height:r})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No unit locations data available"})},FX=({rows:t,columns:e,onDeleteRow:n=void 0,deleteRowLabel:r=void 0,onEditRow:i=void 0,editRowLabel:s=void 0,selectionMode:o="none",selectedRowKeys:a=[],onSelectedRowKeysChanged:l=void 0,selectionDisabled:c})=>{const u=D.useMemo(()=>{const m={};return a.forEach(v=>{m[v]=!0}),m},[a]),[f,h]=D.useState(null),d=D.useCallback(m=>{l&&(o==="single"?!(m in u)||!u[m]?l([m+""]):l([]):o==="multiple"&&l(Object.keys(u).filter(v=>v!=m&&u[v]).concat(u[m]?[]:[m.toString()])))},[l,o,u]),g=D.useCallback(m=>{h(m)},[]),p=D.useCallback((m,v)=>{v&&n&&n(m),h(null)},[n]),_=D.useCallback(m=>{i&&i(m)},[i]);return R.jsxs(oH,{className:"NiceTable",children:[R.jsx(bH,{children:R.jsxs(pD,{children:[R.jsx(Qp,{style:{width:0}},"_first"),e.map(m=>R.jsx(Qp,{children:m.element?m.element:R.jsx("span",{children:m.label})},m.key))]})}),R.jsx(fH,{children:t.map(m=>R.jsxs(pD,{children:[R.jsxs(Qp,{children:[n&&(f===m.key?R.jsx(kX,{title:r||"",onConfirmDeleteRow:p,rowKey:m.key}):R.jsx(BX,{title:r||"",onDeleteRow:g,rowKey:m.key})),i&&R.jsx(UX,{title:s||"",onEditRow:_,rowKey:m.key}),o!=="none"&&R.jsx(oD,{checked:u[m.key]||!1,onClick:()=>d(m.key),disabled:c})]}),e.map(v=>R.jsx(Qp,{children:R.jsx("span",{children:LX(m.columnValues[v.key])})},v.key))]},m.key))})]})},BX=({title:t,rowKey:e,onDeleteRow:n})=>{const r=D.useCallback(()=>{n&&n(e)},[n,e]);return R.jsx(Vl,{title:t,onClick:r,children:R.jsx(zE,{})})},kX=({title:t,rowKey:e,onConfirmDeleteRow:n})=>{const r=D.useCallback(()=>{n&&n(e,!0)},[n,e]),i=D.useCallback(()=>{n&&n(e,!1)},[n,e]);return R.jsxs("span",{children:["Confirm delete?",R.jsx(Vl,{title:t,onClick:r,children:R.jsx(zE,{})}),R.jsx(Vl,{title:"Cancel",onClick:i,children:R.jsx(w9,{})})]})},UX=({title:t,rowKey:e,onEditRow:n})=>R.jsx(Vl,{title:t,onClick:()=>n&&n(e),children:R.jsx(x9,{})}),LX=t=>t==0?t:t?typeof t=="object"?t.element?t.element:t.text||"":t:"",zX=({width:t,height:e})=>{const{selectedUnitMetrics:n,allUnitMetrics:r,unitMetricSelectionDispatch:i}=gv(),s=D.useMemo(()=>[{key:"metric",label:"Metric"}],[]),o=D.useMemo(()=>(r||[]).map(l=>({key:l,columnValues:{metric:l}})),[r]),a=D.useCallback(l=>{i({type:"selectUnitMetrics",unitMetrics:l})},[i]);return R.jsx("div",{style:{position:"absolute",width:t,height:e},children:R.jsx(FX,{rows:o,columns:s,selectedRowKeys:n,onSelectedRowKeysChanged:a,selectionMode:"multiple"})})},$X=(t,e)=>{t.clearRect(0,0,e.width,e.height);for(const n of e.pixelVerticalLines||[])t.strokeStyle=n.color,t.beginPath(),t.moveTo(n.x,e.margins.top-20),t.lineTo(n.x,e.height-e.margins.bottom),t.stroke();e.barBoxes.forEach(n=>{t.fillStyle=n.color,t.fillRect(n.x1,n.y1,n.x2-n.x1,n.y2-n.y1)}),e.xLabel&&(t.textBaseline="bottom",t.textAlign="center",t.fillStyle="black",t.fillText(e.xLabel,e.width/2,e.height-3));for(const n of e.pixelTicks||[])t.strokeStyle="black",t.beginPath(),t.moveTo(n.x,e.height-e.margins.bottom),t.lineTo(n.x,e.height-e.margins.bottom+6),t.stroke(),t.textBaseline="top",t.textAlign="center",t.fillStyle="black",t.fillText(n.label,n.x,e.height-e.margins.bottom+8)},VX=t=>R.jsx(qn,{width:t.width,height:t.height,draw:$X,drawData:t}),jX={},HX=({bars:t,range:e,ticks:n,verticalLines:r,xLabel:i,onSelectRect:s,width:o,height:a})=>{const{xMin:l,xMax:c}=D.useMemo(()=>e?{xMin:e.min,xMax:e.max}:t.length>0?{xMin:t[0].xStart,xMax:t[t.length-1].xEnd}:{xMin:0,xMax:1},[t,e]),u=D.useMemo(()=>Math.max(...t.map(S=>S.height)),[t]),{barBoxes:f,margins:h,pixelTicks:d,pixelVerticalLines:g}=D.useMemo(()=>{const S={left:3,right:3,top:5,bottom:3+(i?18:0)+(n?18:0)},A=o-S.left-S.right,E=a-S.top-S.bottom,C=t.map(P=>({key:P.key,x1:S.left+(P.xStart-l)/(c-l)*A,x2:S.left+(P.xEnd-l)/(c-l)*A,y1:S.top+E*(1-P.height/u),y2:S.top+E,tooltip:P.tooltip,color:P.color})),M=n?n.map(P=>({x:S.left+(P.x-l)/(c-l)*A,label:`${P.label}`})):void 0,T=r?r.map(P=>({x:S.left+(P.x-l)/(c-l)*A,color:P.color})):void 0;return{barBoxes:C,margins:S,pixelTicks:M,pixelVerticalLines:T}},[t,n,r,l,c,u,o,a,i]),p=D.useCallback((S,{ctrlKey:A,shiftKey:E})=>{const C=[],M={x:S[0],y:S[1],width:S[2],height:S[3]};for(const k of f)k.x1<=M.x+M.width&&k.x2>=M.x&&C.push(k.key);const T=o-h.left-h.right,P=(M.x-h.left)/T*(c-l)+l,I=(M.x+M.width-h.left)/T*(c-l)+l;s&&s(M,C,{ctrlKey:A,shiftKey:E,xMin:P,xMax:I})},[f,s,h.left,h.right,o,l,c]),_=D.useCallback(()=>{},[]),{onMouseMove:m,onMouseDown:v,onMouseUp:y,onMouseLeave:b,paintDragSelectLayer:w}=Cu(o,a,p,_),x=D.useMemo(()=>R.jsx(qn,{width:o,height:a,draw:w,drawData:jX}),[o,a,w]);return R.jsxs("div",{style:{width:o,height:a,position:"relative"},onMouseDown:v,onMouseMove:m,onMouseUp:y,onMouseLeave:b,children:[R.jsx(VX,{barBoxes:f,margins:h,pixelTicks:d,pixelVerticalLines:g,xLabel:i,width:o,height:a}),x]})},WX=(t,e)=>{const n=e-t;let r;n<=30?r=10:n<=120?r=20:n<=300?r=50:n<=600?r=100:n<=1e3?r=150:r=100;const i=[];let s=Math.ceil(t/r);for(;s*r<=e;)i.push(s*r),s++;return i},XX=({metric:t,metricRange:e,units:n,selectedUnitIds:r,setSelectedUnitIds:i,numBins:s,onZoomToRect:o,width:a,height:l})=>{const{bars:c,ticks:u,verticalLines:f}=D.useMemo(()=>{const d=n.map(m=>m.values[t.key]).filter(m=>m!==void 0).map(m=>m),g=n.filter(m=>r.has(m.unitId)).map(m=>m.values[t.key]).filter(m=>m!==void 0).map(m=>m),_=n.filter(m=>r.has(m.unitId)).map(m=>({unitId:m.unitId,value:m.values[t.key]})).filter(m=>m.value!==void 0).map(m=>m.unitId).map(m=>ci(Nt(m)));return qX(d,g,_,s||10)},[n,t,r,s]),h=D.useCallback((d,g,{ctrlKey:p,shiftKey:_,xMin:m,xMax:v})=>{if(_){o&&o({x:m,y:d.y,width:v-m,height:d.height});return}if(g.length===0)return;const y=[];for(const S of g){const A=c[S];y.push(A)}const b=Math.min(...y.map(S=>S.xStart)),w=Math.max(...y.map(S=>S.xEnd)),x=[];for(const S of n){const A=S.values[t.key];A!==void 0&&b<=A&&A<=w&&x.push(S.unitId)}i(p||_?[...new Set([...r,...x])]:x)},[c,t,r,i,n,o]);return R.jsx(HX,{width:a,height:l,bars:c,range:e,ticks:u,verticalLines:f,onSelectRect:h})},qX=(t,e,n,r)=>{if(t.length===0)return{bars:[],ticks:[],verticalLines:[]};let i=Math.min(...t),s=Math.max(...t);if(s<=i)return{bars:[],ticks:[],verticalLines:[]};i-=(s-i)/r/2,s+=(s-i)/r/2;const o=[];for(let f=0;f<r;f++)o.push(0);for(const f of t){const h=Math.min(Math.floor((f-i)/(s-i)*r),r-1);o[h]++}const a=[];for(let f=0;f<r;f++)a.push(0);for(const f of e){const h=Math.min(Math.floor((f-i)/(s-i)*r),r-1);a[h]++}const l=[];e.forEach((f,h)=>{l.push({x:f,color:n[h]})});const u=YX(i,s).map(f=>({x:f,label:`${f}`}));return{bars:[...o.map((f,h)=>({key:h,xStart:i+h*(s-i)/r,xEnd:i+(h+1)*(s-i)/r,height:f,tooltip:"",color:"gray"}))],ticks:u,verticalLines:l}},YX=(t,e)=>{const n=e-t;if(n<=0)return[];let r=1;for(;n*r<100;)r*=10;for(;n*r>=1e3;)r/=10;return WX(t*r,e*r).map(i=>i/r)},KX=(t,e)=>{t.clearRect(0,0,e.width,e.height),e.markers.forEach(n=>{const r=e.coord2Pixel({x:n.x,y:n.y});t.fillStyle=n.color,t.strokeStyle="black",t.beginPath(),t.ellipse(r.x,r.y,n.radius,n.radius,0,0,2*Math.PI),t.fill(),t.stroke()})},ZX=t=>R.jsx(qn,{width:t.width,height:t.height,draw:KX,drawData:t}),GX={},QX=({markers:t,xRange:e,yRange:n,onSelectRect:r,onClickPoint:i,width:s,height:o})=>{const{margins:a}=D.useMemo(()=>({margins:{left:20,right:20,top:20,bottom:20}}),[]),{xMin:l,xMax:c,yMin:u,yMax:f}=D.useMemo(()=>{let x,S,A,E;return e?(x=e.min,S=e.max):t.length>0?(x=Math.min(...t.map(C=>C.x)),S=Math.max(...t.map(C=>C.x))):(x=0,S=1),n?(A=n.min,E=n.max):t.length>0?(A=Math.min(...t.map(C=>C.y)),E=Math.max(...t.map(C=>C.y))):(A=0,E=1),{xMin:x,xMax:S,yMin:A,yMax:E}},[t,e,n]),{coord2Pixel:h,pixel2Coord:d}=D.useMemo(()=>{const x=s-a.left-a.right,S=o-a.top-a.bottom;return{coord2Pixel:C=>({x:a.left+(C.x-l)/(c-l)*x,y:a.top+(1-(C.y-u)/(f-u))*S}),pixel2Coord:C=>({x:l+(C.x-a.left)/x*(c-l),y:u+(1-(C.y-a.top)/S)*(f-u)})}},[s,o,a,l,c,u,f]),g=D.useCallback((x,{ctrlKey:S,shiftKey:A})=>{const E={x:x[0],y:x[1],width:x[2],height:x[3]},C=[];for(const T of t){const P=h({x:T.x,y:T.y}),I={xmin:P.x-T.radius,ymin:P.y-T.radius,xmax:P.x+T.radius,ymax:P.y+T.radius};Qd({xmin:E.x,xmax:E.x+E.width,ymin:E.y,ymax:E.y+E.height},I)&&C.push(T.key)}const M=JX(d,E);r&&r(M,C,{ctrlKey:S,shiftKey:A})},[r,d,t,h]),p=D.useCallback((x,{ctrlKey:S,shiftKey:A})=>{const E={x:x[0],y:x[1]},C={x:E.x,y:E.y,width:1,height:1};let M;for(const T of t){const P=h({x:T.x,y:T.y}),I={xmin:P.x-T.radius,ymin:P.y-T.radius,xmax:P.x+T.radius,ymax:P.y+T.radius};Qd({xmin:C.x,xmax:C.x+C.width,ymin:C.y,ymax:C.y+C.height},I)&&(M=T.key)}i&&i(d(E),M,{ctrlKey:S,shiftKey:A})},[h,t,i,d]),{onMouseMove:_,onMouseDown:m,onMouseUp:v,onMouseLeave:y,paintDragSelectLayer:b}=Cu(s,o,g,p),w=D.useMemo(()=>R.jsx(qn,{width:s,height:o,draw:b,drawData:GX}),[s,o,b]);return R.jsxs("div",{style:{width:s,height:o,position:"relative"},onMouseDown:m,onMouseMove:_,onMouseUp:v,onMouseLeave:y,children:[R.jsx(ZX,{markers:t,margins:a,coord2Pixel:h,width:s,height:o}),w]})},JX=(t,e)=>{const n=t({x:e.x,y:e.y}),r=t({x:e.x+e.width,y:e.y+e.height});return{x:Math.min(n.x,r.x),y:Math.min(n.y,r.y),width:Math.abs(r.x-n.x),height:Math.abs(r.y-n.y)}},eq=({metric1:t,metric2:e,metric1Range:n,metric2Range:r,units:i,selectedUnitIds:s,setSelectedUnitIds:o,onZoomToRect:a,width:l,height:c})=>{const f=D.useMemo(()=>{const g=[];for(const p of i){const _=p.values[t.key],m=p.values[e.key];_!==void 0&&m!==void 0&&g.push({key:p.unitId,x:_,y:m,color:s.has(p.unitId)?ci(Nt(p.unitId)):"lightgray",radius:6,tooltip:`Unit ${p.unitId}`})}return g},[i,t,e,s]),h=D.useCallback((g,p,{ctrlKey:_,shiftKey:m})=>{if(m){a&&a(g);return}let v=p;_&&(v=[...new Set([...p,...s])]),o(v)},[o,s,a]),d=D.useCallback((g,p,{ctrlKey:_,shiftKey:m})=>{let v;if(_||m){const y=new Set([...s]);p!==void 0&&(y.has(p)?y.delete(p):y.add(p)),v=[...y]}else p===void 0?v=[]:v=[p];o(v)},[o,s]);return R.jsx(QX,{width:l,height:c,markers:f,xRange:n,yRange:r,onSelectRect:h,onClickPoint:d})},tq=({type:t,metric1:e,metric2:n,metric1Range:r,metric2Range:i,units:s,selectedUnitIds:o,setSelectedUnitIds:a,numHistogramBins:l,onZoomToRect:c,width:u,height:f})=>{if(t==="histogram"){if(!e)throw Error("Unexpected: metric1 not defined");return R.jsx(XX,{metric:e,metricRange:r,units:s,selectedUnitIds:o,setSelectedUnitIds:a,numBins:l,onZoomToRect:c,width:u,height:f})}else if(t==="scatter"){if(!e)throw Error("Unexpected: metric1 not defined");if(!n)throw Error("Unexpected: metric2 not defined");return R.jsx(eq,{metric1:e,metric2:n,metric1Range:r,metric2Range:i,units:s,selectedUnitIds:o,setSelectedUnitIds:a,onZoomToRect:c,width:u,height:f})}else{if(t==="bottom-label")return R.jsx("div",{style:{width:u,textAlign:"center"},children:e?.label||R.jsx("span",{children:" "})});if(t==="left-label")return R.jsx("div",{style:{width:u,height:f,overflow:"hidden",writingMode:"vertical-lr",transform:"rotate(-180deg)",textAlign:"center"},children:e?.label||R.jsx("span",{children:" "})});throw Error(`Unexpected type: ${t}`)}},nq=({data:t,width:e,height:n})=>{const{units:r,metrics:i}=t,{selectedUnitIds:s,unitIdSelectionDispatch:o}=Vr(),{selectedUnitMetrics:a}=gv(),[l,c]=D.useState(1),[u,f]=D.useState(10),[h,d]=D.useState({}),g=D.useMemo(()=>r.sort((v,y)=>s.has(v.unitId)&&!s.has(y.unitId)?1:!s.has(v.unitId)&&s.has(y.unitId)?-1:Nt(v.unitId)-Nt(y.unitId)),[r,s]);D.useEffect(()=>{o({type:$o,newUnitOrder:si(g.map(v=>v.unitId))})},[g,o]);const p=D.useMemo(()=>{const v=a.length===0?[{type:"text",content:"Box size",title:"Set box size"},{type:"button",callback:()=>c(w=>w*1.3),title:"Increase box size",icon:R.jsx(sp,{})},{type:"button",callback:()=>c(w=>w/1.3),title:"Decrease box size",icon:R.jsx(ip,{})}]:[],y=[{type:"text",content:"# bins",title:""},{type:"button",callback:()=>f(w=>w+5),title:"Increase num. histogram bins",icon:R.jsx(sp,{})},{type:"button",callback:()=>f(w=>Math.max(5,w-5)),title:"Decrease num. histogram bins",icon:R.jsx(ip,{})}],b={type:"button",callback:()=>d({}),title:"Reset zoom",text:"reset"};return[...v,{type:"divider"},...y,{type:"divider"},b]},[a.length]),_=Qu,m=D.useMemo(()=>{const v=y=>{o({type:"SET_SELECTION",incomingSelectedUnitIds:y})};if(a.length===0)return i.map(y=>{const b={type:"histogram",metric1:y,metric2:y,metric1Range:h[y.key],metric2Range:h[y.key],units:g,width:400*l,height:400*l,numHistogramBins:u,selectedUnitIds:s,setSelectedUnitIds:v,onZoomToRect:x=>{d({...h,[y.key]:{min:x.x,max:x.x+x.width}})}};return{key:y.key,label:y.label,unitId:"",labelColor:"black",props:b}});{const{plotWidth:w,plotHeight:x}=LD(e-_-30-10,n-30-10,a.length),S=[];for(const A of a){const E=i.filter(C=>C.key===A)[0];{const C={type:"left-label",metric1:E,metric2:E,units:g,numHistogramBins:u,width:30,height:x,selectedUnitIds:s,setSelectedUnitIds:v};S.push({key:`left-label-${A}`,label:void 0,unitId:"",labelColor:"black",props:C,hideBorderColor:!0})}for(const C of a){const M=i.filter(T=>T.key===C)[0];if(E&&M){const T={type:A===C?"histogram":"scatter",metric1:M,metric2:E,metric1Range:h[M.key],metric2Range:h[E.key],units:g,numHistogramBins:u,width:w,height:x,selectedUnitIds:s,setSelectedUnitIds:v,onZoomToRect:P=>{d(A!==C?{...h,[M.key]:{min:P.x,max:P.x+P.width},[E.key]:{min:P.y,max:P.y+P.height}}:{...h,[E.key]:{min:P.x,max:P.x+P.width}})}};S.push({key:`${C}-${A}`,label:T.type==="histogram"?A:void 0,unitId:"",labelColor:"black",props:T})}}}{const A={type:"bottom-label",metric1:void 0,metric2:void 0,units:g,numHistogramBins:u,width:30,height:30,selectedUnitIds:s,setSelectedUnitIds:v};S.push({key:"left-bottom-label",label:void 0,unitId:"",labelColor:"black",props:A,hideBorderColor:!0})}for(const A of a){const E=i.filter(M=>M.key===A)[0],C={type:"bottom-label",metric1:E,metric2:E,units:g,numHistogramBins:u,width:w,height:30,selectedUnitIds:s,setSelectedUnitIds:v};S.push({key:`bottom-label-${A}`,label:void 0,unitId:"",labelColor:"black",props:C,hideBorderColor:!0})}return S}},[i,s,g,l,a,u,e,n,o,h,_]);return R.jsxs(Jo,{width:e,height:n,initialPosition:_,adjustable:!1,children:[R.jsx(Ju,{width:_,height:n,customActions:p}),R.jsx(tp,{width:0,height:0,disableScroll:a.length>0,children:R.jsx(ep,{plots:m,plotComponent:tq,numPlotsPerRow:a.length===0?void 0:a.length+1})})]})},rq=({data:t,width:e,height:n})=>{const{metrics:r}=t,{unitMetricSelectionDispatch:i}=gv();return D.useEffect(()=>{i({type:"initialize",unitMetrics:r.map(s=>s.key)})},[r,i]),R.jsxs(Jo,{width:e,height:n,initialPosition:200,adjustable:!0,children:[R.jsx(zX,{width:0,height:0}),R.jsx(nq,{data:t,width:0,height:0})]})},iq=t=>vd(t,{key:yd,label:yd,dtype:yd}),sq=t=>vd(t,{unitId:EB([AB,yd]),values:()=>!0}),oq=t=>vd(t,{type:CB("UnitMetricsGraph"),metrics:_3(iq),units:_3(sq)}),aq=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.metrics||[],d=await t.getDatasetData("units_data",{});if(!d||d.length===0)throw new Error("Empty units data");const g=new Uint8Array(d),p=new TextDecoder("utf-8").decode(g),_=JSON.parse(p);if(u)return;const m={type:"UnitMetricsGraph",metrics:h,units:_.map(v=>({unitId:v.unit_id,values:v.values}))};if(!oq(m))throw new Error("Invalid view data structure");s(m)}catch(h){console.error("Error loading unit metrics graph data:",h),a(`Failed to load unit metrics graph data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading unit metrics data..."}):i?R.jsx(lq,{context:e.unitMetricSelection,children:R.jsx(ui,{context:e.unitSelection,children:R.jsx(rq,{data:i,width:n,height:r})})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No unit metrics data available"})},lq=({context:t,children:e})=>{const{state:n,dispatch:r}=Jp(t);return!r||!n?R.jsx(R.Fragment,{children:"Waiting for unit metric selection context..."}):R.jsx(o3.Provider,{value:{unitMetricSelection:n,unitMetricSelectionDispatch:r},children:e})},cq=({zarrGroup:t,contexts:e,width:n,height:r})=>{const[i,s]=D.useState(null),[o,a]=D.useState(null),[l,c]=D.useState(!0);return D.useEffect(()=>{let u=!1;return(async()=>{try{c(!0),a(null);const h=t.attrs.unit_ids||[],d=t.attrs.similarity_scores||[],g=t.attrs.range;if(u)return;const p={type:"UnitSimilarityMatrix",unitIds:h,similarityScores:d};g&&(p.range=g),s(p)}catch(h){console.error("Error loading unit similarity matrix data:",h),a(`Failed to load unit similarity matrix data: ${h instanceof Error?h.message:String(h)}`)}finally{c(!1)}})(),()=>{u=!0}},[t]),o?R.jsxs("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:["Error: ",o]}):l?R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"Loading unit similarity matrix data..."}):i?R.jsx(ui,{context:e.unitSelection,children:R.jsx(oW,{data:i,width:n,height:r})}):R.jsx("div",{style:{width:n,height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#666",backgroundColor:"#f5f5f5"},children:"No unit similarity matrix data available"})};function lg(t,e){if(!t)throw new Error(e||"loader assertion failed.")}const X_=!!(typeof process!="object"||String(process)!=="[object process]"||process.browser),nM=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version);nM&&parseFloat(nM[1]);const rM=globalThis,iM=globalThis.process||{},uq=globalThis.navigator||{};function sM(t){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;const n=typeof navigator<"u"&&navigator.userAgent;return!!(n&&n.indexOf("Electron")>=0)}function na(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||sM()}function fq(t){return na()?sM()?"Electron":(uq.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown":"Node"}const oM="4.1.0";function hq(t){try{const e=window[t],n="__storage_test__";return e.setItem(n,n),e.removeItem(n),e}catch{return null}}class dq{constructor(e,n,r="sessionStorage"){this.storage=hq(r),this.id=e,this.config=n,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){const n=JSON.stringify(this.config);this.storage.setItem(this.id,n)}}_loadConfiguration(){let e={};if(this.storage){const n=this.storage.getItem(this.id);e=n?JSON.parse(n):{}}return Object.assign(this.config,e),this}}function pq(t){let e;return t<10?e=`${t.toFixed(2)}ms`:t<100?e=`${t.toFixed(1)}ms`:t<1e3?e=`${t.toFixed(0)}ms`:e=`${(t/1e3).toFixed(2)}s`,e}function gq(t,e=8){const n=Math.max(e-t.length,0);return`${" ".repeat(n)}${t}`}var cg;(function(t){t[t.BLACK=30]="BLACK",t[t.RED=31]="RED",t[t.GREEN=32]="GREEN",t[t.YELLOW=33]="YELLOW",t[t.BLUE=34]="BLUE",t[t.MAGENTA=35]="MAGENTA",t[t.CYAN=36]="CYAN",t[t.WHITE=37]="WHITE",t[t.BRIGHT_BLACK=90]="BRIGHT_BLACK",t[t.BRIGHT_RED=91]="BRIGHT_RED",t[t.BRIGHT_GREEN=92]="BRIGHT_GREEN",t[t.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",t[t.BRIGHT_BLUE=94]="BRIGHT_BLUE",t[t.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",t[t.BRIGHT_CYAN=96]="BRIGHT_CYAN",t[t.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(cg||(cg={}));const mq=10;function aM(t){return typeof t!="string"?t:(t=t.toUpperCase(),cg[t]||cg.WHITE)}function yq(t,e,n){return!na&&typeof t=="string"&&(e&&(t=`\x1B[${aM(e)}m${t}\x1B[39m`),n&&(t=`\x1B[${aM(n)+mq}m${t}\x1B[49m`)),t}function vq(t,e=["constructor"]){const n=Object.getPrototypeOf(t),r=Object.getOwnPropertyNames(n),i=t;for(const s of r){const o=i[s];typeof o=="function"&&(e.find(a=>s===a)||(i[s]=o.bind(t)))}}function q_(t,e){if(!t)throw new Error("Assertion failed")}function Xl(){let t;if(na()&&rM.performance)t=rM?.performance?.now?.();else if("hrtime"in iM){const e=iM?.hrtime?.();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}const ql={debug:na()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},_q={enabled:!0,level:0};function Yl(){}const lM={},cM={once:!0};class of{constructor({id:e}={id:""}){this.VERSION=oM,this._startTs=Xl(),this._deltaTs=Xl(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new dq(`__probe-${this.id}__`,_q),this.timeStamp(`${this.id} started`),vq(this),Object.seal(this)}set level(e){this.setLevel(e)}get level(){return this.getLevel()}isEnabled(){return this._storage.config.enabled}getLevel(){return this._storage.config.level}getTotal(){return Number((Xl()-this._startTs).toPrecision(10))}getDelta(){return Number((Xl()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._storage.setConfiguration({enabled:e}),this}setLevel(e){return this._storage.setConfiguration({level:e}),this}get(e){return this._storage.config[e]}set(e,n){this._storage.setConfiguration({[e]:n})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,n){if(!e)throw new Error(n||"Assertion failed")}warn(e){return this._getLogFunction(0,e,ql.warn,arguments,cM)}error(e){return this._getLogFunction(0,e,ql.error,arguments)}deprecated(e,n){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${n}\` instead`)}removed(e,n){return this.error(`\`${e}\` has been removed. Use \`${n}\` instead`)}probe(e,n){return this._getLogFunction(e,n,ql.log,arguments,{time:!0,once:!0})}log(e,n){return this._getLogFunction(e,n,ql.debug,arguments)}info(e,n){return this._getLogFunction(e,n,console.info,arguments)}once(e,n){return this._getLogFunction(e,n,ql.debug||ql.info,arguments,cM)}table(e,n,r){return n?this._getLogFunction(e,n,console.table||Yl,r&&[r],{tag:xq(n)}):Yl}time(e,n){return this._getLogFunction(e,n,console.time?console.time:console.info)}timeEnd(e,n){return this._getLogFunction(e,n,console.timeEnd?console.timeEnd:console.info)}timeStamp(e,n){return this._getLogFunction(e,n,console.timeStamp||Yl)}group(e,n,r={collapsed:!1}){const i=fM({logLevel:e,message:n,opts:r}),{collapsed:s}=r;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}groupCollapsed(e,n,r={}){return this.group(e,n,Object.assign({},r,{collapsed:!0}))}groupEnd(e){return this._getLogFunction(e,"",console.groupEnd||Yl)}withGroup(e,n,r){this.group(e,n)();try{r()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&this.getLevel()>=uM(e)}_getLogFunction(e,n,r,i,s){if(this._shouldLog(e)){s=fM({logLevel:e,message:n,args:i,opts:s}),r=r||s.method,q_(r),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=Xl();const o=s.tag||s.message;if(s.once&&o)if(!lM[o])lM[o]=Xl();else return Yl;return n=bq(this.id,s.message,s),r.bind(console,n,...s.args)}return Yl}}of.VERSION=oM;function uM(t){if(!t)return 0;let e;switch(typeof t){case"number":e=t;break;case"object":e=t.logLevel||t.priority||0;break;default:return 0}return q_(Number.isFinite(e)&&e>=0),e}function fM(t){const{logLevel:e,message:n}=t;t.logLevel=uM(e);const r=t.args?Array.from(t.args):[];for(;r.length&&r.shift()!==n;);switch(typeof e){case"string":case"function":n!==void 0&&r.unshift(n),t.message=e;break;case"object":Object.assign(t,e);break}typeof t.message=="function"&&(t.message=t.message());const i=typeof t.message;return q_(i==="string"||i==="object"),Object.assign(t,{args:r},t.opts)}function bq(t,e,n){if(typeof e=="string"){const r=n.time?gq(pq(n.total)):"";e=n.time?`${t}: ${r} ${e}`:`${t}: ${e}`,e=yq(e,n.color,n.background)}return e}function xq(t){for(const e in t)for(const n in t[e])return n||"untitled";return"empty"}const Y_="4.3.3",wq=Y_[0]>="0"&&Y_[0]<="9"?`v${Y_}`:"";function Sq(){const t=new of({id:"loaders.gl"});return globalThis.loaders=globalThis.loaders||{},globalThis.loaders.log=t,globalThis.loaders.version=wq,globalThis.probe=globalThis.probe||{},globalThis.probe.loaders=t,t}const Tq=Sq();function Aq(t,e){return hM(t||{},e)}function hM(t,e,n=0){if(n>3)return e;const r={...t};for(const[i,s]of Object.entries(e))s&&typeof s=="object"&&!Array.isArray(s)?r[i]=hM(r[i]||{},e[i],n+1):r[i]=e[i];return r}const Eq="latest";function Cq(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.3.3"),globalThis._loadersgl_.version}const Dq=Cq();function oo(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}const ra=typeof process!="object"||String(process)!=="[object process]"||process.browser,Mq=typeof window<"u"&&typeof window.orientation<"u",dM=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version);dM&&parseFloat(dM[1]);class Rq{name;workerThread;isRunning=!0;result;_resolve=()=>{};_reject=()=>{};constructor(e,n){this.name=e,this.workerThread=n,this.result=new Promise((r,i)=>{this._resolve=r,this._reject=i})}postMessage(e,n){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:n})}done(e){oo(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){oo(this.isRunning),this.isRunning=!1,this._reject(e)}}class K_{terminate(){}}const Z_=new Map;function Iq(t){oo(t.source&&!t.url||!t.source&&t.url);let e=Z_.get(t.source||t.url);return e||(t.url&&(e=Pq(t.url),Z_.set(t.url,e)),t.source&&(e=pM(t.source),Z_.set(t.source,e))),oo(e),e}function Pq(t){if(!t.startsWith("http"))return t;const e=Oq(t);return pM(e)}function pM(t){const e=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(e)}function Oq(t){return`try {
|
|
192
192
|
importScripts('${t}');
|
|
193
193
|
} catch (error) {
|
|
194
194
|
console.error(error);
|
|
File without changes
|
|
File without changes
|
{figpack_spike_sorting-0.1.11 → figpack_spike_sorting-0.1.12}/figpack_spike_sorting/style.css
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|