(function(){"use strict";let I,i,F={},T;onmessage=function(t){if(t.data.canvas&&(I=t.data.canvas,w()),t.data.opts&&(i=t.data.opts,w()),t.data.tracesDataChunk){const n=t.data.tracesDataChunk;F[n.chunkIndex]=n,w()}t.data.sortingUnits&&(T=t.data.sortingUnits,w())};function O(t,n){let a=!1;return()=>{a||(a=!0,setTimeout(()=>{a=!1,t()},n))}}let P=0;async function R(){if(!I||!i)return;const{margins:t,canvasWidth:n,canvasHeight:a,visibleStartTimeSec:k,visibleEndTimeSec:f,channels:W,samplingFrequency:D,chunkSizeInFrames:v}=i,A=W.length;I.width=n,I.height=a;const e=I.getContext("2d");if(!e)return;P+=1;const E=P;e.clearRect(0,0,n,a),i.zoomInRequired&&(e.fillStyle="pink",e.textAlign="center",e.font="bold 26px Arial",e.fillText("Zoom in to view traces",n/2,a/2));const x=d=>a-t.bottom-(d+.5-0)/(A-0)*(a-t.top-t.bottom),y=d=>t.left+(d/D-k)/(f-k)*(n-t.left-t.right),L=d=>{if(!T||!i)return;const h=[];for(let r of T.units){let M=0,s=2*Math.PI,p=(r.unitId+"").startsWith("A")?"top":(r.unitId+"").startsWith("B")?"bottom":"both";p==="top"?(M=Math.PI,s=2*Math.PI):p==="bottom"&&(M=0,s=Math.PI),e.strokeStyle=r.color;let u;if(r.peakChannelId!==void 0){const l=i.channels.map(c=>c.channelId).indexOf(r.peakChannelId);l>=0&&(u=x(l))}for(let l of r.spikeFrames){const c=y(l);if(d.top&&(e.lineWidth=1,e.beginPath(),e.moveTo(c,0),e.lineTo(c,t.top),e.stroke()),d.channelLocation&&u!==void 0){e.lineWidth=3;let o=6;e.beginPath(),e.ellipse(c,u,6,6,0,M,s,!1),e.stroke(),h.push({rect:p==="top"?{x:c-o,y:u-o,w:o*2,h:o}:p==="bottom"?{x:c-o,y:u,w:o*2,h:o}:{x:c-o,y:u-o,w:o*2,h:o*2},unitId:r.unitId})}}}postMessage({spikeMarkerLocations:h}),e.lineWidth=1};L({top:!0,channelLocation:!0}),e.save(),e.beginPath(),e.rect(t.left,t.top,n-t.left-t.right,a-t.top-t.bottom),e.clip();const H=Math.floor(k*D/v),B=Math.ceil(f*D/v);let U=Date.now();const X=z(A);for(const d of X){const h=d.index;if(E!==P)return;let r=-99;i.mode==="traces"&&(e.strokeStyle="black",e.beginPath());for(let s=H;s<=B;s++){const p=F[s];if(p){const u=x(0)-x(1),l=s*v,c=(s+1)*v,o=p.data[h],S=W[h];if(i.mode==="traces"){const C=x(h);for(let g=l;g<c;g++){const m=y(g),b=C-(o[g-l]-S.offset)*u/2*i.amplitudeScaleFactor*S.scale;g===l&&s!==r+1?e.moveTo(m,b):e.lineTo(m,b)}}else if(i.mode==="heatmap"){const C=x(h+d.increment-.5),g=x(h-.5);for(let m=l;m<c;m++){const b=y(m),Y=y(m+1),Z=(o[m-l]-S.offset)*i.amplitudeScaleFactor*S.scale;e.fillStyle=q(Z),e.fillRect(b,C,Y-b+1,g-C+1)}}r=s}}i.mode==="traces"&&e.stroke(),Date.now()-U>200&&(U=Date.now(),await $(0))}e.restore(),L({channelLocation:!0})}const w=O(R,100);function $(t){return new Promise(n=>{setTimeout(n,t)})}function q(t){const n=Math.min(255,Math.max(0,128+t*128));return`rgb(${n},${n},${n})`}const z=t=>{const n=[],a=new Set;for(const k of[256,128,64,32,16,8,4,2,1])for(let f=0;f<t;f+=k)a.has(f)||(n.push({index:f,increment:k}),a.add(f));return n}})();
