@wafertools/wafermap 0.39.0 → 0.40.0

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +24 -3
  2. package/README.md +2 -2
  3. package/dist/packages/canvas-adapter/charts/commonality.js +4 -1
  4. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +5 -0
  5. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  6. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
  8. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  9. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  10. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  11. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  12. package/dist/packages/canvas-adapter/sweepEditor.js +1 -1
  13. package/dist/packages/canvas-adapter/toCanvas.d.ts +1 -0
  14. package/dist/packages/canvas-adapter/toCanvas.js +1 -1
  15. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  16. package/dist/packages/canvas-adapter/userGuideHtml.js +44 -28
  17. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  18. package/dist/packages/canvas-adapter/version.js +1 -1
  19. package/dist/packages/core/compact.js +2 -2
  20. package/dist/packages/core/dieTable.js +1 -1
  21. package/dist/packages/stats/commonality.d.ts +37 -4
  22. package/dist/packages/stats/commonality.js +1 -1
  23. package/dist/packages/stats/dieRegions.d.ts +2 -0
  24. package/dist/packages/stats/dieRegions.js +1 -1
  25. package/dist/packages/stats/examplePicks.d.ts +6 -0
  26. package/dist/packages/stats/examplePicks.js +1 -1
  27. package/dist/packages/stats/groupEffects.d.ts +66 -0
  28. package/dist/packages/stats/groupEffects.js +1 -0
  29. package/dist/packages/stats/plotData.js +1 -1
  30. package/dist/packages/stats/renderFindingsReport.js +1 -1
  31. package/dist/packages/stats/renderSummaryReport.js +7 -7
  32. package/dist/packages/stats/reportHtml.js +18 -13
  33. package/dist/packages/stats/sweep.d.ts +3 -3
  34. package/dist/packages/stats/sweepXFromName.js +1 -1
  35. package/dist/packages/stats/synthesis.d.ts +13 -0
  36. package/dist/packages/stats/synthesis.js +1 -1
  37. package/package.json +1 -1
@@ -1 +1 @@
1
- import{MEAN_WAFER_YIELD_LABEL as Zt}from"../stats/presentation.js";import{buildFacetTable as en,facetValueOf as ze,FACET_NONE_VALUE as tn,DEFAULT_FACET_CURATION as nn}from"../stats/facets.js";import{mergeTestDefs as He}from"../stats/mergeTestDefs.js";import{isParametricTest as Ce}from"../renderer/buildWaferMap.js";import{dieFailsTest as sn,hasJudgeableTests as an,testsForPassKind as rn,buildTestPassRateData as ot}from"../stats/testPassRate.js";import{fmt as lt}from"../renderer/fmt.js";import{testLabel as dt}from"../renderer/testLabel.js";import{waferDisplayLabel as on,waferIdentityLabel as ln}from"../core/waferLabel.js";import{waferPopulation as dn}from"./chartPopulation.js";import{openDrilldownMenu as Ye}from"./drilldown.js";import{plotStoreFor as cn}from"./plotStore.js";import{createPageFilter as un}from"./pageFilter.js";import{bandButton as fn}from"./filterButton.js";import{itemPassBins as pn,passBinsLabel as ct}from"../core/passBins.js";import{describeWaferPopulation as hn,populationStat as mn}from"../stats/population.js";import{LEADING as Ve,ALPHA as bn,SPACE as O,EDGE_GUTTER as _e,FONT as G,CLR as M,RADIUS as gn,SHADOW as yn,controlStyle as ut,wireControlHover as Be,wireTooltip as ke}from"./toolbar.js";import{ICONS as wn}from"./icons.js";import{renderCapabilityPanel as xn}from"./charts/capability.js";import{renderGroupComparisonPanel as vn}from"./charts/groupComparison.js";import{renderCommonalityPanel as Sn}from"./charts/commonality.js";import{renderPatCard as Cn}from"./charts/patCard.js";import{renderDifferenceMapPanel as Bn}from"./differenceMapPanel.js";import{renderCorrelationPanel as kn}from"./charts/correlation.js";import{cardFrameStyle as $n,pairCards as En,makeChartGridWrap as $e,makeLabeledSelect as ft,makeLinkedGroupSelect as Tn,makeLinkedTestSelect as pt,makeWaferSelect as ht,makeTestSelect as mt,isExpandedCard as In,makeLinkedAxisPrefs as bt,makeToggle as Ge,limitLines as Ee,limitExtent as gt,shouldIncludeLimitsByDefault as yt,hasBothLimitKinds as wt}from"./charts/chartShell.js";import{maxOf as xt,minOf as vt}from"../core/utils.js";import{buildYieldData as St,buildYieldDataCombined as On}from"../stats/yield.js";import{buildLotTestSectionSteps as An,buildLotFunctionalSection as Ln,buildMetadataStripBox as Dn}from"./summaryPanel.js";import{runChunked as Pn}from"./chunked.js";import{buildRegionYieldData as qe,buildRingRegions as Ct,buildQuadrantRegions as Bt,buildReticlePositionRegions as Wn,diesInRegion as Rn}from"../stats/regions.js";import{renderDataSection as Nn}from"./dataTab.js";import{sourceFromDies as Mn,toPlotItems as re}from"./plotItems.js";import{rankTestsByWaferSpread as Fn}from"../stats/testsByWafer.js";import{isYieldEligibleDie as jn}from"../core/dies.js";import{renderPlotCard as zn}from"./plotCard.js";import{orderFieldValues as Hn,axisValues as kt}from"../stats/plotData.js";import{buildSynthesis as Yn,groupColouredChart as Vn,synthesisKey as _n}from"../stats/synthesis.js";import{commonPassBins as Gn}from"../core/passBins.js";import{renderRegionYieldDiagram as Ke}from"./charts/regionYieldDiagram.js";const qn=12,Kn=[{key:"overview",label:"Overview"},{key:"distributions",label:"Distributions"},{key:"correlation",label:"Correlation"}],Xn={key:"data",label:"Data"},Un={key:"plot",label:"My plots"},Qn={overview:"Yield, bins and what stands out",distributions:"How each test\u2019s values spread",correlation:"How tests move together",data:"The same scope as tables, with CSV exports",plot:"Plots you have built and saved"};export function createInsightsTab(T){const{getItems:$t,getLotStats:Xe,getBinColors:ie,getRingCount:Q,onSaveImage:W,onSaveText:J,openWafer:oe,focusTest:Te,locateDie:me}=T,ye={...nn,...T.attributes},Et=T.showMetadataStrip??!0,le=T.contentInset??_e,a=T.ownerDocument??document,Y=a.createElement("div");Object.assign(Y.style,{display:"none",flexDirection:"column",width:"100%",paddingTop:"0"});const Tt=_e,ce=a.createElement("div");Object.assign(ce.style,{paddingLeft:Tt});const te=a.createElement("div");Object.assign(te.style,{display:"flex",gap:O.xs,alignItems:"center",background:M.menuBg,border:`1px solid ${M.menuBorder}`,borderRadius:gn.container,boxShadow:yn.panel,padding:`0 ${O.lg}`,margin:"0"}),te.setAttribute("role","tablist");const Ie=a.createElement("div");Object.assign(Ie.style,{position:"sticky",top:"var(--wmap-sticky-top, 0px)",zIndex:"1",background:M.menuBg,paddingLeft:le,paddingRight:le,paddingBottom:O.lg}),Ie.appendChild(te),te.addEventListener("keydown",e=>{if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=Array.from(te.querySelectorAll('[role="tab"]')),s=t.indexOf(a.activeElement);if(s===-1)return;e.preventDefault();const o=t[(s+(e.key==="ArrowRight"?1:-1)+t.length)%t.length];o.focus(),o.click()});const se=a.createElement("div");Object.assign(se.style,{display:"flex",flexDirection:"column",gap:O.lg,marginTop:"0",isolation:"isolate",paddingLeft:le,paddingRight:le});const we=T.pageFilter??un({doc:a,initial:T.filter,onChange:T.onFilterChange,attributes:T.attributes,getRingCount:T.getRingCount}),Ue=we.createBand(()=>Me(),{marginLeft:le,marginRight:le,marginBottom:O.lg}),It=Ue.el;let de,Oe=null;const Ot=()=>{let e=0;for(const t of Array.from(Y.querySelectorAll("[data-wmap-chart-grid]")))t.offsetParent!==null&&(e=Math.max(e,Array.from(t.children).filter(s=>s.offsetParent!==null).length));return e},xe=()=>{if(de===void 0){Y.style.removeProperty("--wmap-insights-cols"),Y.style.removeProperty("--wmap-insights-min");return}const e=Ot(),t=e>0?Math.min(de,e):de;Y.style.getPropertyValue("--wmap-insights-cols")!==String(t)&&Y.style.setProperty("--wmap-insights-cols",String(t)),Y.style.setProperty("--wmap-insights-min","0px")},Qe=e=>{de=e,xe(),Oe&&(Oe.value=e===void 0?"auto":String(e))},Je=a.defaultView?.MutationObserver;let Ae=0;const Ze=Je?new Je(()=>{if(Ae||de===void 0)return;const e=a.defaultView;if(!e){xe();return}Ae=e.requestAnimationFrame(()=>{Ae=0,xe()})}):void 0;Ze?.observe(se,{childList:!0,subtree:!0});const et=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||!/^[0-5]$/.test(e.key)||!Y.isConnected||Y.style.display==="none"||a.querySelector('[data-wmap-panels-hover], [role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||(e.preventDefault(),Qe(e.key==="0"?void 0:Number(e.key)))};a.addEventListener("keydown",et),Y.appendChild(ce),Y.appendChild(Ie),Y.appendChild(It),Y.appendChild(se);const At=[...Kn,Xn,Un],ue=T.plotStore??cn(T),Z=(e,t)=>{import("./plotModal.js").then(({openPlotEditor:s})=>s({doc:a,anchor:Y,store:ue,plot:e,draft:!0,items:[...t.items],ctx:t.ctx,title:e.title?`New plot from \u201C${e.title}\u201D`:"New plot",chart:{onSaveImage:W,binColors:ie()}}))};let X=T.defaultView==="sweeps"?"plot":T.defaultView??"overview",N,Le=!1;we.subscribe(()=>ne());let tt="statistics",nt="wide",q=null,st=null,De=[],V=null,Pe=T.initialAxisPrefs??{includeLimits:void 0,clipOutliers:!1,limits:"both"};const ee=e=>zn({...e,chart:{onSaveText:J,...e.chart}}),ae=(e,t,s)=>({limits:t.limits??"both",axes:{[e]:{...t.includeLimits!==void 0?{includeLimits:t.includeLimits}:{},...t.clipOutliers?{clip:!0}:{},...s?{scale:"log"}:{}}}}),We=new Map,Re=(e,t,s=!1)=>{Pe=e;for(const o of We.values())for(const l of o)l!==t&&l.setAxisPrefs(e);s||T.onAxisPrefsChange?.(e)},Ne=e=>{V!==e&&(V=e,ne())};let fe=new Map;function at(){for(const e of fe.values())e.destroy();fe=new Map}function rt(e,t,s){oe?.(e,t,s)}function ve(e){return(t,s,o)=>{const l=e.find(f=>f.waferIndex===t);if(!l)return;o.preventDefault();const v=dn(l.dies,{waferLabel:l.identity,testDefs:l.testDefs,activeTest:s??q??void 0,waferIndex:t,wafer:l.wafer,passBins:l.passBins,ringCount:Q()});Ye({x:o.clientX,y:o.clientY},o.target,v,{plots:ue,getBinColors:ie,onSaveImage:W,onSaveText:J,onLocateDie:me})}}function Lt(e,t,s,o,l){pe({x:e.clientX,y:e.clientY},e.target,t,s,o,l)}function pe(e,t,s,o,l,v){const f=Mn(s.map(d=>({label:d.identity??d.label,dies:d.dies,waferIndex:d.waferIndex,wafer:d.wafer,passBins:d.passBins,ringCount:Q()})),o,l,He(s).defs,v);f&&Ye(e,t,f,{plots:ue,getBinColors:ie,onSaveImage:W,onSaveText:J,onLocateDie:me})}function it(e){return oe?{open:(t,s)=>rt(t,`Wafer ${e.find(o=>o.waferIndex===t)?.label??t}`,s)}:Te&&e.length===1?{open:(t,s)=>Te(s),label:"show this test on the map"}:null}function Me(){return $t().map((e,t)=>e==null?null:{metadata:e.wafer.metadata??void 0,dies:e.dies,wafer:e.wafer,label:on(e,t),identity:ln(e),waferIndex:t,passBins:pn(e),statsSummary:e.statsSummary,testDefs:e.testDefs,source:e}).filter(e=>e!=null)}function Dt(e,t){Object.assign(e.style,{background:"none",border:"none",borderBottom:t?`2px solid ${M.iconActive}`:"2px solid transparent",color:t?M.iconActive:M.label,fontWeight:t?"700":"500",fontSize:G.body,padding:`${O.sm} ${_e} ${O.md}`,cursor:"pointer"})}function Pt(e,t){const s=a.createElement("button");s.type="button",s.textContent=t;const o=e===X;Dt(s,o),s.dataset.on=o?"true":"false",Be(s,"bare"),s.dataset.wmapInsightsTab=e;const l=Qn[e];return l&&ke(s,l),s.setAttribute("role","tab"),s.setAttribute("aria-selected",o?"true":"false"),s.tabIndex=o?0:-1,s.addEventListener("click",()=>{X!==e&&(X=e,ne({keepSections:!0}))}),s}function Wt(e,t,s,o=!0){const l=$e(a),v=ie(),f=s??"group",d=ct(e.map(r=>r.passBins)),b=re(e.map(r=>({label:r.identity??r.label.replace(/\s*·\s*\d+(\.\d+)?%$/,""),dies:r.dies,waferIndex:r.waferIndex,wafer:r.wafer,passBins:r.passBins,ringCount:Q()}))),c=He(e).defs,p=t?N:void 0,u={testDefs:c,groupBy:p,curation:T.attributes},g=(r,x,S=!1)=>({id:"card-yield",title:t?`Yield by ${f} (pass: ${d})`:`Yield by wafer (pass: ${d})`,chart:"bar",fields:{x:S?[{slot:"groupBy"},{builtin:"wafer"}]:{slot:"groupBy"},y:{builtin:"yield"},color:t?{follow:"groupBy"}:{none:!0}},...S?{}:{valueLabels:!0},...r&&!S?{sort:"value"}:{},...x>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}}),A=t?t.length:e.length;let k=null,$=!1;o&&(k=ee({doc:a,editAsPlot:Z,items:b,ctx:u,spec:{choices:[{current:"natural",options:r=>[["value","Sort: yield"],["natural",t&&!r?`Sort: ${f}`:"Sort: wafer"],...t&&!r?[["nested",`${f}, then wafer`,`Each ${f} with its wafers inside it`]]:[]]}],build:([r])=>($=r==="nested",g(r==="value",A,$))},drill:t&&p?r=>{if($)return null;const x=ze(b[r[0]?.item]?.metadata,p,T.attributes);if(x===void 0)return null;const S=t.find(P=>P.key===x)?.items.length??0;return P=>({...P,title:`Yield by wafer \u2014 ${f}: ${x} (pass: ${d})`,fields:{...P.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:p},values:[x]}]},axes:S>=3?{y:{references:[{stat:"median"}]}}:void 0})}:void 0,drillLabel:()=>$?void 0:"see its wafers",chart:{onSaveImage:W,onOpenWafer:oe?r=>rt(b[r].waferIndex??r,`Wafer ${b[r].label}`):void 0,onWaferMenu:ve(e)}}),k.card.style.minHeight="360px",l.appendChild(k.card));const j={current:"hbin",options:[["hbin","Hard bins","The physical sort result: where the part goes on the handler"],["sbin","Soft bins","The test program\u2019s failure category: many soft bins can map to one hard bin"]]},_={current:"share",options:[["count","Counts"],["share",`Share of ${f}`,`Each ${f}\u2019s dies in a bin as a share of all its dies, so ${f} values of different sizes compare`],["mix","Bin mix",`Each ${f} as one bar split into its bins, as shares of its own dies`]]},R=15,i=(r,x)=>t&&x==="mix"?{id:"card-bin-pareto",title:`${r==="sbin"?"Soft":"Hard"} bin mix by ${f}`,chart:"bar",stack:"percent",fields:{x:{slot:"groupBy"},color:{builtin:r==="sbin"?"sbin":"hbin"}}}:{id:"card-bin-pareto",title:`${r==="sbin"?"Soft":"Hard"} bin pareto`,chart:"bar",sort:"value",fields:{x:{builtin:r==="sbin"?"sbin":"hbin"},color:t?{follow:"groupBy"}:{builtin:r==="sbin"?"sbin":"hbin"}},...r==="sbin"?{top:R}:{},...t?x==="share"?{barNorm:"percent"}:{}:{cumulative:!0}},w=ee({doc:a,editAsPlot:Z,items:b,ctx:u,spec:t?{choices:[j,_],build:([r,x])=>i(r,x)}:{choices:[j],build:([r])=>i(r,void 0)},chart:{onSaveImage:W,binColors:v,onSelectPoints:(r,x,S,P)=>{const m=w.current().fields,E=m.x,L=m.color,F=B=>!!B&&!Array.isArray(B)&&typeof B=="object"&&"builtin"in B&&B.builtin==="sbin",D=F(E)||F(L)?"sbin":"hbin",n=new Set(r.map(B=>D==="hbin"?B.die?.hbin:B.die?.sbin));if(n.size!==1)return;const h=[...n][0];if(E&&!Array.isArray(E)&&"slot"in E){const B=new Set(r.map(I=>I.die).filter(I=>!!I)),K=new Set(r.map(I=>b[I.item]?.waferIndex));pe(x,S,e.filter(I=>K.has(I.waferIndex)),`in ${D==="hbin"?"hard":"soft"} bin ${h}`,I=>B.has(I));return}const y=t?P?.group:void 0,C=y!==void 0?t?.find(B=>B.key===y)?.items??[]:e;pe(x,S,C,`in ${D==="hbin"?"hard":"soft"} bin ${h}${y!==void 0?` of ${y}`:""}`,B=>jn(B)&&(D==="hbin"?B.hbin:B.sbin)===h)}}});return w.card.style.minHeight="360px",l.appendChild(w.card),{card:l,destroy:()=>{k?.destroy(),w.destroy()}}}function Fe(){const e=a.createElement("div");return e.dataset.wmapChartCard="1",Object.assign(e.style,{...$n(),display:"flex",flexDirection:"column",gap:O.lg,minWidth:"0"}),e}function Rt(e){if(ce.innerHTML="",ce.style.marginBottom="0",!Et)return;const t=Dn(e.map(s=>({metadata:s.metadata})),void 0,{facetableOnly:!1});t&&(t.style.marginBottom="0",ce.appendChild(t),ce.style.marginBottom=O.xs)}function Nt(e,t,s,o,l){if(!e.length)return{elements:[],destroy:()=>{}};const v=e.map(w=>w.wafer),f=e.map(w=>w.dies),d=Q(),b=[],c=[],p=o??[{key:"",items:e}],u=e.flatMap(w=>w.dies),g=["spec","testFlag","functional"].filter(w=>an(s,w,u));if(g.length){const w={spec:{label:"Test limits",hint:"Judged from each die\u2019s measured value against the test\u2019s limits",title:"Parametric pass rate \xB7 test limits"},testFlag:{label:"Tester flag",hint:"The pass or fail the tester recorded for each die",title:"Parametric pass rate \xB7 tester flag"},functional:{label:"Functional",hint:"Tests that only pass or fail and have no measured value",title:"Functional test pass rate"}},r=!!o,x=re(e.map(n=>({label:n.identity??n.label,dies:n.dies,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:d}))),S=25,P=n=>rn(s,n).map(h=>h.testNumber),m=n=>ot(p.map(h=>({key:h.key,items:h.items.map(y=>({dies:y.dies}))})),s,n).rows.map(h=>h.testNumber),E=n=>n==="testFlag"?{judge:"flag"}:{},L=(n,h="bars",y="worst")=>r&&h==="grid"?{id:`card-pass-rate-${n}`,title:w[n].title,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},y:{tests:m(n).slice(0,S),passRate:!0,...E(n)}}}:{id:`card-pass-rate-${n}`,title:w[n].title,chart:"bar",orientation:"horizontal",sort:"ascending",...P(n).length>S&&y==="worst"?{top:S}:{},fields:{x:{builtin:"test"},y:{tests:P(n),passRate:!0,...E(n)},color:r?{follow:"groupBy"}:{none:!0}},...r?{}:{valueLabels:!0},axes:{y:{min:0,max:100}}},F=n=>n.id.slice(15),D=ee({doc:a,editAsPlot:Z,items:x,ctx:{testDefs:s,groupBy:r?N:void 0,curation:T.attributes},spec:(()=>{const n=g.some(y=>P(y).length>S),h=[];return g.length>1&&h.push({current:g[0],options:g.map(y=>[y,w[y].label,w[y].hint])}),r&&h.push({current:"bars",options:[["bars","Bars"],["grid","Grid",`The worst ${S} tests as a grid of test by group`]]}),n&&h.push({current:"worst",options:[["worst",`Worst ${S}`],["all","All tests"]]}),h.length?{choices:h,build:y=>{let C=0;const B=g.length>1?y[C++]:g[0],K=r?y[C++]:"bars",I=n?y[C++]:"worst";return L(B,K,I)}}:L(g[0])})(),notes:n=>{const h=F(n);if(h==="functional")return[];const y=ot(p.map(C=>({key:C.key,items:C.items.map(B=>({dies:B.dies}))})),s,h).disagreementDies;return y?[`${y.toLocaleString("en-GB")} die${y===1?"":"s"} judged differently by test limits and the tester flag`]:[]},chart:{onSaveImage:W,selectActionLabel:"chart or tabulate the dies that fail its test",onSelectPoints:(n,h,y,C)=>{const B=s.find(U=>U.testNumber===C?.test);if(!B)return;const K=F(D.current()),I=C?.group!==void 0?p.find(U=>U.key===C.group)?.items??e:e;pe(h,y,I,`failing ${dt(B,B.testNumber)}${C?.group!==void 0?` in ${C.group}`:""}`,U=>sn(U,B,K)===!0,Ce(B)?B.testNumber:void 0)}}});D.card.style.minHeight="300px",b.push(D.card),c.push(D.destroy)}const A=w=>(r,x)=>{const S=new Set;for(const P of e)for(const m of Rn(P.dies,P.wafer,d,r.key,w))S.add(m);Lt(x,e,`in ${r.label}`,P=>S.has(P))},k=qe(f,v,d,w=>e[w].passBins,Ct),$=k.length?Ke({title:"Ring yield",mode:"ring",rows:k,onSelectRegion:A(Ct),onSaveImage:W,ownerDocument:a}):void 0;$&&c.push($.destroy);const j=(w,r,x,S)=>{const P=!!o,m=re(e.map(L=>({label:L.identity??L.label,dies:L.dies,waferIndex:L.waferIndex,wafer:L.wafer,passBins:L.passBins,ringCount:d}))),E=ee({doc:a,editAsPlot:Z,items:m,ctx:{testDefs:s,groupBy:P?N:void 0,curation:T.attributes},spec:{id:w,title:`${x} yield by ${P?l??"group":"wafer"}`,chart:"heatmap",fields:{x:{slot:"groupBy"},rows:{builtin:r},y:{builtin:"yield"}}},chart:{onSaveImage:W}});E.card.style.minHeight="300px",b.push(S?En([{label:"Heatmap",card:E.card},{label:"Diagram",card:S.card}],a):E.card),c.push(E.destroy)};k.length&&e.length>=2?j("card-ring-wafer","ring","Ring",$):$&&b.push($.card);const _=qe(f,v,d,w=>e[w].passBins,Bt);if(_.length){const w=Ke({title:"Quadrant yield",mode:"quadrant",rows:_,onSelectRegion:A(Bt),onSaveImage:W,ownerDocument:a});c.push(w.destroy),e.length>=2?j("card-quadrant-wafer","quadrant","Quadrant",w):b.push(w.card)}const R=v.find(w=>w.reticle!==void 0)?.reticle;if(R){const w=(x,S)=>Wn(x,S.reticle),r=qe(f,v,d,x=>e[x].passBins,w);if(r.length){const x=Ke({title:"Reticle cell yield",mode:"reticleCell",rows:r,grid:{width:Math.max(1,Math.floor(R.width)),height:Math.max(1,Math.floor(R.height))},onSelectRegion:A(w),onSaveImage:W,ownerDocument:a});b.push(x.card),c.push(x.destroy)}}const i=new Set;for(const w of e)for(const r of w.dies)r.siteNum!==void 0&&i.add(r.siteNum);if(i.size>=2){const w=re(e.map(x=>({label:x.identity??x.label,dies:x.dies,waferIndex:x.waferIndex,wafer:x.wafer,passBins:x.passBins,ringCount:d}))),r=ee({doc:a,editAsPlot:Z,items:w,ctx:{testDefs:s,curation:T.attributes},spec:{id:"card-site",title:"Yield by site",chart:"bar",fields:{x:{builtin:"site"},y:{builtin:"yield"},color:{none:!0}},valueLabels:!0,...i.size>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}},chart:{onSaveImage:W}});b.push(r.card),c.push(r.destroy)}if(e.some(w=>w.dies.some(r=>r.retestCount!==void 0))){const w=re(e.map(S=>({label:S.identity??S.label,dies:S.dies,waferIndex:S.waferIndex,wafer:S.wafer,passBins:S.passBins,ringCount:d}))),r=!!o,x=ee({doc:a,editAsPlot:Z,items:w,ctx:{testDefs:s,groupBy:r?N:void 0,curation:T.attributes},spec:{id:"card-reprobed",title:`Re-probed dies by ring and ${r?l??"group":"wafer"}`,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},rows:{builtin:"ring"},y:{builtin:"reprobed"}}},chart:{onSaveImage:W}});x.card.style.minHeight="300px",b.push(x.card),c.push(x.destroy)}return{elements:b,destroy:()=>{for(const w of c)w()}}}function Mt(e,t,s){if(!e.length)return{cards:[],destroy:()=>{}};const o=e.map(u=>u.dies),l=e.flatMap(u=>u.dies),v=e.map(u=>u.statsSummary),f=v.every(u=>u!==void 0)?v:void 0,d=[],b=[];let c=null;if(t.length){const u=Fe();let g=null;const A=Pn(An(l,t,void 0,f,J,o.map(k=>({dies:k})),void 0,"full"),{onDone:k=>{g=k,u.removeAttribute("aria-busy"),k?u.replaceChildren(k):u.remove()}});if(A.done)g&&(c=u);else{const k=a.createElement("div");k.textContent="Computing test statistics\u2026",Object.assign(k.style,{color:M.label,fontSize:G.body}),u.setAttribute("aria-busy","true"),u.appendChild(k),c=u,d.push(()=>A.cancel())}}let p=null;if(s.length){const u=Ln(l,s,f,J);if(u){const g=Fe();g.appendChild(u),p=g}}return c&&b.push(c),p&&b.push(p),{cards:b,destroy:()=>{for(const u of d)u()}}}function Ft(e){const t=ct(e.map(c=>c.passBins)),s=e.length===1,o=e[0],l=Fe();Object.assign(l.style,{flexDirection:"row",flexWrap:"wrap",gap:O.md});const v=c=>{const p=c.lastElementChild;return p&&Object.assign(p.style,{borderRight:"none",paddingRight:"0",marginRight:"0"}),c};function f(c,p,u){const g=a.createElement("div");Object.assign(g.style,{display:"flex",alignItems:"baseline",gap:O.sm,paddingRight:O.xxl,marginRight:O.md,borderRight:`1px solid ${M.menuBorder}`});const A=a.createElement("div");A.textContent=c,Object.assign(A.style,{fontSize:G.heading,fontWeight:"700",color:M.value,lineHeight:Ve.tight});const k=a.createElement("div");if(k.textContent=p,Object.assign(k.style,{fontSize:G.body,color:M.label}),g.append(A,k),u){const $=a.createElement("div");$.textContent=u,Object.assign($.style,{fontSize:G.meta,color:M.label,opacity:bn.muted}),g.appendChild($)}return g}if(s){const c=St([{...o,key:o.waferIndex}])[0]?.percent;return c!==void 0&&l.appendChild(f(`${c.toFixed(1)}%`,`Yield \xB7 pass: ${t}`)),l.appendChild(f(String(o.dies.length),"Total dies")),v(l)}l.appendChild(f(String(e.length),"Wafers"));const d=St(e.map(c=>({...c,key:c.waferIndex}))).map(c=>c.percent).filter(c=>Number.isFinite(c));if(d.length){const c=d.reduce((g,A)=>g+A,0)/d.length,p=On([{key:"all",items:e.map(g=>({...g,key:g.waferIndex}))}])[0]?.percent,u=p!==void 0&&p.toFixed(1)!==c.toFixed(1);l.appendChild(f(`${c.toFixed(1)}%`,`${Zt} \xB7 pass: ${t}`,u?`${p.toFixed(1)}% by dies`:void 0))}const b=e.map(c=>c.statsSummary);if(b.every(c=>c!==void 0)){const c=b.reduce((u,g)=>u+g.stats.analyzedDies,0),p=b.reduce((u,g)=>u+g.stats.excludedDies,0);l.appendChild(f(c.toLocaleString(),"Dies analysed",p?`${p.toLocaleString()} excluded`:void 0))}else l.appendChild(f(e.reduce((c,p)=>c+p.dies.length,0).toLocaleString(),"Total dies"));return v(l)}function jt(e,t,s,o,l){const v=a.createElement("div");Object.assign(v.style,{display:"flex",flexDirection:"column",gap:O.lg});const f=e.length===1&&!o;e.length&&!o&&v.appendChild(Ft(e));const d=Wt(e,o,l,!f),b=Nt(e,t,s,o,l);for(const u of b.elements)d.card.appendChild(u);const c=zt(e,s);if(c&&v.appendChild(c.el),e.length>=4&&De.length){const u=Sn({wafers:e,fields:De,curation:ye,groupedBy:N,onGroupBy:g=>{N=g,V=null,ne()},ownerDocument:a});v.appendChild(u.card)}v.appendChild(d.card);const p=Cn({items:e.map(u=>({...u,ringCount:Q()})),testDefs:s,ownerDocument:a,showMap:T.showPatMap});return p&&v.appendChild(p.card),v.appendChild(Ht()),{card:v,destroy:()=>{d.destroy(),b.destroy(),c?.destroy()}}}function zt(e,t){const s=Xe?.()??(e.length===1?e[0].statsSummary:void 0);if(!s)return null;const o=a.createElement("section");o.dataset.wmapWorthALook="1",Object.assign(o.style,{display:"flex",flexDirection:"column",gap:O.md});const l=a.createElement("h3");l.textContent="Worth a look",Object.assign(l.style,{margin:"0",fontSize:G.heading,fontWeight:"600",color:M.value}),o.appendChild(l);const v=(p,u)=>{const g=a.createElement("p");g.textContent=p,u&&(g.dataset[u]="1"),Object.assign(g.style,{margin:"0",fontSize:G.body,color:M.label,lineHeight:Ve.base}),o.appendChild(g)};if(Le||V!==null)return v("Worth a look describes the whole lot, as What stands out beside the map does. Switch the filter off, or Show all groups, to see it here.","wmapWorthNarrowed"),{el:o,destroy:()=>{}};const f=Yn(s,{passBins:Gn(e.map(p=>p.passBins)),attributes:T.attributes});if(f.items.length===0)return v(f.nothing??"Nothing stands out.","wmapWorthNothing"),{el:o,destroy:()=>{}};const d=$e(a);o.appendChild(d);const b=re(e.map(p=>({label:p.identity??p.label,dies:p.dies,waferIndex:p.waferIndex,wafer:p.wafer,passBins:p.passBins,ringCount:Q()}))),c=[];if(f.items.forEach((p,u)=>{const g=a.createElement("div");g.dataset.wmapWorthWhy="1",g.textContent=`Shown because: ${p.reason}`,p.text!==p.reason&&ke(g,p.text),Object.assign(g.style,{flexBasis:"100%",fontSize:G.body,color:M.text,lineHeight:Ve.base});const A=[g];if(T.showOnMap){const $=a.createElement("button");$.type="button",$.textContent="Show on map",$.dataset.wmapWorthShowOnMap="1",Object.assign($.style,{...ut("outlined"),fontSize:G.body,padding:`0 ${O.md}`}),Be($),ke($,"Leave Insights and show this on the map, as its row in What stands out does"),$.addEventListener("click",()=>T.showOnMap(p.target)),A.push($)}const k=ee({doc:a,items:b,ctx:{testDefs:t,curation:ye,groupBy:N},spec:{id:`worth-${u}`,...Vn(p.chart,!!N)},extras:A,editAsPlot:Z,chart:{onSaveImage:W}});k.card.dataset.wmapWorthKey=_n(p),d.appendChild(k.card),c.push(k.destroy)}),f.also){const p=f.also.items.map(u=>u.brief).join("; ");v(`Also: ${p}${f.also.more?`; and ${f.also.more} more`:""}. Their rows in What stands out show them on the map.`,"wmapWorthAlso")}return{el:o,destroy:()=>c.forEach(p=>p())}}function Ht(){const e=a.createElement("div");Object.assign(e.style,{fontSize:G.body,color:M.label});const t=a.createElement("button");return t.type="button",t.textContent="Data tab",t.dataset.wmapOpenDataTab="1",Object.assign(t.style,{border:"none",background:"none",padding:"0",cursor:"pointer",font:"inherit",color:M.iconActive,textDecoration:"underline"}),Be(t,"bare"),t.addEventListener("click",()=>{X="data",ne({keepSections:!0})}),e.append("Test statistics, every die and every wafer as tables, with CSV export: see the ",t,"."),e}function Yt(e,t,s,o){const l=a.createElement("div");l.style.width="100%";let v,f=!1;return import("./plotTab.js").then(({createPlotSection:d})=>{if(f)return;const b=d({doc:a,store:ue,items:e,testDefs:t,ringCount:Q(),attributes:T.attributes,groupBy:s,groupLabel:o,onSaveImage:W,onSaveText:J,getBinColors:ie,waferMenu:ve(e),openWafer:oe?(c,p,u)=>oe(c,p,u):void 0,focusTest:Te,locateDie:me,pickPlotsFile:T.onPickPlotsFile});l.appendChild(b.card),v=b}),{card:l,destroy:()=>{f=!0,v?.destroy()}}}function Vt(e,t,s,o,l){const v=Le?void 0:Xe?.(),f=()=>{fe.get("data")?.destroy(),fe.delete("data"),ne({keepSections:!0})};return Nn({doc:a,items:e,testDefs:t,allTestDefs:s,groups:o,groupLabelText:l,ringCount:Q(),attributes:T.attributes,yieldByWaferIndex:new Map(v?.lotYieldSeries.map(d=>[d.waferIndex,d.yieldPercent])),onSaveText:J,onLocateDie:me,onOpenWafer:oe?(d,b)=>oe(d,b):void 0,buildStatistics:d=>Mt(d,t,s),view:tt,onViewChange:d=>{tt=d,f()},diesLayout:nt,onDiesLayoutChange:d=>{nt=d}})}function Se(e,t){const s=a.createElement("h3");return s.textContent=e,s.dataset.wmapRowHeading=t,Object.assign(s.style,{gridColumn:"1 / -1",margin:`${O.md} 0 0`,color:M.value,fontSize:G.heading,fontWeight:"600"}),s}function _t(e,t,s,o){const l=$e(a),v=it(e),f=re(e.map(n=>({label:n.identity??n.label,dies:n.dies,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:Q()}))),d=t.filter(n=>n.testNumber!==void 0),b=!!s&&!!N,c=b&&V!==null,p={testDefs:t,groupBy:b?N:void 0,curation:T.attributes},u=d.length>1;let g;const A=[];function k(n){let h=Pe,y=!1,C;const B=pt(d,q??d[0]?.testNumber??null,H=>{C?.refresh(),S(H)},{ownerDocument:a}),K=a.createElement("span");Object.assign(K.style,{display:"inline-flex",flexWrap:"wrap",gap:O.sm,alignItems:"center"});const I={setAxisPrefs:H=>{U.set(H)&&(h=H,C?.refresh())}},U=bt(K,h,H=>{h=H,C?.refresh(),Re(H,I)},a),be=[B.el,K];n.logToggle&&be.push(Ge("Log scale",y,H=>{y=H,C?.refresh()},a,"Draw the value axis on a logarithmic scale")),be.push(...n.extras??[]),C=ee({doc:a,editAsPlot:Z,items:f,ctx:p,...n.card,spec:{choices:n.choices??[],build:H=>n.build(h,y,H)},slots:()=>({test:B.get()??void 0}),extras:be,onResolved:H=>{const he=t.find(Jt=>Jt.testNumber===B.get()),ge=Ee(he,h.limits),je=kt(H,n.valueRole),{lo:Xt,hi:Ut}=gt(ge),Qt=je.length>0&&ge.length>0&&yt(vt(je),xt(je),Xt,Ut);U.sync(h.includeLimits??Qt,Ee(he).length>0,wt(he))},chart:n.chart});const z=C;if(u){const H=()=>{B.el.style.display=In(z.card)?"":"none"};H();const he=a.defaultView?.MutationObserver;if(he){const ge=new he(H);ge.observe(z.card,{attributes:!0,attributeFilter:["data-wmap-expanded"]}),A.push(ge)}}return{card:z.card,setTest:H=>{B.set(H)&&z.refresh()},refresh:()=>z.refresh(),setAxisPrefs:I.setAxisPrefs,destroy:()=>z.destroy()}}const $=v?(n,h)=>v.open(f[n]?.waferIndex??n,h??q??d[0]?.testNumber??0):void 0;let j=!1,_=!1;const R=k({valueRole:"y",logToggle:!0,choices:[{current:b&&!c?"groups":"wafers",options:[...b&&!c?[["groups",`By ${o??"group"}`],["nested",`${o??"Group"}, then wafer`,"Each group with its wafers inside it"]]:[["wafers","By wafer"]],["radius","By radius","A box for each ring, from the centre to the edge: whether the test changes across the wafer"]]}],build:(n,h,[y])=>(j=b&&!c&&y==="nested",_=y==="radius",{id:"card-box",title:_?"Test value by radius":"Test value distribution",chart:"box",orientation:"horizontal",fields:{x:_?{builtin:"ring"}:j?[{slot:"groupBy"},{builtin:"wafer"}]:b&&!c?{slot:"groupBy"}:{builtin:"wafer"},y:{slot:"test"},color:j?{follow:"groupBy"}:{none:!0}},...c?{where:{conditions:[{field:{meta:N},values:[V]}]}}:{},...ae("y",n,h)}),card:{...b&&!c?{drill:n=>{if(j||_)return null;const h=ze(f[n[0]?.item]?.metadata,N,T.attributes);return h===void 0?null:y=>({...y,fields:{...y.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:N},values:[h]}]}})},drillLabel:()=>j||_?void 0:"see its wafers"}:{},...V!==null?{externalBack:{shown:()=>V!==null,onBack:()=>Ne(null)}}:{}},chart:{onSaveImage:W,onOpenWafer:$,openActionLabel:v?.label,onWaferMenu:ve(e)}});let i=null;const w=b?[]:[ht(f.map(n=>({label:n.label})),null,n=>{i=n,r.refresh()},{ownerDocument:a})],r=k({valueRole:"x",logToggle:!0,extras:w,choices:[{current:"bars",options:[["bars","Histogram"],["cumulative","Cumulative","The share of dies at or below each value, as one curve per colour"]]},...b?[{current:"percent",options:[["percent",`Share of ${o??"group"}`,"Each group\u2019s bars as a share of its own dies, so groups of different sizes compare"],["count","Counts"]]}]:[]],card:V!==null?{externalBack:{shown:()=>V!==null,onBack:()=>Ne(null)}}:{},build:(n,h,[y,C])=>({id:"card-histogram",title:y==="cumulative"?"Cumulative distribution":"Value histogram",chart:y==="cumulative"?"probability":"histogram",fields:{y:{slot:"test"},color:b?{follow:"groupBy"}:{none:!0}},...b&&C!=="count"&&y!=="cumulative"?{histNorm:"percent"}:{},...i!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[f[i].label]}]}}:{},...ae("x",n,h)}),chart:{onSaveImage:W,onSelectPoints:(n,h,y,C)=>{const B=t.find(z=>z.testNumber===(q??d[0]?.testNumber)),K=new Set(n.map(z=>z.die).filter(z=>!!z)),I=new Set(n.map(z=>f[z.item]?.waferIndex)),U=C?.range,be=B&&U?`with ${dt(B,B.testNumber)} from ${lt(U.lo,B.unit,"engineering")} to ${lt(U.hi,B.unit,"engineering")}${C?.group?` in ${C.group}`:""}`:"selected in the histogram";pe(h,y,e.filter(z=>I.has(z.waferIndex)),be,z=>K.has(z),B?.testNumber)}}}),x=k({valueRole:"y",logToggle:!0,choices:e.length>=3?[{current:"trend",options:[["trend","Trend","Each wafer\u2019s mean with a band of one standard deviation"],["control","Control chart","One value per wafer against control limits, with the points that break a Western Electric rule marked"]]}]:[],build:(n,h,[y])=>y==="control"?{id:"card-trend",title:"Wafer-to-wafer control chart",chart:"control",aggregate:"mean",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:b?{follow:"groupBy"}:{none:!0}},...ae("y",n,h)}:{id:"card-trend",title:"Wafer-to-wafer trend",chart:"line",aggregate:"mean",spread:"sd",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:{none:!0}},...ae("y",n,h),axes:{...ae("y",n,h).axes,y:{...ae("y",n,h).axes.y,references:[{stat:"mean",label:mn(hn(e.map(C=>C.wafer.metadata)),"mean")}]}}},card:{ctx:p,...e.length<2?{unavailable:"A trend needs at least two wafers"}:{}},chart:{onSaveImage:W,onWaferMenu:ve(e),selectActionLabel:$?"open that wafer":"chart or tabulate its dies",selectRangeLabel:"wafers",onSelectPoints:(n,h,y)=>{const C=new Set(n.map(I=>I.item));if(C.size===1&&$){$([...C][0]);return}const B=new Set(n.map(I=>I.die).filter(I=>!!I)),K=new Set(n.map(I=>f[I.item]?.waferIndex));pe(h,y,e.filter(I=>K.has(I.waferIndex)),"selected in the trend",I=>B.has(I),q??void 0)}}}),S=n=>{q=n,g?.set(n),R.setTest(n),r.setTest(n),x.setTest(n),L.setTest(n),m?.setTest(n),E?.setTest(n)},P=()=>vn({groups:s,testDefs:t,groupLabelText:o,control:st,onControlChange:n=>{st=n;const h=P();m.card.replaceWith(h.card),m=h},selectedTestNumber:q??void 0,onSelectTest:n=>S(n),onSaveText:J,ownerDocument:a});let m=s&&s.length>=2?P():void 0;const E=s&&s.length>=2?Bn({groups:s,testDefs:t,groupLabelText:o,selectedTestNumber:q??void 0,onSaveImage:W,ownerDocument:a}):void 0;We.set("distribution",[R,r,x]);const L=xn({title:"Process capability",items:e,testDefs:t,onSaveImage:W,selectedTestNumber:q??void 0,onSelectTest:n=>S(n),ownerDocument:a}),F=e.length>=2?Fn(e.map(n=>({dies:n.dies})),t.filter(n=>n.testNumber!==void 0&&Ce(n)).map(n=>n.testNumber),qn):[],D=F.length>=2?ee({doc:a,editAsPlot:Z,items:f,ctx:p,spec:{id:"card-tests-wafer",title:`Tests by ${s?o??"group":"wafer"} (z-scores)`,chart:"heatmap",level:"wafer",aggregate:"mean",normalize:"zscore",fields:{x:{slot:"groupBy"},y:{tests:F}}},chart:{onSaveImage:W}}):void 0;if(D&&(D.card.style.minHeight="300px"),D&&(l.append(Se(`Tests across ${s?o??"groups":"wafers"}`,"tests-grid")),l.append(D.card)),(m||E)&&(l.append(Se(`Comparing ${o??"groups"}`,"comparing")),m&&l.append(m.card),E&&l.append(E.card)),u){g=pt(d,q??d[0]?.testNumber??null,B=>S(B),{ownerDocument:a});const n=a.createElement("div");n.dataset.wmapSectionTest="1",Object.assign(n.style,{gridColumn:"1 / -1",display:"flex",alignItems:"center",gap:O.lg,flexWrap:"wrap",marginTop:O.md});const h=Se("Test by test","tests");h.style.margin="0";const y=a.createElement("label");Object.assign(y.style,{display:"inline-flex",alignItems:"center",gap:O.xs,fontSize:G.body,color:M.label});const C=a.createElement("span");C.textContent="Test",y.append(C,g.el),n.append(h,y),l.append(n)}else(m||E)&&l.append(Se("Test by test","tests"));return l.append(L.card,R.card,r.card,x.card),{card:l,destroy:()=>{for(const n of A)n.disconnect();L.destroy(),R.destroy(),r.destroy(),x.destroy(),m?.destroy(),E?.destroy(),D?.destroy()}}}function Gt(e,t,s,o){const l=$e(a),v=it(e),f=re(e.map(m=>({label:m.identity??m.label,dies:m.dies,waferIndex:m.waferIndex,wafer:m.wafer,passBins:m.passBins,ringCount:Q()}))),d=t.filter(m=>m.testNumber!==void 0&&Ce(m));let b=d[0]?.testNumber,c=d[1]?.testNumber??b,p=null,u=Pe;const g=!!s&&!!N,A=(m,E)=>{const L=a.createElement("label");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:O.xs,fontSize:G.body,color:M.label});const F=a.createElement("span");return F.textContent=m,L.append(F,E),L},k=mt(d,b??null,m=>{b=m,S.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:a}),$=mt(d,c??null,m=>{c=m,S.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:a}),j=a.createElement("span");Object.assign(j.style,{display:"inline-flex",flexWrap:"wrap",gap:O.sm,alignItems:"center"});let _=!1,R=!1;const i={setXY:(m,E)=>{b=m,c=E,k.value=String(m),$.value=String(E),S.refresh()},setAxisPrefs:m=>{w.set(m)&&(u=m,S.refresh())},destroy:()=>S.destroy()},w=bt(j,u,m=>{u=m,S.refresh(),Re(m,i)},a),r=m=>{const E=t.find(L=>L.testNumber===m);return E?.name?{test:m??0,name:E.name}:{test:m??0}},x=[A("X:",k),A("Y:",$),j,Ge("Log X",_,m=>{_=m,S.refresh()},a,"Draw the X axis on a logarithmic scale"),Ge("Log Y",R,m=>{R=m,S.refresh()},a,"Draw the Y axis on a logarithmic scale")];!g&&e.length>1&&x.push(ht(f.map(m=>({label:m.label})),null,m=>{p=m,S.refresh()},{ownerDocument:a}));const S=ee({doc:a,editAsPlot:Z,items:f,ctx:{testDefs:t,groupBy:g?N:void 0,curation:T.attributes},extras:x,onResolved:m=>{const E=[b,c].map(F=>t.find(D=>D.testNumber===F)),L=["x","y"].some((F,D)=>{const n=Ee(E[D],u.limits),h=kt(m,F),{lo:y,hi:C}=gt(n);return h.length>0&&n.length>0&&yt(vt(h),xt(h),y,C)});w.sync(u.includeLimits??L,E.some(F=>Ee(F).length>0),E.some(wt))},spec:{choices:[],build:()=>({id:"card-scatter",title:"Test scatter",chart:"scatter",limits:u.limits??"both",axes:{...ae("x",u,_).axes,...ae("y",u,R).axes},fields:{x:r(b),y:r(c),color:g?{follow:"groupBy"}:{builtin:"hbin"}},...g?{fit:"linear"}:{},...p!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[f[p].label]}]}}:{}})},...b===void 0?{unavailable:"No parametric test has values to plot"}:{},chart:{onSaveImage:W,binColors:ie(),onOpenWafer:v?(m,E)=>v.open(f[m]?.waferIndex??m,E??b??0):void 0,openActionLabel:v?.label,onSelectPoints:(m,E,L)=>{const F=new Map;for(const h of m){const y=f[h.item]?.waferIndex;if(y===void 0||!h.die)continue;const C=F.get(y);C?C.push(h.die):F.set(y,[h.die])}const D=[...F].flatMap(([h,y])=>{const C=e.find(B=>B.waferIndex===h);return C?[{label:C.identity??C.label,dies:y,waferIndex:h,wafer:C.wafer,passBins:C.passBins,ringCount:Q()}]:[]});if(D.length===0)return;const n=D.length===1?`selected on ${D[0].label} in the scatter`:`selected in the scatter, across ${D.length} wafers`;Ye(E,L,{items:D,population:n,testDefs:t,activeTest:b},{plots:ue,getBinColors:ie,onSaveImage:W,onSaveText:J,onLocateDie:me})}}});We.set("correlation",[i]);const P=kn({title:"Test correlation matrix",items:e,testDefs:t,onSaveImage:W,onSaveText:J,...g&&s&&s.length>=2?{groups:s,groupLabelText:o}:{},onSelectPair:(m,E)=>i.setXY(m,E),ownerDocument:a});return l.append(P.card,S.card),{card:l,destroy:()=>{P.destroy(),i.destroy()}}}const qt=(e,t,s,o)=>fn(a,e,t,s,o),Kt=()=>we.openEditor(Y,Me());function ne(e){e?.keepSections||at(),se.innerHTML="",te.innerHTML="";for(const i of At)te.appendChild(Pt(i.key,i.label));const t=Me(),s=we.keep(t),o=s.items;Le=s.narrowing,Ue.refresh(s.result,t),Rt(o);const l=en(o,{facetableOnly:!0,curation:ye}).filter(i=>i.splittable);De=l.map(i=>({key:i.key,label:i.label}));const v=a.createElement("div");Object.assign(v.style,{display:"flex",gap:O.md,alignItems:"center",marginLeft:O.xxl,paddingBottom:O.xs}),T.showFilterButton!==!1&&v.appendChild(qt("Filter\u2026","wmapInsightsFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>Kt()));let f;l.length>0?(v.appendChild(ft("Group by:",[{value:"",label:"None"},...l.map(i=>({value:i.key,label:`${i.label} (${i.values.length})`}))],N??"",i=>{N=i||void 0,V=null,ne()},{hook:"group-by",ownerDocument:a,hint:"Split every chart by a wafer attribute, such as lot or tester"})),f=l.find(i=>i.key===N)?.label):N=void 0;let d;if(N){const i=new Map,w=[];for(const r of o){const x=ze(r.metadata,N,ye)??tn;i.has(x)||(i.set(x,[]),w.push(x)),i.get(x).push(r)}d=Hn(w).map(r=>({key:r,items:i.get(r)}))}V!==null&&!d?.some(i=>i.key===V)&&(V=null),d&&d.length>0&&v.appendChild(Tn(d.map(i=>i.key),"Show:",V,i=>Ne(i),{ownerDocument:a,hint:"Show every group, or analyse just one"}).el);const b=ft("Columns:",[{value:"auto",label:"Auto (0)"},...[1,2,3,4,5].map(i=>({value:String(i),label:`${i} (${i})`}))],de===void 0?"auto":String(de),i=>Qe(i==="auto"?void 0:Number(i)),{hook:"insights-columns",maxWidth:"90px",ownerDocument:a,hint:"The most cards that sit side by side (a tab with fewer cards uses fewer); the keys 1 to 5 set it and 0 returns to Auto"});Oe=b.querySelector("button"),v.appendChild(b);let c=null;if(T.onOpenGuide){const i=a.createElement("button");i.type="button",i.innerHTML=wn.help,i.setAttribute("aria-label","User guide"),Object.assign(i.style,{...ut("bare"),display:"inline-flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",flexShrink:"0"}),Be(i,"bare"),ke(i,"User guide"),i.addEventListener("click",()=>T.onOpenGuide()),Object.assign(i.style,{marginLeft:"auto"}),c=i}te.appendChild(v),c&&te.appendChild(c);const p=V!==null?d?.find(i=>i.key===V):void 0,u=p?.items??o,g=p?void 0:d,A=He(u),k=A.defs,$=k.filter(Ce);if(q!==null&&!$.some(i=>i.testNumber===q)&&(q=null),o.length===0){const i=a.createElement("div");i.dataset.wmapInsightsFilterEmpty="1",i.textContent="The filter keeps no wafer and no die. Edit the filter or switch it off to see the data.",Object.assign(i.style,{color:M.label,fontSize:G.body,padding:O.xl}),se.appendChild(i);return}const j=e?.keepSections?fe.get(X):void 0,_=j??(X==="overview"?jt(u,$,k,g,f):X==="distributions"?_t(u,$,g,f):X==="data"?Vt(u,$,k,g,f):X==="plot"?Yt(u,k,p?void 0:N,p?void 0:f):Gt(u,$,g,f));j||fe.set(X,_);const R=A.conflicts.filter(i=>i.excluded);if(R.length>0){const i=a.createElement("div");Object.assign(i.style,{color:M.label,fontSize:G.body,padding:`0 ${le} ${O.sm}`});const w=R.slice(0,6).map(S=>S.testNumber).join(", "),r=R.length>6?`, and ${R.length-6} more`:"",x=R.length===1?"it":"them";i.textContent=`${R.length} test ${R.length===1?"number is":"numbers are"} hidden (${w}${r}) \u2014 the wafers in view describe ${x} differently, so their values cannot be pooled. `+(d&&d.length>0?`Pick one ${f??"group"} under "Show:" to analyse ${x}.`:"Load one test program at a time to analyse them."),i.dataset.wmapWithheldTests=String(R.length),se.appendChild(i)}se.appendChild(_.card),xe()}return{el:Y,render:ne,destroy:()=>{a.removeEventListener("keydown",et),Ze?.disconnect(),at(),ue.flush(),Y.remove()},setAxisPrefs:e=>Re(e,null,!0),showWorthCard:e=>{X!=="overview"&&(X="overview",ne({keepSections:!0}));const t=[...se.querySelectorAll("[data-wmap-worth-key]")].find(l=>l.dataset.wmapWorthKey===e);if(!t)return!1;const s=a.defaultView,o=()=>t.scrollIntoView({block:"center"});return s?.requestAnimationFrame?s.requestAnimationFrame(()=>s.requestAnimationFrame(o)):o(),t.style.outline=`2px solid ${M.iconActive}`,t.style.outlineOffset="2px",setTimeout(()=>{t.style.outline="",t.style.outlineOffset=""},1600),!0}}}
1
+ import{MEAN_WAFER_YIELD_LABEL as en}from"../stats/presentation.js";import{buildFacetTable as tn,facetValueOf as Ye,FACET_NONE_VALUE as nn,DEFAULT_FACET_CURATION as sn}from"../stats/facets.js";import{mergeTestDefs as _e}from"../stats/mergeTestDefs.js";import{isParametricTest as Be}from"../renderer/buildWaferMap.js";import{dieFailsTest as rn,hasJudgeableTests as an,testsForPassKind as on,buildTestPassRateData as lt}from"../stats/testPassRate.js";import{fmt as dt}from"../renderer/fmt.js";import{testLabel as ct}from"../renderer/testLabel.js";import{waferDisplayLabel as ln,waferIdentityLabel as dn}from"../core/waferLabel.js";import{waferPopulation as cn}from"./chartPopulation.js";import{openDrilldownMenu as Ve}from"./drilldown.js";import{plotStoreFor as un}from"./plotStore.js";import{createPageFilter as fn}from"./pageFilter.js";import{bandButton as pn}from"./filterButton.js";import{itemPassBins as hn,passBinsLabel as ut}from"../core/passBins.js";import{describeWaferPopulation as mn,populationStat as gn}from"../stats/population.js";import{LEADING as Ge,ALPHA as bn,SPACE as A,EDGE_GUTTER as qe,FONT as G,CLR as M,RADIUS as yn,SHADOW as wn,controlStyle as ft,wireControlHover as $e,wireTooltip as ke}from"./toolbar.js";import{ICONS as xn}from"./icons.js";import{renderCapabilityPanel as Sn}from"./charts/capability.js";import{renderGroupComparisonPanel as vn}from"./charts/groupComparison.js";import{renderCommonalityPanel as Cn}from"./charts/commonality.js";import{renderPatCard as Bn}from"./charts/patCard.js";import{renderDifferenceMapPanel as $n}from"./differenceMapPanel.js";import{renderCorrelationPanel as kn}from"./charts/correlation.js";import{cardFrameStyle as En,pairCards as In,makeChartGridWrap as Ee,makeLabeledSelect as pt,makeLinkedGroupSelect as Tn,makeLinkedTestSelect as ht,makeWaferSelect as mt,makeTestSelect as gt,isExpandedCard as On,makeLinkedAxisPrefs as bt,makeToggle as Ke,limitLines as Ie,limitExtent as yt,shouldIncludeLimitsByDefault as wt,hasBothLimitKinds as xt}from"./charts/chartShell.js";import{maxOf as St,minOf as vt}from"../core/utils.js";import{buildYieldData as Ct,buildYieldDataCombined as An}from"../stats/yield.js";import{buildLotTestSectionSteps as Pn,buildLotFunctionalSection as Ln,buildMetadataStripBox as Wn}from"./summaryPanel.js";import{runChunked as Dn}from"./chunked.js";import{buildRegionYieldData as Xe,buildRingRegions as Bt,buildQuadrantRegions as $t,buildReticlePositionRegions as Rn,diesInRegion as Nn}from"../stats/regions.js";import{renderDataSection as Mn}from"./dataTab.js";import{sourceFromDies as jn,toPlotItems as oe}from"./plotItems.js";import{rankTestsByWaferSpread as Fn}from"../stats/testsByWafer.js";import{isYieldEligibleDie as zn}from"../core/dies.js";import{renderPlotCard as Hn}from"./plotCard.js";import{orderFieldValues as Yn,axisValues as kt}from"../stats/plotData.js";import{buildSynthesis as _n,groupColouredChart as Vn,synthesisKey as Gn,SYNTHESIS_POSSIBLE_HEADING as qn}from"../stats/synthesis.js";import{commonPassBins as Kn}from"../core/passBins.js";import{renderRegionYieldDiagram as Ue}from"./charts/regionYieldDiagram.js";const Xn=12,Un=[{key:"overview",label:"Overview"},{key:"distributions",label:"Distributions"},{key:"correlation",label:"Correlation"}],Qn={key:"data",label:"Data"},Jn={key:"plot",label:"My plots"},Zn={overview:"Yield, bins and what stands out",distributions:"How each test\u2019s values spread",correlation:"How tests move together",data:"The same scope as tables, with CSV exports",plot:"Plots you have built and saved"};export function createInsightsTab(I){const{getItems:Et,getLotStats:Qe,getBinColors:ie,getRingCount:Q,onSaveImage:R,onSaveText:J,openWafer:se,focusTest:Te,locateDie:me}=I,xe={...sn,...I.attributes},It=I.showMetadataStrip??!0,le=I.contentInset??qe,r=I.ownerDocument??document,Y=r.createElement("div");Object.assign(Y.style,{display:"none",flexDirection:"column",width:"100%",paddingTop:"0"});const Tt=qe,ue=r.createElement("div");Object.assign(ue.style,{paddingLeft:Tt});const te=r.createElement("div");Object.assign(te.style,{display:"flex",gap:A.xs,alignItems:"center",background:M.menuBg,border:`1px solid ${M.menuBorder}`,borderRadius:yn.container,boxShadow:wn.panel,padding:`0 ${A.lg}`,margin:"0"}),te.setAttribute("role","tablist");const Oe=r.createElement("div");Object.assign(Oe.style,{position:"sticky",top:"var(--wmap-sticky-top, 0px)",zIndex:"1",background:M.menuBg,paddingLeft:le,paddingRight:le,paddingBottom:A.lg}),Oe.appendChild(te),te.addEventListener("keydown",e=>{if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=Array.from(te.querySelectorAll('[role="tab"]')),s=t.indexOf(r.activeElement);if(s===-1)return;e.preventDefault();const i=t[(s+(e.key==="ArrowRight"?1:-1)+t.length)%t.length];i.focus(),i.click()});const re=r.createElement("div");Object.assign(re.style,{display:"flex",flexDirection:"column",gap:A.lg,marginTop:"0",isolation:"isolate",paddingLeft:le,paddingRight:le});const Se=I.pageFilter??fn({doc:r,initial:I.filter,onChange:I.onFilterChange,attributes:I.attributes,getRingCount:I.getRingCount}),Je=Se.createBand(()=>Fe(),{marginLeft:le,marginRight:le,marginBottom:A.lg}),Ot=Je.el;let de,Ae=null;const At=()=>{let e=0;for(const t of Array.from(Y.querySelectorAll("[data-wmap-chart-grid]")))t.offsetParent!==null&&(e=Math.max(e,Array.from(t.children).filter(s=>s.offsetParent!==null).length));return e},ve=()=>{if(de===void 0){Y.style.removeProperty("--wmap-insights-cols"),Y.style.removeProperty("--wmap-insights-min");return}const e=At(),t=e>0?Math.min(de,e):de;Y.style.getPropertyValue("--wmap-insights-cols")!==String(t)&&Y.style.setProperty("--wmap-insights-cols",String(t)),Y.style.setProperty("--wmap-insights-min","0px")},Ze=e=>{de=e,ve(),Ae&&(Ae.value=e===void 0?"auto":String(e))},et=r.defaultView?.MutationObserver;let Pe=0;const tt=et?new et(()=>{if(Pe||de===void 0)return;const e=r.defaultView;if(!e){ve();return}Pe=e.requestAnimationFrame(()=>{Pe=0,ve()})}):void 0;tt?.observe(re,{childList:!0,subtree:!0});const nt=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||!/^[0-5]$/.test(e.key)||!Y.isConnected||Y.style.display==="none"||r.querySelector('[data-wmap-panels-hover], [role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||(e.preventDefault(),Ze(e.key==="0"?void 0:Number(e.key)))};r.addEventListener("keydown",nt),Y.appendChild(ue),Y.appendChild(Oe),Y.appendChild(Ot),Y.appendChild(re);const Pt=[...Un,Qn,Jn],fe=I.plotStore??un(I),Z=(e,t)=>{import("./plotModal.js").then(({openPlotEditor:s})=>s({doc:r,anchor:Y,store:fe,plot:e,draft:!0,items:[...t.items],ctx:t.ctx,title:e.title?`New plot from \u201C${e.title}\u201D`:"New plot",chart:{onSaveImage:R,binColors:ie()}}))};let X=I.defaultView==="sweeps"?"plot":I.defaultView??"overview",W,Le=!1;Se.subscribe(()=>ne());let st="statistics",rt="wide",q=null,at=null,We=[],_=null,De=I.initialAxisPrefs??{includeLimits:void 0,clipOutliers:!1,limits:"both"};const ee=e=>Hn({...e,chart:{onSaveText:J,...e.chart}}),ae=(e,t,s)=>({limits:t.limits??"both",axes:{[e]:{...t.includeLimits!==void 0?{includeLimits:t.includeLimits}:{},...t.clipOutliers?{clip:!0}:{},...s?{scale:"log"}:{}}}}),Re=new Map,Ne=(e,t,s=!1)=>{De=e;for(const i of Re.values())for(const f of i)f!==t&&f.setAxisPrefs(e);s||I.onAxisPrefsChange?.(e)},Me=e=>{_!==e&&(_=e,ne())};let pe=new Map;function ot(){for(const e of pe.values())e.destroy();pe=new Map}function je(e,t,s){se?.(e,t,s)}function ge(e){return(t,s,i)=>{const f=e.find(d=>d.waferIndex===t);if(!f)return;i.preventDefault();const S=cn(f.dies,{waferLabel:f.identity,testDefs:f.testDefs,activeTest:s??q??void 0,waferIndex:t,wafer:f.wafer,passBins:f.passBins,ringCount:Q()});Ve({x:i.clientX,y:i.clientY},i.target,S,{plots:fe,getBinColors:ie,onSaveImage:R,onSaveText:J,onLocateDie:me})}}function Lt(e,t,s,i,f){ce({x:e.clientX,y:e.clientY},e.target,t,s,i,f)}function be(e,t,s){return(i,f,S,d)=>{const c=new Set(i.map(o=>o.die).filter(o=>!!o)),m=new Set(i.map(o=>e[o.item]?.waferIndex));ce(f,S,t.filter(o=>m.has(o.waferIndex)),s(d),c.size?o=>c.has(o):()=>!0)}}function ce(e,t,s,i,f,S){const d=jn(s.map(c=>({label:c.identity??c.label,dies:c.dies,waferIndex:c.waferIndex,wafer:c.wafer,passBins:c.passBins,ringCount:Q()})),i,f,_e(s).defs,S);d&&Ve(e,t,d,{plots:fe,getBinColors:ie,onSaveImage:R,onSaveText:J,onLocateDie:me})}function it(e){return se?{open:(t,s)=>je(t,`Wafer ${e.find(i=>i.waferIndex===t)?.label??t}`,s)}:Te&&e.length===1?{open:(t,s)=>Te(s),label:"show this test on the map"}:null}function Fe(){return Et().map((e,t)=>e==null?null:{metadata:e.wafer.metadata??void 0,dies:e.dies,wafer:e.wafer,label:ln(e,t),identity:dn(e),waferIndex:t,passBins:hn(e),statsSummary:e.statsSummary,testDefs:e.testDefs,source:e}).filter(e=>e!=null)}function Wt(e,t){Object.assign(e.style,{background:"none",border:"none",borderBottom:t?`2px solid ${M.iconActive}`:"2px solid transparent",color:t?M.iconActive:M.label,fontWeight:t?"700":"500",fontSize:G.body,padding:`${A.sm} ${qe} ${A.md}`,cursor:"pointer"})}function Dt(e,t){const s=r.createElement("button");s.type="button",s.textContent=t;const i=e===X;Wt(s,i),s.dataset.on=i?"true":"false",$e(s,"bare"),s.dataset.wmapInsightsTab=e;const f=Zn[e];return f&&ke(s,f),s.setAttribute("role","tab"),s.setAttribute("aria-selected",i?"true":"false"),s.tabIndex=i?0:-1,s.addEventListener("click",()=>{X!==e&&(X=e,ne({keepSections:!0}))}),s}function Rt(e,t,s,i=!0){const f=Ee(r),S=ie(),d=s??"group",c=ut(e.map(a=>a.passBins)),m=oe(e.map(a=>({label:a.identity??a.label.replace(/\s*·\s*\d+(\.\d+)?%$/,""),dies:a.dies,waferIndex:a.waferIndex,wafer:a.wafer,passBins:a.passBins,ringCount:Q()}))),o=_e(e).defs,u=t?W:void 0,p={testDefs:o,groupBy:u,curation:I.attributes},b=(a,y,v=!1)=>({id:"card-yield",title:t?`Yield by ${d} (pass: ${c})`:`Yield by wafer (pass: ${c})`,chart:"bar",fields:{x:v?[{slot:"groupBy"},{builtin:"wafer"}]:{slot:"groupBy"},y:{builtin:"yield"},color:t?{follow:"groupBy"}:{none:!0}},...v?{}:{valueLabels:!0},...a&&!v?{sort:"value"}:{},...y>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}}),P=t?t.length:e.length;let k=null,C=!1;i&&(k=ee({doc:r,editAsPlot:Z,items:m,ctx:p,spec:{choices:[{current:"natural",options:a=>[["value","Sort: yield"],["natural",t&&!a?`Sort: ${d}`:"Sort: wafer"],...t&&!a?[["nested",`${d}, then wafer`,`Each ${d} with its wafers inside it`]]:[]]}],build:([a])=>(C=a==="nested",b(a==="value",P,C))},drill:t&&u?a=>{if(C)return null;const y=Ye(m[a[0]?.item]?.metadata,u,I.attributes);if(y===void 0)return null;const v=t.find(D=>D.key===y)?.items.length??0;return D=>({...D,title:`Yield by wafer \u2014 ${d}: ${y} (pass: ${c})`,fields:{...D.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:u},values:[y]}]},axes:v>=3?{y:{references:[{stat:"median"}]}}:void 0})}:void 0,drillLabel:()=>C?void 0:"see its wafers",chart:{onSaveImage:R,onOpenWafer:se?a=>je(m[a].waferIndex??a,`Wafer ${m[a].label}`):void 0,onWaferMenu:ge(e)}}),k.card.style.minHeight="360px",f.appendChild(k.card));const F={current:"hbin",options:[["hbin","Hard bins","The physical sort result: where the part goes on the handler"],["sbin","Soft bins","The test program\u2019s failure category: many soft bins can map to one hard bin"]]},V={current:"share",options:[["count","Counts"],["share",`Share of ${d}`,`Each ${d}\u2019s dies in a bin as a share of all its dies, so ${d} values of different sizes compare`],["mix","Bin mix",`Each ${d} as one bar split into its bins, as shares of its own dies`]]},N=15,l=(a,y)=>t&&y==="mix"?{id:"card-bin-pareto",title:`${a==="sbin"?"Soft":"Hard"} bin mix by ${d}`,chart:"bar",stack:"percent",fields:{x:{slot:"groupBy"},color:{builtin:a==="sbin"?"sbin":"hbin"}}}:{id:"card-bin-pareto",title:`${a==="sbin"?"Soft":"Hard"} bin pareto`,chart:"bar",sort:"value",fields:{x:{builtin:a==="sbin"?"sbin":"hbin"},color:t?{follow:"groupBy"}:{builtin:a==="sbin"?"sbin":"hbin"}},...a==="sbin"?{top:N}:{},...t?y==="share"?{barNorm:"percent"}:{}:{cumulative:!0}},w=ee({doc:r,editAsPlot:Z,items:m,ctx:p,spec:t?{choices:[F,V],build:([a,y])=>l(a,y)}:{choices:[F],build:([a])=>l(a,void 0)},chart:{onSaveImage:R,binColors:S,onSelectPoints:(a,y,v,D)=>{const g=w.current().fields,E=g.x,O=g.color,j=$=>!!$&&!Array.isArray($)&&typeof $=="object"&&"builtin"in $&&$.builtin==="sbin",L=j(E)||j(O)?"sbin":"hbin",n=new Set(a.map($=>L==="hbin"?$.die?.hbin:$.die?.sbin));if(n.size!==1)return;const h=[...n][0];if(E&&!Array.isArray(E)&&"slot"in E){const $=new Set(a.map(T=>T.die).filter(T=>!!T)),K=new Set(a.map(T=>m[T.item]?.waferIndex));ce(y,v,e.filter(T=>K.has(T.waferIndex)),`in ${L==="hbin"?"hard":"soft"} bin ${h}`,T=>$.has(T));return}const x=t?D?.group:void 0,B=x!==void 0?t?.find($=>$.key===x)?.items??[]:e;ce(y,v,B,`in ${L==="hbin"?"hard":"soft"} bin ${h}${x!==void 0?` of ${x}`:""}`,$=>zn($)&&(L==="hbin"?$.hbin:$.sbin)===h)}}});return w.card.style.minHeight="360px",f.appendChild(w.card),{card:f,destroy:()=>{k?.destroy(),w.destroy()}}}function ze(){const e=r.createElement("div");return e.dataset.wmapChartCard="1",Object.assign(e.style,{...En(),display:"flex",flexDirection:"column",gap:A.lg,minWidth:"0"}),e}function Nt(e){if(ue.innerHTML="",ue.style.marginBottom="0",!It)return;const t=Wn(e.map(s=>({metadata:s.metadata})),void 0,{facetableOnly:!1});t&&(t.style.marginBottom="0",ue.appendChild(t),ue.style.marginBottom=A.xs)}function Mt(e,t,s,i,f){if(!e.length)return{elements:[],destroy:()=>{}};const S=e.map(w=>w.wafer),d=e.map(w=>w.dies),c=Q(),m=[],o=[],u=i??[{key:"",items:e}],p=e.flatMap(w=>w.dies),b=["spec","testFlag","functional"].filter(w=>an(s,w,p));if(b.length){const w={spec:{label:"Test limits",hint:"Judged from each die\u2019s measured value against the test\u2019s limits",title:"Parametric pass rate \xB7 test limits"},testFlag:{label:"Tester flag",hint:"The pass or fail the tester recorded for each die",title:"Parametric pass rate \xB7 tester flag"},functional:{label:"Functional",hint:"Tests that only pass or fail and have no measured value",title:"Functional test pass rate"}},a=!!i,y=oe(e.map(n=>({label:n.identity??n.label,dies:n.dies,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:c}))),v=25,D=n=>on(s,n).map(h=>h.testNumber),g=n=>lt(u.map(h=>({key:h.key,items:h.items.map(x=>({dies:x.dies}))})),s,n).rows.map(h=>h.testNumber),E=n=>n==="testFlag"?{judge:"flag"}:{},O=(n,h="bars",x="worst")=>a&&h==="grid"?{id:`card-pass-rate-${n}`,title:w[n].title,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},y:{tests:g(n).slice(0,v),passRate:!0,...E(n)}}}:{id:`card-pass-rate-${n}`,title:w[n].title,chart:"bar",orientation:"horizontal",sort:"ascending",...D(n).length>v&&x==="worst"?{top:v}:{},fields:{x:{builtin:"test"},y:{tests:D(n),passRate:!0,...E(n)},color:a?{follow:"groupBy"}:{none:!0}},...a?{}:{valueLabels:!0},axes:{y:{min:0,max:100}}},j=n=>n.id.slice(15),L=ee({doc:r,editAsPlot:Z,items:y,ctx:{testDefs:s,groupBy:a?W:void 0,curation:I.attributes},spec:(()=>{const n=b.some(x=>D(x).length>v),h=[];return b.length>1&&h.push({current:b[0],options:b.map(x=>[x,w[x].label,w[x].hint])}),a&&h.push({current:"bars",options:[["bars","Bars"],["grid","Grid",`The worst ${v} tests as a grid of test by group`]]}),n&&h.push({current:"worst",options:[["worst",`Worst ${v}`],["all","All tests"]]}),h.length?{choices:h,build:x=>{let B=0;const $=b.length>1?x[B++]:b[0],K=a?x[B++]:"bars",T=n?x[B++]:"worst";return O($,K,T)}}:O(b[0])})(),notes:n=>{const h=j(n);if(h==="functional")return[];const x=lt(u.map(B=>({key:B.key,items:B.items.map($=>({dies:$.dies}))})),s,h).disagreementDies;return x?[`${x.toLocaleString("en-GB")} die${x===1?"":"s"} judged differently by test limits and the tester flag`]:[]},chart:{onSaveImage:R,selectActionLabel:"chart or tabulate the dies that fail its test",onSelectPoints:(n,h,x,B)=>{const $=s.find(U=>U.testNumber===B?.test);if(!$)return;const K=j(L.current()),T=B?.group!==void 0?u.find(U=>U.key===B.group)?.items??e:e;ce(h,x,T,`failing ${ct($,$.testNumber)}${B?.group!==void 0?` in ${B.group}`:""}`,U=>rn(U,$,K)===!0,Be($)?$.testNumber:void 0)}}});L.card.style.minHeight="300px",m.push(L.card),o.push(L.destroy)}const P=w=>(a,y)=>{const v=new Set;for(const D of e)for(const g of Nn(D.dies,D.wafer,c,a.key,w))v.add(g);Lt(y,e,`in ${a.label}`,D=>v.has(D))},k=Xe(d,S,c,w=>e[w].passBins,Bt),C=k.length?Ue({title:"Ring yield",mode:"ring",rows:k,onSelectRegion:P(Bt),onSaveImage:R,ownerDocument:r}):void 0;C&&o.push(C.destroy);const F=(w,a,y,v)=>{const D=!!i,g=oe(e.map(O=>({label:O.identity??O.label,dies:O.dies,waferIndex:O.waferIndex,wafer:O.wafer,passBins:O.passBins,ringCount:c}))),E=ee({doc:r,editAsPlot:Z,items:g,ctx:{testDefs:s,groupBy:D?W:void 0,curation:I.attributes},spec:{id:w,title:`${y} yield by ${D?f??"group":"wafer"}`,chart:"heatmap",fields:{x:{slot:"groupBy"},rows:{builtin:a},y:{builtin:"yield"}}},chart:{onSaveImage:R,onSelectPoints:be(g,e,O=>`in ${O?.cell?.row??y}, ${O?.cell?.column??""}`)}});E.card.style.minHeight="300px",m.push(v?In([{label:"Heatmap",card:E.card},{label:"Diagram",card:v.card}],r):E.card),o.push(E.destroy)};k.length&&e.length>=2?F("card-ring-wafer","ring","Ring",C):C&&m.push(C.card);const V=Xe(d,S,c,w=>e[w].passBins,$t);if(V.length){const w=Ue({title:"Quadrant yield",mode:"quadrant",rows:V,onSelectRegion:P($t),onSaveImage:R,ownerDocument:r});o.push(w.destroy),e.length>=2?F("card-quadrant-wafer","quadrant","Quadrant",w):m.push(w.card)}const N=S.find(w=>w.reticle!==void 0)?.reticle;if(N){const w=(y,v)=>Rn(y,v.reticle),a=Xe(d,S,c,y=>e[y].passBins,w);if(a.length){const y=Ue({title:"Reticle cell yield",mode:"reticleCell",rows:a,grid:{width:Math.max(1,Math.floor(N.width)),height:Math.max(1,Math.floor(N.height))},onSelectRegion:P(w),onSaveImage:R,ownerDocument:r});m.push(y.card),o.push(y.destroy)}}const l=new Set;for(const w of e)for(const a of w.dies)a.siteNum!==void 0&&l.add(a.siteNum);if(l.size>=2){const w=oe(e.map(y=>({label:y.identity??y.label,dies:y.dies,waferIndex:y.waferIndex,wafer:y.wafer,passBins:y.passBins,ringCount:c}))),a=ee({doc:r,editAsPlot:Z,items:w,ctx:{testDefs:s,curation:I.attributes},spec:{id:"card-site",title:"Yield by site",chart:"bar",fields:{x:{builtin:"site"},y:{builtin:"yield"},color:{none:!0}},valueLabels:!0,...l.size>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}},chart:{onSaveImage:R,onSelectPoints:be(w,e,y=>`at site ${y?.category??""}`)}});m.push(a.card),o.push(a.destroy)}if(e.some(w=>w.dies.some(a=>a.retestCount!==void 0))){const w=oe(e.map(v=>({label:v.identity??v.label,dies:v.dies,waferIndex:v.waferIndex,wafer:v.wafer,passBins:v.passBins,ringCount:c}))),a=!!i,y=ee({doc:r,editAsPlot:Z,items:w,ctx:{testDefs:s,groupBy:a?W:void 0,curation:I.attributes},spec:{id:"card-reprobed",title:`Re-probed dies by ring and ${a?f??"group":"wafer"}`,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},rows:{builtin:"ring"},y:{builtin:"reprobed"}}},chart:{onSaveImage:R,onSelectPoints:be(w,e,v=>`re-probed dies in ${v?.cell?.row??"a ring"}, ${v?.cell?.column??""}`)}});y.card.style.minHeight="300px",m.push(y.card),o.push(y.destroy)}return{elements:m,destroy:()=>{for(const w of o)w()}}}function jt(e,t,s){if(!e.length)return{cards:[],destroy:()=>{}};const i=e.map(p=>p.dies),f=e.flatMap(p=>p.dies),S=e.map(p=>p.statsSummary),d=S.every(p=>p!==void 0)?S:void 0,c=[],m=[];let o=null;if(t.length){const p=ze();let b=null;const P=Dn(Pn(f,t,void 0,d,J,i.map(k=>({dies:k})),void 0,"full"),{onDone:k=>{b=k,p.removeAttribute("aria-busy"),k?p.replaceChildren(k):p.remove()}});if(P.done)b&&(o=p);else{const k=r.createElement("div");k.textContent="Computing test statistics\u2026",Object.assign(k.style,{color:M.label,fontSize:G.body}),p.setAttribute("aria-busy","true"),p.appendChild(k),o=p,c.push(()=>P.cancel())}}let u=null;if(s.length){const p=Ln(f,s,d,J);if(p){const b=ze();b.appendChild(p),u=b}}return o&&m.push(o),u&&m.push(u),{cards:m,destroy:()=>{for(const p of c)p()}}}function Ft(e){const t=ut(e.map(o=>o.passBins)),s=e.length===1,i=e[0],f=ze();Object.assign(f.style,{flexDirection:"row",flexWrap:"wrap",gap:A.md});const S=o=>{const u=o.lastElementChild;return u&&Object.assign(u.style,{borderRight:"none",paddingRight:"0",marginRight:"0"}),o};function d(o,u,p){const b=r.createElement("div");Object.assign(b.style,{display:"flex",alignItems:"baseline",gap:A.sm,paddingRight:A.xxl,marginRight:A.md,borderRight:`1px solid ${M.menuBorder}`});const P=r.createElement("div");P.textContent=o,Object.assign(P.style,{fontSize:G.heading,fontWeight:"700",color:M.value,lineHeight:Ge.tight});const k=r.createElement("div");if(k.textContent=u,Object.assign(k.style,{fontSize:G.body,color:M.label}),b.append(P,k),p){const C=r.createElement("div");C.textContent=p,Object.assign(C.style,{fontSize:G.meta,color:M.label,opacity:bn.muted}),b.appendChild(C)}return b}if(s){const o=Ct([{...i,key:i.waferIndex}])[0]?.percent;return o!==void 0&&f.appendChild(d(`${o.toFixed(1)}%`,`Yield \xB7 pass: ${t}`)),f.appendChild(d(String(i.dies.length),"Total dies")),S(f)}f.appendChild(d(String(e.length),"Wafers"));const c=Ct(e.map(o=>({...o,key:o.waferIndex}))).map(o=>o.percent).filter(o=>Number.isFinite(o));if(c.length){const o=c.reduce((b,P)=>b+P,0)/c.length,u=An([{key:"all",items:e.map(b=>({...b,key:b.waferIndex}))}])[0]?.percent,p=u!==void 0&&u.toFixed(1)!==o.toFixed(1);f.appendChild(d(`${o.toFixed(1)}%`,`${en} \xB7 pass: ${t}`,p?`${u.toFixed(1)}% by dies`:void 0))}const m=e.map(o=>o.statsSummary);if(m.every(o=>o!==void 0)){const o=m.reduce((p,b)=>p+b.stats.analyzedDies,0),u=m.reduce((p,b)=>p+b.stats.excludedDies,0);f.appendChild(d(o.toLocaleString(),"Dies analysed",u?`${u.toLocaleString()} excluded`:void 0))}else f.appendChild(d(e.reduce((o,u)=>o+u.dies.length,0).toLocaleString(),"Total dies"));return S(f)}function zt(e,t,s,i,f){const S=r.createElement("div");Object.assign(S.style,{display:"flex",flexDirection:"column",gap:A.lg});const d=e.length===1&&!i;e.length&&!i&&S.appendChild(Ft(e));const c=Rt(e,i,f,!d),m=Mt(e,t,s,i,f);for(const p of m.elements)c.card.appendChild(p);const o=Ht(e,s);if(o&&S.appendChild(o.el),e.length>=4&&We.length){const p=Cn({wafers:e,fields:We,curation:xe,groupedBy:W,onGroupBy:b=>{W=b,_=null,ne()},ownerDocument:r});S.appendChild(p.card)}S.appendChild(c.card);const u=Bn({items:e.map(p=>({...p,ringCount:Q()})),testDefs:s,ownerDocument:r,showMap:I.showPatMap});return u&&S.appendChild(u.card),S.appendChild(Yt()),{card:S,destroy:()=>{c.destroy(),m.destroy(),o?.destroy()}}}function Ht(e,t){const s=Qe?.()??(e.length===1?e[0].statsSummary:void 0);if(!s)return null;const i=r.createElement("section");i.dataset.wmapWorthALook="1",Object.assign(i.style,{display:"flex",flexDirection:"column",gap:A.md});const f=r.createElement("h3");f.textContent="Worth a look",Object.assign(f.style,{margin:"0",fontSize:G.heading,fontWeight:"600",color:M.value}),i.appendChild(f);const S=(u,p)=>{const b=r.createElement("p");b.textContent=u,p&&(b.dataset[p]="1"),Object.assign(b.style,{margin:"0",fontSize:G.body,color:M.label,lineHeight:Ge.base}),i.appendChild(b)};if(Le||_!==null)return S("Worth a look describes the whole lot, as What stands out beside the map does. Switch the filter off, or Show all groups, to see it here.","wmapWorthNarrowed"),{el:i,destroy:()=>{}};const d=_n(s,{passBins:Kn(e.map(u=>u.passBins)),attributes:I.attributes});if(d.items.length===0)return S(d.nothing??"Nothing stands out.","wmapWorthNothing"),{el:i,destroy:()=>{}};const c=Ee(r);i.appendChild(c);const m=oe(e.map(u=>({label:u.identity??u.label,dies:u.dies,waferIndex:u.waferIndex,wafer:u.wafer,passBins:u.passBins,ringCount:Q()}))),o=[];if(d.items.forEach((u,p)=>{if(u.target.kind==="group"&&W!==void 0&&u.target.fields.includes(W))return;const b=r.createElement("div");b.dataset.wmapWorthWhy="1",b.textContent=`Shown because: ${u.reason}`,u.text!==u.reason&&ke(b,u.text),Object.assign(b.style,{flexBasis:"100%",fontSize:G.body,color:M.text,lineHeight:Ge.base});const P=[b];if(I.showOnMap&&u.target.kind!=="group"){const C=r.createElement("button");C.type="button",C.textContent="Show on map",C.dataset.wmapWorthShowOnMap="1",Object.assign(C.style,{...ft("outlined"),fontSize:G.body,padding:`0 ${A.md}`}),$e(C),ke(C,"Leave Insights and show this on the map, as its row in What stands out does"),C.addEventListener("click",()=>I.showOnMap(u.target)),P.push(C)}const k=ee({doc:r,items:m,ctx:{testDefs:t,curation:xe,groupBy:W},spec:{id:`worth-${p}`,...Vn(u.chart,!!W)},extras:P,editAsPlot:Z,chart:{onSaveImage:R,onSelectPoints:be(m,e,C=>C?.cell?`in ${C.cell.row}, ${C.cell.column}`:C?.category!==void 0?`in ${C.category}${C.group!==void 0?`, ${C.group}`:""}`:"in this part of the chart"),onWaferMenu:ge(e),onOpenWafer:se?C=>je(m[C].waferIndex??C,`Wafer ${m[C].label}`):void 0}});k.card.dataset.wmapWorthKey=Gn(u),c.appendChild(k.card),o.push(k.destroy)}),d.also){const u=d.also.items.map(p=>p.brief).join("; ");S(`Also: ${u}${d.also.more?`; and ${d.also.more} more`:""}. Their rows in What stands out show them on the map.`,"wmapWorthAlso")}return d.possible?.length&&S(`${qn}: ${d.possible.map(u=>u.reason).join("; ")}.`,"wmapWorthPossible"),{el:i,destroy:()=>o.forEach(u=>u())}}function Yt(){const e=r.createElement("div");Object.assign(e.style,{fontSize:G.body,color:M.label});const t=r.createElement("button");return t.type="button",t.textContent="Data tab",t.dataset.wmapOpenDataTab="1",Object.assign(t.style,{border:"none",background:"none",padding:"0",cursor:"pointer",font:"inherit",color:M.iconActive,textDecoration:"underline"}),$e(t,"bare"),t.addEventListener("click",()=>{X="data",ne({keepSections:!0})}),e.append("Test statistics, every die and every wafer as tables, with CSV export: see the ",t,"."),e}function _t(e,t,s,i){const f=r.createElement("div");f.style.width="100%";let S,d=!1;return import("./plotTab.js").then(({createPlotSection:c})=>{if(d)return;const m=c({doc:r,store:fe,items:e,testDefs:t,ringCount:Q(),attributes:I.attributes,groupBy:s,groupLabel:i,onSaveImage:R,onSaveText:J,getBinColors:ie,waferMenu:ge(e),openWafer:se?(o,u,p)=>se(o,u,p):void 0,focusTest:Te,locateDie:me,pickPlotsFile:I.onPickPlotsFile});f.appendChild(m.card),S=m}),{card:f,destroy:()=>{d=!0,S?.destroy()}}}function Vt(e,t,s,i,f){const S=Le?void 0:Qe?.(),d=()=>{pe.get("data")?.destroy(),pe.delete("data"),ne({keepSections:!0})};return Mn({doc:r,items:e,testDefs:t,allTestDefs:s,groups:i,groupLabelText:f,ringCount:Q(),attributes:I.attributes,yieldByWaferIndex:new Map(S?.lotYieldSeries.map(c=>[c.waferIndex,c.yieldPercent])),onSaveText:J,onLocateDie:me,onOpenWafer:se?(c,m)=>se(c,m):void 0,buildStatistics:c=>jt(c,t,s),view:st,onViewChange:c=>{st=c,d()},diesLayout:rt,onDiesLayoutChange:c=>{rt=c}})}function Ce(e,t){const s=r.createElement("h3");return s.textContent=e,s.dataset.wmapRowHeading=t,Object.assign(s.style,{gridColumn:"1 / -1",margin:`${A.md} 0 0`,color:M.value,fontSize:G.heading,fontWeight:"600"}),s}function Gt(e,t,s,i){const f=Ee(r),S=it(e),d=oe(e.map(n=>({label:n.identity??n.label,dies:n.dies,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:Q()}))),c=t.filter(n=>n.testNumber!==void 0),m=!!s&&!!W,o=m&&_!==null,u={testDefs:t,groupBy:m?W:void 0,curation:I.attributes},p=c.length>1;let b;const P=[];function k(n){let h=De,x=!1,B;const $=ht(c,q??c[0]?.testNumber??null,H=>{B?.refresh(),v(H)},{ownerDocument:r}),K=r.createElement("span");Object.assign(K.style,{display:"inline-flex",flexWrap:"wrap",gap:A.sm,alignItems:"center"});const T={setAxisPrefs:H=>{U.set(H)&&(h=H,B?.refresh())}},U=bt(K,h,H=>{h=H,B?.refresh(),Ne(H,T)},r),ye=[$.el,K];n.logToggle&&ye.push(Ke("Log scale",x,H=>{x=H,B?.refresh()},r,"Draw the value axis on a logarithmic scale")),ye.push(...n.extras??[]),B=ee({doc:r,editAsPlot:Z,items:d,ctx:u,...n.card,spec:{choices:n.choices??[],build:H=>n.build(h,x,H)},slots:()=>({test:$.get()??void 0}),extras:ye,onResolved:H=>{const he=t.find(Zt=>Zt.testNumber===$.get()),we=Ie(he,h.limits),He=kt(H,n.valueRole),{lo:Ut,hi:Qt}=yt(we),Jt=He.length>0&&we.length>0&&wt(vt(He),St(He),Ut,Qt);U.sync(h.includeLimits??Jt,Ie(he).length>0,xt(he))},chart:n.chart});const z=B;if(p){const H=()=>{$.el.style.display=On(z.card)?"":"none"};H();const he=r.defaultView?.MutationObserver;if(he){const we=new he(H);we.observe(z.card,{attributes:!0,attributeFilter:["data-wmap-expanded"]}),P.push(we)}}return{card:z.card,setTest:H=>{$.set(H)&&z.refresh()},refresh:()=>z.refresh(),setAxisPrefs:T.setAxisPrefs,destroy:()=>z.destroy()}}const C=S?(n,h)=>S.open(d[n]?.waferIndex??n,h??q??c[0]?.testNumber??0):void 0;let F=!1,V=!1;const N=k({valueRole:"y",logToggle:!0,choices:[{current:m&&!o?"groups":"wafers",options:[...m&&!o?[["groups",`By ${i??"group"}`],["nested",`${i??"Group"}, then wafer`,"Each group with its wafers inside it"]]:[["wafers","By wafer"]],["radius","By radius","A box for each ring, from the centre to the edge: whether the test changes across the wafer"]]}],build:(n,h,[x])=>(F=m&&!o&&x==="nested",V=x==="radius",{id:"card-box",title:V?"Test value by radius":"Test value distribution",chart:"box",orientation:"horizontal",fields:{x:V?{builtin:"ring"}:F?[{slot:"groupBy"},{builtin:"wafer"}]:m&&!o?{slot:"groupBy"}:{builtin:"wafer"},y:{slot:"test"},color:F?{follow:"groupBy"}:{none:!0}},...o?{where:{conditions:[{field:{meta:W},values:[_]}]}}:{},...ae("y",n,h)}),card:{...m&&!o?{drill:n=>{if(F||V)return null;const h=Ye(d[n[0]?.item]?.metadata,W,I.attributes);return h===void 0?null:x=>({...x,fields:{...x.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:W},values:[h]}]}})},drillLabel:()=>F||V?void 0:"see its wafers"}:{},..._!==null?{externalBack:{shown:()=>_!==null,onBack:()=>Me(null)}}:{}},chart:{onSaveImage:R,onOpenWafer:C,openActionLabel:S?.label,onWaferMenu:ge(e)}});let l=null;const w=m?[]:[mt(d.map(n=>({label:n.label})),null,n=>{l=n,a.refresh()},{ownerDocument:r})],a=k({valueRole:"x",logToggle:!0,extras:w,choices:[{current:"bars",options:[["bars","Histogram"],["cumulative","Cumulative","The share of dies at or below each value, as one curve per colour"]]},...m?[{current:"percent",options:[["percent",`Share of ${i??"group"}`,"Each group\u2019s bars as a share of its own dies, so groups of different sizes compare"],["count","Counts"]]}]:[]],card:_!==null?{externalBack:{shown:()=>_!==null,onBack:()=>Me(null)}}:{},build:(n,h,[x,B])=>({id:"card-histogram",title:x==="cumulative"?"Cumulative distribution":"Value histogram",chart:x==="cumulative"?"probability":"histogram",fields:{y:{slot:"test"},color:m?{follow:"groupBy"}:{none:!0}},...m&&B!=="count"&&x!=="cumulative"?{histNorm:"percent"}:{},...l!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[d[l].label]}]}}:{},...ae("x",n,h)}),chart:{onSaveImage:R,onSelectPoints:(n,h,x,B)=>{const $=t.find(z=>z.testNumber===(q??c[0]?.testNumber)),K=new Set(n.map(z=>z.die).filter(z=>!!z)),T=new Set(n.map(z=>d[z.item]?.waferIndex)),U=B?.range,ye=$&&U?`with ${ct($,$.testNumber)} from ${dt(U.lo,$.unit,"engineering")} to ${dt(U.hi,$.unit,"engineering")}${B?.group?` in ${B.group}`:""}`:"selected in the histogram";ce(h,x,e.filter(z=>T.has(z.waferIndex)),ye,z=>K.has(z),$?.testNumber)}}}),y=k({valueRole:"y",logToggle:!0,choices:e.length>=3?[{current:"trend",options:[["trend","Trend","Each wafer\u2019s mean with a band of one standard deviation"],["control","Control chart","One value per wafer against control limits, with the points that break a Western Electric rule marked"]]}]:[],build:(n,h,[x])=>x==="control"?{id:"card-trend",title:"Wafer-to-wafer control chart",chart:"control",aggregate:"mean",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:m?{follow:"groupBy"}:{none:!0}},...ae("y",n,h)}:{id:"card-trend",title:"Wafer-to-wafer trend",chart:"line",aggregate:"mean",spread:"sd",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:{none:!0}},...ae("y",n,h),axes:{...ae("y",n,h).axes,y:{...ae("y",n,h).axes.y,references:[{stat:"mean",label:gn(mn(e.map(B=>B.wafer.metadata)),"mean")}]}}},card:{ctx:u,...e.length<2?{unavailable:"A trend needs at least two wafers"}:{}},chart:{onSaveImage:R,onWaferMenu:ge(e),selectActionLabel:C?"open that wafer":"chart or tabulate its dies",selectRangeLabel:"wafers",onSelectPoints:(n,h,x)=>{const B=new Set(n.map(T=>T.item));if(B.size===1&&C){C([...B][0]);return}const $=new Set(n.map(T=>T.die).filter(T=>!!T)),K=new Set(n.map(T=>d[T.item]?.waferIndex));ce(h,x,e.filter(T=>K.has(T.waferIndex)),"selected in the trend",T=>$.has(T),q??void 0)}}}),v=n=>{q=n,b?.set(n),N.setTest(n),a.setTest(n),y.setTest(n),O.setTest(n),g?.setTest(n),E?.setTest(n)},D=()=>vn({groups:s,testDefs:t,groupLabelText:i,control:at,onControlChange:n=>{at=n;const h=D();g.card.replaceWith(h.card),g=h},selectedTestNumber:q??void 0,onSelectTest:n=>v(n),onSaveText:J,ownerDocument:r});let g=s&&s.length>=2?D():void 0;const E=s&&s.length>=2?$n({groups:s,testDefs:t,groupLabelText:i,selectedTestNumber:q??void 0,onSaveImage:R,ownerDocument:r}):void 0;Re.set("distribution",[N,a,y]);const O=Sn({title:"Process capability",items:e,testDefs:t,onSaveImage:R,selectedTestNumber:q??void 0,onSelectTest:n=>v(n),ownerDocument:r}),j=e.length>=2?Fn(e.map(n=>({dies:n.dies})),t.filter(n=>n.testNumber!==void 0&&Be(n)).map(n=>n.testNumber),Xn):[],L=j.length>=2?ee({doc:r,editAsPlot:Z,items:d,ctx:u,spec:{id:"card-tests-wafer",title:`Tests by ${s?i??"group":"wafer"} (z-scores)`,chart:"heatmap",level:"wafer",aggregate:"mean",normalize:"zscore",fields:{x:{slot:"groupBy"},y:{tests:j}}},chart:{onSaveImage:R,onSelectPoints:be(d,e,n=>`on ${n?.cell?.column??"the wafer"}, for ${n?.cell?.row??"a test"}`)}}):void 0;if(L&&(L.card.style.minHeight="300px"),L&&(f.append(Ce(`Tests across ${s?i??"groups":"wafers"}`,"tests-grid")),f.append(L.card)),(g||E)&&(f.append(Ce(`Comparing ${i??"groups"}`,"comparing")),g&&f.append(g.card),E&&f.append(E.card)),p){b=ht(c,q??c[0]?.testNumber??null,$=>v($),{ownerDocument:r});const n=r.createElement("div");n.dataset.wmapSectionTest="1",Object.assign(n.style,{gridColumn:"1 / -1",display:"flex",alignItems:"center",gap:A.lg,flexWrap:"wrap",marginTop:A.md});const h=Ce("Test by test","tests");h.style.margin="0";const x=r.createElement("label");Object.assign(x.style,{display:"inline-flex",alignItems:"center",gap:A.xs,fontSize:G.body,color:M.label});const B=r.createElement("span");B.textContent="Test",x.append(B,b.el),n.append(h,x),f.append(n)}else(g||E)&&f.append(Ce("Test by test","tests"));return f.append(O.card,N.card,a.card,y.card),{card:f,destroy:()=>{for(const n of P)n.disconnect();O.destroy(),N.destroy(),a.destroy(),y.destroy(),g?.destroy(),E?.destroy(),L?.destroy()}}}function qt(e,t,s,i){const f=Ee(r),S=it(e),d=oe(e.map(g=>({label:g.identity??g.label,dies:g.dies,waferIndex:g.waferIndex,wafer:g.wafer,passBins:g.passBins,ringCount:Q()}))),c=t.filter(g=>g.testNumber!==void 0&&Be(g));let m=c[0]?.testNumber,o=c[1]?.testNumber??m,u=null,p=De;const b=!!s&&!!W,P=(g,E)=>{const O=r.createElement("label");Object.assign(O.style,{display:"inline-flex",alignItems:"center",gap:A.xs,fontSize:G.body,color:M.label});const j=r.createElement("span");return j.textContent=g,O.append(j,E),O},k=gt(c,m??null,g=>{m=g,v.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:r}),C=gt(c,o??null,g=>{o=g,v.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:r}),F=r.createElement("span");Object.assign(F.style,{display:"inline-flex",flexWrap:"wrap",gap:A.sm,alignItems:"center"});let V=!1,N=!1;const l={setXY:(g,E)=>{m=g,o=E,k.value=String(g),C.value=String(E),v.refresh()},setAxisPrefs:g=>{w.set(g)&&(p=g,v.refresh())},destroy:()=>v.destroy()},w=bt(F,p,g=>{p=g,v.refresh(),Ne(g,l)},r),a=g=>{const E=t.find(O=>O.testNumber===g);return E?.name?{test:g??0,name:E.name}:{test:g??0}},y=[P("X:",k),P("Y:",C),F,Ke("Log X",V,g=>{V=g,v.refresh()},r,"Draw the X axis on a logarithmic scale"),Ke("Log Y",N,g=>{N=g,v.refresh()},r,"Draw the Y axis on a logarithmic scale")];!b&&e.length>1&&y.push(mt(d.map(g=>({label:g.label})),null,g=>{u=g,v.refresh()},{ownerDocument:r}));const v=ee({doc:r,editAsPlot:Z,items:d,ctx:{testDefs:t,groupBy:b?W:void 0,curation:I.attributes},extras:y,onResolved:g=>{const E=[m,o].map(j=>t.find(L=>L.testNumber===j)),O=["x","y"].some((j,L)=>{const n=Ie(E[L],p.limits),h=kt(g,j),{lo:x,hi:B}=yt(n);return h.length>0&&n.length>0&&wt(vt(h),St(h),x,B)});w.sync(p.includeLimits??O,E.some(j=>Ie(j).length>0),E.some(xt))},spec:{choices:[],build:()=>({id:"card-scatter",title:"Test scatter",chart:"scatter",limits:p.limits??"both",axes:{...ae("x",p,V).axes,...ae("y",p,N).axes},fields:{x:a(m),y:a(o),color:b?{follow:"groupBy"}:{builtin:"hbin"}},...b?{fit:"linear"}:{},...u!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[d[u].label]}]}}:{}})},...m===void 0?{unavailable:"No parametric test has values to plot"}:{},chart:{onSaveImage:R,binColors:ie(),onOpenWafer:S?(g,E)=>S.open(d[g]?.waferIndex??g,E??m??0):void 0,openActionLabel:S?.label,onSelectPoints:(g,E,O)=>{const j=new Map;for(const h of g){const x=d[h.item]?.waferIndex;if(x===void 0||!h.die)continue;const B=j.get(x);B?B.push(h.die):j.set(x,[h.die])}const L=[...j].flatMap(([h,x])=>{const B=e.find($=>$.waferIndex===h);return B?[{label:B.identity??B.label,dies:x,waferIndex:h,wafer:B.wafer,passBins:B.passBins,ringCount:Q()}]:[]});if(L.length===0)return;const n=L.length===1?`selected on ${L[0].label} in the scatter`:`selected in the scatter, across ${L.length} wafers`;Ve(E,O,{items:L,population:n,testDefs:t,activeTest:m},{plots:fe,getBinColors:ie,onSaveImage:R,onSaveText:J,onLocateDie:me})}}});Re.set("correlation",[l]);const D=kn({title:"Test correlation matrix",items:e,testDefs:t,onSaveImage:R,onSaveText:J,...b&&s&&s.length>=2?{groups:s,groupLabelText:i}:{},onSelectPair:(g,E)=>l.setXY(g,E),ownerDocument:r});return f.append(D.card,v.card),{card:f,destroy:()=>{D.destroy(),l.destroy()}}}const Kt=(e,t,s,i)=>pn(r,e,t,s,i),Xt=()=>Se.openEditor(Y,Fe());function ne(e){e?.keepSections||ot(),re.innerHTML="",te.innerHTML="";for(const l of Pt)te.appendChild(Dt(l.key,l.label));const t=Fe(),s=Se.keep(t),i=s.items;Le=s.narrowing,Je.refresh(s.result,t),Nt(i);const f=tn(i,{facetableOnly:!0,curation:xe}).filter(l=>l.splittable);We=f.map(l=>({key:l.key,label:l.label}));const S=r.createElement("div");Object.assign(S.style,{display:"flex",gap:A.md,alignItems:"center",marginLeft:A.xxl,paddingBottom:A.xs}),I.showFilterButton!==!1&&S.appendChild(Kt("Filter\u2026","wmapInsightsFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>Xt()));let d;f.length>0?(S.appendChild(pt("Group by:",[{value:"",label:"None"},...f.map(l=>({value:l.key,label:`${l.label} (${l.values.length})`}))],W??"",l=>{W=l||void 0,_=null,ne()},{hook:"group-by",ownerDocument:r,hint:"Split every chart by a wafer attribute, such as lot or tester"})),d=f.find(l=>l.key===W)?.label):W=void 0;let c;if(W){const l=new Map,w=[];for(const a of i){const y=Ye(a.metadata,W,xe)??nn;l.has(y)||(l.set(y,[]),w.push(y)),l.get(y).push(a)}c=Yn(w).map(a=>({key:a,items:l.get(a)}))}_!==null&&!c?.some(l=>l.key===_)&&(_=null),c&&c.length>0&&S.appendChild(Tn(c.map(l=>l.key),"Show:",_,l=>Me(l),{ownerDocument:r,hint:"Show every group, or analyse just one"}).el);const m=pt("Columns:",[{value:"auto",label:"Auto (0)"},...[1,2,3,4,5].map(l=>({value:String(l),label:`${l} (${l})`}))],de===void 0?"auto":String(de),l=>Ze(l==="auto"?void 0:Number(l)),{hook:"insights-columns",maxWidth:"90px",ownerDocument:r,hint:"The most cards that sit side by side (a tab with fewer cards uses fewer); the keys 1 to 5 set it and 0 returns to Auto"});Ae=m.querySelector("button"),S.appendChild(m);let o=null;if(I.onOpenGuide){const l=r.createElement("button");l.type="button",l.innerHTML=xn.help,l.setAttribute("aria-label","User guide"),Object.assign(l.style,{...ft("bare"),display:"inline-flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",flexShrink:"0"}),$e(l,"bare"),ke(l,"User guide"),l.addEventListener("click",()=>I.onOpenGuide()),Object.assign(l.style,{marginLeft:"auto"}),o=l}te.appendChild(S),o&&te.appendChild(o);const u=_!==null?c?.find(l=>l.key===_):void 0,p=u?.items??i,b=u?void 0:c,P=_e(p),k=P.defs,C=k.filter(Be);if(q!==null&&!C.some(l=>l.testNumber===q)&&(q=null),i.length===0){const l=r.createElement("div");l.dataset.wmapInsightsFilterEmpty="1",l.textContent="The filter keeps no wafer and no die. Edit the filter or switch it off to see the data.",Object.assign(l.style,{color:M.label,fontSize:G.body,padding:A.xl}),re.appendChild(l);return}const F=e?.keepSections?pe.get(X):void 0,V=F??(X==="overview"?zt(p,C,k,b,d):X==="distributions"?Gt(p,C,b,d):X==="data"?Vt(p,C,k,b,d):X==="plot"?_t(p,k,u?void 0:W,u?void 0:d):qt(p,C,b,d));F||pe.set(X,V);const N=P.conflicts.filter(l=>l.excluded);if(N.length>0){const l=r.createElement("div");Object.assign(l.style,{color:M.label,fontSize:G.body,padding:`0 ${le} ${A.sm}`});const w=N.slice(0,6).map(v=>v.testNumber).join(", "),a=N.length>6?`, and ${N.length-6} more`:"",y=N.length===1?"it":"them";l.textContent=`${N.length} test ${N.length===1?"number is":"numbers are"} hidden (${w}${a}) \u2014 the wafers in view describe ${y} differently, so their values cannot be pooled. `+(c&&c.length>0?`Pick one ${d??"group"} under "Show:" to analyse ${y}.`:"Load one test program at a time to analyse them."),l.dataset.wmapWithheldTests=String(N.length),re.appendChild(l)}re.appendChild(V.card),ve()}return{el:Y,render:ne,destroy:()=>{r.removeEventListener("keydown",nt),tt?.disconnect(),ot(),fe.flush(),Y.remove()},setAxisPrefs:e=>Ne(e,null,!0),showWorthCard:e=>{X!=="overview"&&(X="overview",ne({keepSections:!0}));const t=[...re.querySelectorAll("[data-wmap-worth-key]")].find(f=>f.dataset.wmapWorthKey===e);if(!t)return!1;const s=r.defaultView,i=()=>t.scrollIntoView({block:"center"});return s?.requestAnimationFrame?s.requestAnimationFrame(()=>s.requestAnimationFrame(i)):i(),t.style.outline=`2px solid ${M.iconActive}`,t.style.outlineOffset="2px",setTimeout(()=>{t.style.outline="",t.style.outlineOffset=""},1600),!0}}}
@@ -1 +1 @@
1
- import{createViewSwitch as Ms}from"./viewSwitch.js";import{createSummaryToggle as ks}from"./summaryToggle.js";import{getUniqueTestNumbers as Ds,resolveTestNumber as Bs,findTestDef as Es,collectMetadataValues as Os}from"../renderer/buildView.js";import{metadataCategoricalValue as Ts}from"../core/metadata.js";import{resolveBinColorsForMaps as Ls,mergeBinDefs as Vt,binColorWarning as Ps,mixedPassBinsWarning as Ws,binColorsEqual as Rs}from"../renderer/binColors.js";import{commonPassBins as oi,itemPassBins as Ue}from"../core/passBins.js";import{PAT_MODE_FIELD as As,PAT_MODE_KEY as Fs,PAT_MODE_ORDER as $s,isPatMode as mt,patModeOffered as Is,withPatField as Vs,withPatVerdicts as Hs}from"./patMode.js";import{requireRingCount as ne}from"../core/ringCount.js";import{NO_DATA_FILL as js}from"../renderer/colorMap.js";import{metadataValueColor as zs}from"../renderer/colorMap.js";import{resolveCanvasTheme as Ns}from"./canvasTheme.js";import{ICONS as Tn}from"./icons.js";import{SHADOW as Ln,LEADING as ii,TRACKING as _s,controlStyle as Ks,wireControlHover as Pn,SPACE as M,EDGE_GUTTER as oe,MAP_CHROME_INSET as Gs,RADIUS as Y,FONT as N,CLR as w,sevColor as si,MODE_LABELS as qs,BIN_LEGEND_MODES as ai,STACKED_MODES as ie,applyOverlayZ as Xs,getTooltip as Ys,hideTooltip as li,createToolbarHelpers as Us,buildModeMenuEl as Zs,openDetachWindow as Qs,openFloatingWindow as Js,openModal as ea,copyWmapThemeTokens as ta,syncWmapPopupTheme as na,makePaletteBtn as oa,makeLogScaleBtn as ia,makeLegendStyleBtn as sa,makeOverlaysBtn as aa,makeOrientationBtn as la,menuLayerFor as ri,saveImageBlob as ra,markMenuTrigger as gt,wireMenuA11y as ci,wireTooltip as Wn,requestedPassFailDisplay as di,overlayMenuRows as ca,anyOverlayActive as da,openCompactDiagnostics as ua,roomForPanel as ui,logWmapVersionOnce as fa,buildDataModeEntries as pa,metadataKeyHasData as ma,metadataModeEntry as fi}from"./toolbar.js";import{openReportModal as ga,openUserGuideWindow as ha,registerGuideOpener as ya}from"./guideWindow.js";import{waferDisplayLabel as ht,waferIdentityLabel as Se}from"../core/waferLabel.js";import{bandButton as ba}from"./filterButton.js";import{metadataDisplayValue as wa}from"../core/metadata.js";import{withExportContext as va}from"./exportName.js";import{sortBinsForDisplay as Sa}from"../stats/binPareto.js";import{diePassStatus as Ca,isYieldEligibleDie as xa}from"../core/dies.js";import{aggregateValues as Ma,aggregateBinCounts as pi}from"../core/aggregates.js";import{renderWaferMap as ka,renderWaferMapCard as mi,toPublicViewOptions as Ht}from"./renderWaferMap.js";import{waferPopulation as Da,selectionPopulation as Ba,LOT_STACK_REASON as Rn}from"./chartPopulation.js";import{sourceFromBins as gi}from"./plotItems.js";import{plotStoreFor as Ea}from"./plotStore.js";import{classifyChanged as An,COLOR_KEYS as Oa,findingBin as Ta,findingPlotMode as La}from"./renderWaferMap.js";import{findingPatternKey as hi}from"../stats/filterFindings.js";import{synthesisSource as Pa}from"../stats/synthesis.js";import{buildWaferMap as Wa,computeCoverage as Ra,computeYield as Aa,defaultBinMode as Fa,getTestPassStatus as yi,isParametricTest as Fn,getDieTestValue as $a,isBuiltMap as Ia}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as $n}from"../stats/analyzeWaferMap.js";import{lotTestValueStatus as Va}from"../stats/testValueBudget.js";import{testValueNotice as Ha}from"./testValueOffer.js";import{axisPrefsFromOptions as In,optionsFromAxisPrefs as ja,CHART_PREF_KEYS as Vn}from"./chartPrefs.js";import{collectWarnings as za,buildWarningsMenuEl as Na,severityOf as _a}from"./warnings.js";import{asList as Hn,compareNatural as jn,arrayEqual as jt,toggleHighlight as bi}from"../core/utils.js";import{buildCompactMap as Ka,compactLayoutOffered as Ga}from"../core/compact.js";import{attachExpandableMetadata as wi}from"./identityHeader.js";import{createSummaryPanelEl as zn,buildMetadataStripRow as qa,metadataEntries as Xa,renderLotSummaryContentSteps as Ya,reportMapsFromItems as Ua}from"./summaryPanel.js";import{prettyKey as Za}from"../stats/facets.js";import{testLabel as Qa,markedTestLabel as Ja,derivedFields as el}from"../renderer/testLabel.js";import{mergeTestDefs as tl}from"../stats/mergeTestDefs.js";import{getDieKey as zt,hasPosition as nl}from"../core/dies.js";import{testValue as ol}from"../core/dieTable.js";import{runChunked as il}from"./chunked.js";function vi(r){if(typeof r!="number"||!Number.isFinite(r))return;const k=Math.round(r);return k>=1?k:void 0}const Nn=12;function sl(r,k,f){let z=k;if(k.length>Nn){const D=k.slice(0,Nn-1),T=k.slice(Nn-1),I=T.reduce(($,de)=>$+de.count,0);z=[...D,{color:w.label,count:I,label:`Other (${T.length} bins)`}]}const O=r.createElement("div");Object.assign(O.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:Y.control,overflow:"hidden",border:`1px solid ${w.menuBorder}`,boxSizing:"border-box",marginTop:M.xs,flexShrink:"0"}),O.setAttribute("role","img"),O.setAttribute("aria-label",`Population split: ${z.map(D=>`${D.label} ${Nt(D.count/f*100)}`).join(", ")}`);for(const D of z){const T=D.count/f*100,I=r.createElement("div");Object.assign(I.style,{flex:`${T} 1 0`,minWidth:T>0?"2px":"0",background:D.color}),Wn(I,`${D.label} \xB7 ${D.count.toLocaleString()} dies \xB7 ${Nt(T)}`),O.appendChild(I)}return O}function Nt(r){return r>0&&r<.1?"<0.1%":`${r.toFixed(1)}%`}function Si(r,k,f){const z=new Map;let O=0,D=0;for(const T of r){const I=f?new Set(f(T)):void 0;for(const $ of T.dies){if(!xa($))continue;const de=k($);de!==void 0&&(z.set(de,(z.get(de)??0)+1),O++,I&&Ca($,I)&&D++)}}return{counts:z,total:O,pass:D}}function Ci(r,k){const f=r.ownerDocument.createElement("div");Object.assign(f.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${M.xxs} ${M.xs}`,borderRadius:Y.control});const z=r.ownerDocument.createElement("span");Object.assign(z.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:k.color,border:k.isActive?`2px solid ${w.iconActive}`:`1px solid ${w.menuBorder}`,borderRadius:Y.control,boxSizing:"border-box"});const O=r.ownerDocument.createElement("span");if(O.textContent=k.label,Object.assign(O.style,{fontWeight:k.isActive?"700":"400",color:k.isActive?w.iconActive:w.text,whiteSpace:"nowrap"}),f.appendChild(z),f.appendChild(O),k.count!==void 0){const D=r.ownerDocument.createElement("span");if(D.textContent=k.count.toLocaleString(),Object.assign(D.style,{color:k.isActive?w.iconActive:w.text,fontWeight:k.isActive?"700":"400",whiteSpace:"nowrap"}),f.appendChild(D),k.percent!==void 0){const T=r.ownerDocument.createElement("span");T.textContent=Nt(k.percent),Object.assign(T.style,{color:w.label,whiteSpace:"nowrap"}),f.appendChild(T)}}if(f.setAttribute("role","button"),f.setAttribute("aria-pressed",k.isActive?"true":"false"),f.tabIndex=0,f.addEventListener("mouseenter",()=>{f.style.background=w.bgHover}),f.addEventListener("mouseleave",()=>{f.style.background="transparent"}),f.addEventListener("focus",()=>{f.style.background=w.bgHover}),f.addEventListener("blur",()=>{f.style.background="transparent"}),f.addEventListener("click",D=>k.onClick(D.ctrlKey||D.metaKey)),f.addEventListener("keydown",D=>{if(D.key==="Enter"||D.key===" ")D.preventDefault(),k.onClick(D.ctrlKey||D.metaKey);else if(k.onMenu&&(D.key==="ContextMenu"||D.key==="F10"&&D.shiftKey)){D.preventDefault();const T=f.getBoundingClientRect();k.onMenu({x:T.left+T.width/2,y:T.bottom},f)}}),k.onMenu){const D=k.onMenu;f.addEventListener("contextmenu",T=>{T.preventDefault(),D({x:T.clientX,y:T.clientY},f)}),Wn(f,"Right-click: charts and tables for these dies")}r.appendChild(f)}export function renderWaferGallery(r,k,f={}){fa();const z=6;let O=vi(f.columns);const D=f.showHelpButton??!1,T=f.userGuideExtension,I=f.insights?.enabled??!0,$=Ea(f.insights),de={enabled:!1,plotStore:$},xi=Xs(f.zIndex),Re=f.summaryPanel,Ce=e=>[...Ue(e)],_n=()=>W.flatMap(e=>e?[ne(e,"renderWaferGallery")]:[]),yt=()=>_n()[0];function Mi(e){const t=[...new Set(e)].sort((n,o)=>n-o);return t.length<2?null:{code:"ring-count-mixed",severity:"warning",message:`These wafers were built with different ring counts (${t.join(", ")}). Each card and each wafer's findings use their own; the lot's ring yield in the Summary panel, report and Insights uses ${e[0]} rings.`}}let _=f.lotStatsSummary,Ae;const se=()=>ae?Ae:_;let Ze=f.viewOptions?.legendPosition??"default",bt=f.perCardLegend??!1;function Qe(){const e=a.plotMode??"hardBin";return ai.has(e)?null:a.colorbarRangeMode==="data"?"Each map has its own value range, so it keeps its own colour bar":"These wafers have no shared colour bar for value mode, so each map keeps its own"}function Kn(){const e=bt||Qe()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let a={plotMode:Fa(k.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...f.viewOptions},C=[],ue=[],Fe=[],x=[];const V=va(()=>{const e=x.filter(n=>n!=null),t=[...new Set(e.map(n=>wa(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(jn);return{prefix:f.downloadFilename,lots:t,...e.length===1?{wafer:Se(e[0])}:{waferCount:e.length}}},f.onSaveImage,f.onSaveText);let W=k.map(e=>typeof e=="function"?null:e),q=null,Gn=null,_t=!1,xe=0,ae=!1,wt=!1;const fe=new WeakSet,qn=new WeakMap,Me=()=>{const e=q?.get();return!!e&&!e.off};function Xn(e,t){return{dies:e.dies,wafer:e.wafer,label:ht(e,t),identity:Se(e),waferIndex:t,passBins:Ue(e),testDefs:e.testDefs,statsSummary:e.statsSummary}}const Kt=new Map;function Je(e,t){if(!q||!Me())return e;const n=qn.get(e);if(n&&n.v===xe)return n.item;const o=q.mark([Xn(e,t)]);let i=e;if(o.narrowing){const s=o.items[0].dies,l=s.filter(u=>!u.filteredOut);i={...e,dies:s,statsSummary:Kt.get(e),...e.yield?{yield:Aa(s,[...Ue(e)],e.yield.yieldPercentGross!=null?"denominator-only":"exclude")}:{},...e.dataCoverage?{dataCoverage:Ra(l)}:{}},o.hidden.size&&fe.add(i)}return qn.set(e,{v:xe,item:i}),i}const Yn=new WeakMap;function Gt(e,t){const n=Je(e,t);if(!mt(a))return n;const o=Yn.get(n);if(o)return o;const i={...n,dies:Hs(n.dies,n.testDefs,Ue(n)),metadataFields:Vs(n.metadataFields)};return fe.has(n)&&fe.add(i),Yn.set(n,i),i}const Un=new WeakMap;function ki(e,t){if(!q||!Me())return e;const n=Un.get(e);if(n&&n.v===xe)return n.item;const o=Je(e,t),i=o===e?e:fe.has(o)?null:{...o,dies:o.dies.filter(s=>!s.filteredOut)};return Un.set(e,{v:xe,item:i}),i}function B(){return!q||!Me()?W:W.map((e,t)=>e?ki(e,t):null)}let vt=0,et=!1;function Zn(){const e=++vt;Ae=void 0,Kt.clear();const t=()=>{et=!1,R(),re()};if(!ae){t();return}const n=Jt();if(!n||!(_||n.some(s=>s.statsSummary))){t();return}const o=B().flatMap((s,l)=>s?[{it:s,i:l}]:[]);if(o.length===0){t();return}et=!0;const i=_?.analysisOptions??n.find(s=>s.statsSummary)?.statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(async({analyzeWaferLotAsync:s,remapLotWaferIndices:l})=>{const u=await s(o.map(m=>m.it),i);if(e!==vt||_t)return;const d=o.map(m=>m.i);Ae=l(u,d),u.perWafer.forEach((m,v)=>Kt.set(W[d[v]],m.summary)),xe++,W.forEach((m,v)=>{if(!m||ie.has(a.plotMode))return;const p=Gt(m,v);x[v]=p,C[v]?.setStatsSummary(p.statsSummary)}),Te(),t()}).catch(()=>{e===vt&&t()})}const $e=e=>q&&Me()||mt(a)?e.map((t,n)=>typeof t=="function"?t:Gt(t,n)):e;function qt(){return Gn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const t=e({doc:r.ownerDocument,initial:f.insights?.filter,onChange:f.insights?.onFilterChange,savedFilters:f.insights?.savedFilters,onSavedFiltersChange:f.insights?.onSavedFiltersChange,pickFiltersFile:f.insights?.onPickFiltersFile,onSaveText:f.onSaveText,attributes:f.attributes,getRingCount:()=>ne({ringCount:yt()},"the page filter")});return _t||(q=t,pe=t.createBand(()=>Yt(),{marginLeft:oe,marginRight:oe,marginBottom:M.lg}),r.insertBefore(pe.el,Z),t.subscribe(Ut),t.get()&&Ut()),t}),Gn}let pe=null,St=null,Xt;const Yt=()=>W.flatMap((e,t)=>e?[Xn(e,t)]:[]);function Qn(){clearTimeout(Xt),Xt=setTimeout(()=>{if(!q||!pe)return;const e=Yt(),t=q.keep(e);pe.refresh(t.result,e),pe.el.style.display=q.get()&&!Ke?"":"none"},0)}function Jn(){if(q){if(ke>0){Me()&&(wt=!0);return}xe++,ae=Me()&&W.some((e,t)=>e!==null&&Je(e,t)!==e),Ae=void 0,et=ae&&!!_,Zn()}}function Ut(){if(xe++,ae=!1,ke>0){wt=!0,Qn();return}wt=!1;const e=a.plotMode;ae=Me()&&W.some((t,n)=>t!==null&&Je(t,n)!==t),Ae=void 0,et=ae&&!!_,W.length>0&&(ie.has(e)?(a={...a,...$t(e)},X(qe(e))):X($e(W.filter(t=>t!==null)))),Qn(),Zn()}function Ie(){return tl(B())}function tt(){if(B().some(e=>e?.testDefs?.length))return Ie().defs}let nt=0,ke=0;const Q=new Map;let Di=0,Ct=null,J=null,me=null,Ve=null;function xt(){J===null&&me===null&&(Ve={plotMode:a.plotMode,activeTest:a.activeTest})}function eo(){Ve&&P({...Ve},{fireCallback:!1}),Ve=null}let to=new Set,S=null,Bi={};function no(e){return B()[e]?.statsSummary??se()?.perWafer.find(t=>t.waferIndex===e)?.summary}function oo(){return!!(B().some(e=>e?.statsSummary?.findings.length)||se()?.perWafer.some(e=>e.summary.findings.length))}const Ei=Ys(),He=Us(Ei),{makeBtn:je,setActive:io,makeSep:De,syncSeparators:Zt,syncToolbarVisible:Qt,makeMenuRow:Oi,makeMenuSection:Ti,makeDropdown:so,closeOpenMenu:Mt,getOpenMenu:ot,setOpenMenu:it}=He;r.ownerDocument.addEventListener("click",Mt,!0);const ao=()=>li();window.addEventListener("blur",ao);let lo=f.findingsNotice,Be=null;function Jt(){const e=W;return e.length>0&&e.every(t=>t!=null&&Ia(t))?e:null}function Li(){return _?.stats.testValueAnalysis??Va(B().flatMap(e=>e?.statsSummary?[e.statsSummary]:[]))}const en=()=>lo??(Jt()?Ha(Li(),B().length,Be!==null,Pi):void 0);function Pi(){const e=Jt();if(Be||!e)return;const t=new AbortController;Be=t,R();const n=_?.analysisOptions??e[0].statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(({analyzeWaferLotAsync:o})=>o(e,{...n,enableTestValueAnalysis:!0,signal:t.signal})).then(o=>{if(t.signal.aborted)return;Be=null;const i=o.perWafer.map(s=>s.summary);W=W.map((s,l)=>s&&{...s,statsSummary:i[l]}),ie.has(a.plotMode)||(x=x.map((s,l)=>s&&{...s,statsSummary:i[l]}),C.forEach((s,l)=>s?.setStatsSummary(i[l]))),_=o,Te(),R(),re(),f.onStatsSummaryChange?.({summaries:i,lotStatsSummary:o})}).catch(o=>{if(!t.signal.aborted)throw Be=null,R(),o})}function tn(){Be?.abort(),Be=null}function ro(e){to=new Set(e);const t=[...F.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=to.has(i);o.style.outline=s?`3px solid ${w.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function nn(){ro([])}let kt=!1;function on(){kt=!0;for(const e of C)e&&e.clearSelection();kt=!1}function co(e){return t=>{!kt&&(J!==null||me!==null)&&(Ve=null,Oe(),R()),ln.set(e,t.length),le&&!st&&!kt&&Wi(e,t),e.onSelect?.(t)}}function ge(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),F.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let le=!1,st=!1,Ee=new Set;function Wi(e,t){st=!0;try{Ee=new Set(t.map(n=>zt(n))),x.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>Ee.has(zt(s))))})}finally{st=!1}Lt()}function uo(){Ee=new Set,st=!0;try{for(const e of C)e?.clearSelection()}finally{st=!1}Lt()}function sn(){if(!le||Ee.size===0)return;const e=[];let t=!1;if(x.forEach((i,s)=>{if(!i)return;const l=i.dies.filter(u=>Ee.has(zt(u)));l.length!==0&&(i.isLotStack&&(t=!0),e.push({label:Se(i)??i.label??`Wafer ${s+1}`,dies:l,waferIndex:s,wafer:i.wafer,passBins:Ce(i),ringCount:ne(i,"renderWaferGallery")}))}),e.length===0)return;const n=Ie(),o=a;return{source:{items:e,population:e.length===1?`selected on ${e[0].label}`:`selected at the same die positions on ${e.length} wafers`,testDefs:n.defs,activeTest:o.plotMode==="value"?o.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>ge(s,i)}}}function fo(){const e=[];let t=!1;if(x.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:Se(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:Ce(o),ringCount:ne(o,"renderWaferGallery")}))}),e.length<2)return;const n=a;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:Ie().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(o,i)=>ge(i,o)}}}function Ri(e){const t=sn()??go(e);if(t)return t;const n=fo(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function an(e,t,n){J!==e&&t.click();const o=S;if(!o)return;const i=se()?.findings.find(l=>l.id===e),s=sn()??fo()??Fi()??(i?po(ho(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:l})=>{o.isConnected&&l(n,o,s.source,{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...s.ctx})})}function Ai(e,t,n,o){const i=Hn(a.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],l=[];let u=!1;x.forEach((g,h)=>{g&&(g.isLotStack&&(u=!0),l.push({label:Se(g)??g.label??`Wafer ${h+1}`,dies:g.dies,waferIndex:h,wafer:g.wafer,passBins:Ce(g),ringCount:ne(g,"renderWaferGallery")}))});const d=Ie().defs,m=gi(l,e,s,d,void 0,u);if(!m)return;const v={plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(g,h)=>ge(h,g)},p=s.length>1?gi(l,e,[t],d,void 0,u):null,c=p?{...v,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:p,ctx:v}}:v;import("./drilldown.js").then(({openDrilldownMenu:g})=>{o.isConnected&&g(n,o,m,c)})}function po(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((l,u)=>l-u)){const l=x[s];l&&(l.isLotStack&&(o=!0),n.push({label:Se(l)??l.label??`Wafer ${s+1}`,dies:l.dies,waferIndex:s,wafer:l.wafer,passBins:Ce(l),ringCount:ne(l,"renderWaferGallery")}))}if(n.length===0)return;const i=a;return{source:{items:n,population:n.length===1?`on ${n[0].label}`:`on ${n.length} ${t}wafers`,testDefs:Ie().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(s,l)=>ge(l,s)}}}function Fi(){let e;for(let i=0;i<C.length;i++)if((C[i]?.getSelectedDies().length??0)!==0){if(e!==void 0)return;e=i}const t=e===void 0?void 0:x[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=a;return{source:Ba(n,{waferLabel:Se(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:Ce(t),ringCount:ne(t,"renderWaferGallery")}),ctx:{onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>ge(s??e,i)}}}function $i(e){e||uo(),le=e,Lt()}function Dt(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=x[i],l=C[i];if(!s||!l)continue;const u=s.dies.filter(d=>n.has(zt(d)));l.setSelection(u)}}const U=new Set,ln=new Map;function mo(){[...F.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=U.has(o)?`2px solid ${w.iconActive}`:"",n.style.outlineOffset=U.has(o)?"-2px":""});const t=U.size;ee.style.display=t>0?"":"none",ee.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,ee.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function Ii(e){e<0||(U.has(e)?U.delete(e):U.add(e),mo())}function Vi(){U.clear(),mo()}function go(e){if(!(U.size===0||!U.has(e))){for(const t of ln.values())if(t>0)return;return po([...U],"picked ")}}function Hi(){const e=[];for(let t=0;t<B().length;t++){const n=B()[t];if(!n)continue;const o=no(t)?.findings??[];o.length&&e.push({index:t,item:n,unusualCount:o.filter(i=>i.severity==="unusual").length,notableCount:o.filter(i=>i.severity==="notable").length,totalCount:o.length})}return e}function ji(e){const t=x[e]??B()[e];t&&ut(e,t)}function zi(e){const t=no(e)?.findings??[];if(t.length)return{total:t.length,unusual:t.filter(n=>n.severity==="unusual").length,notable:t.filter(n=>n.severity==="notable").length}}function Ni(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{ga(e(Ua(B(),yt())),{anchor:r})})}function _i(){if(!S)return;S.innerHTML="";const e=Hi();if(B().length>0){const n=r.ownerDocument.createElement("div"),o=e.length,i=B().filter(Boolean).length;n.textContent=o===0?`No findings on any of the ${i} wafers`:`${o} of ${i} wafer${i===1?"":"s"} with findings`,Object.assign(n.style,{fontSize:N.body,color:w.label,marginBottom:M.md}),S.appendChild(n)}if(e.length>0){const n=r.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{...Ks("outlined"),marginBottom:M.lg,display:"block",width:"100%",textAlign:"left"}),Pn(n),n.addEventListener("click",Ni),S.appendChild(n)}if(e.length===0){const n=r.ownerDocument.createElement("div");Object.assign(n.style,{color:w.icon,fontSize:N.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",S.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:l}of e){const u=i?"unusual":s?"notable":"info",d=i+s||l,m=r.ownerDocument.createElement("button");m.type="button",Object.assign(m.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:M.xs,border:"none",borderLeft:`3px solid ${si(u)}`,borderRadius:Y.control,background:w.bgHover,cursor:"pointer",fontSize:N.body,textAlign:"left",boxSizing:"border-box"}),m.addEventListener("mouseover",()=>{m.style.background=w.bgActive}),m.addEventListener("mouseout",()=>{m.style.background=w.bgHover});const v=r.ownerDocument.createElement("span");v.textContent=ht(o,n),Object.assign(v.style,{color:w.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const p=r.ownerDocument.createElement("span");p.textContent=String(d),m.setAttribute("aria-label",`${ht(o,n)} \u2014 ${d} finding${d===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(p.style,{marginLeft:M.sm,flexShrink:"0",background:si(u),color:"#fff",borderRadius:Y.container,padding:"1px 5px",fontSize:N.body,fontWeight:"600"}),m.appendChild(v),m.appendChild(p),m.addEventListener("click",()=>ut(n,o)),S.appendChild(m)}const t=r.ownerDocument.createElement("div");t.style.height="12px",S.appendChild(t)}let ze=null,at=null;function R(){if(!S||ae&&_&&!Ae&&et)return;ze?.cancel(),ze=null;const e=se();if(e){const t=Vt(B().map(o=>o?.hbinDefs)),n=Vt(B().map(o=>o?.sbinDefs));ze=il(Ya(S,{lotSummary:e,items:B(),hbinDefs:t.length?t:void 0,sbinDefs:n.length?n:void 0,testDefs:tt(),ringCount:yt(),binColors:a.binColors,plotMode:a.plotMode??"hardBin",fallbackFormat:a.fallbackFormat,activeFindingId:J,warnings:f.warnings?.display??!0?he:[],findingsFilter:Bi,findingsNotice:en(),onFindingsFilterChange:R,onSaveText:V.onSaveText,attributes:f.attributes,onFindingClick:(o,i)=>{J===o.id?(Oe(),eo()):(xt(),So(o,i)),R()},activeTest:me,onTestClick:o=>{const i=me===o;i||xt(),Oe(),i?eo():vo(o),R()},onShowChart:I?o=>{Ge(!0),Io().then(i=>i?.showWorthCard(o))}:void 0,onWaferClick:ji,findingsFor:zi,dieListOptions:f.dieList,onLocateDie:(o,i)=>ge(i,o),onClose:()=>cn(!1)}),{onDone:()=>{const o=at;at=null,o?.()}})}else _i()}function ho(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let Bt=[];function yo(){if(Bt.length!==0){for(const e of Bt)C[e]?.setOptions({plotMode:a.plotMode,activeTest:a.activeTest});Bt=[]}}function Oe(){J=null,me=null,nn(),on(),yo(),P({highlightBin:void 0},{fireCallback:!1})}function bo(){J===null&&me===null||(Ve=null,Oe(),R())}function wo(e,t){const n=tt();if(n===void 0||n.some(i=>i.testNumber===e))P({plotMode:"value",activeTest:e,highlightBin:void 0},{fireCallback:!1});else{P({highlightBin:void 0},{fireCallback:!1});const s=ie.has(a.plotMode??"hardBin")?null:t;if(s){for(const l of s)C[l]?.setOptions({plotMode:"value",activeTest:e});Bt=[...s]}}}function vo(e){me=e;const t=o=>x[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=x.map((o,i)=>i).filter(o=>t(o)?.length);if(wo(e,n.length?n:null),nn(),on(),!ie.has(a.plotMode??"hardBin"))for(const o of n)Dt(t(o),[o])}function So(e,t){if(J===e.id){Oe();return}J=e.id,me=null,t&&(t.style.background=w.bgActive,t.style.fontWeight="600"),yo();const{kind:n,index:o}=e.variable;if(n==="test")wo(o??0,ho(e));else{const s=x.some(u=>u?.dies?.some(d=>d.hbin!=null)),l=oi(x.map(u=>u?Ue(u):void 0));P({plotMode:La(e,a.plotMode,s),highlightBin:Ta(e,l,s)},{fireCallback:!1})}nn(),on();const i=e.highlight;if(i.kind==="wafer"){ro(i.waferIndices);const s=hi(e);for(const l of i.waferIndices){const u=i.dieKeysByWafer?void 0:x[l]?.statsSummary?.findings.find(m=>hi(m)===s),d=i.dieKeysByWafer?.[l]??u?.highlight?.dieKeys;d?.length&&Dt(d,[l])}}else i.kind==="bin"?i.dieKeys?.length&&Dt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Dt(i.dieKeys)}function rn(){return!!S&&S.style.display!=="none"}function cn(e){!S||e===rn()||(e&&R(),S.style.display=e?"flex":"none",re())}function re(){Ct&&(Zt(H),Qt(H,"inline-flex"),Ct.sync({visible:!!(_||se()||oo())&&!!S&&!Ke,open:rn(),notable:!!(se()?.hasNotableFindings||B().some(e=>e?.statsSummary?.hasNotableFindings))}))}const H=r.ownerDocument.createElement("div");H.dataset.wmapToolbar="gallery",Object.assign(H.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,padding:"0",boxShadow:Ln.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const Co=()=>{const e=ot();e&&(e.remove(),it(null)),gt(ce,!1)},ce=je("mode","Plot mode",()=>{if(ot()){Co();return}const e=B().flatMap(y=>y?.dies??[]),t=tt(),{testEntries:n,binEntries:o,stackedEntries:i}=pa(e,t,{includeStacked:!0}),s=B().filter(Boolean).length,l=y=>{if(y===void 0)return s;let E=0;for(const A of B())A?.dies?.some(j=>yi(j,y)!==void 0||ol(j,y)!==void 0)&&E++;return E},u=s<2?n:n.map(y=>{const E=l(y.activeTest);return E===s?y:{...y,label:`${y.label} \u2014 ${E} of ${s} wafers`}}),d=a.plotMode??"hardBin",m=a.activeTest??0;function v(y){return y.plotMode!==d?!1:y.plotMode==="value"?m===(y.activeTest??0):y.plotMode==="metadata"?a.activeMetadataKey===y.activeMetadataKey:!0}function p(y,E){y.activeTest!==void 0?P({plotMode:"value",activeTest:y.activeTest,activeMetadataKey:void 0,logScale:y.logScale}):y.activeMetadataKey!==void 0?P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:y.activeMetadataKey,passFailDisplay:"off"}):P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),it(null),gt(ce,!1)}const c=new Set,g=B().flatMap(y=>y?.metadataFields??[]).filter(y=>!c.has(y.key)&&c.add(y.key)).filter(y=>ma(e,y.key)).map(fi);ke===0&&Is(B())&&g.push(fi(As));const h=Zs(ce.getBoundingClientRect(),u,o,i,v,p,{makeMenuRow:Oi,makeMenuSection:Ti},d,ce.ownerDocument.defaultView??window,g);ri(ce).appendChild(h),it(h),gt(ce,!0),ci(h,ce,Co)});gt(ce,!1);const Ki=()=>x.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:Gi,sync:xo}=oa(He,()=>({...a,plotMode:a.plotMode??"hardBin"}),Ki,e=>P(e));xo();const qi=k.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function Et(){const e=tt(),{testNumber:t}=Bs(a.activeTest??0,e);return{testNumber:t,td:Es(e,t)}}function Mo(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function lt(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&!Fn(e)}function Xi(){if((a.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=Et();return B().some(n=>n?.dies?.some(o=>yi(o,e,t)!==void 0))}function Yi(e,t){if(!t||!Fn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((di(a)==="spec"&&n?"spec":a.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,l=-1/0;for(const u of B())if(u)for(const d of u.dies){const m=$a(d,e);m!==void 0&&(m<s&&(s=m),m>l&&(l=m))}if(isFinite(s))return s===l?[s,s+1]:[s,l]}function Ot(e,t,n){const o=a[e];if(o===t||o!=null&&t!=null&&n(o,t))return!1;a={...a,[e]:t};for(const i of C)i&&i.setOptions({[e]:t});return!0}function ko(){if((a.plotMode??"hardBin")!=="metadata")return;const e=a.activeMetadataKey;if(!e)return;if(mt(a))return{key:e,values:[...$s]};const t=new Set;for(const n of B())if(n)for(const o of Os(n.dies,e))t.add(o);return{key:e,values:[...t].sort(jn)}}function dn(){Ot("metadataValueOrder",ko(),(e,t)=>e.key===t.key&&jt(e.values,t.values))}function un(){if((a.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=Et(),n=Yi(e,t);Ot("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const l=m=>Array.isArray(m)?{test:void 0,range:m}:{test:m.test,range:m.range},u=l(i),d=l(s);return u.test===d.test&&jt(u.range,d.range)})}let fn=!1;function Ui(){if(fn)return;fn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{fn=!1,un(),dn(),Oo(),Eo()})}let pn=!1;function Zi(){if(pn)return;pn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{pn=!1,Ft()})}let Do=[];function K(){const{colors:e,mixedHardBins:t}=Ls(B().filter(n=>n!=null),{binColorScheme:a.binColorScheme,useDefinedBinColors:a.useDefinedBinColors});return Do=t,e}function mn(){return x.filter(e=>e!=null).flatMap(e=>e.dies)}function Bo(){return a.compact?Ka(mn()):void 0}const Qi=(e,t)=>jt(e.columns,t.columns)&&jt(e.rows,t.rows);function Eo(){Ot("compactMap",Bo(),Qi)&&zo()}function Ji(){return Ga(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig))}function Oo(){Ot("binColors",K(),Rs),Te()}const es=aa(He,()=>ca(a,qi,{functionalActive:lt(),hasLimits:Mo()&&!lt(),hasRecorded:Xi()&&!lt(),binMode:(a.plotMode??"hardBin")==="hardBin"||(a.plotMode??"hardBin")==="softBin"},e=>P(e),{on:!!a.compact,offered:Ji(),onChange:e=>P({compact:e}),onDiagnostics:()=>ua(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:r,onSaveText:V.onSaveText})}),()=>da(a)),{btn:ts,sync:To}=sa(He,()=>({plotMode:a.plotMode,legendPosition:Ze}),e=>{Ze=e;for(const t of C)t&&t.setOptions({legendPosition:Ze})},{get:()=>bt,set:e=>{bt=e,Kn()},blockedReason:Qe});To();const ns=[{value:"mean",label:"Mean"},{value:"median",label:"Median"},{value:"stddev",label:"Std Dev"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"count",label:"Count"}],Lo=so("aggr","Aggregation method",()=>ns,()=>a.aggregationMethod??"mean",e=>P({aggregationMethod:e}));function Po(){const e=a.plotMode==="stackedValues";Lo.style.display=e?"":"none"}Po();const{btn:os,sync:Wo}=ia(He,()=>({...a,functionalActive:lt()}),e=>P(e));Wo();const Tt=je("specRange","Colour bar range: test limits",()=>{const e=a.colorbarRangeMode==="data"?"spec":"data";P({colorbarRangeMode:e})});function Ro(){const e=(a.plotMode??"hardBin")==="value"&&Mo()&&di(a)==="off"&&!lt();Tt.style.display=e?"":"none";const t=(a.colorbarRangeMode??"spec")==="spec";io(Tt,t),Tt.ariaLabel=t?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"}Ro();const is=la(He,()=>a,e=>P(e)),ss=je("downloadAll","Download gallery PNG",Ss),Ne=je("boxSelect","Select the same dies on every wafer",()=>{le&&Ee.size>0?uo():$i(!le)});Ne.style.position="relative";const rt=r.ownerDocument.createElement("span");rt.dataset.wmapSelectAcrossCount="1",Object.assign(rt.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:Y.pill,background:w.iconActive,color:w.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Ne.appendChild(rt);function Lt(){io(Ne,le);const e=le?Ee.size:0;rt.style.display=e>0?"block":"none",rt.textContent=e>99?"99+":String(e),Ne.ariaLabel=le?e>0?`Select the same dies on every wafer: on, ${e.toLocaleString()} die position${e===1?"":"s"} selected (click to clear the selection)`:"Select the same dies on every wafer: on (click to turn off)":"Select the same dies on every wafer: off (click to turn on)",Ne.setAttribute("aria-pressed",String(le))}const ee=r.ownerDocument.createElement("button");ee.type="button",ee.dataset.wmapPickedWafers="1",Object.assign(ee.style,{display:"none",border:"none",background:w.bgActive,color:w.iconActive,borderRadius:Y.control,padding:`${M.xs} ${M.md}`,fontSize:N.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),Pn(ee,"bare"),ee.addEventListener("click",Vi);const Ao=()=>{const e=x.filter(o=>o!=null&&!fe.has(o)).length,t=Math.min(5,Math.max(1,e)),n=Array.from({length:t},(o,i)=>i+1);return O!=null&&!n.includes(O)&&n.push(O),n},as=so("columns","Columns",()=>[{value:"auto",label:"Auto (0)"},...Ao().map(e=>({value:String(e),label:`${e} column${e===1?"":"s"} (${e})`}))],()=>O!=null?String(O):"auto",e=>Sn(e==="auto"?void 0:Number(e))),L=r.ownerDocument.createElement("div");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:"0"}),H.appendChild(L),L.appendChild(ce),L.appendChild(Gi),L.appendChild(Lo),L.appendChild(os),L.appendChild(Tt),L.appendChild(De()),L.appendChild(es),L.appendChild(De()),L.appendChild(ts),L.appendChild(De()),L.appendChild(is),L.appendChild(De()),L.appendChild(as),L.appendChild(De()),L.appendChild(Ne),L.appendChild(ee),L.appendChild(ss),Lt();let te=null,Pt=null,he=[],Fo=!1;function Te(){const e=za({lotStatsSummary:se(),result:{warnings:[...B().flatMap(n=>n?.warnings??[]),...Ie().warnings]},extra:[a.binColors&&Ps(a.binColors,a.plotMode),Ws(Do),Mi(_n())].filter(n=>!!n)}),t=e.length!==he.length||e.some((n,o)=>n.code!==he[o]?.code||n.message!==he[o]?.message);he=e,(t||!Fo)&&(Fo=!0,f.warnings?.onWarning?.(e)),ls()}function ls(){if(!te||!Pt)return;const e=he.length,t=e>0;if(te.style.display=t?"flex":"none",Pt.style.display=t?"":"none",Zt(H),Qt(H,"inline-flex"),!t)return;const n=_a(he[0]),o=`${e} data ${e===1?"warning":"warnings"}`;te.style.color=n==="error"?w.errText:w.warnText,te.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(f.warnings?.display??!0)&&(Pt=De(),te=je("warning","Data warnings",()=>{const e=ot();if(Mt(new MouseEvent("click")),e)return;const t=Na(te.getBoundingClientRect(),he,te.ownerDocument.defaultView??window);ri(r).appendChild(t),it(t),ci(t,te,()=>Mt(new MouseEvent("click")))}),gt(te,!1),H.appendChild(Pt),H.appendChild(te)),Te();function gn(e){import("./userGuideHtml.js").then(t=>ha({buildWaferMap:Wa,renderWaferMap:ka,renderWaferGallery,analyzeWaferMap:$n},t.USER_GUIDE_HTML,T,r,e))}const rs=ya(e=>gn(e));D&&(H.appendChild(De()),H.appendChild(je("help","User guide",()=>gn())));const _e=r.ownerDocument.createElement("div");_e.dataset.wmapGalleryMeta="1",Object.assign(_e.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${M.sm} ${M.lg}`,fontSize:N.sub,lineHeight:ii.none,boxSizing:"border-box"});const Le=r.ownerDocument.createElement("div");Object.assign(Le.style,{background:w.canvasBg,display:"flex",alignItems:"stretch",gap:M.lg,paddingBottom:M.lg,minWidth:"0"});const ye=r.ownerDocument.createElement("div");ye.dataset.wmapGalleryLegend="1",Object.assign(ye.style,{display:"flex",flexDirection:"column",gap:M.sm,background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,padding:`${M.sm} ${M.lg}`,marginBottom:M.lg,boxShadow:Ln.panel,fontSize:N.body,lineHeight:ii.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const Z=r.ownerDocument.createElement("div");Object.assign(Z.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let be=null,ct=null,$o=null;function Io(){return I?be?Promise.resolve(be):($o??=Promise.all([import("./insightsTab.js"),qt()]).then(([{createInsightsTab:e},t])=>(be=e({pageFilter:t,showFilterButton:!1,initialAxisPrefs:In(a),onAxisPrefsChange:n=>{a={...a,...ja(n)};const o=[...Vn];f.onViewOptionsChange?.(Ht(a),o,An(o))},attributes:f.attributes,getItems:()=>W,getLotStats:()=>_,getBinColors:()=>a.binColors??K(),getRingCount:()=>ne({ringCount:yt()},"the Insights tab"),defaultView:f.insights?.defaultView,plotStore:$,onPickPlotsFile:f.insights?.onPickPlotsFile,showPatMap:()=>{Ge(!1),P({plotMode:"metadata",activeTest:void 0,activeMetadataKey:Fs,passFailDisplay:"off"})},showOnMap:n=>{if(Ge(!1),n.kind==="test")xt(),Oe(),vo(n.testNumber);else{const o=se(),i=o?Pa(o).findings.find(s=>s.id===n.id):void 0;i&&J!==i.id&&(xt(),So(i))}cn(!0),R()},onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,ownerDocument:r.ownerDocument,locateDie:(n,o)=>{Ge(!1),ge(o,n)},openWafer:(n,o,i)=>{const s=B()[n];if(!s)return;let l=null;const u=ea({title:o,onClose:()=>l?.destroy(),anchor:r});Xo(u,o,s.wafer.metadata??void 0),l=kn(u.contentWrap,s,i,void 0,ui(u))}}),ct=be.el,ct.style.display="none",r.appendChild(ct),be)),$o):Promise.resolve(null)}let Ke=!1,hn=null;function Ge(e){I&&(Ke=e,hn?.setInsightsOpen(e),ct&&(ct.style.display=e?"flex":"none"),Z.style.display=e?"none":"flex",pe&&(pe.el.style.display=q?.get()&&!e?"":"none"),L.style.display=e?"none":"inline-flex",Zt(H),Qt(H,"inline-flex"),H.style.display="inline-flex",re(),Ft(),e&&Io().then(t=>{!t||!Ke||(t.el.style.display="flex",t.render())}))}I&&f.insights?.defaultOpen&&queueMicrotask(()=>Ge(!0));const cs=6,ds=4,Wt=240,yn=480,us=720,fs=1.25;let Pe=yn;function Vo(e){const t=z*2+110+2,n=Ho();if(n)return Math.ceil(n.across*ds+t);let o=null;for(const i of e){if(i==null||!i.dies?.length)continue;const s=i.dies[0].width;if(!(s>0))continue;const l=i.wafer.radius*2*(cs/s),u=Math.ceil(l+t);(o==null||u>o)&&(o=u)}return o}function ps(e){const t=Vo(e);return t==null?Wt:Math.min(Pe,Math.max(Wt,t))}function ms(e){const t=Vo(e);if(t==null)return!1;const n=Math.min(us,Math.max(yn,t));return n<=Pe?!1:(Pe=n,!0)}function Ho(){const e=a.compact?a.compactMap:void 0,t=x.find(i=>i?.dies?.length)?.dies[0];if(!e||!t||e.columns.length===0||e.rows.length===0||!(t.width>0)||!(t.height>0))return;const n=(a.rotation??0)%180!==0,o=a.showXYIndicator?2.5:0;return{across:(n?e.rows.length:e.columns.length)+o,down:(n?e.columns.length:e.rows.length)+o,cellAspect:n?t.height/t.width:t.width/t.height}}function jo(e,t){const n=Ho();if(!n){e.style.aspectRatio="1",t.style.flex="1",t.style.width="",t.style.aspectRatio="";return}e.style.aspectRatio="auto",t.style.flex="none",t.style.width="100%",t.style.aspectRatio=String(n.across*n.cellAspect/n.down)}function gs(){for(const e of ue)e?.parentElement&&jo(e.parentElement,e)}function zo(){Pe=yn,dt=Wt,vn(x.map(e=>e??null)),Rt(),gs()}function bn(){return No()?`${Pe}px`:"none"}function No(){return O==null&&!wn}let wn=!1;function Rt(){const e=bn();for(const t of Array.from(F.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let dt=Wt,_o=0;function vn(e){if(ms(e)&&Rt(),O==null){const n=ps(e);n>dt&&(dt=n)}xn()}function Sn(e){O=vi(e),Rt(),xn()}let At=!1;r.addEventListener("pointerenter",()=>{At=!0}),r.addEventListener("pointermove",()=>{At=!0}),r.addEventListener("pointerleave",()=>{At=!1});const hs=()=>{if(At)return!0;try{return r.matches(":hover")}catch{return!1}},Ko=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||Ke||!hs()&&!r.contains(e.target)||!/^[0-5]$/.test(e.key)||r.ownerDocument.querySelector('[role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||e.key!=="0"&&!Ao().includes(Number(e.key))||(e.preventDefault(),Sn(e.key==="0"?void 0:Number(e.key)))};r.ownerDocument.addEventListener("keydown",Ko);function Cn(e){return`repeat(${e}, minmax(0, ${No()?`${Pe}px`:"1fr"}))`}function Go(e){F.style.gridTemplateColumns!==e&&(F.style.gridTemplateColumns=e)}function xn(){if(O!=null){Go(Cn(O));return}const e=Math.max(1,_o),t=12,n=F.clientWidth||0,o=l=>(n-t*(l-1))/l;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const l=Math.min(Pe,dt*fs),u=d=>{let m=0;for(;m<e&&o(m+1)>=d;)m++;return m};i=u(l)||u(dt)||1}const s=n>0&&i<e;s!==wn&&(wn=s,Rt()),Go(Cn(i))}const F=r.ownerDocument.createElement("div");if(Object.assign(F.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Cn(1),gap:M.xl,paddingLeft:oe,paddingRight:oe,justifyContent:"start",alignContent:"start",isolation:"isolate"}),Re?.placement){const e=Re.placement;S=zn(e,oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.display="flex",S.style.flexDirection="column"}else if(_||se()||oo()){const e=!!Re?.defaultOpen;S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display=e?"flex":"none",R()}re(),(Re?.placement??"right")==="left"?(S&&Z.appendChild(S),Z.appendChild(F)):(Z.appendChild(F),S&&Z.appendChild(S));const We=r.ownerDocument.createElement("div");Object.assign(We.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:oe,paddingRight:oe,paddingTop:oe,zIndex:"1",background:w.menuBg}),Le.appendChild(_e),Le.appendChild(H),Ct=ks(r.ownerDocument,()=>cn(!rn())),Le.appendChild(Ct.el),re(),I&&(hn=Ms(r.ownerDocument,"Maps","lot",e=>Ge(e)),Le.appendChild(hn.el)),I&&(St=ba(r.ownerDocument,"Filter\u2026","wmapGalleryFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{qt().then(e=>e.openEditor(St??r,Yt()))}),St.style.order="1",Le.appendChild(St)),We.appendChild(Le),We.appendChild(ye),r.appendChild(We),r.appendChild(Z);function Ft(){ye.innerHTML="";const e=a.plotMode??"hardBin",t=!Ke&&ai.has(e),n=x.filter(b=>b!=null&&!fe.has(b)),o=n.find(b=>b.isLotStack),i=qa(n.map(b=>({metadata:b.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:f.attributes}),s=e==="metadata",l=a.activeMetadataKey,u=t&&!s?Si(n,b=>(e==="softBin"?b.sbin:b.hbin)??void 0,Ce):{counts:new Map,total:0,pass:0},d=t&&!s?a.binColors??K():void 0,m=d?e==="softBin"?d.pass.soft:d.pass.hard:new Set,v=Sa(u.counts.entries(),m).map(([b])=>b),p=t&&s&&l?Si(n,b=>Ts(b.metadata?.[l])):{counts:new Map,total:0,pass:0},c=s?ko()?.values:void 0,g=t&&s?(c??[...p.counts.keys()].sort(jn)).filter(b=>p.counts.has(b)):[];if(_e.innerHTML="",i&&_e.appendChild(i),_e.style.display=i?"flex":"none",!v.length&&!g.length){ye.style.display="none";return}ye.style.display="flex";const h=r.ownerDocument.createElement("div");Object.assign(h.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${M.sm} ${M.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),ye.appendChild(h);const y=Hn(a.highlightBin),E=x.flatMap(b=>b?.metadataFields??[]).find(b=>b.key===l),A=s?E?.label??(l?Za(l):"Metadata"):qs[e],j=r.ownerDocument.createElement("span");if(j.textContent=A,Object.assign(j.style,{fontSize:N.body,fontWeight:"700",letterSpacing:_s,textTransform:"uppercase",color:w.label,flexShrink:"0"}),h.appendChild(j),!s&&u.total>0){const b=u.pass,G=b/u.total*100,we=r.ownerDocument.createElement("span");we.textContent=`Yield ${Nt(G)}`,Object.assign(we.style,{fontSize:N.body,fontWeight:"700",color:w.value,whiteSpace:"nowrap",flexShrink:"0"});const ve=r.ownerDocument.createElement("span");ve.textContent=`${b.toLocaleString()} / ${u.total.toLocaleString()} dies`,Object.assign(ve.style,{fontSize:N.body,color:w.label,whiteSpace:"nowrap",flexShrink:"0"}),h.appendChild(we),h.appendChild(ve)}if(s){const b=Hn(a.highlightMetadataValue);g.forEach((G,we)=>{const ve=b.includes(G),Ye=E?.values?.find(On=>On.value===G),pt=Ye?.color??zs(we),ni=p.counts.get(G)??0;Ci(h,{color:pt,isActive:ve,label:Ye?.label??G,count:ni,percent:p.total>0?ni/p.total*100:void 0,onClick:On=>{const xs=bi(a.highlightMetadataValue,G,On);bo(),P({highlightMetadataValue:xs})}})});return}const ft=e==="softBin"?x.flatMap(b=>b?.sbinDefs??[]):x.flatMap(b=>b?.hbinDefs??[]),Jo=new Set,Bn=[];for(const b of ft)Jo.has(b.bin)||(Jo.add(b.bin),Bn.push(b));const En=Bn.length>0?new Map(Bn.map(b=>[b.bin,b])):null,ei=d??a.binColors??K(),Cs=e==="softBin"?ei.soft:ei.hard,ti=b=>Cs.get(b)??js;for(const b of v){const G=y.includes(b),we=En?.get(b),ve=u.counts.get(b)??0;Ci(h,{color:ti(b),isActive:G,label:we?.name?`${b} \xB7 ${we.name}`:`Bin ${b}`,count:ve,percent:u.total>0?ve/u.total*100:void 0,onMenu:(Ye,pt)=>Ai(e==="softBin"?"soft":"hard",b,Ye,pt),onClick:Ye=>{const pt=bi(a.highlightBin,b,Ye);bo(),P({highlightBin:pt})}})}u.total>0&&v.length>1&&ye.appendChild(sl(r.ownerDocument,[...u.counts.entries()].sort(([,b],[,G])=>G-b).map(([b,G])=>({color:ti(b),count:G,label:En?.get(b)?.name?`${b} \xB7 ${En.get(b).name}`:`Bin ${b}`})),u.total))}function qe(e){const t=B().filter(p=>p!==null&&!fe.has(p));if(!t.length)return[];const n=t.map(p=>p.dies.filter(nl).filter(c=>!c.filteredOut)),o=t[0].wafer,i=t.length,s=oi(t.map(p=>Ue(p)));if(!s)return[];const l=new Set(t.map(p=>ne(p,"renderWaferGallery")));if(l.size!==1)return[];const u=[...l][0],d=o.metadata?{...o,metadata:(({wafer:p,waferId:c,...g})=>g)(o.metadata)}:o;function m(p,c){return{...p,stats:{...p.stats,isLotStack:!0,aggregationMethod:c,lotSize:i}}}function v(p,c){const g=p.map(h=>({...h,hbin:void 0,sbin:void 0}));return $n({wafer:d,dies:g,passBins:[...s],ringCount:u,testDefs:[{testNumber:0,name:c}]},{testNumbers:[0]})}if(e==="stackedValues"){const p=tt();let c=p?.filter(Fn);if(p!==void 0&&c?.length===0)return[];if(p?.length||(c=Ds(t.flatMap(y=>y.dies)).map(y=>({testNumber:y,name:Qa(void 0,y)}))),!c?.length)return[];const g=a.aggregationMethod??"mean";return c.map(h=>{const y=Ma(n,g,h.testNumber),E={testNumber:0,name:h.name,unit:h.unit,...el(h)};return{wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E],label:`${Ja(h,h.testNumber)} \xB7 ${g}`,isLotStack:!0,aggrMethod:g,lotSize:i,statsSummary:m($n({wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E]},{testNumbers:[0]}),g)}})}if(e==="stackedBins"){let p=Vt(t.map(c=>c?.hbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.hbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=pi(n,c.bin,"hard"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,hbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in hard bin ${c.bin}`),"countBin")}})}if(e==="stackedSoftBins"){let p=Vt(t.map(c=>c?.sbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.sbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=pi(n,c.bin,"soft"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,sbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in soft bin ${c.bin}`),"countBin")}})}return t}function $t(e){const t=B().length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:a.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function P(e,{fireCallback:t=!0}={}){const n=Object.keys(e);if(n.length>0&&n.every(c=>Vn.includes(c))){a={...a,...e},be?.setAxisPrefs(In(a)),t&&f.onViewOptionsChange?.(Ht(a),n,An(n));return}Vn.some(c=>c in e)&&be?.setAxisPrefs(In({...a,...e}));const o=a.plotMode,i=mt(a),s=Qe()!==null;a={...a,...e};const l=a.plotMode,u=ie.has(l),d=mt(a),m=o!==void 0&&ie.has(o),v=ke>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const c=K();a={...a,binColors:c},e={...e,binColors:c}}if("compact"in e){const c=Bo();a={...a,compactMap:c},e={...e,compactMap:c}}if(("compact"in e||a.compact&&("rotation"in e||"showXYIndicator"in e))&&zo(),e.plotMode!==void 0)if(u){const c=$t(l);if(a={...a,...c},v)for(const g of C)g&&g.setOptions(e);else X(qe(l))}else if(m){const{valueRange:c,lotSize:g,aggregationMethod:h,...y}=a;if(a=y,v)for(const E of C)E&&E.setOptions(e);else X(d?$e(W.filter(E=>E!==null)):B().filter(E=>E!==null))}else if(i!==d&&!v)X($e(W.filter(c=>c!==null)));else for(const c of C)c&&c.setOptions(e);else if(e.aggregationMethod!==void 0&&l==="stackedValues")if(v)for(const c of C)c&&c.setOptions(e);else X(qe("stackedValues"));else for(const c of C)c&&c.setOptions(e);Qe()!==null!==s&&Kn(),Ft(),Po(),To(),xo();const p=e.plotMode!==void 0&&e.plotMode!==o;(Oa.some(c=>c in e)||p)&&R(),Te(),Wo(),Ro(),un(),dn(),t&&f.onViewOptionsChange?.(Ht(a),n,An(n))}function qo(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:N.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=wi(e,o,t,n,f.attributes);return{wrap:o,metaPanel:s}}function Xo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||Xa(n??{}).length===0)return;const i=o.parentElement,s=r.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const l=wi(r.ownerDocument,s,t,n,f.attributes);l&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(l))}function Mn(e,t,n){const o=r.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,boxShadow:Ln.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:bn(),maxHeight:bn()});const i=r.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm});const{wrap:s,metaPanel:l}=qo(document,ht(e,t),e.wafer.metadata??void 0);i.appendChild(s);const u=r.ownerDocument.createElement("button");u.dataset.wmapExpandBtn="1",u.setAttribute("aria-label","Open full view"),Wn(u),u.innerHTML=Tn.expand,Object.assign(u.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,background:w.panelBg,color:w.label,padding:M.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),Pn(u),i.appendChild(u),i.addEventListener("click",c=>{(c.ctrlKey||c.metaKey)&&(c.preventDefault(),c.stopPropagation(),Ii(x.indexOf(e)))},!0),o.appendChild(i);const d=r.ownerDocument.createElement("div");Object.assign(d.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(d),jo(o,d),l&&d.appendChild(l),F.appendChild(o),o.addEventListener("contextmenu",c=>{if(c.defaultPrevented)return;c.preventDefault();const g=e.viewOptions?{...a,...e.viewOptions}:a,h=sn()??go(t),y=h?.source??Da(e.dies,{waferLabel:Se(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:g.plotMode==="value"?g.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:Ce(e),ringCount:ne(e,"renderWaferGallery")}),E={x:c.clientX,y:c.clientY};import("./drilldown.js").then(({openDrilldownMenu:A})=>{o.isConnected&&A(E,o,y,h?{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...h.ctx}:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:p.getSaveImageHook(),onSaveText:p.getSaveTextHook(),onLocateDie:j=>ge(t,j)})})});const m=bt||Qe()!==null,v=e.viewOptions?{...a,...e.viewOptions}:a,p=mi(d,e,{viewOptions:{...v,showLegend:m,legendPosition:Ze},showTooltip:!0,padding:z,statsSummary:e.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:e.onClick,onSelect:co(e),drilldownSourceOverride:()=>Ri(t),insights:de,onExpand:()=>ut(t,e),showIdentity:!1,chromeInset:Gs,drawWhenVisible:!0});return p.setViewControlsVisible(!1),p.setSummaryVisible(!1),u.onclick=()=>ut(t,e),fe.has(e)&&(o.style.display="none"),{card:o,ctrl:p,canvasWrapper:d,expandBtn:u}}function ys(e){const t=Fe[e];if(!t)return;const n=[...Q.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Tn.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>ws(n.id)):(t.innerHTML=Tn.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>ut(e,x[e]))}function X(e){vs(),ot()?.remove(),it(null),Oe(),x=[],U.clear(),ln.clear(),ee.style.display="none";for(const d of C)d&&d.destroy();C=[],ue=[],Fe=[],ke=0,F.innerHTML="",_o=e.length,vn(e.map(d=>typeof d=="function"?null:d));const t=[];for(let d=0;d<e.length;d++){const m=e[d];if(typeof m=="function"){const v=r.ownerDocument.createElement("div");v.className="wmap-gallery-card",Object.assign(v.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const p=r.ownerDocument.createElement("span");p.textContent="\u2026",Object.assign(p.style,{color:w.label,fontSize:"18px"}),v.appendChild(p),F.appendChild(v),x.push(null),C.push(null),ue.push(null),Fe.push(null),t.push({index:d,factory:m,placeholder:v}),ke++}else{const{ctrl:v,canvasWrapper:p,expandBtn:c}=Mn(m,d,e.length);x.push(m),C.push(v),ue.push(p),Fe.push(c)}}Oo(),Ft(),un(),dn(),Eo();const n=++nt,o=()=>{setTimeout(()=>{n===nt&&f.onItemsResolved?.()},0)},i=d=>{setTimeout(()=>{n===nt&&f.onItemResolved?.(d,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let l=0;function u(){if(n!==nt)return;if(l>=t.length){if(ie.has(a.plotMode)){const A=a.plotMode;X(qe(A));return}if(wt){Ut();return}at=o,R(),ze||(at=null,o());return}const{index:d,factory:m,placeholder:v}=t[l++],p=m();W[d]=p;const c=Gt(p,d);Je(p,d)!==p&&(ae=!0),x[d]=c,vn([c]);const{card:g,ctrl:h,canvasWrapper:y,expandBtn:E}=Mn(c,d,e.length);C[d]=h,ue[d]=y,Fe[d]=E,ke--,v.replaceWith(g),i(++s),Zi(),Ui(),!S&&!Re?.placement&&c.statsSummary?.findings.length&&(S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display="none",(Re?.placement??"right")==="left"?Z.insertBefore(S,F):Z.appendChild(S),R(),re()),re(),setTimeout(u,0)}t.length>0?setTimeout(u,0):o()}if(ie.has(a.plotMode)&&B().length>0){const e=$t(a.plotMode);a={...a,...e},X(qe(a.plotMode))}else X($e(k));f.insights?.filter!==void 0&&qt(),Te();let Xe=0;const Yo=new(r.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Xe)return;Xe=(r.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Xe=0,O==null&&xn()})});Yo.observe(F);const Uo=()=>{r.style.setProperty("--wmap-sticky-top",`${We.offsetHeight}px`)};Uo();const Zo=new(r.ownerDocument.defaultView??window).ResizeObserver(Uo);Zo.observe(We),S&&R();function bs(e,t){const n=ue[e];if(!n)return;n.innerHTML="",Object.assign(n.style,{alignItems:"center",justifyContent:"center"});const o=r.ownerDocument.createElement("span");o.textContent=t?"Opened in its own window":"Opened in the wafer viewer",Object.assign(o.style,{color:w.label,fontSize:N.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function ut(e,t){for(const l of Q.values())if(l.cardIndex===e)return;const n=ht(t,e),o=Di++,i=C[e]?.getOptions(),s=Qs(n);if(s){const l=s.document;l.title=n,Object.assign(l.documentElement.style,{height:"100%"}),Object.assign(l.body.style,{margin:"0",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",fontFamily:N.family}),ta(r,l.documentElement);const u=na(r,l.documentElement,()=>y.setOptions({})),d=l.createElement("div");d.dataset.wmapWindowBanner="1",d.textContent=n,Object.assign(d.style,{display:"none",padding:`${M.sm} ${M.xl}`,fontSize:N.body,fontWeight:"700",background:w.warnBg,color:w.warnText,borderBottom:`1px solid ${w.warnBorder}`,flexShrink:"0"}),l.body.appendChild(d);const m=l.createElement("div");Object.assign(m.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),l.body.appendChild(m);const{wrap:v,metaPanel:p}=qo(l,n,t.wafer.metadata??void 0),c=l.createElement("div");Object.assign(c.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm}),c.appendChild(v),m.appendChild(c);const g=l.createElement("div");Object.assign(g.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),p&&g.appendChild(p),m.appendChild(g);let h=0;const y=kn(g,t,void 0,i,(A,j)=>{const ft=A?j:-h;try{s.resizeBy(ft,0),h=A?j:0}catch{}}),E=setInterval(()=>{s.closed&&It(o)},400);s.addEventListener("pagehide",()=>It(o)),Q.set(o,{id:o,ctrl:y,cardIndex:e,label:n,closePollId:E,stopThemeSync:u,close:()=>{s.closed||s.close()},setTitle:A=>{l.title=A,d.textContent=A,d.style.display="block"}})}else{const l=Js({title:n,onClose:()=>It(o),anchor:r});l.contentWrap.style.flexDirection="column",Xo(l,n,t.wafer.metadata??void 0);const u=kn(l.contentWrap,t,void 0,i,ui(l));Q.set(o,{id:o,ctrl:u,cardIndex:e,label:n,closePollId:null,close:()=>l.close(),setTitle:d=>{const m=l.box.querySelector("[data-wmap-window-title]");m&&(m.textContent=d,m.title=d)}})}C[e]?.destroy(),C[e]=null,bs(e,s!==null),ys(e)}function kn(e,t,n,o,i){const s=t.viewOptions?{...a,...t.viewOptions}:a,l=o?{...s,...o}:s,d={...n!==void 0?{...l,plotMode:"value",activeTest:n}:l,showLegend:!0,legendPosition:Ze},m=mi(e,t,{viewOptions:d,showTooltip:!0,padding:z,statsSummary:t.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:t.onClick,onSelect:co(t),insights:de,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return m.setViewControlsVisible(!0),m.setSummaryVisible(!0),m.setExpandVisible(!1),m}function It(e){const t=Q.get(e);if(!t||(Q.delete(e),t.closePollId!=null&&clearInterval(t.closePollId),t.stopThemeSync?.(),t.ctrl.destroy(),t.cardIndex===null))return;const n=t.cardIndex,o=x[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:l,expandBtn:u}=Mn(o,n,x.length);ue[n]?.parentElement?.replaceWith(i),C[n]=s,ue[n]=l,Fe[n]=u}function ws(e){const t=Q.get(e);t&&(t.close(),It(e))}function vs(){for(const e of Q.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function Dn(){for(const e of C)e?.drawPendingNow()}const Qo=r.ownerDocument.defaultView??window;Qo.addEventListener("beforeprint",Dn);function Ss(){Dn();const e=[...F.querySelectorAll("canvas")];if(!e.length)return;const t=e.length,n=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/n),i=e[0].width,s=e[0].height,l=8,u=(r.ownerDocument.defaultView??window).devicePixelRatio||1,d=Math.round(26*u),m=Math.round(12*u),v=r.ownerDocument.createElement("canvas");v.width=n*i+(n-1)*l,v.height=o*(s+d)+(o-1)*l;const p=v.getContext("2d"),c=Ns(F);p.fillStyle=c.background,p.fillRect(0,0,v.width,v.height),e.forEach((g,h)=>{const y=h%n,E=Math.floor(h/n),A=y*(i+l),j=E*(s+d+l),ft=g.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";p.fillStyle=c.surface,p.fillRect(A,j,i,d),p.fillStyle=c.text,p.font=`700 ${m}px system-ui, sans-serif`,p.textAlign="left",p.textBaseline="middle",p.fillText(ft,A+Math.round(10*u),j+d/2,i-Math.round(20*u)),p.drawImage(g,A,j+d)}),v.toBlob(g=>{if(!g)return;const h=C.find(y=>y!=null)?.getExportTitle();ra(g,["gallery",h].filter(Boolean).join(" "),V.onSaveImage)})}return{setItems(e){tn(),W=e.map(n=>typeof n=="function"?null:n);const t=a.plotMode;if(ie.has(t))if(e.some(o=>typeof o=="function"))X($e(e));else{const o=$t(t);a={...a,...o},X(qe(t))}else X($e(e));Jn()},setOptions(e){P(e,{fireCallback:!1})},getOptions(){return Ht(a)},setFindingsNotice(e){lo=e,R()},setColumns(e){Sn(e)},getBinColors(){return a.binColors??K()},setLotStatsSummary(e){tn(),_=e,Jn(),Te(),S&&R(),re()},openUserGuide:()=>gn(),destroy(){rs(),$.flush(),tn(),nt++,Qo.removeEventListener("beforeprint",Dn),r.ownerDocument.removeEventListener("keydown",Ko),ze?.cancel(),ze=null,at=null;for(const e of[...Q.values()])e.closePollId!=null&&clearInterval(e.closePollId),e.close(),e.ctrl.destroy();Q.clear();for(const e of C)e&&e.destroy();C=[],ot()?.remove(),Yo.disconnect(),Zo.disconnect(),Xe&&((r.ownerDocument.defaultView??window).cancelAnimationFrame(Xe),Xe=0),r.ownerDocument.removeEventListener("click",Mt,!0),window.removeEventListener("blur",ao),xi(),li(),We.remove(),Z.remove(),S?.remove(),_t=!0,vt++,clearTimeout(Xt),pe?.el.remove(),be?.destroy()}}}
1
+ import{createViewSwitch as Ms}from"./viewSwitch.js";import{createSummaryToggle as ks}from"./summaryToggle.js";import{getUniqueTestNumbers as Ds,resolveTestNumber as Bs,findTestDef as Es,collectMetadataValues as Os}from"../renderer/buildView.js";import{metadataCategoricalValue as Ts}from"../core/metadata.js";import{resolveBinColorsForMaps as Ls,mergeBinDefs as Vt,binColorWarning as Ps,mixedPassBinsWarning as Ws,binColorsEqual as Rs}from"../renderer/binColors.js";import{commonPassBins as oi,itemPassBins as Ue}from"../core/passBins.js";import{PAT_MODE_FIELD as As,PAT_MODE_KEY as Fs,PAT_MODE_ORDER as $s,isPatMode as mt,patModeOffered as Is,withPatField as Vs,withPatVerdicts as Hs}from"./patMode.js";import{requireRingCount as ne}from"../core/ringCount.js";import{NO_DATA_FILL as js}from"../renderer/colorMap.js";import{metadataValueColor as zs}from"../renderer/colorMap.js";import{resolveCanvasTheme as Ns}from"./canvasTheme.js";import{ICONS as Tn}from"./icons.js";import{SHADOW as Ln,LEADING as ii,TRACKING as _s,controlStyle as Ks,wireControlHover as Pn,SPACE as M,EDGE_GUTTER as oe,MAP_CHROME_INSET as Gs,RADIUS as Y,FONT as N,CLR as w,sevColor as si,MODE_LABELS as qs,BIN_LEGEND_MODES as ai,STACKED_MODES as ie,applyOverlayZ as Xs,getTooltip as Ys,hideTooltip as li,createToolbarHelpers as Us,buildModeMenuEl as Zs,openDetachWindow as Qs,openFloatingWindow as Js,openModal as ea,copyWmapThemeTokens as ta,syncWmapPopupTheme as na,makePaletteBtn as oa,makeLogScaleBtn as ia,makeLegendStyleBtn as sa,makeOverlaysBtn as aa,makeOrientationBtn as la,menuLayerFor as ri,saveImageBlob as ra,markMenuTrigger as gt,wireMenuA11y as ci,wireTooltip as Wn,requestedPassFailDisplay as di,overlayMenuRows as ca,anyOverlayActive as da,openCompactDiagnostics as ua,roomForPanel as ui,logWmapVersionOnce as fa,buildDataModeEntries as pa,metadataKeyHasData as ma,metadataModeEntry as fi}from"./toolbar.js";import{openReportModal as ga,openUserGuideWindow as ha,registerGuideOpener as ya}from"./guideWindow.js";import{waferDisplayLabel as ht,waferIdentityLabel as Se}from"../core/waferLabel.js";import{bandButton as ba}from"./filterButton.js";import{metadataDisplayValue as wa}from"../core/metadata.js";import{withExportContext as va}from"./exportName.js";import{sortBinsForDisplay as Sa}from"../stats/binPareto.js";import{diePassStatus as Ca,isYieldEligibleDie as xa}from"../core/dies.js";import{aggregateValues as Ma,aggregateBinCounts as pi}from"../core/aggregates.js";import{renderWaferMap as ka,renderWaferMapCard as mi,toPublicViewOptions as Ht}from"./renderWaferMap.js";import{waferPopulation as Da,selectionPopulation as Ba,LOT_STACK_REASON as Rn}from"./chartPopulation.js";import{sourceFromBins as gi}from"./plotItems.js";import{plotStoreFor as Ea}from"./plotStore.js";import{classifyChanged as An,COLOR_KEYS as Oa,findingBin as Ta,findingPlotMode as La}from"./renderWaferMap.js";import{findingPatternKey as hi}from"../stats/filterFindings.js";import{synthesisSource as Pa}from"../stats/synthesis.js";import{buildWaferMap as Wa,computeCoverage as Ra,computeYield as Aa,defaultBinMode as Fa,getTestPassStatus as yi,isParametricTest as Fn,getDieTestValue as $a,isBuiltMap as Ia}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as $n}from"../stats/analyzeWaferMap.js";import{lotTestValueStatus as Va}from"../stats/testValueBudget.js";import{testValueNotice as Ha}from"./testValueOffer.js";import{axisPrefsFromOptions as In,optionsFromAxisPrefs as ja,CHART_PREF_KEYS as Vn}from"./chartPrefs.js";import{collectWarnings as za,buildWarningsMenuEl as Na,severityOf as _a}from"./warnings.js";import{asList as Hn,compareNatural as jn,arrayEqual as jt,toggleHighlight as bi}from"../core/utils.js";import{buildCompactMap as Ka,compactLayoutOffered as Ga}from"../core/compact.js";import{attachExpandableMetadata as wi}from"./identityHeader.js";import{createSummaryPanelEl as zn,buildMetadataStripRow as qa,metadataEntries as Xa,renderLotSummaryContentSteps as Ya,reportMapsFromItems as Ua}from"./summaryPanel.js";import{prettyKey as Za}from"../stats/facets.js";import{testLabel as Qa,markedTestLabel as Ja,derivedFields as el}from"../renderer/testLabel.js";import{mergeTestDefs as tl}from"../stats/mergeTestDefs.js";import{getDieKey as zt,hasPosition as nl}from"../core/dies.js";import{testValue as ol}from"../core/dieTable.js";import{runChunked as il}from"./chunked.js";function vi(r){if(typeof r!="number"||!Number.isFinite(r))return;const k=Math.round(r);return k>=1?k:void 0}const Nn=12;function sl(r,k,f){let z=k;if(k.length>Nn){const D=k.slice(0,Nn-1),T=k.slice(Nn-1),I=T.reduce(($,de)=>$+de.count,0);z=[...D,{color:w.label,count:I,label:`Other (${T.length} bins)`}]}const O=r.createElement("div");Object.assign(O.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:Y.control,overflow:"hidden",border:`1px solid ${w.menuBorder}`,boxSizing:"border-box",marginTop:M.xs,flexShrink:"0"}),O.setAttribute("role","img"),O.setAttribute("aria-label",`Population split: ${z.map(D=>`${D.label} ${Nt(D.count/f*100)}`).join(", ")}`);for(const D of z){const T=D.count/f*100,I=r.createElement("div");Object.assign(I.style,{flex:`${T} 1 0`,minWidth:T>0?"2px":"0",background:D.color}),Wn(I,`${D.label} \xB7 ${D.count.toLocaleString()} dies \xB7 ${Nt(T)}`),O.appendChild(I)}return O}function Nt(r){return r>0&&r<.1?"<0.1%":`${r.toFixed(1)}%`}function Si(r,k,f){const z=new Map;let O=0,D=0;for(const T of r){const I=f?new Set(f(T)):void 0;for(const $ of T.dies){if(!xa($))continue;const de=k($);de!==void 0&&(z.set(de,(z.get(de)??0)+1),O++,I&&Ca($,I)&&D++)}}return{counts:z,total:O,pass:D}}function Ci(r,k){const f=r.ownerDocument.createElement("div");Object.assign(f.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${M.xxs} ${M.xs}`,borderRadius:Y.control});const z=r.ownerDocument.createElement("span");Object.assign(z.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:k.color,border:k.isActive?`2px solid ${w.iconActive}`:`1px solid ${w.menuBorder}`,borderRadius:Y.control,boxSizing:"border-box"});const O=r.ownerDocument.createElement("span");if(O.textContent=k.label,Object.assign(O.style,{fontWeight:k.isActive?"700":"400",color:k.isActive?w.iconActive:w.text,whiteSpace:"nowrap"}),f.appendChild(z),f.appendChild(O),k.count!==void 0){const D=r.ownerDocument.createElement("span");if(D.textContent=k.count.toLocaleString(),Object.assign(D.style,{color:k.isActive?w.iconActive:w.text,fontWeight:k.isActive?"700":"400",whiteSpace:"nowrap"}),f.appendChild(D),k.percent!==void 0){const T=r.ownerDocument.createElement("span");T.textContent=Nt(k.percent),Object.assign(T.style,{color:w.label,whiteSpace:"nowrap"}),f.appendChild(T)}}if(f.setAttribute("role","button"),f.setAttribute("aria-pressed",k.isActive?"true":"false"),f.tabIndex=0,f.addEventListener("mouseenter",()=>{f.style.background=w.bgHover}),f.addEventListener("mouseleave",()=>{f.style.background="transparent"}),f.addEventListener("focus",()=>{f.style.background=w.bgHover}),f.addEventListener("blur",()=>{f.style.background="transparent"}),f.addEventListener("click",D=>k.onClick(D.ctrlKey||D.metaKey)),f.addEventListener("keydown",D=>{if(D.key==="Enter"||D.key===" ")D.preventDefault(),k.onClick(D.ctrlKey||D.metaKey);else if(k.onMenu&&(D.key==="ContextMenu"||D.key==="F10"&&D.shiftKey)){D.preventDefault();const T=f.getBoundingClientRect();k.onMenu({x:T.left+T.width/2,y:T.bottom},f)}}),k.onMenu){const D=k.onMenu;f.addEventListener("contextmenu",T=>{T.preventDefault(),D({x:T.clientX,y:T.clientY},f)}),Wn(f,"Right-click: charts and tables for these dies")}r.appendChild(f)}export function renderWaferGallery(r,k,f={}){fa();const z=6;let O=vi(f.columns);const D=f.showHelpButton??!1,T=f.userGuideExtension,I=f.insights?.enabled??!0,$=Ea(f.insights),de={enabled:!1,plotStore:$},xi=Xs(f.zIndex),Re=f.summaryPanel,Ce=e=>[...Ue(e)],_n=()=>W.flatMap(e=>e?[ne(e,"renderWaferGallery")]:[]),yt=()=>_n()[0];function Mi(e){const t=[...new Set(e)].sort((n,o)=>n-o);return t.length<2?null:{code:"ring-count-mixed",severity:"warning",message:`These wafers were built with different ring counts (${t.join(", ")}). Each card and each wafer's findings use their own; the lot's ring yield in the Summary panel, report and Insights uses ${e[0]} rings.`}}let _=f.lotStatsSummary,Ae;const se=()=>ae?Ae:_;let Ze=f.viewOptions?.legendPosition??"default",bt=f.perCardLegend??!1;function Qe(){const e=a.plotMode??"hardBin";return ai.has(e)?null:a.colorbarRangeMode==="data"?"Each map has its own value range, so it keeps its own colour bar":"These wafers have no shared colour bar for value mode, so each map keeps its own"}function Kn(){const e=bt||Qe()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let a={plotMode:Fa(k.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...f.viewOptions},C=[],ue=[],Fe=[],x=[];const V=va(()=>{const e=x.filter(n=>n!=null),t=[...new Set(e.map(n=>wa(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(jn);return{prefix:f.downloadFilename,lots:t,...e.length===1?{wafer:Se(e[0])}:{waferCount:e.length}}},f.onSaveImage,f.onSaveText);let W=k.map(e=>typeof e=="function"?null:e),q=null,Gn=null,_t=!1,xe=0,ae=!1,wt=!1;const fe=new WeakSet,qn=new WeakMap,Me=()=>{const e=q?.get();return!!e&&!e.off};function Xn(e,t){return{dies:e.dies,wafer:e.wafer,label:ht(e,t),identity:Se(e),waferIndex:t,passBins:Ue(e),testDefs:e.testDefs,statsSummary:e.statsSummary}}const Kt=new Map;function Je(e,t){if(!q||!Me())return e;const n=qn.get(e);if(n&&n.v===xe)return n.item;const o=q.mark([Xn(e,t)]);let i=e;if(o.narrowing){const s=o.items[0].dies,l=s.filter(u=>!u.filteredOut);i={...e,dies:s,statsSummary:Kt.get(e),...e.yield?{yield:Aa(s,[...Ue(e)],e.yield.yieldPercentGross!=null?"denominator-only":"exclude")}:{},...e.dataCoverage?{dataCoverage:Ra(l)}:{}},o.hidden.size&&fe.add(i)}return qn.set(e,{v:xe,item:i}),i}const Yn=new WeakMap;function Gt(e,t){const n=Je(e,t);if(!mt(a))return n;const o=Yn.get(n);if(o)return o;const i={...n,dies:Hs(n.dies,n.testDefs,Ue(n)),metadataFields:Vs(n.metadataFields)};return fe.has(n)&&fe.add(i),Yn.set(n,i),i}const Un=new WeakMap;function ki(e,t){if(!q||!Me())return e;const n=Un.get(e);if(n&&n.v===xe)return n.item;const o=Je(e,t),i=o===e?e:fe.has(o)?null:{...o,dies:o.dies.filter(s=>!s.filteredOut)};return Un.set(e,{v:xe,item:i}),i}function B(){return!q||!Me()?W:W.map((e,t)=>e?ki(e,t):null)}let vt=0,et=!1;function Zn(){const e=++vt;Ae=void 0,Kt.clear();const t=()=>{et=!1,R(),re()};if(!ae){t();return}const n=Jt();if(!n||!(_||n.some(s=>s.statsSummary))){t();return}const o=B().flatMap((s,l)=>s?[{it:s,i:l}]:[]);if(o.length===0){t();return}et=!0;const i=_?.analysisOptions??n.find(s=>s.statsSummary)?.statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(async({analyzeWaferLotAsync:s,remapLotWaferIndices:l})=>{const u=await s(o.map(m=>m.it),i);if(e!==vt||_t)return;const d=o.map(m=>m.i);Ae=l(u,d),u.perWafer.forEach((m,v)=>Kt.set(W[d[v]],m.summary)),xe++,W.forEach((m,v)=>{if(!m||ie.has(a.plotMode))return;const p=Gt(m,v);x[v]=p,C[v]?.setStatsSummary(p.statsSummary)}),Te(),t()}).catch(()=>{e===vt&&t()})}const $e=e=>q&&Me()||mt(a)?e.map((t,n)=>typeof t=="function"?t:Gt(t,n)):e;function qt(){return Gn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const t=e({doc:r.ownerDocument,initial:f.insights?.filter,onChange:f.insights?.onFilterChange,savedFilters:f.insights?.savedFilters,onSavedFiltersChange:f.insights?.onSavedFiltersChange,pickFiltersFile:f.insights?.onPickFiltersFile,onSaveText:f.onSaveText,attributes:f.attributes,getRingCount:()=>ne({ringCount:yt()},"the page filter")});return _t||(q=t,pe=t.createBand(()=>Yt(),{marginLeft:oe,marginRight:oe,marginBottom:M.lg}),r.insertBefore(pe.el,Z),t.subscribe(Ut),t.get()&&Ut()),t}),Gn}let pe=null,St=null,Xt;const Yt=()=>W.flatMap((e,t)=>e?[Xn(e,t)]:[]);function Qn(){clearTimeout(Xt),Xt=setTimeout(()=>{if(!q||!pe)return;const e=Yt(),t=q.keep(e);pe.refresh(t.result,e),pe.el.style.display=q.get()&&!Ke?"":"none"},0)}function Jn(){if(q){if(ke>0){Me()&&(wt=!0);return}xe++,ae=Me()&&W.some((e,t)=>e!==null&&Je(e,t)!==e),Ae=void 0,et=ae&&!!_,Zn()}}function Ut(){if(xe++,ae=!1,ke>0){wt=!0,Qn();return}wt=!1;const e=a.plotMode;ae=Me()&&W.some((t,n)=>t!==null&&Je(t,n)!==t),Ae=void 0,et=ae&&!!_,W.length>0&&(ie.has(e)?(a={...a,...$t(e)},X(qe(e))):X($e(W.filter(t=>t!==null)))),Qn(),Zn()}function Ie(){return tl(B())}function tt(){if(B().some(e=>e?.testDefs?.length))return Ie().defs}let nt=0,ke=0;const Q=new Map;let Di=0,Ct=null,J=null,me=null,Ve=null;function xt(){J===null&&me===null&&(Ve={plotMode:a.plotMode,activeTest:a.activeTest})}function eo(){Ve&&P({...Ve},{fireCallback:!1}),Ve=null}let to=new Set,S=null,Bi={};function no(e){return B()[e]?.statsSummary??se()?.perWafer.find(t=>t.waferIndex===e)?.summary}function oo(){return!!(B().some(e=>e?.statsSummary?.findings.length)||se()?.perWafer.some(e=>e.summary.findings.length))}const Ei=Ys(),He=Us(Ei),{makeBtn:je,setActive:io,makeSep:De,syncSeparators:Zt,syncToolbarVisible:Qt,makeMenuRow:Oi,makeMenuSection:Ti,makeDropdown:so,closeOpenMenu:Mt,getOpenMenu:ot,setOpenMenu:it}=He;r.ownerDocument.addEventListener("click",Mt,!0);const ao=()=>li();window.addEventListener("blur",ao);let lo=f.findingsNotice,Be=null;function Jt(){const e=W;return e.length>0&&e.every(t=>t!=null&&Ia(t))?e:null}function Li(){return _?.stats.testValueAnalysis??Va(B().flatMap(e=>e?.statsSummary?[e.statsSummary]:[]))}const en=()=>lo??(Jt()?Ha(Li(),B().length,Be!==null,Pi):void 0);function Pi(){const e=Jt();if(Be||!e)return;const t=new AbortController;Be=t,R();const n=_?.analysisOptions??e[0].statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(({analyzeWaferLotAsync:o})=>o(e,{...n,enableTestValueAnalysis:!0,signal:t.signal})).then(o=>{if(t.signal.aborted)return;Be=null;const i=o.perWafer.map(s=>s.summary);W=W.map((s,l)=>s&&{...s,statsSummary:i[l]}),ie.has(a.plotMode)||(x=x.map((s,l)=>s&&{...s,statsSummary:i[l]}),C.forEach((s,l)=>s?.setStatsSummary(i[l]))),_=o,Te(),R(),re(),f.onStatsSummaryChange?.({summaries:i,lotStatsSummary:o})}).catch(o=>{if(!t.signal.aborted)throw Be=null,R(),o})}function tn(){Be?.abort(),Be=null}function ro(e){to=new Set(e);const t=[...F.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=to.has(i);o.style.outline=s?`3px solid ${w.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function nn(){ro([])}let kt=!1;function on(){kt=!0;for(const e of C)e&&e.clearSelection();kt=!1}function co(e){return t=>{!kt&&(J!==null||me!==null)&&(Ve=null,Oe(),R()),ln.set(e,t.length),le&&!st&&!kt&&Wi(e,t),e.onSelect?.(t)}}function ge(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),F.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let le=!1,st=!1,Ee=new Set;function Wi(e,t){st=!0;try{Ee=new Set(t.map(n=>zt(n))),x.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>Ee.has(zt(s))))})}finally{st=!1}Lt()}function uo(){Ee=new Set,st=!0;try{for(const e of C)e?.clearSelection()}finally{st=!1}Lt()}function sn(){if(!le||Ee.size===0)return;const e=[];let t=!1;if(x.forEach((i,s)=>{if(!i)return;const l=i.dies.filter(u=>Ee.has(zt(u)));l.length!==0&&(i.isLotStack&&(t=!0),e.push({label:Se(i)??i.label??`Wafer ${s+1}`,dies:l,waferIndex:s,wafer:i.wafer,passBins:Ce(i),ringCount:ne(i,"renderWaferGallery")}))}),e.length===0)return;const n=Ie(),o=a;return{source:{items:e,population:e.length===1?`selected on ${e[0].label}`:`selected at the same die positions on ${e.length} wafers`,testDefs:n.defs,activeTest:o.plotMode==="value"?o.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>ge(s,i)}}}function fo(){const e=[];let t=!1;if(x.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:Se(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:Ce(o),ringCount:ne(o,"renderWaferGallery")}))}),e.length<2)return;const n=a;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:Ie().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(o,i)=>ge(i,o)}}}function Ri(e){const t=sn()??go(e);if(t)return t;const n=fo(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function an(e,t,n){J!==e&&t.click();const o=S;if(!o)return;const i=se()?.findings.find(l=>l.id===e),s=sn()??fo()??Fi()??(i?po(ho(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:l})=>{o.isConnected&&l(n,o,s.source,{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...s.ctx})})}function Ai(e,t,n,o){const i=Hn(a.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],l=[];let u=!1;x.forEach((g,h)=>{g&&(g.isLotStack&&(u=!0),l.push({label:Se(g)??g.label??`Wafer ${h+1}`,dies:g.dies,waferIndex:h,wafer:g.wafer,passBins:Ce(g),ringCount:ne(g,"renderWaferGallery")}))});const d=Ie().defs,m=gi(l,e,s,d,void 0,u);if(!m)return;const v={plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(g,h)=>ge(h,g)},p=s.length>1?gi(l,e,[t],d,void 0,u):null,c=p?{...v,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:p,ctx:v}}:v;import("./drilldown.js").then(({openDrilldownMenu:g})=>{o.isConnected&&g(n,o,m,c)})}function po(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((l,u)=>l-u)){const l=x[s];l&&(l.isLotStack&&(o=!0),n.push({label:Se(l)??l.label??`Wafer ${s+1}`,dies:l.dies,waferIndex:s,wafer:l.wafer,passBins:Ce(l),ringCount:ne(l,"renderWaferGallery")}))}if(n.length===0)return;const i=a;return{source:{items:n,population:n.length===1?`on ${n[0].label}`:`on ${n.length} ${t}wafers`,testDefs:Ie().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(s,l)=>ge(l,s)}}}function Fi(){let e;for(let i=0;i<C.length;i++)if((C[i]?.getSelectedDies().length??0)!==0){if(e!==void 0)return;e=i}const t=e===void 0?void 0:x[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=a;return{source:Ba(n,{waferLabel:Se(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:Ce(t),ringCount:ne(t,"renderWaferGallery")}),ctx:{onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>ge(s??e,i)}}}function $i(e){e||uo(),le=e,Lt()}function Dt(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=x[i],l=C[i];if(!s||!l)continue;const u=s.dies.filter(d=>n.has(zt(d)));l.setSelection(u)}}const U=new Set,ln=new Map;function mo(){[...F.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=U.has(o)?`2px solid ${w.iconActive}`:"",n.style.outlineOffset=U.has(o)?"-2px":""});const t=U.size;ee.style.display=t>0?"":"none",ee.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,ee.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function Ii(e){e<0||(U.has(e)?U.delete(e):U.add(e),mo())}function Vi(){U.clear(),mo()}function go(e){if(!(U.size===0||!U.has(e))){for(const t of ln.values())if(t>0)return;return po([...U],"picked ")}}function Hi(){const e=[];for(let t=0;t<B().length;t++){const n=B()[t];if(!n)continue;const o=no(t)?.findings??[];o.length&&e.push({index:t,item:n,unusualCount:o.filter(i=>i.severity==="unusual").length,notableCount:o.filter(i=>i.severity==="notable").length,totalCount:o.length})}return e}function ji(e){const t=x[e]??B()[e];t&&ut(e,t)}function zi(e){const t=no(e)?.findings??[];if(t.length)return{total:t.length,unusual:t.filter(n=>n.severity==="unusual").length,notable:t.filter(n=>n.severity==="notable").length}}function Ni(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{ga(e(Ua(B(),yt())),{anchor:r})})}function _i(){if(!S)return;S.innerHTML="";const e=Hi();if(B().length>0){const n=r.ownerDocument.createElement("div"),o=e.length,i=B().filter(Boolean).length;n.textContent=o===0?`No findings on any of the ${i} wafers`:`${o} of ${i} wafer${i===1?"":"s"} with findings`,Object.assign(n.style,{fontSize:N.body,color:w.label,marginBottom:M.md}),S.appendChild(n)}if(e.length>0){const n=r.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{...Ks("outlined"),marginBottom:M.lg,display:"block",width:"100%",textAlign:"left"}),Pn(n),n.addEventListener("click",Ni),S.appendChild(n)}if(e.length===0){const n=r.ownerDocument.createElement("div");Object.assign(n.style,{color:w.icon,fontSize:N.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",S.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:l}of e){const u=i?"unusual":s?"notable":"info",d=i+s||l,m=r.ownerDocument.createElement("button");m.type="button",Object.assign(m.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:M.xs,border:"none",borderLeft:`3px solid ${si(u)}`,borderRadius:Y.control,background:w.bgHover,cursor:"pointer",fontSize:N.body,textAlign:"left",boxSizing:"border-box"}),m.addEventListener("mouseover",()=>{m.style.background=w.bgActive}),m.addEventListener("mouseout",()=>{m.style.background=w.bgHover});const v=r.ownerDocument.createElement("span");v.textContent=ht(o,n),Object.assign(v.style,{color:w.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const p=r.ownerDocument.createElement("span");p.textContent=String(d),m.setAttribute("aria-label",`${ht(o,n)} \u2014 ${d} finding${d===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(p.style,{marginLeft:M.sm,flexShrink:"0",background:si(u),color:"#fff",borderRadius:Y.container,padding:"1px 5px",fontSize:N.body,fontWeight:"600"}),m.appendChild(v),m.appendChild(p),m.addEventListener("click",()=>ut(n,o)),S.appendChild(m)}const t=r.ownerDocument.createElement("div");t.style.height="12px",S.appendChild(t)}let ze=null,at=null;function R(){if(!S||ae&&_&&!Ae&&et)return;ze?.cancel(),ze=null;const e=se();if(e){const t=Vt(B().map(o=>o?.hbinDefs)),n=Vt(B().map(o=>o?.sbinDefs));ze=il(Ya(S,{lotSummary:e,items:B(),hbinDefs:t.length?t:void 0,sbinDefs:n.length?n:void 0,testDefs:tt(),ringCount:yt(),binColors:a.binColors,plotMode:a.plotMode??"hardBin",fallbackFormat:a.fallbackFormat,activeFindingId:J,warnings:f.warnings?.display??!0?he:[],findingsFilter:Bi,findingsNotice:en(),onFindingsFilterChange:R,onSaveText:V.onSaveText,attributes:f.attributes,onFindingClick:(o,i)=>{J===o.id?(Oe(),eo()):(xt(),So(o,i)),R()},activeTest:me,onTestClick:o=>{const i=me===o;i||xt(),Oe(),i?eo():vo(o),R()},onShowChart:I?o=>{Ge(!0),Io().then(i=>i?.showWorthCard(o))}:void 0,onWaferClick:ji,findingsFor:zi,dieListOptions:f.dieList,onLocateDie:(o,i)=>ge(i,o),onClose:()=>cn(!1)}),{onDone:()=>{const o=at;at=null,o?.()}})}else _i()}function ho(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let Bt=[];function yo(){if(Bt.length!==0){for(const e of Bt)C[e]?.setOptions({plotMode:a.plotMode,activeTest:a.activeTest});Bt=[]}}function Oe(){J=null,me=null,nn(),on(),yo(),P({highlightBin:void 0},{fireCallback:!1})}function bo(){J===null&&me===null||(Ve=null,Oe(),R())}function wo(e,t){const n=tt();if(n===void 0||n.some(i=>i.testNumber===e))P({plotMode:"value",activeTest:e,highlightBin:void 0},{fireCallback:!1});else{P({highlightBin:void 0},{fireCallback:!1});const s=ie.has(a.plotMode??"hardBin")?null:t;if(s){for(const l of s)C[l]?.setOptions({plotMode:"value",activeTest:e});Bt=[...s]}}}function vo(e){me=e;const t=o=>x[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=x.map((o,i)=>i).filter(o=>t(o)?.length);if(wo(e,n.length?n:null),nn(),on(),!ie.has(a.plotMode??"hardBin"))for(const o of n)Dt(t(o),[o])}function So(e,t){if(J===e.id){Oe();return}J=e.id,me=null,t&&(t.style.background=w.bgActive,t.style.fontWeight="600"),yo();const{kind:n,index:o}=e.variable;if(n==="test")wo(o??0,ho(e));else{const s=x.some(u=>u?.dies?.some(d=>d.hbin!=null)),l=oi(x.map(u=>u?Ue(u):void 0));P({plotMode:La(e,a.plotMode,s),highlightBin:Ta(e,l,s)},{fireCallback:!1})}nn(),on();const i=e.highlight;if(i.kind==="wafer"){ro(i.waferIndices);const s=hi(e);for(const l of i.waferIndices){const u=i.dieKeysByWafer?void 0:x[l]?.statsSummary?.findings.find(m=>hi(m)===s),d=i.dieKeysByWafer?.[l]??u?.highlight?.dieKeys;d?.length&&Dt(d,[l])}}else i.kind==="bin"?i.dieKeys?.length&&Dt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Dt(i.dieKeys)}function rn(){return!!S&&S.style.display!=="none"}function cn(e){!S||e===rn()||(e&&R(),S.style.display=e?"flex":"none",re())}function re(){Ct&&(Zt(H),Qt(H,"inline-flex"),Ct.sync({visible:!!(_||se()||oo())&&!!S&&!Ke,open:rn(),notable:!!(se()?.hasNotableFindings||B().some(e=>e?.statsSummary?.hasNotableFindings))}))}const H=r.ownerDocument.createElement("div");H.dataset.wmapToolbar="gallery",Object.assign(H.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,padding:"0",boxShadow:Ln.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const Co=()=>{const e=ot();e&&(e.remove(),it(null)),gt(ce,!1)},ce=je("mode","Plot mode",()=>{if(ot()){Co();return}const e=B().flatMap(y=>y?.dies??[]),t=tt(),{testEntries:n,binEntries:o,stackedEntries:i}=pa(e,t,{includeStacked:!0}),s=B().filter(Boolean).length,l=y=>{if(y===void 0)return s;let E=0;for(const A of B())A?.dies?.some(j=>yi(j,y)!==void 0||ol(j,y)!==void 0)&&E++;return E},u=s<2?n:n.map(y=>{const E=l(y.activeTest);return E===s?y:{...y,label:`${y.label} \u2014 ${E} of ${s} wafers`}}),d=a.plotMode??"hardBin",m=a.activeTest??0;function v(y){return y.plotMode!==d?!1:y.plotMode==="value"?m===(y.activeTest??0):y.plotMode==="metadata"?a.activeMetadataKey===y.activeMetadataKey:!0}function p(y,E){y.activeTest!==void 0?P({plotMode:"value",activeTest:y.activeTest,activeMetadataKey:void 0,logScale:y.logScale}):y.activeMetadataKey!==void 0?P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:y.activeMetadataKey,passFailDisplay:"off"}):P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),it(null),gt(ce,!1)}const c=new Set,g=B().flatMap(y=>y?.metadataFields??[]).filter(y=>!c.has(y.key)&&c.add(y.key)).filter(y=>ma(e,y.key)).map(fi);ke===0&&Is(B())&&g.push(fi(As));const h=Zs(ce.getBoundingClientRect(),u,o,i,v,p,{makeMenuRow:Oi,makeMenuSection:Ti},d,ce.ownerDocument.defaultView??window,g);ri(ce).appendChild(h),it(h),gt(ce,!0),ci(h,ce,Co)});gt(ce,!1);const Ki=()=>x.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:Gi,sync:xo}=oa(He,()=>({...a,plotMode:a.plotMode??"hardBin"}),Ki,e=>P(e));xo();const qi=k.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function Et(){const e=tt(),{testNumber:t}=Bs(a.activeTest??0,e);return{testNumber:t,td:Es(e,t)}}function Mo(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function lt(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&!Fn(e)}function Xi(){if((a.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=Et();return B().some(n=>n?.dies?.some(o=>yi(o,e,t)!==void 0))}function Yi(e,t){if(!t||!Fn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((di(a)==="spec"&&n?"spec":a.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,l=-1/0;for(const u of B())if(u)for(const d of u.dies){const m=$a(d,e);m!==void 0&&(m<s&&(s=m),m>l&&(l=m))}if(isFinite(s))return s===l?[s,s+1]:[s,l]}function Ot(e,t,n){const o=a[e];if(o===t||o!=null&&t!=null&&n(o,t))return!1;a={...a,[e]:t};for(const i of C)i&&i.setOptions({[e]:t});return!0}function ko(){if((a.plotMode??"hardBin")!=="metadata")return;const e=a.activeMetadataKey;if(!e)return;if(mt(a))return{key:e,values:[...$s]};const t=new Set;for(const n of B())if(n)for(const o of Os(n.dies,e))t.add(o);return{key:e,values:[...t].sort(jn)}}function dn(){Ot("metadataValueOrder",ko(),(e,t)=>e.key===t.key&&jt(e.values,t.values))}function un(){if((a.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=Et(),n=Yi(e,t);Ot("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const l=m=>Array.isArray(m)?{test:void 0,range:m}:{test:m.test,range:m.range},u=l(i),d=l(s);return u.test===d.test&&jt(u.range,d.range)})}let fn=!1;function Ui(){if(fn)return;fn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{fn=!1,un(),dn(),Oo(),Eo()})}let pn=!1;function Zi(){if(pn)return;pn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{pn=!1,Ft()})}let Do=[];function K(){const{colors:e,mixedHardBins:t}=Ls(B().filter(n=>n!=null),{binColorScheme:a.binColorScheme,useDefinedBinColors:a.useDefinedBinColors});return Do=t,e}function mn(){return x.filter(e=>e!=null).flatMap(e=>e.dies)}function Bo(){return a.compact?Ka(mn()):void 0}const Qi=(e,t)=>jt(e.columns,t.columns)&&jt(e.rows,t.rows);function Eo(){Ot("compactMap",Bo(),Qi)&&zo()}function Ji(){return Ga(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig))}function Oo(){Ot("binColors",K(),Rs),Te()}const es=aa(He,()=>ca(a,qi,{functionalActive:lt(),hasLimits:Mo()&&!lt(),hasRecorded:Xi()&&!lt(),binMode:(a.plotMode??"hardBin")==="hardBin"||(a.plotMode??"hardBin")==="softBin"},e=>P(e),{on:!!a.compact,offered:Ji(),onChange:e=>P({compact:e}),onDiagnostics:()=>ua(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:r,onSaveText:V.onSaveText})}),()=>da(a)),{btn:ts,sync:To}=sa(He,()=>({plotMode:a.plotMode,legendPosition:Ze}),e=>{Ze=e;for(const t of C)t&&t.setOptions({legendPosition:Ze})},{get:()=>bt,set:e=>{bt=e,Kn()},blockedReason:Qe});To();const ns=[{value:"mean",label:"Mean"},{value:"median",label:"Median"},{value:"stddev",label:"Std Dev"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"count",label:"Count"}],Lo=so("aggr","Aggregation method",()=>ns,()=>a.aggregationMethod??"mean",e=>P({aggregationMethod:e}));function Po(){const e=a.plotMode==="stackedValues";Lo.style.display=e?"":"none"}Po();const{btn:os,sync:Wo}=ia(He,()=>({...a,functionalActive:lt()}),e=>P(e));Wo();const Tt=je("specRange","Colour bar range: test limits",()=>{const e=a.colorbarRangeMode==="data"?"spec":"data";P({colorbarRangeMode:e})});function Ro(){const e=(a.plotMode??"hardBin")==="value"&&Mo()&&di(a)==="off"&&!lt();Tt.style.display=e?"":"none";const t=(a.colorbarRangeMode??"spec")==="spec";io(Tt,t),Tt.ariaLabel=t?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"}Ro();const is=la(He,()=>a,e=>P(e)),ss=je("downloadAll","Download gallery PNG",Ss),Ne=je("boxSelect","Select the same dies on every wafer",()=>{le&&Ee.size>0?uo():$i(!le)});Ne.style.position="relative";const rt=r.ownerDocument.createElement("span");rt.dataset.wmapSelectAcrossCount="1",Object.assign(rt.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:Y.pill,background:w.iconActive,color:w.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Ne.appendChild(rt);function Lt(){io(Ne,le);const e=le?Ee.size:0;rt.style.display=e>0?"block":"none",rt.textContent=e>99?"99+":String(e),Ne.ariaLabel=le?e>0?`Select the same dies on every wafer: on, ${e.toLocaleString()} die position${e===1?"":"s"} selected (click to clear the selection)`:"Select the same dies on every wafer: on (click to turn off)":"Select the same dies on every wafer: off (click to turn on)",Ne.setAttribute("aria-pressed",String(le))}const ee=r.ownerDocument.createElement("button");ee.type="button",ee.dataset.wmapPickedWafers="1",Object.assign(ee.style,{display:"none",border:"none",background:w.bgActive,color:w.iconActive,borderRadius:Y.control,padding:`${M.xs} ${M.md}`,fontSize:N.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),Pn(ee,"bare"),ee.addEventListener("click",Vi);const Ao=()=>{const e=x.filter(o=>o!=null&&!fe.has(o)).length,t=Math.min(5,Math.max(1,e)),n=Array.from({length:t},(o,i)=>i+1);return O!=null&&!n.includes(O)&&n.push(O),n},as=so("columns","Columns",()=>[{value:"auto",label:"Auto (0)"},...Ao().map(e=>({value:String(e),label:`${e} column${e===1?"":"s"} (${e})`}))],()=>O!=null?String(O):"auto",e=>Sn(e==="auto"?void 0:Number(e))),L=r.ownerDocument.createElement("div");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:"0"}),H.appendChild(L),L.appendChild(ce),L.appendChild(Gi),L.appendChild(Lo),L.appendChild(os),L.appendChild(Tt),L.appendChild(De()),L.appendChild(es),L.appendChild(De()),L.appendChild(ts),L.appendChild(De()),L.appendChild(is),L.appendChild(De()),L.appendChild(as),L.appendChild(De()),L.appendChild(Ne),L.appendChild(ee),L.appendChild(ss),Lt();let te=null,Pt=null,he=[],Fo=!1;function Te(){const e=za({lotStatsSummary:se(),result:{warnings:[...B().flatMap(n=>n?.warnings??[]),...Ie().warnings]},extra:[a.binColors&&Ps(a.binColors,a.plotMode),Ws(Do),Mi(_n())].filter(n=>!!n)}),t=e.length!==he.length||e.some((n,o)=>n.code!==he[o]?.code||n.message!==he[o]?.message);he=e,(t||!Fo)&&(Fo=!0,f.warnings?.onWarning?.(e)),ls()}function ls(){if(!te||!Pt)return;const e=he.length,t=e>0;if(te.style.display=t?"flex":"none",Pt.style.display=t?"":"none",Zt(H),Qt(H,"inline-flex"),!t)return;const n=_a(he[0]),o=`${e} data ${e===1?"warning":"warnings"}`;te.style.color=n==="error"?w.errText:w.warnText,te.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(f.warnings?.display??!0)&&(Pt=De(),te=je("warning","Data warnings",()=>{const e=ot();if(Mt(new MouseEvent("click")),e)return;const t=Na(te.getBoundingClientRect(),he,te.ownerDocument.defaultView??window);ri(r).appendChild(t),it(t),ci(t,te,()=>Mt(new MouseEvent("click")))}),gt(te,!1),H.appendChild(Pt),H.appendChild(te)),Te();function gn(e){import("./userGuideHtml.js").then(t=>ha({buildWaferMap:Wa,renderWaferMap:ka,renderWaferGallery,analyzeWaferMap:$n},t.USER_GUIDE_HTML,T,r,e))}const rs=ya(e=>gn(e));D&&(H.appendChild(De()),H.appendChild(je("help","User guide",()=>gn())));const _e=r.ownerDocument.createElement("div");_e.dataset.wmapGalleryMeta="1",Object.assign(_e.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${M.sm} ${M.lg}`,fontSize:N.sub,lineHeight:ii.none,boxSizing:"border-box"});const Le=r.ownerDocument.createElement("div");Object.assign(Le.style,{background:w.canvasBg,display:"flex",alignItems:"stretch",gap:M.lg,paddingBottom:M.lg,minWidth:"0"});const ye=r.ownerDocument.createElement("div");ye.dataset.wmapGalleryLegend="1",Object.assign(ye.style,{display:"flex",flexDirection:"column",gap:M.sm,background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,padding:`${M.sm} ${M.lg}`,marginBottom:M.lg,boxShadow:Ln.panel,fontSize:N.body,lineHeight:ii.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const Z=r.ownerDocument.createElement("div");Object.assign(Z.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let be=null,ct=null,$o=null;function Io(){return I?be?Promise.resolve(be):($o??=Promise.all([import("./insightsTab.js"),qt()]).then(([{createInsightsTab:e},t])=>(be=e({pageFilter:t,showFilterButton:!1,initialAxisPrefs:In(a),onAxisPrefsChange:n=>{a={...a,...ja(n)};const o=[...Vn];f.onViewOptionsChange?.(Ht(a),o,An(o))},attributes:f.attributes,getItems:()=>W,getLotStats:()=>_,getBinColors:()=>a.binColors??K(),getRingCount:()=>ne({ringCount:yt()},"the Insights tab"),defaultView:f.insights?.defaultView,plotStore:$,onPickPlotsFile:f.insights?.onPickPlotsFile,showPatMap:()=>{Ge(!1),P({plotMode:"metadata",activeTest:void 0,activeMetadataKey:Fs,passFailDisplay:"off"})},showOnMap:n=>{if(Ge(!1),n.kind==="test")xt(),Oe(),vo(n.testNumber);else if(n.kind==="finding"){const o=se(),i=o?Pa(o).findings.find(s=>s.id===n.id):void 0;i&&J!==i.id&&(xt(),So(i))}cn(!0),R()},onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,ownerDocument:r.ownerDocument,locateDie:(n,o)=>{Ge(!1),ge(o,n)},openWafer:(n,o,i)=>{const s=B()[n];if(!s)return;let l=null;const u=ea({title:o,onClose:()=>l?.destroy(),anchor:r});Xo(u,o,s.wafer.metadata??void 0),l=kn(u.contentWrap,s,i,void 0,ui(u))}}),ct=be.el,ct.style.display="none",r.appendChild(ct),be)),$o):Promise.resolve(null)}let Ke=!1,hn=null;function Ge(e){I&&(Ke=e,hn?.setInsightsOpen(e),ct&&(ct.style.display=e?"flex":"none"),Z.style.display=e?"none":"flex",pe&&(pe.el.style.display=q?.get()&&!e?"":"none"),L.style.display=e?"none":"inline-flex",Zt(H),Qt(H,"inline-flex"),H.style.display="inline-flex",re(),Ft(),e&&Io().then(t=>{!t||!Ke||(t.el.style.display="flex",t.render())}))}I&&f.insights?.defaultOpen&&queueMicrotask(()=>Ge(!0));const cs=6,ds=4,Wt=240,yn=480,us=720,fs=1.25;let Pe=yn;function Vo(e){const t=z*2+110+2,n=Ho();if(n)return Math.ceil(n.across*ds+t);let o=null;for(const i of e){if(i==null||!i.dies?.length)continue;const s=i.dies[0].width;if(!(s>0))continue;const l=i.wafer.radius*2*(cs/s),u=Math.ceil(l+t);(o==null||u>o)&&(o=u)}return o}function ps(e){const t=Vo(e);return t==null?Wt:Math.min(Pe,Math.max(Wt,t))}function ms(e){const t=Vo(e);if(t==null)return!1;const n=Math.min(us,Math.max(yn,t));return n<=Pe?!1:(Pe=n,!0)}function Ho(){const e=a.compact?a.compactMap:void 0,t=x.find(i=>i?.dies?.length)?.dies[0];if(!e||!t||e.columns.length===0||e.rows.length===0||!(t.width>0)||!(t.height>0))return;const n=(a.rotation??0)%180!==0,o=a.showXYIndicator?2.5:0;return{across:(n?e.rows.length:e.columns.length)+o,down:(n?e.columns.length:e.rows.length)+o,cellAspect:n?t.height/t.width:t.width/t.height}}function jo(e,t){const n=Ho();if(!n){e.style.aspectRatio="1",t.style.flex="1",t.style.width="",t.style.aspectRatio="";return}e.style.aspectRatio="auto",t.style.flex="none",t.style.width="100%",t.style.aspectRatio=String(n.across*n.cellAspect/n.down)}function gs(){for(const e of ue)e?.parentElement&&jo(e.parentElement,e)}function zo(){Pe=yn,dt=Wt,vn(x.map(e=>e??null)),Rt(),gs()}function bn(){return No()?`${Pe}px`:"none"}function No(){return O==null&&!wn}let wn=!1;function Rt(){const e=bn();for(const t of Array.from(F.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let dt=Wt,_o=0;function vn(e){if(ms(e)&&Rt(),O==null){const n=ps(e);n>dt&&(dt=n)}xn()}function Sn(e){O=vi(e),Rt(),xn()}let At=!1;r.addEventListener("pointerenter",()=>{At=!0}),r.addEventListener("pointermove",()=>{At=!0}),r.addEventListener("pointerleave",()=>{At=!1});const hs=()=>{if(At)return!0;try{return r.matches(":hover")}catch{return!1}},Ko=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||Ke||!hs()&&!r.contains(e.target)||!/^[0-5]$/.test(e.key)||r.ownerDocument.querySelector('[role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||e.key!=="0"&&!Ao().includes(Number(e.key))||(e.preventDefault(),Sn(e.key==="0"?void 0:Number(e.key)))};r.ownerDocument.addEventListener("keydown",Ko);function Cn(e){return`repeat(${e}, minmax(0, ${No()?`${Pe}px`:"1fr"}))`}function Go(e){F.style.gridTemplateColumns!==e&&(F.style.gridTemplateColumns=e)}function xn(){if(O!=null){Go(Cn(O));return}const e=Math.max(1,_o),t=12,n=F.clientWidth||0,o=l=>(n-t*(l-1))/l;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const l=Math.min(Pe,dt*fs),u=d=>{let m=0;for(;m<e&&o(m+1)>=d;)m++;return m};i=u(l)||u(dt)||1}const s=n>0&&i<e;s!==wn&&(wn=s,Rt()),Go(Cn(i))}const F=r.ownerDocument.createElement("div");if(Object.assign(F.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Cn(1),gap:M.xl,paddingLeft:oe,paddingRight:oe,justifyContent:"start",alignContent:"start",isolation:"isolate"}),Re?.placement){const e=Re.placement;S=zn(e,oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.display="flex",S.style.flexDirection="column"}else if(_||se()||oo()){const e=!!Re?.defaultOpen;S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display=e?"flex":"none",R()}re(),(Re?.placement??"right")==="left"?(S&&Z.appendChild(S),Z.appendChild(F)):(Z.appendChild(F),S&&Z.appendChild(S));const We=r.ownerDocument.createElement("div");Object.assign(We.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:oe,paddingRight:oe,paddingTop:oe,zIndex:"1",background:w.menuBg}),Le.appendChild(_e),Le.appendChild(H),Ct=ks(r.ownerDocument,()=>cn(!rn())),Le.appendChild(Ct.el),re(),I&&(hn=Ms(r.ownerDocument,"Maps","lot",e=>Ge(e)),Le.appendChild(hn.el)),I&&(St=ba(r.ownerDocument,"Filter\u2026","wmapGalleryFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{qt().then(e=>e.openEditor(St??r,Yt()))}),St.style.order="1",Le.appendChild(St)),We.appendChild(Le),We.appendChild(ye),r.appendChild(We),r.appendChild(Z);function Ft(){ye.innerHTML="";const e=a.plotMode??"hardBin",t=!Ke&&ai.has(e),n=x.filter(b=>b!=null&&!fe.has(b)),o=n.find(b=>b.isLotStack),i=qa(n.map(b=>({metadata:b.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:f.attributes}),s=e==="metadata",l=a.activeMetadataKey,u=t&&!s?Si(n,b=>(e==="softBin"?b.sbin:b.hbin)??void 0,Ce):{counts:new Map,total:0,pass:0},d=t&&!s?a.binColors??K():void 0,m=d?e==="softBin"?d.pass.soft:d.pass.hard:new Set,v=Sa(u.counts.entries(),m).map(([b])=>b),p=t&&s&&l?Si(n,b=>Ts(b.metadata?.[l])):{counts:new Map,total:0,pass:0},c=s?ko()?.values:void 0,g=t&&s?(c??[...p.counts.keys()].sort(jn)).filter(b=>p.counts.has(b)):[];if(_e.innerHTML="",i&&_e.appendChild(i),_e.style.display=i?"flex":"none",!v.length&&!g.length){ye.style.display="none";return}ye.style.display="flex";const h=r.ownerDocument.createElement("div");Object.assign(h.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${M.sm} ${M.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),ye.appendChild(h);const y=Hn(a.highlightBin),E=x.flatMap(b=>b?.metadataFields??[]).find(b=>b.key===l),A=s?E?.label??(l?Za(l):"Metadata"):qs[e],j=r.ownerDocument.createElement("span");if(j.textContent=A,Object.assign(j.style,{fontSize:N.body,fontWeight:"700",letterSpacing:_s,textTransform:"uppercase",color:w.label,flexShrink:"0"}),h.appendChild(j),!s&&u.total>0){const b=u.pass,G=b/u.total*100,we=r.ownerDocument.createElement("span");we.textContent=`Yield ${Nt(G)}`,Object.assign(we.style,{fontSize:N.body,fontWeight:"700",color:w.value,whiteSpace:"nowrap",flexShrink:"0"});const ve=r.ownerDocument.createElement("span");ve.textContent=`${b.toLocaleString()} / ${u.total.toLocaleString()} dies`,Object.assign(ve.style,{fontSize:N.body,color:w.label,whiteSpace:"nowrap",flexShrink:"0"}),h.appendChild(we),h.appendChild(ve)}if(s){const b=Hn(a.highlightMetadataValue);g.forEach((G,we)=>{const ve=b.includes(G),Ye=E?.values?.find(On=>On.value===G),pt=Ye?.color??zs(we),ni=p.counts.get(G)??0;Ci(h,{color:pt,isActive:ve,label:Ye?.label??G,count:ni,percent:p.total>0?ni/p.total*100:void 0,onClick:On=>{const xs=bi(a.highlightMetadataValue,G,On);bo(),P({highlightMetadataValue:xs})}})});return}const ft=e==="softBin"?x.flatMap(b=>b?.sbinDefs??[]):x.flatMap(b=>b?.hbinDefs??[]),Jo=new Set,Bn=[];for(const b of ft)Jo.has(b.bin)||(Jo.add(b.bin),Bn.push(b));const En=Bn.length>0?new Map(Bn.map(b=>[b.bin,b])):null,ei=d??a.binColors??K(),Cs=e==="softBin"?ei.soft:ei.hard,ti=b=>Cs.get(b)??js;for(const b of v){const G=y.includes(b),we=En?.get(b),ve=u.counts.get(b)??0;Ci(h,{color:ti(b),isActive:G,label:we?.name?`${b} \xB7 ${we.name}`:`Bin ${b}`,count:ve,percent:u.total>0?ve/u.total*100:void 0,onMenu:(Ye,pt)=>Ai(e==="softBin"?"soft":"hard",b,Ye,pt),onClick:Ye=>{const pt=bi(a.highlightBin,b,Ye);bo(),P({highlightBin:pt})}})}u.total>0&&v.length>1&&ye.appendChild(sl(r.ownerDocument,[...u.counts.entries()].sort(([,b],[,G])=>G-b).map(([b,G])=>({color:ti(b),count:G,label:En?.get(b)?.name?`${b} \xB7 ${En.get(b).name}`:`Bin ${b}`})),u.total))}function qe(e){const t=B().filter(p=>p!==null&&!fe.has(p));if(!t.length)return[];const n=t.map(p=>p.dies.filter(nl).filter(c=>!c.filteredOut)),o=t[0].wafer,i=t.length,s=oi(t.map(p=>Ue(p)));if(!s)return[];const l=new Set(t.map(p=>ne(p,"renderWaferGallery")));if(l.size!==1)return[];const u=[...l][0],d=o.metadata?{...o,metadata:(({wafer:p,waferId:c,...g})=>g)(o.metadata)}:o;function m(p,c){return{...p,stats:{...p.stats,isLotStack:!0,aggregationMethod:c,lotSize:i}}}function v(p,c){const g=p.map(h=>({...h,hbin:void 0,sbin:void 0}));return $n({wafer:d,dies:g,passBins:[...s],ringCount:u,testDefs:[{testNumber:0,name:c}]},{testNumbers:[0]})}if(e==="stackedValues"){const p=tt();let c=p?.filter(Fn);if(p!==void 0&&c?.length===0)return[];if(p?.length||(c=Ds(t.flatMap(y=>y.dies)).map(y=>({testNumber:y,name:Qa(void 0,y)}))),!c?.length)return[];const g=a.aggregationMethod??"mean";return c.map(h=>{const y=Ma(n,g,h.testNumber),E={testNumber:0,name:h.name,unit:h.unit,...el(h)};return{wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E],label:`${Ja(h,h.testNumber)} \xB7 ${g}`,isLotStack:!0,aggrMethod:g,lotSize:i,statsSummary:m($n({wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E]},{testNumbers:[0]}),g)}})}if(e==="stackedBins"){let p=Vt(t.map(c=>c?.hbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.hbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=pi(n,c.bin,"hard"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,hbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in hard bin ${c.bin}`),"countBin")}})}if(e==="stackedSoftBins"){let p=Vt(t.map(c=>c?.sbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.sbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=pi(n,c.bin,"soft"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,sbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in soft bin ${c.bin}`),"countBin")}})}return t}function $t(e){const t=B().length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:a.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function P(e,{fireCallback:t=!0}={}){const n=Object.keys(e);if(n.length>0&&n.every(c=>Vn.includes(c))){a={...a,...e},be?.setAxisPrefs(In(a)),t&&f.onViewOptionsChange?.(Ht(a),n,An(n));return}Vn.some(c=>c in e)&&be?.setAxisPrefs(In({...a,...e}));const o=a.plotMode,i=mt(a),s=Qe()!==null;a={...a,...e};const l=a.plotMode,u=ie.has(l),d=mt(a),m=o!==void 0&&ie.has(o),v=ke>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const c=K();a={...a,binColors:c},e={...e,binColors:c}}if("compact"in e){const c=Bo();a={...a,compactMap:c},e={...e,compactMap:c}}if(("compact"in e||a.compact&&("rotation"in e||"showXYIndicator"in e))&&zo(),e.plotMode!==void 0)if(u){const c=$t(l);if(a={...a,...c},v)for(const g of C)g&&g.setOptions(e);else X(qe(l))}else if(m){const{valueRange:c,lotSize:g,aggregationMethod:h,...y}=a;if(a=y,v)for(const E of C)E&&E.setOptions(e);else X(d?$e(W.filter(E=>E!==null)):B().filter(E=>E!==null))}else if(i!==d&&!v)X($e(W.filter(c=>c!==null)));else for(const c of C)c&&c.setOptions(e);else if(e.aggregationMethod!==void 0&&l==="stackedValues")if(v)for(const c of C)c&&c.setOptions(e);else X(qe("stackedValues"));else for(const c of C)c&&c.setOptions(e);Qe()!==null!==s&&Kn(),Ft(),Po(),To(),xo();const p=e.plotMode!==void 0&&e.plotMode!==o;(Oa.some(c=>c in e)||p)&&R(),Te(),Wo(),Ro(),un(),dn(),t&&f.onViewOptionsChange?.(Ht(a),n,An(n))}function qo(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:N.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=wi(e,o,t,n,f.attributes);return{wrap:o,metaPanel:s}}function Xo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||Xa(n??{}).length===0)return;const i=o.parentElement,s=r.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const l=wi(r.ownerDocument,s,t,n,f.attributes);l&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(l))}function Mn(e,t,n){const o=r.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,boxShadow:Ln.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:bn(),maxHeight:bn()});const i=r.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm});const{wrap:s,metaPanel:l}=qo(document,ht(e,t),e.wafer.metadata??void 0);i.appendChild(s);const u=r.ownerDocument.createElement("button");u.dataset.wmapExpandBtn="1",u.setAttribute("aria-label","Open full view"),Wn(u),u.innerHTML=Tn.expand,Object.assign(u.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,background:w.panelBg,color:w.label,padding:M.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),Pn(u),i.appendChild(u),i.addEventListener("click",c=>{(c.ctrlKey||c.metaKey)&&(c.preventDefault(),c.stopPropagation(),Ii(x.indexOf(e)))},!0),o.appendChild(i);const d=r.ownerDocument.createElement("div");Object.assign(d.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(d),jo(o,d),l&&d.appendChild(l),F.appendChild(o),o.addEventListener("contextmenu",c=>{if(c.defaultPrevented)return;c.preventDefault();const g=e.viewOptions?{...a,...e.viewOptions}:a,h=sn()??go(t),y=h?.source??Da(e.dies,{waferLabel:Se(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:g.plotMode==="value"?g.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:Ce(e),ringCount:ne(e,"renderWaferGallery")}),E={x:c.clientX,y:c.clientY};import("./drilldown.js").then(({openDrilldownMenu:A})=>{o.isConnected&&A(E,o,y,h?{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...h.ctx}:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:p.getSaveImageHook(),onSaveText:p.getSaveTextHook(),onLocateDie:j=>ge(t,j)})})});const m=bt||Qe()!==null,v=e.viewOptions?{...a,...e.viewOptions}:a,p=mi(d,e,{viewOptions:{...v,showLegend:m,legendPosition:Ze},showTooltip:!0,padding:z,statsSummary:e.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:e.onClick,onSelect:co(e),drilldownSourceOverride:()=>Ri(t),insights:de,onExpand:()=>ut(t,e),showIdentity:!1,chromeInset:Gs,drawWhenVisible:!0});return p.setViewControlsVisible(!1),p.setSummaryVisible(!1),u.onclick=()=>ut(t,e),fe.has(e)&&(o.style.display="none"),{card:o,ctrl:p,canvasWrapper:d,expandBtn:u}}function ys(e){const t=Fe[e];if(!t)return;const n=[...Q.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Tn.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>ws(n.id)):(t.innerHTML=Tn.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>ut(e,x[e]))}function X(e){vs(),ot()?.remove(),it(null),Oe(),x=[],U.clear(),ln.clear(),ee.style.display="none";for(const d of C)d&&d.destroy();C=[],ue=[],Fe=[],ke=0,F.innerHTML="",_o=e.length,vn(e.map(d=>typeof d=="function"?null:d));const t=[];for(let d=0;d<e.length;d++){const m=e[d];if(typeof m=="function"){const v=r.ownerDocument.createElement("div");v.className="wmap-gallery-card",Object.assign(v.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const p=r.ownerDocument.createElement("span");p.textContent="\u2026",Object.assign(p.style,{color:w.label,fontSize:"18px"}),v.appendChild(p),F.appendChild(v),x.push(null),C.push(null),ue.push(null),Fe.push(null),t.push({index:d,factory:m,placeholder:v}),ke++}else{const{ctrl:v,canvasWrapper:p,expandBtn:c}=Mn(m,d,e.length);x.push(m),C.push(v),ue.push(p),Fe.push(c)}}Oo(),Ft(),un(),dn(),Eo();const n=++nt,o=()=>{setTimeout(()=>{n===nt&&f.onItemsResolved?.()},0)},i=d=>{setTimeout(()=>{n===nt&&f.onItemResolved?.(d,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let l=0;function u(){if(n!==nt)return;if(l>=t.length){if(ie.has(a.plotMode)){const A=a.plotMode;X(qe(A));return}if(wt){Ut();return}at=o,R(),ze||(at=null,o());return}const{index:d,factory:m,placeholder:v}=t[l++],p=m();W[d]=p;const c=Gt(p,d);Je(p,d)!==p&&(ae=!0),x[d]=c,vn([c]);const{card:g,ctrl:h,canvasWrapper:y,expandBtn:E}=Mn(c,d,e.length);C[d]=h,ue[d]=y,Fe[d]=E,ke--,v.replaceWith(g),i(++s),Zi(),Ui(),!S&&!Re?.placement&&c.statsSummary?.findings.length&&(S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display="none",(Re?.placement??"right")==="left"?Z.insertBefore(S,F):Z.appendChild(S),R(),re()),re(),setTimeout(u,0)}t.length>0?setTimeout(u,0):o()}if(ie.has(a.plotMode)&&B().length>0){const e=$t(a.plotMode);a={...a,...e},X(qe(a.plotMode))}else X($e(k));f.insights?.filter!==void 0&&qt(),Te();let Xe=0;const Yo=new(r.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Xe)return;Xe=(r.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Xe=0,O==null&&xn()})});Yo.observe(F);const Uo=()=>{r.style.setProperty("--wmap-sticky-top",`${We.offsetHeight}px`)};Uo();const Zo=new(r.ownerDocument.defaultView??window).ResizeObserver(Uo);Zo.observe(We),S&&R();function bs(e,t){const n=ue[e];if(!n)return;n.innerHTML="",Object.assign(n.style,{alignItems:"center",justifyContent:"center"});const o=r.ownerDocument.createElement("span");o.textContent=t?"Opened in its own window":"Opened in the wafer viewer",Object.assign(o.style,{color:w.label,fontSize:N.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function ut(e,t){for(const l of Q.values())if(l.cardIndex===e)return;const n=ht(t,e),o=Di++,i=C[e]?.getOptions(),s=Qs(n);if(s){const l=s.document;l.title=n,Object.assign(l.documentElement.style,{height:"100%"}),Object.assign(l.body.style,{margin:"0",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",fontFamily:N.family}),ta(r,l.documentElement);const u=na(r,l.documentElement,()=>y.setOptions({})),d=l.createElement("div");d.dataset.wmapWindowBanner="1",d.textContent=n,Object.assign(d.style,{display:"none",padding:`${M.sm} ${M.xl}`,fontSize:N.body,fontWeight:"700",background:w.warnBg,color:w.warnText,borderBottom:`1px solid ${w.warnBorder}`,flexShrink:"0"}),l.body.appendChild(d);const m=l.createElement("div");Object.assign(m.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),l.body.appendChild(m);const{wrap:v,metaPanel:p}=qo(l,n,t.wafer.metadata??void 0),c=l.createElement("div");Object.assign(c.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm}),c.appendChild(v),m.appendChild(c);const g=l.createElement("div");Object.assign(g.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),p&&g.appendChild(p),m.appendChild(g);let h=0;const y=kn(g,t,void 0,i,(A,j)=>{const ft=A?j:-h;try{s.resizeBy(ft,0),h=A?j:0}catch{}}),E=setInterval(()=>{s.closed&&It(o)},400);s.addEventListener("pagehide",()=>It(o)),Q.set(o,{id:o,ctrl:y,cardIndex:e,label:n,closePollId:E,stopThemeSync:u,close:()=>{s.closed||s.close()},setTitle:A=>{l.title=A,d.textContent=A,d.style.display="block"}})}else{const l=Js({title:n,onClose:()=>It(o),anchor:r});l.contentWrap.style.flexDirection="column",Xo(l,n,t.wafer.metadata??void 0);const u=kn(l.contentWrap,t,void 0,i,ui(l));Q.set(o,{id:o,ctrl:u,cardIndex:e,label:n,closePollId:null,close:()=>l.close(),setTitle:d=>{const m=l.box.querySelector("[data-wmap-window-title]");m&&(m.textContent=d,m.title=d)}})}C[e]?.destroy(),C[e]=null,bs(e,s!==null),ys(e)}function kn(e,t,n,o,i){const s=t.viewOptions?{...a,...t.viewOptions}:a,l=o?{...s,...o}:s,d={...n!==void 0?{...l,plotMode:"value",activeTest:n}:l,showLegend:!0,legendPosition:Ze},m=mi(e,t,{viewOptions:d,showTooltip:!0,padding:z,statsSummary:t.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:t.onClick,onSelect:co(t),insights:de,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return m.setViewControlsVisible(!0),m.setSummaryVisible(!0),m.setExpandVisible(!1),m}function It(e){const t=Q.get(e);if(!t||(Q.delete(e),t.closePollId!=null&&clearInterval(t.closePollId),t.stopThemeSync?.(),t.ctrl.destroy(),t.cardIndex===null))return;const n=t.cardIndex,o=x[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:l,expandBtn:u}=Mn(o,n,x.length);ue[n]?.parentElement?.replaceWith(i),C[n]=s,ue[n]=l,Fe[n]=u}function ws(e){const t=Q.get(e);t&&(t.close(),It(e))}function vs(){for(const e of Q.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function Dn(){for(const e of C)e?.drawPendingNow()}const Qo=r.ownerDocument.defaultView??window;Qo.addEventListener("beforeprint",Dn);function Ss(){Dn();const e=[...F.querySelectorAll("canvas")];if(!e.length)return;const t=e.length,n=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/n),i=e[0].width,s=e[0].height,l=8,u=(r.ownerDocument.defaultView??window).devicePixelRatio||1,d=Math.round(26*u),m=Math.round(12*u),v=r.ownerDocument.createElement("canvas");v.width=n*i+(n-1)*l,v.height=o*(s+d)+(o-1)*l;const p=v.getContext("2d"),c=Ns(F);p.fillStyle=c.background,p.fillRect(0,0,v.width,v.height),e.forEach((g,h)=>{const y=h%n,E=Math.floor(h/n),A=y*(i+l),j=E*(s+d+l),ft=g.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";p.fillStyle=c.surface,p.fillRect(A,j,i,d),p.fillStyle=c.text,p.font=`700 ${m}px system-ui, sans-serif`,p.textAlign="left",p.textBaseline="middle",p.fillText(ft,A+Math.round(10*u),j+d/2,i-Math.round(20*u)),p.drawImage(g,A,j+d)}),v.toBlob(g=>{if(!g)return;const h=C.find(y=>y!=null)?.getExportTitle();ra(g,["gallery",h].filter(Boolean).join(" "),V.onSaveImage)})}return{setItems(e){tn(),W=e.map(n=>typeof n=="function"?null:n);const t=a.plotMode;if(ie.has(t))if(e.some(o=>typeof o=="function"))X($e(e));else{const o=$t(t);a={...a,...o},X(qe(t))}else X($e(e));Jn()},setOptions(e){P(e,{fireCallback:!1})},getOptions(){return Ht(a)},setFindingsNotice(e){lo=e,R()},setColumns(e){Sn(e)},getBinColors(){return a.binColors??K()},setLotStatsSummary(e){tn(),_=e,Jn(),Te(),S&&R(),re()},openUserGuide:()=>gn(),destroy(){rs(),$.flush(),tn(),nt++,Qo.removeEventListener("beforeprint",Dn),r.ownerDocument.removeEventListener("keydown",Ko),ze?.cancel(),ze=null,at=null;for(const e of[...Q.values()])e.closePollId!=null&&clearInterval(e.closePollId),e.close(),e.ctrl.destroy();Q.clear();for(const e of C)e&&e.destroy();C=[],ot()?.remove(),Yo.disconnect(),Zo.disconnect(),Xe&&((r.ownerDocument.defaultView??window).cancelAnimationFrame(Xe),Xe=0),r.ownerDocument.removeEventListener("click",Mt,!0),window.removeEventListener("blur",ao),xi(),li(),We.remove(),Z.remove(),S?.remove(),_t=!0,vt++,clearTimeout(Xt),pe?.el.remove(),be?.destroy()}}}