@wafertools/wafermap 0.40.0 → 0.40.1

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 (41) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/packages/canvas-adapter/charts/commonality.js +3 -3
  3. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +5 -2
  4. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  5. package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
  6. package/dist/packages/canvas-adapter/dataTab.d.ts +12 -6
  7. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  8. package/dist/packages/canvas-adapter/drilldown.d.ts +1 -1
  9. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  10. package/dist/packages/canvas-adapter/filterButton.d.ts +2 -0
  11. package/dist/packages/canvas-adapter/filterButton.js +1 -1
  12. package/dist/packages/canvas-adapter/identityHeader.js +1 -1
  13. package/dist/packages/canvas-adapter/insightsTab.d.ts +9 -4
  14. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  15. package/dist/packages/canvas-adapter/openWaferMode.d.ts +7 -0
  16. package/dist/packages/canvas-adapter/openWaferMode.js +1 -0
  17. package/dist/packages/canvas-adapter/plotTab.d.ts +1 -1
  18. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  19. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  20. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  21. package/dist/packages/canvas-adapter/summaryPanel.d.ts +2 -2
  22. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  23. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  24. package/dist/packages/canvas-adapter/userGuideHtml.js +20 -13
  25. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  26. package/dist/packages/canvas-adapter/version.js +1 -1
  27. package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -1
  28. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  29. package/dist/packages/renderer/buildView.js +1 -1
  30. package/dist/packages/renderer/fmt.d.ts +2 -0
  31. package/dist/packages/renderer/fmt.js +1 -1
  32. package/dist/packages/stats/commonality.d.ts +1 -1
  33. package/dist/packages/stats/commonality.js +1 -1
  34. package/dist/packages/stats/examplePicks.js +1 -1
  35. package/dist/packages/stats/groupEffects.d.ts +8 -0
  36. package/dist/packages/stats/groupEffects.js +1 -1
  37. package/dist/packages/stats/plotData.d.ts +7 -2
  38. package/dist/packages/stats/plotData.js +1 -1
  39. package/dist/packages/stats/synthesis.d.ts +8 -1
  40. package/dist/packages/stats/synthesis.js +1 -1
  41. package/package.json +1 -1
@@ -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 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()}}}
1
+ import{createViewSwitch as Bs}from"./viewSwitch.js";import{waferOpenMode as Es}from"./openWaferMode.js";import{createSummaryToggle as Os}from"./summaryToggle.js";import{getUniqueTestNumbers as Ts,resolveTestNumber as Ls,findTestDef as Ws,collectMetadataValues as Ps}from"../renderer/buildView.js";import{metadataCategoricalValue as Rs}from"../core/metadata.js";import{resolveBinColorsForMaps as As,mergeBinDefs as Ht,binColorWarning as $s,mixedPassBinsWarning as Fs,binColorsEqual as Is}from"../renderer/binColors.js";import{commonPassBins as ai,itemPassBins as Ue}from"../core/passBins.js";import{PAT_MODE_FIELD as Vs,PAT_MODE_KEY as Hs,PAT_MODE_ORDER as js,isPatMode as mt,patModeOffered as zs,withPatField as _s,withPatVerdicts as Ns}from"./patMode.js";import{requireRingCount as ie}from"../core/ringCount.js";import{NO_DATA_FILL as Ks}from"../renderer/colorMap.js";import{metadataValueColor as Gs}from"../renderer/colorMap.js";import{resolveCanvasTheme as qs}from"./canvasTheme.js";import{ICONS as Pn}from"./icons.js";import{SHADOW as Rn,LEADING as li,TRACKING as Xs,controlStyle as Ys,wireControlHover as An,SPACE as M,EDGE_GUTTER as se,MAP_CHROME_INSET as Us,RADIUS as Y,FONT as z,CLR as v,sevColor as ri,MODE_LABELS as Zs,BIN_LEGEND_MODES as ci,STACKED_MODES as Q,applyOverlayZ as Qs,getTooltip as Js,hideTooltip as di,createToolbarHelpers as ea,buildModeMenuEl as ta,openDetachWindow as na,openFloatingWindow as oa,openModal as ia,copyWmapThemeTokens as sa,syncWmapPopupTheme as aa,makePaletteBtn as la,makeLogScaleBtn as ra,makeLegendStyleBtn as ca,makeOverlaysBtn as da,makeOrientationBtn as ua,menuLayerFor as ui,saveImageBlob as fa,markMenuTrigger as gt,wireMenuA11y as fi,wireTooltip as $n,requestedPassFailDisplay as pi,overlayMenuRows as pa,anyOverlayActive as ma,openCompactDiagnostics as ga,roomForPanel as mi,logWmapVersionOnce as ha,buildDataModeEntries as ya,metadataKeyHasData as ba,metadataModeEntry as gi}from"./toolbar.js";import{openReportModal as wa,openUserGuideWindow as va,registerGuideOpener as Sa}from"./guideWindow.js";import{waferDisplayLabel as ht,waferIdentityLabel as Ce}from"../core/waferLabel.js";import{bandButton as Ca,filterKeepsNothing as xa}from"./filterButton.js";import{metadataDisplayValue as Ma}from"../core/metadata.js";import{withExportContext as ka}from"./exportName.js";import{sortBinsForDisplay as Da}from"../stats/binPareto.js";import{diePassStatus as Ba,isYieldEligibleDie as Ea}from"../core/dies.js";import{aggregateValues as Oa,aggregateBinCounts as hi}from"../core/aggregates.js";import{renderWaferMap as Ta,renderWaferMapCard as yi,toPublicViewOptions as jt}from"./renderWaferMap.js";import{waferPopulation as La,selectionPopulation as Wa,LOT_STACK_REASON as Fn}from"./chartPopulation.js";import{sourceFromBins as bi}from"./plotItems.js";import{plotStoreFor as Pa}from"./plotStore.js";import{classifyChanged as In,COLOR_KEYS as Ra,findingBin as Aa,findingPlotMode as $a}from"./renderWaferMap.js";import{findingPatternKey as wi}from"../stats/filterFindings.js";import{synthesisSource as Fa}from"../stats/synthesis.js";import{buildWaferMap as Ia,computeCoverage as Va,computeYield as Ha,defaultBinMode as ja,getTestPassStatus as vi,isParametricTest as Vn,getDieTestValue as za,isBuiltMap as _a}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as Hn}from"../stats/analyzeWaferMap.js";import{lotTestValueStatus as Na}from"../stats/testValueBudget.js";import{testValueNotice as Ka}from"./testValueOffer.js";import{axisPrefsFromOptions as jn,optionsFromAxisPrefs as Ga,CHART_PREF_KEYS as zn}from"./chartPrefs.js";import{collectWarnings as qa,buildWarningsMenuEl as Xa,severityOf as Ya}from"./warnings.js";import{asList as _n,compareNatural as Nn,arrayEqual as zt,toggleHighlight as Si}from"../core/utils.js";import{buildCompactMap as Ua,compactLayoutOffered as Za}from"../core/compact.js";import{attachExpandableMetadata as Ci}from"./identityHeader.js";import{createSummaryPanelEl as Kn,buildMetadataStripRow as Qa,metadataEntries as Ja,renderLotSummaryContentSteps as el,reportMapsFromItems as tl}from"./summaryPanel.js";import{commonMetadata as nl,prettyKey as ol}from"../stats/facets.js";import{testLabel as il,markedTestLabel as sl,derivedFields as al}from"../renderer/testLabel.js";import{mergeTestDefs as ll}from"../stats/mergeTestDefs.js";import{getDieKey as _t,hasPosition as rl}from"../core/dies.js";import{testValue as cl}from"../core/dieTable.js";import{runChunked as dl}from"./chunked.js";function xi(d){if(typeof d!="number"||!Number.isFinite(d))return;const k=Math.round(d);return k>=1?k:void 0}const Gn=12;function ul(d,k,u){let j=k;if(k.length>Gn){const D=k.slice(0,Gn-1),T=k.slice(Gn-1),I=T.reduce((F,pe)=>F+pe.count,0);j=[...D,{color:v.label,count:I,label:`Other (${T.length} bins)`}]}const O=d.createElement("div");Object.assign(O.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:Y.control,overflow:"hidden",border:`1px solid ${v.menuBorder}`,boxSizing:"border-box",marginTop:M.xs,flexShrink:"0"}),O.setAttribute("role","img"),O.setAttribute("aria-label",`Population split: ${j.map(D=>`${D.label} ${Nt(D.count/u*100)}`).join(", ")}`);for(const D of j){const T=D.count/u*100,I=d.createElement("div");Object.assign(I.style,{flex:`${T} 1 0`,minWidth:T>0?"2px":"0",background:D.color}),$n(I,`${D.label} \xB7 ${D.count.toLocaleString()} dies \xB7 ${Nt(T)}`),O.appendChild(I)}return O}function Nt(d){return d>0&&d<.1?"<0.1%":`${d.toFixed(1)}%`}function Mi(d,k,u){const j=new Map;let O=0,D=0;for(const T of d){const I=u?new Set(u(T)):void 0;for(const F of T.dies){if(!Ea(F))continue;const pe=k(F);pe!==void 0&&(j.set(pe,(j.get(pe)??0)+1),O++,I&&Ba(F,I)&&D++)}}return{counts:j,total:O,pass:D}}function ki(d,k){const u=d.ownerDocument.createElement("div");Object.assign(u.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${M.xxs} ${M.xs}`,borderRadius:Y.control});const j=d.ownerDocument.createElement("span");Object.assign(j.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:k.color,border:k.isActive?`2px solid ${v.iconActive}`:`1px solid ${v.menuBorder}`,borderRadius:Y.control,boxSizing:"border-box"});const O=d.ownerDocument.createElement("span");if(O.textContent=k.label,Object.assign(O.style,{fontWeight:k.isActive?"700":"400",color:k.isActive?v.iconActive:v.text,whiteSpace:"nowrap"}),u.appendChild(j),u.appendChild(O),k.count!==void 0){const D=d.ownerDocument.createElement("span");if(D.textContent=k.count.toLocaleString(),Object.assign(D.style,{color:k.isActive?v.iconActive:v.text,fontWeight:k.isActive?"700":"400",whiteSpace:"nowrap"}),u.appendChild(D),k.percent!==void 0){const T=d.ownerDocument.createElement("span");T.textContent=Nt(k.percent),Object.assign(T.style,{color:v.label,whiteSpace:"nowrap"}),u.appendChild(T)}}if(u.setAttribute("role","button"),u.setAttribute("aria-pressed",k.isActive?"true":"false"),u.tabIndex=0,u.addEventListener("mouseenter",()=>{u.style.background=v.bgHover}),u.addEventListener("mouseleave",()=>{u.style.background="transparent"}),u.addEventListener("focus",()=>{u.style.background=v.bgHover}),u.addEventListener("blur",()=>{u.style.background="transparent"}),u.addEventListener("click",D=>k.onClick(D.ctrlKey||D.metaKey)),u.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=u.getBoundingClientRect();k.onMenu({x:T.left+T.width/2,y:T.bottom},u)}}),k.onMenu){const D=k.onMenu;u.addEventListener("contextmenu",T=>{T.preventDefault(),D({x:T.clientX,y:T.clientY},u)}),$n(u,"Right-click: charts and tables for these dies")}d.appendChild(u)}export function renderWaferGallery(d,k,u={}){ha();const j=6;let O=xi(u.columns);const D=u.showHelpButton??!1,T=u.userGuideExtension,I=u.insights?.enabled??!0,F=Pa(u.insights),pe={enabled:!1,plotStore:F},Di=Qs(u.zIndex),$e=u.summaryPanel,xe=e=>[...Ue(e)],qn=()=>R.flatMap(e=>e?[ie(e,"renderWaferGallery")]:[]),yt=()=>qn()[0];function Bi(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 _=u.lotStatsSummary,Fe;const J=()=>ae?Fe:_;let Ze=u.viewOptions?.legendPosition??"default",bt=u.perCardLegend??!1;function Qe(){const e=l.plotMode??"hardBin";return ci.has(e)?null:l.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 Xn(){const e=bt||Qe()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let l={plotMode:ja(k.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...u.viewOptions},C=[],me=[],Ie=[],x=[];const V=ka(()=>{const e=x.filter(n=>n!=null),t=[...new Set(e.map(n=>Ma(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(Nn);return{prefix:u.downloadFilename,lots:t,...e.length===1?{wafer:Ce(e[0])}:{waferCount:e.length}}},u.onSaveImage,u.onSaveText);let R=k.map(e=>typeof e=="function"?null:e),q=null,Yn=null,Kt=!1,Me=0,ae=!1,wt=!1;const le=new WeakSet,Un=new WeakMap,re=()=>{const e=q?.get();return!!e&&!e.off};function Zn(e,t){return{dies:e.dies,wafer:e.wafer,label:ht(e,t),identity:Ce(e),waferIndex:t,passBins:Ue(e),testDefs:e.testDefs,statsSummary:e.statsSummary}}const Gt=new Map;function Je(e,t){if(!q||!re())return e;const n=Un.get(e);if(n&&n.v===Me)return n.item;const o=q.mark([Zn(e,t)]);let i=e;if(o.narrowing){const s=o.items[0].dies,a=s.filter(f=>!f.filteredOut);i={...e,dies:s,statsSummary:Gt.get(e),...e.yield?{yield:Ha(s,[...Ue(e)],e.yield.yieldPercentGross!=null?"denominator-only":"exclude")}:{},...e.dataCoverage?{dataCoverage:Va(a)}:{}},o.hidden.size&&le.add(i)}return Un.set(e,{v:Me,item:i}),i}const Qn=new WeakMap;function qt(e,t){const n=Je(e,t);if(!mt(l))return n;const o=Qn.get(n);if(o)return o;const i={...n,dies:Ns(n.dies,n.testDefs,Ue(n)),metadataFields:_s(n.metadataFields)};return le.has(n)&&le.add(i),Qn.set(n,i),i}const Jn=new WeakMap;function Ei(e,t){if(!q||!re())return e;const n=Jn.get(e);if(n&&n.v===Me)return n.item;const o=Je(e,t),i=o===e?e:le.has(o)?null:{...o,dies:o.dies.filter(s=>!s.filteredOut)};return Jn.set(e,{v:Me,item:i}),i}function B(){return!q||!re()?R:R.map((e,t)=>e?Ei(e,t):null)}let vt=0,et=!1;function eo(){const e=++vt;Fe=void 0,Gt.clear();const t=()=>{et=!1,A(),de(),Pe&&fe?.render()};if(!ae){t();return}const n=en();if(!n||!(_||n.some(s=>s.statsSummary))){t();return}const o=B().flatMap((s,a)=>s?[{it:s,i:a}]:[]);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:a})=>{const f=await s(o.map(m=>m.it),i);if(e!==vt||Kt)return;const c=o.map(m=>m.i);Fe=a(f,c),f.perWafer.forEach((m,b)=>Gt.set(R[c[b]],m.summary)),Me++,R.forEach((m,b)=>{if(!m||Q.has(l.plotMode))return;const p=qt(m,b);x[b]=p,C[b]?.setStatsSummary(p.statsSummary)}),Le(),t()}).catch(()=>{e===vt&&t()})}const Ve=e=>q&&re()||mt(l)?e.map((t,n)=>typeof t=="function"?t:qt(t,n)):e;function Xt(){return Yn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const t=e({doc:d.ownerDocument,initial:u.insights?.filter,onChange:u.insights?.onFilterChange,savedFilters:u.insights?.savedFilters,onSavedFiltersChange:u.insights?.onSavedFiltersChange,pickFiltersFile:u.insights?.onPickFiltersFile,onSaveText:u.onSaveText,attributes:u.attributes,getRingCount:()=>ie({ringCount:yt()},"the page filter")});return Kt||(q=t,ge=t.createBand(()=>Ut(),{marginLeft:se,marginRight:se,marginBottom:M.lg}),d.insertBefore(ge.el,Z),t.subscribe(Zt),t.get()&&Zt()),t}),Yn}let ge=null,St=null,tt=null,Yt;const Ut=()=>R.flatMap((e,t)=>e?[Zn(e,t)]:[]);function to(){clearTimeout(Yt),Yt=setTimeout(()=>{if(!q||!ge)return;const e=Ut(),t=q.keep(e);ge.refresh(t.result,e),ge.el.style.display=q.get()&&!Pe?"":"none";const n=re()&&e.length>0&&t.items.length===0;tt??=xa(d.ownerDocument,"wmapGalleryFilterEmpty"),tt.style.gridColumn="1 / -1",n&&!tt.isConnected?$.prepend(tt):n||tt.remove()},0)}function no(){if(q){if(ke>0){re()&&(wt=!0);return}Me++,ae=re()&&R.some((e,t)=>e!==null&&Je(e,t)!==e),Fe=void 0,et=ae&&!!_,eo()}}function Zt(){if(Me++,ae=!1,ke>0){wt=!0,to();return}wt=!1;const e=l.plotMode;ae=re()&&R.some((t,n)=>t!==null&&Je(t,n)!==t),Fe=void 0,et=ae&&!!_,R.length>0&&(Q.has(e)?(l={...l,...Ft(e)},X(qe(e))):X(Ve(R.filter(t=>t!==null)))),to(),eo()}function He(){return ll(B())}function nt(){if(B().some(e=>e?.testDefs?.length))return He().defs}let ot=0,ke=0;const ee=new Map;let Oi=0,Ct=null,te=null,he=null,je=null;function xt(){te===null&&he===null&&(je={plotMode:l.plotMode,activeTest:l.activeTest})}function oo(){je&&W({...je},{fireCallback:!1}),je=null}let io=new Set,S=null,Ti={};function so(e){return B()[e]?.statsSummary??J()?.perWafer.find(t=>t.waferIndex===e)?.summary}function ao(){return!!(B().some(e=>e?.statsSummary?.findings.length)||J()?.perWafer.some(e=>e.summary.findings.length))}const Li=Js(),ze=ea(Li),{makeBtn:_e,setActive:lo,makeSep:De,syncSeparators:Qt,syncToolbarVisible:Jt,makeMenuRow:Wi,makeMenuSection:Pi,makeDropdown:ro,closeOpenMenu:Mt,getOpenMenu:it,setOpenMenu:st}=ze;d.ownerDocument.addEventListener("click",Mt,!0);const co=()=>di();window.addEventListener("blur",co);let uo=u.findingsNotice,Be=null;function en(){const e=R;return e.length>0&&e.every(t=>t!=null&&_a(t))?e:null}function Ri(){return _?.stats.testValueAnalysis??Na(B().flatMap(e=>e?.statsSummary?[e.statsSummary]:[]))}const tn=()=>uo??(en()?Ka(Ri(),B().length,Be!==null,Ai):void 0);function Ai(){const e=en();if(Be||!e)return;const t=new AbortController;Be=t,A();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);R=R.map((s,a)=>s&&{...s,statsSummary:i[a]}),Q.has(l.plotMode)||(x=x.map((s,a)=>s&&{...s,statsSummary:i[a]}),C.forEach((s,a)=>s?.setStatsSummary(i[a]))),_=o,Le(),A(),de(),u.onStatsSummaryChange?.({summaries:i,lotStatsSummary:o})}).catch(o=>{if(!t.signal.aborted)throw Be=null,A(),o})}function nn(){Be?.abort(),Be=null}function fo(e){io=new Set(e);const t=[...$.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=io.has(i);o.style.outline=s?`3px solid ${v.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function on(){fo([])}let kt=!1;function sn(){kt=!0;for(const e of C)e&&e.clearSelection();kt=!1}function po(e){return t=>{!kt&&(te!==null||he!==null)&&(je=null,Te(),A()),cn.set(e,t.length),ce&&!at&&!kt&&$i(e,t),e.onSelect?.(t)}}function an(e,t,n,o){const i=B()[e];if(!i)return null;let s=null;const a=ia({title:t,onClose:()=>s?.destroy(),anchor:d});Zo(a,t,i.wafer.metadata??void 0);const f=Es(l.plotMode,l.activeTest,n,o);return s=Bn(a.contentWrap,i,n,f?{plotMode:f}:void 0,mi(a)),s}function Ee(e,t,n){e!==void 0&&(C.forEach((o,i)=>{o&&i!==e&&o.locateDie(null)}),n!==void 0&&!Q.has(l.plotMode??"hardBin")&&C[e]?.setOptions({plotMode:"value",activeTest:n}),C[e]?.locateDie(t),$.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let ce=!1,at=!1,Oe=new Set;function $i(e,t){at=!0;try{Oe=new Set(t.map(n=>_t(n))),x.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>Oe.has(_t(s))))})}finally{at=!1}Lt()}function mo(){Oe=new Set,at=!0;try{for(const e of C)e?.clearSelection()}finally{at=!1}Lt()}function ln(){if(!ce||Oe.size===0)return;const e=[];let t=!1;if(x.forEach((i,s)=>{if(!i)return;const a=i.dies.filter(f=>Oe.has(_t(f)));a.length!==0&&(i.isLotStack&&(t=!0),e.push({label:Ce(i)??i.label??`Wafer ${s+1}`,dies:a,waferIndex:s,wafer:i.wafer,passBins:xe(i),ringCount:ie(i,"renderWaferGallery")}))}),e.length===0)return;const n=He(),o=l;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?Fn:void 0},ctx:{plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s,a)=>Ee(s,i,a)}}}function go(){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:Ce(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:xe(o),ringCount:ie(o,"renderWaferGallery")}))}),e.length<2)return;const n=l;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:He().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Fn:void 0},ctx:{plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(o,i,s)=>Ee(i,o,s)}}}function Fi(e){const t=ln()??bo(e);if(t)return t;const n=go(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function rn(e,t,n){te!==e&&t.click();const o=S;if(!o)return;const i=J()?.findings.find(a=>a.id===e),s=ln()??go()??Vi()??(i?ho(wo(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:a})=>{o.isConnected&&a(n,o,s.source,{plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,...s.ctx})})}function Ii(e,t,n,o){const i=_n(l.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],a=[];let f=!1;x.forEach((g,w)=>{g&&(g.isLotStack&&(f=!0),a.push({label:Ce(g)??g.label??`Wafer ${w+1}`,dies:g.dies,waferIndex:w,wafer:g.wafer,passBins:xe(g),ringCount:ie(g,"renderWaferGallery")}))});const c=He().defs,m=bi(a,e,s,c,void 0,f);if(!m)return;const b={plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(g,w,h)=>Ee(w,g,h)},p=s.length>1?bi(a,e,[t],c,void 0,f):null,r=p?{...b,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:p,ctx:b}}:b;import("./drilldown.js").then(({openDrilldownMenu:g})=>{o.isConnected&&g(n,o,m,r)})}function ho(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((a,f)=>a-f)){const a=x[s];a&&(a.isLotStack&&(o=!0),n.push({label:Ce(a)??a.label??`Wafer ${s+1}`,dies:a.dies,waferIndex:s,wafer:a.wafer,passBins:xe(a),ringCount:ie(a,"renderWaferGallery")}))}if(n.length===0)return;const i=l;return{source:{items:n,population:n.length===1?`on ${n[0].label}`:`on ${n.length} ${t}wafers`,testDefs:He().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Fn:void 0},ctx:{plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(s,a,f)=>Ee(a,s,f)}}}function Vi(){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=l;return{source:Wa(n,{waferLabel:Ce(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:xe(t),ringCount:ie(t,"renderWaferGallery")}),ctx:{onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s,a)=>Ee(s??e,i,a)}}}function Hi(e){e||mo(),ce=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],a=C[i];if(!s||!a)continue;const f=s.dies.filter(c=>n.has(_t(c)));a.setSelection(f)}}const U=new Set,cn=new Map;function yo(){[...$.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=U.has(o)?`2px solid ${v.iconActive}`:"",n.style.outlineOffset=U.has(o)?"-2px":""});const t=U.size;ne.style.display=t>0?"":"none",ne.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,ne.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function ji(e){e<0||(U.has(e)?U.delete(e):U.add(e),yo())}function zi(){U.clear(),yo()}function bo(e){if(!(U.size===0||!U.has(e))){for(const t of cn.values())if(t>0)return;return ho([...U],"picked ")}}function _i(){const e=[];for(let t=0;t<B().length;t++){const n=B()[t];if(!n)continue;const o=so(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 Ni(e){const t=B()[e];t&&an(e,`Wafer ${t.label??e+1}`,void 0,"bins")}function Ki(e){const t=so(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 Gi(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{wa(e(tl(B(),yt())),{anchor:d})})}function qi(){if(!S)return;S.innerHTML="";const e=_i(),t=B().filter(Boolean).length;if(t>0){const o=d.ownerDocument.createElement("div"),i=e.length;o.textContent=i===0?t===1?"No findings on the wafer":`No findings on any of the ${t} wafers`:`${i} of ${t} wafer${t===1?"":"s"} with findings`,Object.assign(o.style,{fontSize:z.body,color:v.label,marginBottom:M.md}),S.appendChild(o)}if(e.length>0){const o=d.ownerDocument.createElement("button");o.type="button",o.textContent="Summary report",Object.assign(o.style,{...Ys("outlined"),marginBottom:M.lg,display:"block",width:"100%",textAlign:"left"}),An(o),o.addEventListener("click",Gi),S.appendChild(o)}if(e.length===0){if(t===0){const o=d.ownerDocument.createElement("div");Object.assign(o.style,{color:v.icon,fontSize:z.body,padding:"4px 0"}),o.textContent=re()?"The filter keeps no wafer.":"No findings on any wafer.",S.appendChild(o)}}else for(const{index:o,item:i,unusualCount:s,notableCount:a,totalCount:f}of e){const c=s?"unusual":a?"notable":"info",m=s+a||f,b=d.ownerDocument.createElement("button");b.type="button",Object.assign(b.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:M.xs,border:"none",borderLeft:`3px solid ${ri(c)}`,borderRadius:Y.control,background:v.bgHover,cursor:"pointer",fontSize:z.body,textAlign:"left",boxSizing:"border-box"}),b.addEventListener("mouseover",()=>{b.style.background=v.bgActive}),b.addEventListener("mouseout",()=>{b.style.background=v.bgHover});const p=d.ownerDocument.createElement("span");p.textContent=ht(i,o),Object.assign(p.style,{color:v.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const r=d.ownerDocument.createElement("span");r.textContent=String(m),b.setAttribute("aria-label",`${ht(i,o)} \u2014 ${m} finding${m===1?"":"s"}${s?`, ${s} unusual`:""} \u2014 view wafer`),Object.assign(r.style,{marginLeft:M.sm,flexShrink:"0",background:ri(c),color:"#fff",borderRadius:Y.container,padding:"1px 5px",fontSize:z.body,fontWeight:"600"}),b.appendChild(p),b.appendChild(r),b.addEventListener("click",()=>It(o,i)),S.appendChild(b)}const n=d.ownerDocument.createElement("div");n.style.height="12px",S.appendChild(n)}let Ne=null,lt=null;function A(){if(!S||ae&&_&&!Fe&&et)return;Ne?.cancel(),Ne=null;const e=J();if(e){const t=Ht(B().map(o=>o?.hbinDefs)),n=Ht(B().map(o=>o?.sbinDefs));Ne=dl(el(S,{lotSummary:e,items:B(),hbinDefs:t.length?t:void 0,sbinDefs:n.length?n:void 0,testDefs:nt(),ringCount:yt(),binColors:l.binColors,plotMode:l.plotMode??"hardBin",fallbackFormat:l.fallbackFormat,activeFindingId:te,warnings:u.warnings?.display??!0?ye:[],findingsFilter:Ti,findingsNotice:tn(),onFindingsFilterChange:A,onSaveText:V.onSaveText,attributes:u.attributes,onFindingClick:(o,i)=>{te===o.id?(Te(),oo()):(xt(),Mo(o,i)),A()},activeTest:he,onTestClick:o=>{const i=he===o;i||xt(),Te(),i?oo():xo(o),A()},onShowChart:I?o=>{ut(!0),jo().then(i=>i?.showWorthCard(o))}:void 0,onWaferClick:Ni,findingsFor:Ki,dieListOptions:u.dieList,onLocateDie:(o,i,s)=>Ee(i,o,s),onClose:()=>un(!1)}),{onDone:()=>{const o=lt;lt=null,o?.()}})}else qi()}function wo(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let Bt=[];function vo(){if(Bt.length!==0){for(const e of Bt)C[e]?.setOptions({plotMode:l.plotMode,activeTest:l.activeTest});Bt=[]}}function Te(){te=null,he=null,on(),sn(),vo(),W({highlightBin:void 0},{fireCallback:!1})}function So(){te===null&&he===null||(je=null,Te(),A())}function Co(e,t){const n=nt();if(n===void 0||n.some(i=>i.testNumber===e))W({plotMode:"value",activeTest:e,highlightBin:void 0},{fireCallback:!1});else{W({highlightBin:void 0},{fireCallback:!1});const s=Q.has(l.plotMode??"hardBin")?null:t;if(s){for(const a of s)C[a]?.setOptions({plotMode:"value",activeTest:e});Bt=[...s]}}}function xo(e){he=e;const t=o=>x[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=x.map((o,i)=>i).filter(o=>t(o)?.length);if(Co(e,n.length?n:null),on(),sn(),!Q.has(l.plotMode??"hardBin"))for(const o of n)Dt(t(o),[o])}function Mo(e,t){if(te===e.id){Te();return}te=e.id,he=null,t&&(t.style.background=v.bgActive,t.style.fontWeight="600"),vo();const{kind:n,index:o}=e.variable;if(n==="test")Co(o??0,wo(e));else{const s=x.some(f=>f?.dies?.some(c=>c.hbin!=null)),a=ai(x.map(f=>f?Ue(f):void 0));W({plotMode:$a(e,l.plotMode,s),highlightBin:Aa(e,a,s)},{fireCallback:!1})}on(),sn();const i=e.highlight;if(i.kind==="wafer"){fo(i.waferIndices);const s=wi(e);for(const a of i.waferIndices){const f=i.dieKeysByWafer?void 0:x[a]?.statsSummary?.findings.find(m=>wi(m)===s),c=i.dieKeysByWafer?.[a]??f?.highlight?.dieKeys;c?.length&&Dt(c,[a])}}else i.kind==="bin"?i.dieKeys?.length&&Dt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Dt(i.dieKeys)}function dn(){return!!S&&S.style.display!=="none"}function un(e){!S||e===dn()||(e&&A(),S.style.display=e?"flex":"none",de())}function de(){Ct&&(Qt(H),Jt(H,"inline-flex"),Ct.sync({visible:!!(_||J()||ao())&&!!S&&!Pe,open:dn(),notable:!!(J()?.hasNotableFindings||B().some(e=>e?.statsSummary?.hasNotableFindings))}))}const H=d.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:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:Y.control,padding:"0",boxShadow:Rn.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const ko=()=>{const e=it();e&&(e.remove(),st(null)),gt(ue,!1)},ue=_e("mode","Plot mode",()=>{if(it()){ko();return}const e=B().flatMap(h=>h?.dies??[]),t=nt(),{testEntries:n,binEntries:o,stackedEntries:i}=ya(e,t,{includeStacked:!0}),s=B().filter(Boolean).length,a=h=>{if(h===void 0)return s;let E=0;for(const P of B())P?.dies?.some(K=>vi(K,h)!==void 0||cl(K,h)!==void 0)&&E++;return E},f=s<2?n:n.map(h=>{const E=a(h.activeTest);return E===s?h:{...h,label:`${h.label} \u2014 ${E} of ${s} wafers`}}),c=l.plotMode??"hardBin",m=l.activeTest??0;function b(h){return h.plotMode!==c?!1:h.plotMode==="value"?m===(h.activeTest??0):h.plotMode==="metadata"?l.activeMetadataKey===h.activeMetadataKey:!0}function p(h,E){h.activeTest!==void 0?W({plotMode:"value",activeTest:h.activeTest,activeMetadataKey:void 0,logScale:h.logScale}):h.activeMetadataKey!==void 0?W({plotMode:h.plotMode,activeTest:void 0,activeMetadataKey:h.activeMetadataKey,passFailDisplay:"off"}):W({plotMode:h.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),st(null),gt(ue,!1)}const r=new Set,g=B().flatMap(h=>h?.metadataFields??[]).filter(h=>!r.has(h.key)&&r.add(h.key)).filter(h=>ba(e,h.key)).map(gi);ke===0&&zs(B())&&g.push(gi(Vs));const w=ta(ue.getBoundingClientRect(),f,o,i,b,p,{makeMenuRow:Wi,makeMenuSection:Pi},c,ue.ownerDocument.defaultView??window,g);ui(ue).appendChild(w),st(w),gt(ue,!0),fi(w,ue,ko)});gt(ue,!1);const Xi=()=>x.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:Yi,sync:Do}=la(ze,()=>({...l,plotMode:l.plotMode??"hardBin"}),Xi,e=>W(e));Do();const Ui=k.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function Et(){const e=nt(),{testNumber:t}=Ls(l.activeTest??0,e);return{testNumber:t,td:Ws(e,t)}}function Bo(){if((l.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function rt(){if((l.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&!Vn(e)}function Zi(){if((l.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=Et();return B().some(n=>n?.dies?.some(o=>vi(o,e,t)!==void 0))}function Qi(e,t){if(!t||!Vn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((pi(l)==="spec"&&n?"spec":l.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,a=-1/0;for(const f of B())if(f)for(const c of f.dies){const m=za(c,e);m!==void 0&&(m<s&&(s=m),m>a&&(a=m))}if(isFinite(s))return s===a?[s,s+1]:[s,a]}function Ot(e,t,n){const o=l[e];if(o===t||o!=null&&t!=null&&n(o,t))return!1;l={...l,[e]:t};for(const i of C)i&&i.setOptions({[e]:t});return!0}function Eo(){if((l.plotMode??"hardBin")!=="metadata")return;const e=l.activeMetadataKey;if(!e)return;if(mt(l))return{key:e,values:[...js]};const t=new Set;for(const n of B())if(n)for(const o of Ps(n.dies,e))t.add(o);return{key:e,values:[...t].sort(Nn)}}function fn(){Ot("metadataValueOrder",Eo(),(e,t)=>e.key===t.key&&zt(e.values,t.values))}function pn(){if((l.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=Et(),n=Qi(e,t);Ot("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const a=m=>Array.isArray(m)?{test:void 0,range:m}:{test:m.test,range:m.range},f=a(i),c=a(s);return f.test===c.test&&zt(f.range,c.range)})}let mn=!1;function Ji(){if(mn)return;mn=!0,(d.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{mn=!1,pn(),fn(),Wo(),Lo()})}let gn=!1;function es(){if(gn)return;gn=!0,(d.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{gn=!1,$t()})}let Oo=[];function N(){const{colors:e,mixedHardBins:t}=As(B().filter(n=>n!=null),{binColorScheme:l.binColorScheme,useDefinedBinColors:l.useDefinedBinColors});return Oo=t,e}function hn(){return x.filter(e=>e!=null).flatMap(e=>e.dies)}function To(){return l.compact?Ua(hn()):void 0}const ts=(e,t)=>zt(e.columns,t.columns)&&zt(e.rows,t.rows);function Lo(){Ot("compactMap",To(),ts)&&Ko()}function ns(){return Za(hn(),x.filter(e=>e!=null).map(e=>e.reticleConfig))}function Wo(){Ot("binColors",N(),Is),Le()}const os=da(ze,()=>pa(l,Ui,{functionalActive:rt(),hasLimits:Bo()&&!rt(),hasRecorded:Zi()&&!rt(),binMode:(l.plotMode??"hardBin")==="hardBin"||(l.plotMode??"hardBin")==="softBin"},e=>W(e),{on:!!l.compact,offered:ns(),onChange:e=>W({compact:e}),onDiagnostics:()=>ga(hn(),x.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:d,onSaveText:V.onSaveText})}),()=>ma(l)),{btn:is,sync:Po}=ca(ze,()=>({plotMode:l.plotMode,legendPosition:Ze}),e=>{Ze=e;for(const t of C)t&&t.setOptions({legendPosition:Ze})},{get:()=>bt,set:e=>{bt=e,Xn()},blockedReason:Qe});Po();const ss=[{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"}],Ro=ro("aggr","Aggregation method",()=>ss,()=>l.aggregationMethod??"mean",e=>W({aggregationMethod:e}));function Ao(){const e=l.plotMode==="stackedValues";Ro.style.display=e?"":"none"}Ao();const{btn:as,sync:$o}=ra(ze,()=>({...l,functionalActive:rt()}),e=>W(e));$o();const Tt=_e("specRange","Colour bar range: test limits",()=>{const e=l.colorbarRangeMode==="data"?"spec":"data";W({colorbarRangeMode:e})});function Fo(){const e=(l.plotMode??"hardBin")==="value"&&Bo()&&pi(l)==="off"&&!rt();Tt.style.display=e?"":"none";const t=(l.colorbarRangeMode??"spec")==="spec";lo(Tt,t),Tt.ariaLabel=t?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"}Fo();const ls=ua(ze,()=>l,e=>W(e)),rs=_e("downloadAll","Download gallery PNG",Ms),Ke=_e("boxSelect","Select the same dies on every wafer",()=>{ce&&Oe.size>0?mo():Hi(!ce)});Ke.style.position="relative";const ct=d.ownerDocument.createElement("span");ct.dataset.wmapSelectAcrossCount="1",Object.assign(ct.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:Y.pill,background:v.iconActive,color:v.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Ke.appendChild(ct);function Lt(){lo(Ke,ce);const e=ce?Oe.size:0;ct.style.display=e>0?"block":"none",ct.textContent=e>99?"99+":String(e),Ke.ariaLabel=ce?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)",Ke.setAttribute("aria-pressed",String(ce))}const ne=d.ownerDocument.createElement("button");ne.type="button",ne.dataset.wmapPickedWafers="1",Object.assign(ne.style,{display:"none",border:"none",background:v.bgActive,color:v.iconActive,borderRadius:Y.control,padding:`${M.xs} ${M.md}`,fontSize:z.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),An(ne,"bare"),ne.addEventListener("click",zi);const Io=()=>{const e=x.filter(o=>o!=null&&!le.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},cs=ro("columns","Columns",()=>[{value:"auto",label:"Auto (0)"},...Io().map(e=>({value:String(e),label:`${e} column${e===1?"":"s"} (${e})`}))],()=>O!=null?String(O):"auto",e=>xn(e==="auto"?void 0:Number(e))),L=d.ownerDocument.createElement("div");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:"0"}),H.appendChild(L),L.appendChild(ue),L.appendChild(Yi),L.appendChild(Ro),L.appendChild(as),L.appendChild(Tt),L.appendChild(De()),L.appendChild(os),L.appendChild(De()),L.appendChild(is),L.appendChild(De()),L.appendChild(ls),L.appendChild(De()),L.appendChild(cs),L.appendChild(De()),L.appendChild(Ke),L.appendChild(ne),L.appendChild(rs),Lt();let oe=null,Wt=null,ye=[],Vo=!1;function Le(){const e=qa({lotStatsSummary:J(),result:{warnings:[...B().flatMap(n=>n?.warnings??[]),...He().warnings]},extra:[l.binColors&&$s(l.binColors,l.plotMode),Fs(Oo),Bi(qn())].filter(n=>!!n)}),t=e.length!==ye.length||e.some((n,o)=>n.code!==ye[o]?.code||n.message!==ye[o]?.message);ye=e,(t||!Vo)&&(Vo=!0,u.warnings?.onWarning?.(e)),ds()}function ds(){if(!oe||!Wt)return;const e=ye.length,t=e>0;if(oe.style.display=t?"flex":"none",Wt.style.display=t?"":"none",Qt(H),Jt(H,"inline-flex"),!t)return;const n=Ya(ye[0]),o=`${e} data ${e===1?"warning":"warnings"}`;oe.style.color=n==="error"?v.errText:v.warnText,oe.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(u.warnings?.display??!0)&&(Wt=De(),oe=_e("warning","Data warnings",()=>{const e=it();if(Mt(new MouseEvent("click")),e)return;const t=Xa(oe.getBoundingClientRect(),ye,oe.ownerDocument.defaultView??window);ui(d).appendChild(t),st(t),fi(t,oe,()=>Mt(new MouseEvent("click")))}),gt(oe,!1),H.appendChild(Wt),H.appendChild(oe)),Le();function yn(e){import("./userGuideHtml.js").then(t=>va({buildWaferMap:Ia,renderWaferMap:Ta,renderWaferGallery,analyzeWaferMap:Hn},t.USER_GUIDE_HTML,T,d,e))}const us=Sa(e=>yn(e));D&&(H.appendChild(De()),H.appendChild(_e("help","User guide",()=>yn())));const Ge=d.ownerDocument.createElement("div");Ge.dataset.wmapGalleryMeta="1",Object.assign(Ge.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${M.sm} ${M.lg}`,fontSize:z.sub,lineHeight:li.none,boxSizing:"border-box"});const We=d.ownerDocument.createElement("div");Object.assign(We.style,{background:v.canvasBg,display:"flex",alignItems:"stretch",gap:M.lg,paddingBottom:M.lg,minWidth:"0"});const be=d.ownerDocument.createElement("div");be.dataset.wmapGalleryLegend="1",Object.assign(be.style,{display:"flex",flexDirection:"column",gap:M.sm,background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:Y.container,padding:`${M.sm} ${M.lg}`,marginBottom:M.lg,boxShadow:Rn.panel,fontSize:z.body,lineHeight:li.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const Z=d.ownerDocument.createElement("div");Object.assign(Z.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let fe=null,dt=null,Ho=null;function jo(){return I?fe?Promise.resolve(fe):(Ho??=Promise.all([import("./insightsTab.js"),Xt()]).then(([{createInsightsTab:e},t])=>(fe=e({pageFilter:t,showFilterButton:!1,initialAxisPrefs:jn(l),onAxisPrefsChange:n=>{l={...l,...Ga(n)};const o=[...zn];u.onViewOptionsChange?.(jt(l),o,In(o))},attributes:u.attributes,getItems:()=>R,getLotStats:()=>_,getSynthesisSummary:()=>J(),getBinColors:()=>l.binColors??N(),getRingCount:()=>ie({ringCount:yt()},"the Insights tab"),defaultView:u.insights?.defaultView,plotStore:F,onPickPlotsFile:u.insights?.onPickPlotsFile,showPatMap:()=>{ut(!1),W({plotMode:"metadata",activeTest:void 0,activeMetadataKey:Hs,passFailDisplay:"off"})},showOnMap:n=>{if(ut(!1),n.kind==="test")xt(),Te(),xo(n.testNumber);else if(n.kind==="finding"){const o=J(),i=o?Fa(o).findings.find(s=>s.id===n.id):void 0;i&&te!==i.id&&(xt(),Mo(i))}un(!0),A()},onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,ownerDocument:d.ownerDocument,locateDie:(n,o,i)=>{const s=o===void 0?null:B()[o];s&&an(o,`Wafer ${s.label??o+1}`,i)?.locateDie(n)},openWafer:(n,o,i,s)=>{an(n,o,i,s)}}),dt=fe.el,dt.style.display="none",d.appendChild(dt),fe)),Ho):Promise.resolve(null)}let Pe=!1,bn=null;function ut(e){I&&(Pe=e,bn?.setInsightsOpen(e),dt&&(dt.style.display=e?"flex":"none"),Z.style.display=e?"none":"flex",ge&&(ge.el.style.display=q?.get()&&!e?"":"none"),L.style.display=e?"none":"inline-flex",Qt(H),Jt(H,"inline-flex"),H.style.display="inline-flex",de(),$t(),e&&jo().then(t=>{!t||!Pe||(t.el.style.display="flex",t.render())}))}I&&u.insights?.defaultOpen&&queueMicrotask(()=>ut(!0));const fs=6,ps=4,Pt=240,wn=480,ms=720,gs=1.25;let Re=wn;function zo(e){const t=j*2+110+2,n=_o();if(n)return Math.ceil(n.across*ps+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 a=i.wafer.radius*2*(fs/s),f=Math.ceil(a+t);(o==null||f>o)&&(o=f)}return o}function hs(e){const t=zo(e);return t==null?Pt:Math.min(Re,Math.max(Pt,t))}function ys(e){const t=zo(e);if(t==null)return!1;const n=Math.min(ms,Math.max(wn,t));return n<=Re?!1:(Re=n,!0)}function _o(){const e=l.compact?l.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=(l.rotation??0)%180!==0,o=l.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 No(e,t){const n=_o();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 bs(){for(const e of me)e?.parentElement&&No(e.parentElement,e)}function Ko(){Re=wn,ft=Pt,Cn(x.map(e=>e??null)),Rt(),bs()}function vn(){return Go()?`${Re}px`:"none"}function Go(){return O==null&&!Sn}let Sn=!1;function Rt(){const e=vn();for(const t of Array.from($.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let ft=Pt,qo=0;function Cn(e){if(ys(e)&&Rt(),O==null){const n=hs(e);n>ft&&(ft=n)}kn()}function xn(e){O=xi(e),Rt(),kn()}let At=!1;d.addEventListener("pointerenter",()=>{At=!0}),d.addEventListener("pointermove",()=>{At=!0}),d.addEventListener("pointerleave",()=>{At=!1});const ws=()=>{if(At)return!0;try{return d.matches(":hover")}catch{return!1}},Xo=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||Pe||!ws()&&!d.contains(e.target)||!/^[0-5]$/.test(e.key)||d.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"&&!Io().includes(Number(e.key))||(e.preventDefault(),xn(e.key==="0"?void 0:Number(e.key)))};d.ownerDocument.addEventListener("keydown",Xo);function Mn(e){return`repeat(${e}, minmax(0, ${Go()?`${Re}px`:"1fr"}))`}function Yo(e){$.style.gridTemplateColumns!==e&&($.style.gridTemplateColumns=e)}function kn(){if(O!=null){Yo(Mn(O));return}const e=Math.max(1,qo),t=12,n=$.clientWidth||0,o=a=>(n-t*(a-1))/a;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const a=Math.min(Re,ft*gs),f=c=>{let m=0;for(;m<e&&o(m+1)>=c;)m++;return m};i=f(a)||f(ft)||1}const s=n>0&&i<e;s!==Sn&&(Sn=s,Rt()),Yo(Mn(i))}const $=d.ownerDocument.createElement("div");if(Object.assign($.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Mn(1),gap:M.xl,paddingLeft:se,paddingRight:se,justifyContent:"start",alignContent:"start",isolation:"isolate"}),$e?.placement){const e=$e.placement;S=Kn(e,se,d.ownerDocument,rn),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.display="flex",S.style.flexDirection="column"}else if(_||J()||ao()){const e=!!$e?.defaultOpen;S=Kn("right",se,d.ownerDocument,rn),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display=e?"flex":"none",A()}de(),($e?.placement??"right")==="left"?(S&&Z.appendChild(S),Z.appendChild($)):(Z.appendChild($),S&&Z.appendChild(S));const Ae=d.ownerDocument.createElement("div");Object.assign(Ae.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:se,paddingRight:se,paddingTop:se,zIndex:"1",background:v.menuBg}),We.appendChild(Ge),We.appendChild(H),Ct=Os(d.ownerDocument,()=>un(!dn())),We.appendChild(Ct.el),de(),I&&(bn=Bs(d.ownerDocument,"Maps","lot",e=>ut(e)),We.appendChild(bn.el)),I&&(St=Ca(d.ownerDocument,"Filter\u2026","wmapGalleryFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{Xt().then(e=>e.openEditor(St??d,Ut()))}),St.style.order="1",We.appendChild(St)),Ae.appendChild(We),Ae.appendChild(be),d.appendChild(Ae),d.appendChild(Z);function $t(){be.innerHTML="";const e=l.plotMode??"hardBin",t=!Pe&&ci.has(e),n=x.filter(y=>y!=null&&!le.has(y)),o=n.find(y=>y.isLotStack),i=o?B().filter(y=>y!==null&&!le.has(y)):n,s=Qa(i.map(y=>({metadata:y.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:u.attributes}),a=e==="metadata",f=l.activeMetadataKey,c=t&&!a?Mi(n,y=>(e==="softBin"?y.sbin:y.hbin)??void 0,xe):{counts:new Map,total:0,pass:0},m=t&&!a?l.binColors??N():void 0,b=m?e==="softBin"?m.pass.soft:m.pass.hard:new Set,p=Da(c.counts.entries(),b).map(([y])=>y),r=t&&a&&f?Mi(n,y=>Rs(y.metadata?.[f])):{counts:new Map,total:0,pass:0},g=a?Eo()?.values:void 0,w=t&&a?(g??[...r.counts.keys()].sort(Nn)).filter(y=>r.counts.has(y)):[];if(Ge.innerHTML="",s&&Ge.appendChild(s),Ge.style.display=s?"flex":"none",!p.length&&!w.length){be.style.display="none";return}be.style.display="flex";const h=d.ownerDocument.createElement("div");Object.assign(h.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${M.sm} ${M.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),be.appendChild(h);const E=_n(l.highlightBin),P=x.flatMap(y=>y?.metadataFields??[]).find(y=>y.key===f),K=a?P?.label??(f?ol(f):"Metadata"):Zs[e],we=d.ownerDocument.createElement("span");if(we.textContent=K,Object.assign(we.style,{fontSize:z.body,fontWeight:"700",letterSpacing:Xs,textTransform:"uppercase",color:v.label,flexShrink:"0"}),h.appendChild(we),!a&&c.total>0){const y=c.pass,G=y/c.total*100,ve=d.ownerDocument.createElement("span");ve.textContent=`Yield ${Nt(G)}`,Object.assign(ve.style,{fontSize:z.body,fontWeight:"700",color:v.value,whiteSpace:"nowrap",flexShrink:"0"});const Se=d.ownerDocument.createElement("span");Se.textContent=`${y.toLocaleString()} / ${c.total.toLocaleString()} dies`,Object.assign(Se.style,{fontSize:z.body,color:v.label,whiteSpace:"nowrap",flexShrink:"0"}),h.appendChild(ve),h.appendChild(Se)}if(a){const y=_n(l.highlightMetadataValue);w.forEach((G,ve)=>{const Se=y.includes(G),Ye=P?.values?.find(Wn=>Wn.value===G),pt=Ye?.color??Gs(ve),si=r.counts.get(G)??0;ki(h,{color:pt,isActive:Se,label:Ye?.label??G,count:si,percent:r.total>0?si/r.total*100:void 0,onClick:Wn=>{const Ds=Si(l.highlightMetadataValue,G,Wn);So(),W({highlightMetadataValue:Ds})}})});return}const On=e==="softBin"?x.flatMap(y=>y?.sbinDefs??[]):x.flatMap(y=>y?.hbinDefs??[]),ni=new Set,Tn=[];for(const y of On)ni.has(y.bin)||(ni.add(y.bin),Tn.push(y));const Ln=Tn.length>0?new Map(Tn.map(y=>[y.bin,y])):null,oi=m??l.binColors??N(),ks=e==="softBin"?oi.soft:oi.hard,ii=y=>ks.get(y)??Ks;for(const y of p){const G=E.includes(y),ve=Ln?.get(y),Se=c.counts.get(y)??0;ki(h,{color:ii(y),isActive:G,label:ve?.name?`${y} \xB7 ${ve.name}`:`Bin ${y}`,count:Se,percent:c.total>0?Se/c.total*100:void 0,onMenu:(Ye,pt)=>Ii(e==="softBin"?"soft":"hard",y,Ye,pt),onClick:Ye=>{const pt=Si(l.highlightBin,y,Ye);So(),W({highlightBin:pt})}})}c.total>0&&p.length>1&&be.appendChild(ul(d.ownerDocument,[...c.counts.entries()].sort(([,y],[,G])=>G-y).map(([y,G])=>({color:ii(y),count:G,label:Ln?.get(y)?.name?`${y} \xB7 ${Ln.get(y).name}`:`Bin ${y}`})),c.total))}function qe(e){const t=B().filter(p=>p!==null&&!le.has(p));if(!t.length)return[];const n=t.map(p=>p.dies.filter(rl).filter(r=>!r.filteredOut)),o=t[0].wafer,i=t.length,s=ai(t.map(p=>Ue(p)));if(!s)return[];const a=new Set(t.map(p=>ie(p,"renderWaferGallery")));if(a.size!==1)return[];const f=[...a][0],c=o.metadata?{...o,metadata:(({wafer:p,waferId:r,...g})=>g)(nl(t.map(p=>({metadata:p.wafer.metadata??void 0}))))}:o;function m(p,r){return{...p,stats:{...p.stats,isLotStack:!0,aggregationMethod:r,lotSize:i}}}function b(p,r){const g=p.map(w=>({...w,hbin:void 0,sbin:void 0}));return Hn({wafer:c,dies:g,passBins:[...s],ringCount:f,testDefs:[{testNumber:0,name:r}]},{testNumbers:[0]})}if(e==="stackedValues"){const p=nt();let r=p?.filter(Vn);if(p!==void 0&&r?.length===0)return[];if(p?.length||(r=Ts(t.flatMap(h=>h.dies)).map(h=>({testNumber:h,name:il(void 0,h)}))),!r?.length)return[];const g=l.aggregationMethod??"mean";return r.map(w=>{const h=Oa(n,g,w.testNumber),E={testNumber:0,name:w.name,unit:w.unit,...al(w)};return{wafer:c,dies:h,passBins:[...s],ringCount:f,testDefs:[E],label:`${sl(w,w.testNumber)} \xB7 ${g}`,isLotStack:!0,aggrMethod:g,lotSize:i,statsSummary:m(Hn({wafer:c,dies:h,passBins:[...s],ringCount:f,testDefs:[E]},{testNumbers:[0]}),g)}})}if(e==="stackedBins"){let p=Ht(t.map(r=>r?.hbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(w=>w.hbin).filter(w=>w!=null)))].sort((g,w)=>g-w).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(r=>{const g=hi(n,r.bin,"hard"),w=[{bin:r.bin,name:r.name}];return{wafer:c,dies:g,passBins:[...s],ringCount:f,hbinDefs:w,label:`${r.bin} \xB7 ${r.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(b(g,`Wafers in hard bin ${r.bin}`),"countBin")}})}if(e==="stackedSoftBins"){let p=Ht(t.map(r=>r?.sbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(w=>w.sbin).filter(w=>w!=null)))].sort((g,w)=>g-w).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(r=>{const g=hi(n,r.bin,"soft"),w=[{bin:r.bin,name:r.name}];return{wafer:c,dies:g,passBins:[...s],ringCount:f,sbinDefs:w,label:`${r.bin} \xB7 ${r.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(b(g,`Wafers in soft bin ${r.bin}`),"countBin")}})}return t}function Ft(e){const t=B().length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:l.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function W(e,{fireCallback:t=!0}={}){const n=Object.keys(e);if(n.length>0&&n.every(r=>zn.includes(r))){l={...l,...e},fe?.setAxisPrefs(jn(l)),t&&u.onViewOptionsChange?.(jt(l),n,In(n));return}zn.some(r=>r in e)&&fe?.setAxisPrefs(jn({...l,...e}));const o=l.plotMode,i=mt(l),s=Qe()!==null;l={...l,...e};const a=l.plotMode,f=Q.has(a),c=mt(l),m=o!==void 0&&Q.has(o),b=ke>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const r=N();l={...l,binColors:r},e={...e,binColors:r}}if("compact"in e){const r=To();l={...l,compactMap:r},e={...e,compactMap:r}}if(("compact"in e||l.compact&&("rotation"in e||"showXYIndicator"in e))&&Ko(),e.plotMode!==void 0)if(f){const r=Ft(a);if(l={...l,...r},b)for(const g of C)g&&g.setOptions(e);else X(qe(a))}else if(m){const{valueRange:r,lotSize:g,aggregationMethod:w,...h}=l;if(l=h,b)for(const E of C)E&&E.setOptions(e);else X(c?Ve(R.filter(E=>E!==null)):B().filter(E=>E!==null))}else if(i!==c&&!b)X(Ve(R.filter(r=>r!==null)));else for(const r of C)r&&r.setOptions(e);else if(e.aggregationMethod!==void 0&&a==="stackedValues")if(b)for(const r of C)r&&r.setOptions(e);else X(qe("stackedValues"));else for(const r of C)r&&r.setOptions(e);Qe()!==null!==s&&Xn(),$t(),Ao(),Po(),Do();const p=e.plotMode!==void 0&&e.plotMode!==o;(Ra.some(r=>r in e)||p)&&A(),Le(),$o(),Fo(),pn(),fn(),t&&u.onViewOptionsChange?.(jt(l),n,In(n))}function Uo(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:z.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=Ci(e,o,t,n,u.attributes);return{wrap:o,metaPanel:s}}function Zo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||Ja(n??{}).length===0)return;const i=o.parentElement,s=d.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 a=Ci(d.ownerDocument,s,t,n,u.attributes);a&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(a))}function Dn(e,t,n){const o=d.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:Y.container,boxShadow:Rn.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:vn(),maxHeight:vn()});const i=d.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${v.menuBorder}`,flexShrink:"0",gap:M.sm});const{wrap:s,metaPanel:a}=Uo(document,ht(e,t),e.wafer.metadata??void 0);i.appendChild(s);const f=d.ownerDocument.createElement("button");f.dataset.wmapExpandBtn="1",f.setAttribute("aria-label","Open full view"),$n(f),f.innerHTML=Pn.expand,Object.assign(f.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${v.menuBorder}`,borderRadius:Y.control,background:v.panelBg,color:v.label,padding:M.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),An(f),i.appendChild(f),i.addEventListener("click",r=>{(r.ctrlKey||r.metaKey)&&(r.preventDefault(),r.stopPropagation(),ji(x.indexOf(e)))},!0),o.appendChild(i);const c=d.ownerDocument.createElement("div");Object.assign(c.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(c),No(o,c),a&&c.appendChild(a),$.appendChild(o),o.addEventListener("contextmenu",r=>{if(r.defaultPrevented)return;r.preventDefault();const g=e.viewOptions?{...l,...e.viewOptions}:l,w=ln()??bo(t),h=w?.source??La(e.dies,{waferLabel:Ce(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:g.plotMode==="value"?g.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:xe(e),ringCount:ie(e,"renderWaferGallery")}),E={x:r.clientX,y:r.clientY};import("./drilldown.js").then(({openDrilldownMenu:P})=>{o.isConnected&&P(E,o,h,w?{plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,...w.ctx}:{plots:F,getBinColors:()=>l.binColors??N(),attributes:u.attributes,onSaveImage:p.getSaveImageHook(),onSaveText:p.getSaveTextHook(),onLocateDie:(K,we,On)=>Ee(t,K,On)})})});const m=bt||Qe()!==null,b=e.viewOptions?{...l,...e.viewOptions}:l,p=yi(c,e,{viewOptions:{...b,showLegend:m,legendPosition:Ze},showTooltip:!0,padding:j,statsSummary:e.statsSummary,testValueOffer:tn,onSaveImage:u.onSaveImage,onSaveText:u.onSaveText,downloadFilename:u.downloadFilename,onClick:e.onClick,onSelect:po(e),drilldownSourceOverride:()=>Fi(t),insights:pe,onExpand:()=>It(t,e),showIdentity:!1,chromeInset:Us,drawWhenVisible:!0});return p.setViewControlsVisible(!1),p.setSummaryVisible(!1),f.onclick=()=>It(t,e),le.has(e)&&(o.style.display="none"),{card:o,ctrl:p,canvasWrapper:c,expandBtn:f}}function vs(e){const t=Ie[e];if(!t)return;const n=[...ee.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Pn.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>Cs(n.id)):(t.innerHTML=Pn.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>It(e,x[e]))}function X(e){xs(),it()?.remove(),st(null),Te(),x=[],U.clear(),cn.clear(),ne.style.display="none";for(const c of C)c&&c.destroy();C=[],me=[],Ie=[],ke=0,$.innerHTML="",qo=e.length,Cn(e.map(c=>typeof c=="function"?null:c));const t=[];for(let c=0;c<e.length;c++){const m=e[c];if(typeof m=="function"){const b=d.ownerDocument.createElement("div");b.className="wmap-gallery-card",Object.assign(b.style,{background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:Y.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const p=d.ownerDocument.createElement("span");p.textContent="\u2026",Object.assign(p.style,{color:v.label,fontSize:"18px"}),b.appendChild(p),$.appendChild(b),x.push(null),C.push(null),me.push(null),Ie.push(null),t.push({index:c,factory:m,placeholder:b}),ke++}else{const{ctrl:b,canvasWrapper:p,expandBtn:r}=Dn(m,c,e.length);x.push(m),C.push(b),me.push(p),Ie.push(r)}}Wo(),$t(),pn(),fn(),Lo();const n=++ot,o=()=>{setTimeout(()=>{n===ot&&u.onItemsResolved?.()},0)},i=c=>{setTimeout(()=>{n===ot&&u.onItemResolved?.(c,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let a=0;function f(){if(n!==ot)return;if(a>=t.length){if(Q.has(l.plotMode)){const P=l.plotMode;X(qe(P));return}if(wt){Zt();return}lt=o,A(),Ne||(lt=null,o());return}const{index:c,factory:m,placeholder:b}=t[a++],p=m();R[c]=p;const r=qt(p,c);Je(p,c)!==p&&(ae=!0),x[c]=r,Cn([r]);const{card:g,ctrl:w,canvasWrapper:h,expandBtn:E}=Dn(r,c,e.length);C[c]=w,me[c]=h,Ie[c]=E,ke--,b.replaceWith(g),i(++s),es(),Ji(),!S&&!$e?.placement&&r.statsSummary?.findings.length&&(S=Kn("right",se,d.ownerDocument,rn),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display="none",($e?.placement??"right")==="left"?Z.insertBefore(S,$):Z.appendChild(S),A(),de()),de(),setTimeout(f,0)}t.length>0?setTimeout(f,0):o()}if(Q.has(l.plotMode)&&B().length>0){const e=Ft(l.plotMode);l={...l,...e},X(qe(l.plotMode))}else X(Ve(k));u.insights?.filter!==void 0&&Xt(),Le();let Xe=0;const Qo=new(d.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Xe)return;Xe=(d.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Xe=0,O==null&&kn()})});Qo.observe($);const Jo=()=>{d.style.setProperty("--wmap-sticky-top",`${Ae.offsetHeight}px`)};Jo();const ei=new(d.ownerDocument.defaultView??window).ResizeObserver(Jo);ei.observe(Ae),S&&A();function Ss(e,t){const n=me[e];if(!n)return;n.innerHTML="",Object.assign(n.style,{alignItems:"center",justifyContent:"center"});const o=d.ownerDocument.createElement("span");o.textContent=t?"Opened in its own window":"Opened in the wafer viewer",Object.assign(o.style,{color:v.label,fontSize:z.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function It(e,t){for(const a of ee.values())if(a.cardIndex===e)return;const n=ht(t,e),o=Oi++,i=C[e]?.getOptions(),s=na(n);if(s){const a=s.document;a.title=n,Object.assign(a.documentElement.style,{height:"100%"}),Object.assign(a.body.style,{margin:"0",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",fontFamily:z.family}),sa(d,a.documentElement);const f=aa(d,a.documentElement,()=>h.setOptions({})),c=a.createElement("div");c.dataset.wmapWindowBanner="1",c.textContent=n,Object.assign(c.style,{display:"none",padding:`${M.sm} ${M.xl}`,fontSize:z.body,fontWeight:"700",background:v.warnBg,color:v.warnText,borderBottom:`1px solid ${v.warnBorder}`,flexShrink:"0"}),a.body.appendChild(c);const m=a.createElement("div");Object.assign(m.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),a.body.appendChild(m);const{wrap:b,metaPanel:p}=Uo(a,n,t.wafer.metadata??void 0),r=a.createElement("div");Object.assign(r.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${v.menuBorder}`,flexShrink:"0",gap:M.sm}),r.appendChild(b),m.appendChild(r);const g=a.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 w=0;const h=Bn(g,t,void 0,i,(P,K)=>{const we=P?K:-w;try{s.resizeBy(we,0),w=P?K:0}catch{}}),E=setInterval(()=>{s.closed&&Vt(o)},400);s.addEventListener("pagehide",()=>Vt(o)),ee.set(o,{id:o,ctrl:h,cardIndex:e,label:n,closePollId:E,stopThemeSync:f,close:()=>{s.closed||s.close()},setTitle:P=>{a.title=P,c.textContent=P,c.style.display="block"}})}else{const a=oa({title:n,onClose:()=>Vt(o),anchor:d});a.contentWrap.style.flexDirection="column",Zo(a,n,t.wafer.metadata??void 0);const f=Bn(a.contentWrap,t,void 0,i,mi(a));ee.set(o,{id:o,ctrl:f,cardIndex:e,label:n,closePollId:null,close:()=>a.close(),setTitle:c=>{const m=a.box.querySelector("[data-wmap-window-title]");m&&(m.textContent=c,m.title=c)}})}C[e]?.destroy(),C[e]=null,Ss(e,s!==null),vs(e)}function Bn(e,t,n,o,i){const s=t.viewOptions?{...l,...t.viewOptions}:l,a=o?{...s,...o}:s,c={...n!==void 0?{...a,plotMode:"value",activeTest:n}:a,showLegend:!0,legendPosition:Ze},m=yi(e,t,{viewOptions:c,showTooltip:!0,padding:j,statsSummary:t.statsSummary,testValueOffer:tn,onSaveImage:u.onSaveImage,onSaveText:u.onSaveText,downloadFilename:u.downloadFilename,onClick:t.onClick,onSelect:po(t),insights:pe,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return m.setViewControlsVisible(!0),m.setSummaryVisible(!0),m.setExpandVisible(!1),m}function Vt(e){const t=ee.get(e);if(!t||(ee.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:a,expandBtn:f}=Dn(o,n,x.length);me[n]?.parentElement?.replaceWith(i),C[n]=s,me[n]=a,Ie[n]=f}function Cs(e){const t=ee.get(e);t&&(t.close(),Vt(e))}function xs(){for(const e of ee.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function En(){for(const e of C)e?.drawPendingNow()}const ti=d.ownerDocument.defaultView??window;ti.addEventListener("beforeprint",En);function Ms(){En();const e=[...$.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,a=8,f=(d.ownerDocument.defaultView??window).devicePixelRatio||1,c=Math.round(26*f),m=Math.round(12*f),b=d.ownerDocument.createElement("canvas");b.width=n*i+(n-1)*a,b.height=o*(s+c)+(o-1)*a;const p=b.getContext("2d"),r=qs($);p.fillStyle=r.background,p.fillRect(0,0,b.width,b.height),e.forEach((g,w)=>{const h=w%n,E=Math.floor(w/n),P=h*(i+a),K=E*(s+c+a),we=g.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";p.fillStyle=r.surface,p.fillRect(P,K,i,c),p.fillStyle=r.text,p.font=`700 ${m}px system-ui, sans-serif`,p.textAlign="left",p.textBaseline="middle",p.fillText(we,P+Math.round(10*f),K+c/2,i-Math.round(20*f)),p.drawImage(g,P,K+c)}),b.toBlob(g=>{if(!g)return;const w=C.find(h=>h!=null)?.getExportTitle();fa(g,["gallery",w].filter(Boolean).join(" "),V.onSaveImage)})}return{setItems(e){nn(),R=e.map(n=>typeof n=="function"?null:n);const t=l.plotMode;if(Q.has(t))if(e.some(o=>typeof o=="function"))X(Ve(e));else{const o=Ft(t);l={...l,...o},X(qe(t))}else X(Ve(e));no()},setOptions(e){W(e,{fireCallback:!1})},getOptions(){return jt(l)},setFindingsNotice(e){uo=e,A()},setColumns(e){xn(e)},getBinColors(){return l.binColors??N()},setLotStatsSummary(e){nn(),_=e,no(),Le(),S&&A(),de()},openUserGuide:()=>yn(),destroy(){us(),F.flush(),nn(),ot++,ti.removeEventListener("beforeprint",En),d.ownerDocument.removeEventListener("keydown",Xo),Ne?.cancel(),Ne=null,lt=null;for(const e of[...ee.values()])e.closePollId!=null&&clearInterval(e.closePollId),e.close(),e.ctrl.destroy();ee.clear();for(const e of C)e&&e.destroy();C=[],it()?.remove(),Qo.disconnect(),ei.disconnect(),Xe&&((d.ownerDocument.defaultView??window).cancelAnimationFrame(Xe),Xe=0),d.ownerDocument.removeEventListener("click",Mt,!0),window.removeEventListener("blur",co),Di(),di(),Ae.remove(),Z.remove(),S?.remove(),Kt=!0,vt++,clearTimeout(Yt),ge?.el.remove(),fe?.destroy()}}}
@@ -1 +1 @@
1
- import{createViewSwitch as Vo}from"./viewSwitch.js";import{createSummaryToggle as zo}from"./summaryToggle.js";import{buildView as Yo,buildHoverText as Ho,findTestDef as Zt,resolveTestNumber as Fn,buildMapTitle as _o}from"../renderer/buildView.js";import{drawMapCanvas as No,BIN_LEGEND_W as Hi,BIN_LEGEND_W_COMPACT as Xo,BIN_LEGEND_MAP_GAP as Rn,BIN_LEGEND_ADAPT_COMPACT as Ko,BIN_LEGEND_ADAPT_FLOATING as jo,PATH_SHAPES as $o}from"./toCanvas.js";import{buildWaferMap as Go,computeCoverage as _i,computeYield as Ni,defaultBinMode as Uo,getTestPassStatus as Zo,isParametricTest as An,isBuiltMap as Wn}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as In}from"../stats/analyzeWaferMap.js";import{SHADOW as qo,LEADING as Xi,wireControlHover as Ki,SPACE as V,EDGE_GUTTER as Qo,RADIUS as ji,FONT as qt,CLR as A,applyOverlayZ as Jo,getTooltip as $i,hideTooltip as Qt,positionTooltip as Gi,createToolbarHelpers as es,buildModeMenuEl as ts,openReparentedModal as ns,makePaletteBtn as is,makeLogScaleBtn as os,makeLegendStyleBtn as ss,makeOverlaysBtn as ls,makeOrientationBtn as as,menuLayerFor as Ui,saveImageBlob as rs,markMenuTrigger as mt,wireMenuA11y as Zi,wireExpandToggle as ds,nextFrame as Vn,requestedPassFailDisplay as cs,overlayMenuRows as fs,anyOverlayActive as us,openCompactDiagnostics as ps,roomForPanel as hs,logWmapVersionOnce as gs,buildDataModeEntries as ms,metadataKeyHasData as ys,metadataModeEntry as qi}from"./toolbar.js";import{openUserGuideWindow as bs,registerGuideOpener as vs}from"./guideWindow.js";import{waferIdentityLabel as ws}from"../core/waferLabel.js";import{metadataDisplayValue as xs}from"../core/metadata.js";import{withExportContext as Cs}from"./exportName.js";import{testValueNotice as Ss}from"./testValueOffer.js";import{axisPrefsFromOptions as Qi,optionsFromAxisPrefs as Ms,CHART_PREF_KEYS as zn}from"./chartPrefs.js";import{createSummaryPanelEl as Yn,wrapWithSummaryPanel as Hn,renderWaferSummaryContentSteps as Es}from"./summaryPanel.js";import{runChunked as Bs}from"./chunked.js";import{collectWarnings as ks,buildWarningsMenuEl as Ds,severityOf as Ps}from"./warnings.js";import{plotStoreFor as Ls}from"./plotStore.js";import{selectionPopulation as Ts,waferPopulation as Os}from"./chartPopulation.js";import{sourceFromBins as Ji}from"./plotItems.js";import{createIdentityHeader as Fs,collapsedLabel as _n}from"./identityHeader.js";import{getDieKey as de,hasPosition as eo,isPositionedDie as Rs}from"../core/dies.js";import{bandButton as As}from"./filterButton.js";import{buildDieListSection as Ws}from"./dieList.js";import{buildMaplessSummary as Is}from"./maplessSummary.js";import{resolveBinColors as Vs,binColorWarning as zs}from"../renderer/binColors.js";import{isPassBin as Ys,requirePassBins as Hs}from"../core/passBins.js";import{PAT_MODE_FIELD as _s,PAT_MODE_KEY as Ns,isPatMode as to,patModeOffered as Xs,withPatField as Ks,withPatVerdicts as js}from"./patMode.js";import{requireRingCount as ze}from"../core/ringCount.js";import{asList as $s,toggleHighlight as no}from"../core/utils.js";import{buildCompactMap as Gs,compactLayoutOffered as Us}from"../core/compact.js";const Zs={binColorScheme:!0,valueColorScheme:!0,reverseValueScheme:!0,useDefinedBinColors:!0,showDieLabels:!0,showRingBoundaries:!0,showQuadrantBoundaries:!0,showReticle:!0,showXYIndicator:!0,showAxes:!0,legendPosition:!0,colorbarRangeMode:!0,markFailingDies:!0,fallbackFormat:!0,chartAxisIncludesLimits:!0,chartClipOutliers:!0,chartLimitLines:!0};export const WAFER_PREFERENCE_KEYS=Object.keys(Zs);const io=new Set(WAFER_PREFERENCE_KEYS);export const COLOR_KEYS=["binColorScheme","valueColorScheme","reverseValueScheme","useDefinedBinColors","binColors"];export function classifyChanged(P){const h=P.some(u=>io.has(u)),y=P.some(u=>!io.has(u));return h&&y?"mixed":h?"preference":"state"}export function findingBin(P,h,y){const{kind:u,bin:B}=P.variable;if(!(u!=="hardBin"&&u!=="softBin"||B===void 0))return h&&Ys(u,B,h,y)?void 0:B}export function findingPlotMode(P,h,y){const{kind:u}=P.variable;return u==="hardBin"||u==="softBin"?u:h==="hardBin"||h==="softBin"?h:y?"hardBin":"softBin"}export function toPublicViewOptions(P){const{metadataValueOrder:h,binColors:y,lotSize:u,compactMap:B,...Je}=P;return Je}export function renderWaferMap(P,h,y={}){return renderWaferMapCard(P,h,y)}export function renderWaferMapCard(P,h,y={}){gs();const u=P.ownerDocument,B=u.defaultView??window,Je=()=>C.label,yt=()=>ws({label:Je(),wafer:$}),ce=Cs(()=>{const e=xs($.metadata?.lot);return{prefix:y.downloadFilename,lots:e!==void 0?[e]:[],...C.isLotStack?{stackedWafers:g?.lotSize??!0}:{wafer:yt()}}},y.onSaveImage,y.onSaveText);function Nn(){const e=g.plotMode==="softBin"||g.plotMode==="stackedSoftBins"?oe:ie,{primary:n,secondary:t}=_o(g,d.fallbackFormat,e);return[n,C.isLotStack?"":t].filter(Boolean).join(" ")||"wafer-map"}B.getComputedStyle(P).position==="static"&&(P.style.position="relative");const oo=P.clientHeight;y.height!=null&&(P.style.height=typeof y.height=="number"?`${y.height}px`:y.height);const Jt=h.dataCoverage?h.dataCoverage.unpositionedDies:h.dies.filter(e=>!eo(e)).length,et=(h.dataCoverage?h.dataCoverage.totalDies:h.dies.length-Jt)===0&&Jt>0,Ye=u.createElement("div");Object.assign(Ye.style,{display:"flex",flexDirection:"column",width:"100%",height:"100%"}),P.appendChild(Ye);const Ee=u.createElement("div");Object.assign(Ee.style,{position:"relative",width:"100%",flex:"1 1 auto",minHeight:"0"});const me=y.chromeInset??Qo,z=u.createElement("div");Object.assign(z.style,{display:"flex",alignItems:"stretch",gap:V.sm,background:A.canvasBg,paddingBottom:V.lg,paddingTop:me,paddingLeft:me,paddingRight:me,flexShrink:"0",minWidth:"0"}),Ye.appendChild(z),Ye.appendChild(Ee);function He(){const e=[...z.children].some(n=>n.style.display!=="none");z.style.display=e?"flex":"none"}const M=u.createElement("div");Object.assign(M.style,{position:"relative",width:"100%",height:"100%"});const a=u.createElement("canvas");Object.assign(a.style,{width:"100%",height:"100%",display:"block"}),M.appendChild(a),Ee.appendChild(M);let bt=null;if(Jt>0){let t=function(){if(n){const l=Ws(e,h.testDefs,{...y.dieList,onSaveText:ce.onSaveText,waferMetadata:$.metadata,metadataFields:Ke,attributes:y.attributes,ownerDocument:u});if(l)return l}const o=Zt(h.testDefs,d.activeTest??0),s=An(o)?d.logScale??o?.logScale??!1:!1;return Is(e,h.testDefs,{plotMode:d.plotMode??"hardBin",activeTest:d.activeTest,hbinDefs:ie,sbinDefs:oe,binColors:g.binColors,valueColorScheme:d.valueColorScheme,reverseValueScheme:d.reverseValueScheme,logScale:s,colorbarRangeMode:d.colorbarRangeMode,valueRangeDies:h.dies})},i=function(o){const s=u.createElement("button");return s.type="button",Ki(s),Object.assign(s.style,{fontSize:qt.body,padding:`${V.xxs} ${V.sm}`,borderRadius:ji.control,flexShrink:"0",border:`1px solid ${A.menuBorder}`,background:A.menuBg,color:A.text,cursor:"pointer"}),s.textContent=n?"View chart":"View die list",s.addEventListener("click",l=>{l.stopPropagation(),n=!n,s.textContent=n?"View chart":"View die list",o()}),s};const e=h.dies.filter(o=>!eo(o));let n=!1;if(et){const o=u.createElement("div");Object.assign(o.style,{position:"absolute",inset:"0",background:A.panelBg,padding:V.xl,boxSizing:"border-box",overflow:"hidden",display:"flex",flexDirection:"column",gap:V.md,zIndex:"1"});const s=u.createElement("div");Object.assign(s.style,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:V.md});const l=u.createElement("span");Object.assign(l.style,{fontSize:qt.body,color:A.label,lineHeight:Xi.base}),l.textContent="No die position data for this wafer.",s.appendChild(l);const r=u.createElement("div");Object.assign(r.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),s.appendChild(i(()=>r.replaceChildren(t()))),o.appendChild(s),o.appendChild(r),M.appendChild(o),bt=()=>{n||r.replaceChildren(t())}}else{const o=u.createElement("div");Object.assign(o.style,{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"3",background:A.panelBg,borderTop:`1px solid ${A.menuBorder}`,fontSize:qt.body,color:A.text,cursor:"pointer",padding:`${V.xs} ${V.md}`,display:"flex",alignItems:"center",justifyContent:"space-between",gap:V.md}),Ki(o,"bare");const s=u.createElement("span");s.textContent=`+${e.length} ${e.length===1?"die":"dies"} without position data`,o.appendChild(s);const l=u.createElement("span");l.textContent="\u25BE",Object.assign(l.style,{fontSize:qt.body,lineHeight:Xi.none,color:A.label,flexShrink:"0"}),o.appendChild(l),o.setAttribute("aria-expanded","false"),o.setAttribute("aria-label",`${e.length} dies without position data. Click to view.`);let r=null,c=null;ds(o,f=>{if(l.textContent=f?"\u25B4":"\u25BE",o.setAttribute("aria-expanded",String(f)),f){r=u.createElement("div");const p=o.getBoundingClientRect().height||28;Object.assign(r.style,{position:"absolute",left:"0",right:"0",bottom:`${p}px`,top:"20%",zIndex:"2",background:A.panelBg,borderTop:`1px solid ${A.menuBorder}`,padding:V.md,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:V.md}),r.addEventListener("click",R=>R.stopPropagation());const b=u.createElement("div");Object.assign(b.style,{display:"flex",justifyContent:"flex-end"}),b.appendChild(i(()=>{c&&c.replaceChildren(t())})),r.appendChild(b),c=u.createElement("div"),Object.assign(c.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),c.appendChild(t()),r.appendChild(c),M.appendChild(r)}else r&&(r.remove(),r=null,c=null)}),M.appendChild(o),bt=()=>{c&&!n&&c.replaceChildren(t())}}}const{onHover:vt,onClick:so,onSelect:fe,onViewOptionsChange:Xn,showTooltip:lo=!0,showToolbar:Be=!0,showIdentity:Kn=!0,summaryPanel:tt,showHelpButton:jn=!1,userGuideExtension:ao,onExpand:$n,showExpandButton:Gn=!0,zIndex:ro,insights:J,warnings:Un,viewOptions:co={},..._e}=y,ke=J?.enabled??Be;let nt=null,Ne=null;ke&&(nt=Vo(u,"Map","wafer",e=>Ce(e)),Be||(nt.el.style.marginLeft="auto"),z.appendChild(nt.el)),ke&&(Ne=As(u,"Filter\u2026","wmapMapFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{nn().then(e=>e.openEditor(Ne??P,[St()]))}),Ne.style.order="1",z.appendChild(Ne));const fo=.4,uo=20,ne=[...Hs(h,"renderWaferMap")],Zn=Un?.display??!0,po=Jo(ro);let ue=y.statsSummary,De=!1,wt;const pe=()=>De?wt:ue;let we=[],qn=!1,xt=null,Qn=!1;function en(){const e=ks({result:h,statsSummary:pe(),extra:xt?[xt]:[]}),n=e.length!==we.length||e.some((t,i)=>t.code!==we[i]?.code||t.message!==we[i]?.message);we=e,(n||!qn)&&(qn=!0,Un?.onWarning?.(e))}en();let C=h,$=h.wafer,Ct=h.dies,W=h.dies,xe=null,Jn=null,Pe=null;const St=()=>({dies:Ct,wafer:$,label:Je()??"Wafer",identity:yt(),waferIndex:0,passBins:ne,testDefs:X,statsSummary:ue});function tn(){const e=xe?.get();if(wt=void 0,!xe||!e||e.off)return De=!1,Ct;const n=xe.mark([St()]);De=n.narrowing;const t=n.items[0].dies;if(De&&ue&&Wn(C)){const i=t.filter(o=>!o.filteredOut);try{wt=i.length===0?void 0:In({...C,dies:i,yield:Ni(t,ne,C.yield?.yieldPercentGross!=null?"denominator-only":"exclude"),dataCoverage:_i(i)},ue.analysisOptions)}catch{wt=void 0}}return t}function ei(){if(!xe||!Pe)return;const e=[St()];Pe.refresh(xe.keep(e).result,e),Pe.el.style.display=xe.get()&&!ge?"":"none"}function ti(){W=tn(),ei(),at(),x(),gn(ue)}function nn(){return Jn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const n=e({doc:u,initial:J?.filter,onChange:J?.onFilterChange,savedFilters:J?.savedFilters,onSavedFiltersChange:J?.onSavedFiltersChange,pickFiltersFile:J?.onPickFiltersFile,onSaveText:y.onSaveText,attributes:y.attributes,getRingCount:()=>ze(C,"renderWaferMap")});return xe=n,Pe=n.createBand(()=>[St()],{marginLeft:me,marginRight:me,marginBottom:V.lg}),Ye.insertBefore(Pe.el,Ee),n.subscribe(()=>{Xe||ti()}),n.get()&&!Xe&&ti(),n}),Jn}let w=new Set,Le=null;const on=J?.plotStore??Ls(J),Mt={plots:on,getBinColors:()=>g.binColors,attributes:y.attributes,onSaveImage:ce.onSaveImage,onSaveText:ce.onSaveText,onLocateDie:e=>Xt(e)},Et=()=>!et;let sn=null,Bt=null,kt=!1,Xe=!1,ie=h.hbinDefs,oe=h.sbinDefs,X=h.testDefs,Ke=h.metadataFields,ni=h.reticles?.length?h.reticles:void 0,Dt=h.reticleConfig,ii=h.dataAxisFlip,ln=h.isLotStack??!1,an=h.aggrMethod,rn=h.lotSize,ee=null,he=null,Pt=null;function Lt(e){Pt&&(Pt.style.display=e?"flex":"none",Ze?.())}Kn&&(ee=Fs(_n($.metadata??{},it())??"",$.metadata,{lotStack:it(),ownerDocument:u,attributes:y.attributes}),M.appendChild(ee.metaPanel),ee.metaPanel.style.visibility="visible",ee.isEmpty()||(he=oi(ee.wrap),z.insertBefore(he,z.firstChild),He()));function oi(e){const n=u.createElement("div");return Object.assign(n.style,{display:"flex",alignItems:"center",padding:`${V.sm} ${V.lg}`,flex:"1 1 auto",minWidth:"0",overflow:"hidden",gap:V.sm}),Object.assign(e.style,{flex:"1",minWidth:"0"}),n.appendChild(e),n}function it(){return ln?{lotSize:rn??1,aggrMethod:an}:void 0}function ho(){if(!ee)return;ee.update(_n($.metadata??{},it())??"",$.metadata,it());const e=he?.isConnected??!1,n=!ee.isEmpty();!n&&e?(he.remove(),he=null):n&&!e&&(he=oi(ee.wrap),he.style.display="",z.insertBefore(he,z.firstChild),He())}const go=[...ie??[],...oe??[]].some(e=>e.color);let d={plotMode:Uo([h.dies]),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,showReticle:!1,showXYIndicator:!1,compact:!1,rotation:0,flipX:!1,flipY:!1,legendPosition:"default",...co},K=null,ge=!1,si=null;function li(){return ke?K?Promise.resolve(K):(si??=Promise.all([import("./insightsTab.js"),nn()]).then(([{createInsightsTab:e},n])=>(K=e({pageFilter:n,showFilterButton:!1,initialAxisPrefs:Qi(d),onAxisPrefsChange:t=>{d={...d,...Ms(t)};const i=[...zn];Xn?.(d,i,classifyChanged(i))},attributes:y.attributes,getItems:()=>[{wafer:$,dies:Ct,hbinDefs:ie,sbinDefs:oe,testDefs:X,label:Je(),passBins:ne,ringCount:ze(C,"renderWaferMap"),statsSummary:ue}],getBinColors:()=>g.binColors,getRingCount:()=>ze(C,"renderWaferMap"),onSaveImage:ce.onSaveImage,onSaveText:ce.onSaveText,defaultView:J?.defaultView,plotStore:on,onPickPlotsFile:J?.onPickPlotsFile,showPatMap:()=>{Ce(!1),T({plotMode:"metadata",activeTest:void 0,activeMetadataKey:Ns,passFailDisplay:"off"})},showOnMap:t=>{if(Ce(!1),t.kind==="test")pi(t.testNumber);else if(t.kind==="finding"){const i=pe()?.findings.find(o=>o.id===t.id);i&&hi(i)}pe()&&Ht(!0)},showMetadataStrip:!1,contentInset:me,onOpenGuide:jn&&!Be?()=>jt():void 0,focusTest:t=>{T({plotMode:"value",activeTest:t,highlightBin:void 0}),Ce(!1)},locateDie:t=>{Ce(!1),Xt(t)},ownerDocument:u}),Object.assign(K.el.style,{position:"absolute",inset:"0",background:A.canvasBg,overflowY:"auto",paddingTop:"0"}),K.el.style.setProperty("--wmap-sticky-top","0px"),K.el.style.display="none",Ee.appendChild(K.el),K)),si):Promise.resolve(null)}let ai=0;const dn=["wheel","touchstart","pointerdown","keydown"];function mo(e,n){if(n<=0)return;let t=!1;const i=[],o=()=>{t=!0;for(const l of i)B.clearTimeout(l);i.length=0;for(const l of dn)e.removeEventListener(l,o)},s=()=>t||!ge?!0:(e.scrollTop=n,e.scrollTop>=n);if(!s()){for(const l of dn)e.addEventListener(l,o,{passive:!0,once:!0});for(const l of[0,50,150,300,600])i.push(B.setTimeout(()=>{s()},l));i.push(B.setTimeout(()=>{for(const l of dn)e.removeEventListener(l,o)},700))}}function cn(){for(const e of[Z,F])e&&(e.style.visibility=ge?"hidden":"")}function Ce(e){if(!ke)return;const n=ge;ge=e,nt?.setInsightsOpen(e),Pe&&(Pe.el.style.display=xe?.get()&&!e?"":"none"),K&&!e&&n&&(ai=K.el.scrollTop),K&&(K.el.style.display=e?"flex":"none"),M.style.visibility=e?"hidden":"",cn(),N&&(N.style.display=e||et?"none":"flex"),I&&(I.style.display=e?"none":"flex"),Lt(!Ae),le&&(le.style.display="flex"),he&&(he.style.display=""),He(),Ze?.(),ee&&e&&ee.collapse(),ct(),e&&li().then(t=>{!t||!ge||(t.el.style.display="flex",t.render(),mo(t.el,ai))})}ke&&J?.defaultOpen&&queueMicrotask(()=>Ce(!0));let g,Te,G=null,O=null,Tt=[],fn;function ri(e){fn!==e&&(fn=e,x())}let Oe=null,un=_e.legendOffset??{x:0,y:0},ot=!1,je=!1,st={x:0,y:0},pn={x:0,y:0},Fe=!1,$e=!1,U="select",Ge={x:0,y:0},Ot={x:0,y:0},Y={x:0,y:0},H={x:0,y:0},lt=!1,Ue=!1;const hn=()=>to(d)?Ks(Ke):Ke;function at(){const e=d,i=(to(e)?js(W,X,ne):W).filter(Rs);g=Yo($,i,{compact:d.compact?d.compactMap??Gs(i):void 0,plotMode:e.plotMode,binColorScheme:e.binColorScheme,valueColorScheme:e.valueColorScheme,reverseValueScheme:e.reverseValueScheme,useDefinedBinColors:e.useDefinedBinColors,binColors:e.binColors??Vs(W,{passBins:ne,binColorScheme:e.binColorScheme,hbinDefs:ie,sbinDefs:oe,useDefinedBinColors:e.useDefinedBinColors}),passBins:ne,showDieLabels:e.showDieLabels,showRingBoundaries:e.showRingBoundaries,showQuadrantBoundaries:e.showQuadrantBoundaries,showReticle:e.showReticle,showXYIndicator:e.showXYIndicator,reticles:ni,ringCount:ze(C,"renderWaferMap"),highlightBin:e.highlightBin,highlightMetadataValue:e.highlightMetadataValue,activeTest:e.activeTest,activeMetadataKey:e.activeMetadataKey,testDefs:X,valueRange:e.valueRange,metadataValueOrder:e.metadataValueOrder,logScale:e.logScale,isLotStack:ln,aggregationMethod:an??e.aggregationMethod,lotSize:rn??e.lotSize,dataAxisFlip:ii,colorbarRangeMode:e.colorbarRangeMode,passFailDisplay:e.passFailDisplay,fallbackFormat:e.fallbackFormat,interactiveTransform:{rotation:e.rotation??0,flipX:e.flipX??!1,flipY:e.flipY??!1}},{hbinDefs:ie,sbinDefs:oe,metadataFields:hn()}),Te=void 0;const o=e.binColors?null:zs(g.binColors,g.plotMode);o?.message!==xt?.message&&(xt=o,en(),Qn&&yn())}at();function di(){return d.showAxes??_e.showAxes??O!==null}function yo(){return Us(W,[Dt])}let Z=null,Re=null,ye=null,Se=null,Ft=null;function ci(){ye===null&&Se===null&&(Ft={plotMode:d.plotMode,activeTest:d.activeTest})}function fi(){T({...Ft??{},highlightBin:void 0}),Ft=null}function gn(e){const n=e!==ue;if(ue=e,n&&De&&(W=tn(),at(),x()),en(),yn(),Z)se();else if(F)Wt();else if(e&&!tt?.placement){const t=tt?.defaultOpen??!Be;F=Yn("right",me,u,Dn),F.style.display=t?"block":"none";const i=M.parentElement,o=M.nextSibling;be=Hn(M,F,"right"),i?.insertBefore(be,o),Wt(),cn()}ct()}function Rt(){Z?se():F&&Wt()}let ui=y.findingsNotice,rt=!1;const bo=()=>ui??(y.testValueOffer?y.testValueOffer():void 0)??(!y.testValueOffer&&Wn(C)?Ss(pe()?.stats.testValueAnalysis,1,rt,vo):void 0);function vo(){const e=ue,n=C;if(rt||!e||!Wn(n))return;rt=!0,Rt();const t=u.defaultView?.requestAnimationFrame?.bind(u.defaultView)??(s=>setTimeout(s,16));let i=!1;const o=()=>{if(i||Xe)return;i=!0;let s;try{s=In(n,{...e.analysisOptions,enableTestValueAnalysis:!0})}catch(l){throw rt=!1,Rt(),l}if(rt=!1,C!==n||ue!==e){Rt();return}gn(s),y.onStatsSummaryChange?.(s)};t(()=>t(o)),setTimeout(o,120)}let wo={},F=null,be=null;function xo(e){const{kind:n,index:t}=e.variable;if(n==="test")T({plotMode:"value",activeTest:t??0,highlightBin:void 0});else{const o=W.some(s=>s.hbin!=null);T({plotMode:findingPlotMode(e,d.plotMode,o),highlightBin:findingBin(e,ne,o)})}const i=e.highlight;(i.kind==="bin"||i.kind==="region"||i.kind==="dies")&&Yt(i.dieKeys)}const dt=new Map,mn=new WeakSet;function At(e){if(dt.get(e)?.cancel(),dt.delete(e),e.style.display==="none"){mn.add(e);return}mn.delete(e);const n=Bs(Es(e,{wafer:$,dies:W,yieldSummary:De?Ni(W,ne,C.yield?.yieldPercentGross!=null?"denominator-only":"exclude"):C.yield,dataCoverage:De?_i(W.filter(t=>!t.filteredOut)):C.dataCoverage,hbinDefs:ie,sbinDefs:oe,testDefs:X,statsSummary:pe(),warnings:Zn?we:[],passBins:ne,ringCount:ze(C,"renderWaferMap"),binColors:g.binColors,plotMode:d.plotMode??"hardBin",metadataShownElsewhere:Kn,fallbackFormat:d.fallbackFormat,activeFindingId:ye,findingsFilter:wo,findingsNotice:bo(),onFindingsFilterChange:se,onSaveText:ce.onSaveText,metadataFields:Ke,dieListOptions:y.dieList,onLocateDie:t=>Xt(t),attributes:y.attributes,onClose:Be&&pe()?()=>Ht(!1):void 0,activeTest:Se,onTestClick:t=>{Se===t?(Se=null,Yt([]),fi(),se()):pi(t)},onFindingClick:(t,i)=>{ye===t.id?(ye=null,Yt([]),fi(),se()):hi(t)},onShowChart:ke?t=>{Ce(!0),li().then(i=>i?.showWorthCard(t))}:void 0}));n.done||dt.set(e,n)}function pi(e){ci(),ye=null,Se=e,T({plotMode:"value",activeTest:e,highlightBin:void 0}),Yt(pe()?.stats.testFailures?.[e]?.dieKeys),se()}function hi(e){ci(),Se=null,ye=e.id,xo(e),se()}function se(){Z?At(Z):F&&At(F)}function Wt(){F&&At(F)}if(tt?.placement){const e=tt.placement;Z=Yn(e,me,u,Dn);const n=M.parentElement,t=M.nextSibling;Re=Hn(M,Z,e),n?.insertBefore(Re,t),se()}else if(pe()){const e=tt?.defaultOpen??!Be;F=Yn("right",me,u,Dn),F.style.display=e?"block":"none";const n=M.parentElement,t=M.nextSibling;be=Hn(M,F,"right"),n?.insertBefore(be,t),Wt()}cn();const _=lo?$i(u):null;let le=null,j=null,Ze=null,N=null,I=null,It=null,Vt=null,gi=!0,mi=null,ve=null,zt=null;Qn=!0;function yn(){if(!ve||!zt)return;const e=we.length,n=e>0;if(ve.style.display=n?"flex":"none",zt.style.display=n?"":"none",Ze?.(),!n)return;const t=Ps(we[0]),i=`${e} data ${e===1?"warning":"warnings"}`;ve.style.color=t==="error"?A.errText:A.warnText,ve.ariaLabel=t==="error"?`${i} \u2014 the map may be positionally wrong`:i}let bn=null,yi=null,vn=null,wn=null,xn=null,Cn=null;function Me(e="selection"){ye===null&&Se===null||(ye=null,Se=null,Ft=null,e==="selection"?T({highlightBin:void 0}):(w=new Set,fe?.([])),se())}function Yt(e){w=new Set(e??[]),fe&&fe(We()),x()}function ct(){if(!Vt)return;Ze?.();const e=Z??F;Vt.sync({visible:gi&&!!pe()&&!!e&&!ge,open:!!e&&e.style.display!=="none",notable:!!pe()?.hasNotableFindings})}function Ht(e){const n=Z??F;if(!n)return;const t=n.style.display!=="none",i=M.getBoundingClientRect().width;if(n.style.display=e?"block":"none",e!==t){const o=i-M.getBoundingClientRect().width;(y.onSummaryPanelChange??_t)?.(e,e?o:0)}e&&mn.has(n)&&At(n),ct()}if(Be){let R=function(L){U=L,i(v,L==="zoom"),i(q,L==="pan"),It&&i(It,L==="select"),a.style.cursor=L==="pan"?"grab":"crosshair"};le=u.createElement("div"),le.dataset.wmapToolbar="single",Object.assign(le.style,{marginLeft:"auto",flexShrink:"0",display:"flex",flexDirection:"row",alignItems:"center",flexWrap:"wrap-reverse",justifyContent:"flex-end",maxWidth:"100%",background:A.menuBg,border:`1px solid ${A.menuBorder}`,borderRadius:ji.control,boxShadow:qo.panel,pointerEvents:"auto"});const e=$i(u),n=es(e),{makeBtn:t,setActive:i,makeSep:o,syncSeparators:s,syncToolbarVisible:l,makeMenuRow:r,makeMenuSection:c,closeOpenMenu:f,getOpenMenu:p,setOpenMenu:b}=n;Ze=()=>{j&&s(j),le&&l(le,"flex"),He()},bn=f,yi=p,u.addEventListener("click",f,!0),N=u.createElement("div"),Object.assign(N.style,{display:et?"none":"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),le.appendChild(N);const ae=t("download","Download PNG",ko);N.appendChild(ae),N.appendChild(o());const v=t("zoomMode","Zoom (drag to zoom region)",()=>R("zoom")),k=t("zoomIn","Zoom in",()=>Qe(a.clientWidth/2,a.clientHeight/2,1.2)),S=t("zoomOut","Zoom out",()=>Qe(a.clientWidth/2,a.clientHeight/2,1/1.2)),D=t("reset","Reset zoom (double-click)",()=>ut());N.appendChild(v),N.appendChild(k),N.appendChild(S),N.appendChild(D),N.appendChild(o());const q=t("pan","Pan (drag to move)",()=>R("pan"));N.appendChild(q),It=t("boxSelect","Select (drag to select dies)",()=>R("select")),N.appendChild(It);{const L=t("drilldown","Chart this wafer",()=>{const re=L.getBoundingClientRect();Pn({x:re.left,y:re.bottom+4},L)});L.setAttribute("aria-haspopup","menu"),Bt=L,ki(),N.appendChild(L)}R(U);{let L=function(m){return m.plotMode!==(d.plotMode??"hardBin")?!1:m.plotMode==="value"?(d.activeTest??0)===(m.activeTest??0):m.plotMode==="metadata"?d.activeMetadataKey===m.activeMetadataKey:!0},re=function(m,E){m.activeTest!==void 0?T({plotMode:m.plotMode,activeTest:m.activeTest,activeMetadataKey:void 0,logScale:m.logScale}):m.activeMetadataKey!==void 0?T({plotMode:m.plotMode,activeTest:void 0,activeMetadataKey:m.activeMetadataKey,passFailDisplay:"off"}):T({plotMode:m.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),b(null),mt(Q,!1)};j=u.createElement("div"),Object.assign(j.style,{display:"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),le.appendChild(j),I=u.createElement("div"),Object.assign(I.style,{display:"flex",alignItems:"center",gap:"0"}),j.appendChild(I),I.appendChild(o());const pt=()=>{const m=p();m&&(m.remove(),b(null)),mt(Q,!1)},Q=t("mode","Plot mode",()=>{if(p()){pt();return}const m=W,E=g.testDefs,{testEntries:Gt,binEntries:Ie,stackedEntries:ht}=ms(m,E,{includeStacked:g.isLotStack}),Ut=(Ke??[]).filter(Ve=>ys(m,Ve.key)).map(qi);Xs([{dies:m,testDefs:E}])&&Ut.push(qi(_s));const gt=ts(Q.getBoundingClientRect(),Gt,Ie,ht,L,re,{makeMenuRow:r,makeMenuSection:c},d.plotMode??"hardBin",Q.ownerDocument.defaultView??window,Ut);Ui(Q).appendChild(gt),b(gt),mt(Q,!0),Zi(gt,Q,pt)});mt(Q,!1);const{btn:Tn,sync:On}=is(n,()=>({...d,plotMode:d.plotMode??"hardBin"}),()=>go,T);wn=On,wn();const To=ls(n,()=>{const m=!!g.hasReticle,E=(d.plotMode??"hardBin")==="value",{testNumber:Gt}=Fn(d.activeTest??0,g.testDefs),Ie=Zt(g.testDefs,Gt),ht=E&&Ie!==void 0&&!An(Ie),Ut=E&&!ht&&(Ie?.limitLow!==void 0||Ie?.limitHigh!==void 0),gt=E&&!ht&&g.dies.some(Ve=>Zo(Ve,Gt,Ie)!==void 0);return fs({...d,showAxes:di()},m,{functionalActive:ht,hasLimits:Ut,hasRecorded:gt,binMode:(d.plotMode??"hardBin")==="hardBin"||(d.plotMode??"hardBin")==="softBin"},Ve=>T(Ve),{on:!!d.compact,offered:yo(),onChange:Ve=>T({compact:Ve}),onDiagnostics:()=>ps(W,[Dt],{anchor:a,onSaveText:ce.onSaveText})})},()=>us(d)),{btn:Oo,sync:Fo}=ss(n,()=>d,m=>T({legendPosition:m}));vn=Fo,vn();const Yi=()=>{const{testNumber:m}=Fn(d.activeTest??0,X),E=Zt(X,m);return E!==void 0&&!An(E)},{btn:Ro,sync:Ao}=os(n,()=>({...d,functionalActive:Yi()}),m=>T(m));xn=Ao,xn();const Wo=()=>{const{testNumber:m}=Fn(d.activeTest??0,X),E=Zt(X,m);return E!==void 0&&(E.limitLow!==void 0||E.limitHigh!==void 0)},$t=t("specRange","Colour bar range: test limits",()=>{const m=d.colorbarRangeMode==="data"?"spec":"data";T({colorbarRangeMode:m})});Cn=()=>{const m=d.plotMode==="value"&&Wo()&&cs(d)==="off"&&!Yi();$t.style.display=m?"":"none";const E=(d.colorbarRangeMode??"spec")==="spec";i($t,E),$t.ariaLabel=E?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"},Cn();const Io=as(n,()=>d,m=>T(m));I.appendChild(Q),I.appendChild(Tn),I.appendChild(Ro),I.appendChild($t),et||(I.appendChild(o()),I.appendChild(To),I.appendChild(o()),I.appendChild(Oo),I.appendChild(o()),I.appendChild(Io)),Vt=zo(u,()=>{const m=Z??F;m&&Ht(m.style.display==="none")}),z.insertBefore(Vt.el,nt?.el??null),ct(),Zn&&(zt=o(),ve=t("warning","Data warnings",()=>{const m=p();if(f(new MouseEvent("click")),m)return;const E=Ds(ve.getBoundingClientRect(),we,B);Ui(Ee).appendChild(E),b(E),Zi(E,ve,()=>f(new MouseEvent("click")))}),mt(ve,!1),j.appendChild(zt),j.appendChild(ve),yn()),Gn&&(j.appendChild(o()),Pt=t("expand","Expand (E)",$n??bi),j.appendChild(Pt)),jn&&(j.appendChild(o()),mi=t("help","User guide",()=>jt()),j.appendChild(mi)),Ze?.()}z.appendChild(le),Ne&&z.appendChild(Ne),He()}let Ae=null,_t=null;function bi(){Ae&&(Ae.close(),Ae=null);const e=Ee;e.style.flex="1",e.style.minWidth="0",e.style.minHeight="0";const n=_n($.metadata??{},it()),t=z.childElementCount>0?[z,e]:[e],i=ns(t,{ownerDocument:u,boxSize:ge?{width:"min(96vw, 1600px)",height:"min(92vh, 1000px)"}:void 0,onClosed:()=>{Ae=null,_t=null,Lt(!0),ge||a.focus({preventScroll:!0})}});if(!i)return;i.box.setAttribute("aria-label",n??"Expanded wafer map"),t.length>1&&(i.contentWrap.style.flexDirection="column"),Ae=i,_t=hs(i);const o=Z??F,s=Re??be;if(o&&s&&o.style.display!=="none"){const l=parseFloat(u.defaultView?.getComputedStyle(s).columnGap??"")||0,r=o.getBoundingClientRect().width+l;r>0&&_t(!0,r)}Lt(!1)}function vi(e){("binColorScheme"in e||"useDefinedBinColors"in e)&&!("binColors"in e)&&d.binColors!==void 0&&(e={...e,binColors:void 0});const n=d.plotMode;d={...d,...e},zn.some(l=>l in e)&&K?.setAxisPrefs(Qi(d));const t=Object.keys(e);if(t.length>0&&t.every(l=>zn.includes(l)))return;("compact"in e||"compactMap"in e)&&(G=null,O=null),e.plotMode!==void 0&&e.plotMode,Object.keys(e).every(l=>l==="legendPosition"||l==="showLegend"||l==="markFailingDies"||l==="showAxes")||at(),vn?.(),wn?.(),xn?.(),Cn?.(),x();const o=e.plotMode!==void 0&&e.plotMode!==n,s=COLOR_KEYS.some(l=>l in e);(s||o)&&se(),(s||o||e.activeTest!==void 0||e.logScale!==void 0||e.colorbarRangeMode!==void 0)&&bt?.()}function T(e){vi(e);const n=Object.keys(e);Xn?.(d,n,classifyChanged(n))}let Sn=!1;const Mn=y.drawWhenVisible&&B.IntersectionObserver?new B.IntersectionObserver(e=>{qe=e[e.length-1].isIntersecting,qe&&Nt&&x()},{rootMargin:"25%"}):null;let qe=Mn===null,Nt=!1;Mn?.observe(a);function En(){Sn||(Sn=!0,Vn(()=>{Sn=!1,x()},B))}function x(){if(!qe){Nt=!0;return}Nt=!1;const e=O??void 0,n=g.dies[0],t=n?{x:n.width,y:n.height}:_e.diePitchMm,i=Math.floor(a.clientWidth||a.width),o=!!(ie?.length||oe?.length||g.dies.some(b=>b.hbin!=null||b.sbin!=null)),s=d.legendPosition??"default",l=d.showLegend??!0,r=s==="default"||s==="compact",c=(_e.colorbarWidth??16)+28,f=o&&r?s!=="default"?Math.max(Hi+Rn,c):i<jo?0:i<Ko?Math.max(Xo+Rn,c):Math.max(Hi+Rn,c):void 0,p=No(a,g,{..._e,minRightReserve:l?f:0,showColorbar:l&&(_e.showColorbar??!0),markFailingDies:d.markFailingDies??!1,legendPosition:s,legendOffset:un,diePitchMm:t,fallbackFormat:d.fallbackFormat,showAxes:di(),viewport:e,activeBin:d.plotMode==="metadata"?d.highlightMetadataValue:d.highlightBin,hoverBin:fn,afterDies:w.size>0||Le!==null?Co:void 0,hbinDefs:ie,sbinDefs:oe,metadataFields:hn()});Tt=p.binLegendRows,Oe=p.legendBox??null,O===null&&(G=p.viewport),$e&&Bo(),ki()}function Co(e,n,t){w.size>0&&Mo(e,n,t),Le!==null&&So(e,n,t)}function So(e,n,t){Te??=new Map(g.dies.map((b,R)=>[de(b),R]));const i=Le===null?void 0:Te.get(Le);if(i===void 0)return;const o=g.hoverPoints[i],s=g.rectangles[0],l=s?s.width/2*n.ppm:n.ppm*.5,r=s?s.height/2*n.ppm:n.ppm*.5,c=n.originX+o.x*n.ppm,f=n.originY-o.y*n.ppm,p=Math.max(l,r)*1.25+5;e.save(),e.setLineDash([]),e.beginPath(),e.arc(c,f,p,0,Math.PI*2),e.strokeStyle=t.background,e.lineWidth=6,e.stroke(),e.strokeStyle=t.text,e.lineWidth=3,e.stroke(),e.restore()}function Xt(e){if(Le=e===null?null:de(e),e!==null&&O!==null){ut();return}x()}function wi(){Le!==null&&(Le=null,x())}function Mo(e,n,t){const i=g.hoverPoints,o=g.rectangles[0],s=o?o.width/2*n.ppm:n.ppm*.5,l=o?o.height/2*n.ppm:n.ppm*.5,r=new Set;w.size>0&&(Te??=new Map(g.dies.map((v,k)=>[de(v),k])));for(const v of w){const k=Te.get(v);k!==void 0&&r.add(k)}if(!r.size)return;e.save(),e.setLineDash([]),e.fillStyle=t.background,e.globalAlpha=.7;let c=0;e.beginPath();for(let v=0;v<i.length;v++)r.has(v)||(e.rect(n.originX+i[v].x*n.ppm-s,n.originY-i[v].y*n.ppm-l,s*2,l*2),++c===$o&&(e.fill(),e.beginPath(),c=0));c&&e.fill(),e.globalAlpha=1;const{cw:f,ch:p}=Eo(n,s,l),b=new Map,R=v=>Math.round(v*100),ae=(v,k,S,D)=>{const q=`${R(v)},${R(k)},${R(S)},${R(D)}`;b.has(q)?b.delete(q):b.set(q,[v,k,S,D])};for(const v of r){const k=n.originX+i[v].x*n.ppm,S=n.originY-i[v].y*n.ppm,D=k-f,q=k+f,L=S-p,re=S+p;ae(D,L,q,L),ae(D,re,q,re),ae(D,L,D,re),ae(q,L,q,re)}e.strokeStyle=t.text,e.lineWidth=2,e.lineCap="square",e.beginPath();for(const[v,k,S,D]of b.values())e.moveTo(v,k),e.lineTo(S,D);e.stroke(),e.restore()}function Eo(e,n,t){const i=g.hoverPoints,o=g.dies;let s=0,l=0;for(let r=0;r<o.length&&(!s||!l);r++){const c=o[r];if(!(c.x==null||c.y==null))for(const f of[Te.get(`${c.x+1},${c.y}`),Te.get(`${c.x},${c.y+1}`)]){if(f===void 0)continue;const p=Math.abs(i[f].x-i[r].x)*e.ppm,b=Math.abs(i[f].y-i[r].y)*e.ppm;p>b?s||=p/2:l||=b/2}}return{cw:s||n,ch:l||t}}function Bo(){const e=a.getContext("2d"),n=Math.min(Y.x,H.x),t=Math.min(Y.y,H.y),i=Math.abs(H.x-Y.x),o=Math.abs(H.y-Y.y);e.save(),e.fillStyle="rgba(0,0,0,0.08)",e.fillRect(n,t,i,o),e.setLineDash([5,3]),e.strokeStyle="rgba(255,255,255,0.9)",e.lineWidth=3,e.strokeRect(n,t,i,o),e.strokeStyle="rgba(0,0,0,0.9)",e.lineWidth=1.5,e.strokeRect(n,t,i,o),e.restore()}function xi(){if(!Nt)return;const e=qe;qe=!0,x(),qe=e}function ko(){xi(),a.toBlob(e=>{e&&rs(e,Nn(),ce.onSaveImage)})}function Ci(e){return G?Math.max(G.ppm*fo,Math.min(G.ppm*uo,e)):e}function Qe(e,n,t){const i=O??G;if(!i)return;const o=Ci(i.ppm*t),s=o/i.ppm,l=e-(e-i.originX)*s,r=n-(n-i.originY)*s,c=(G?.snapDist??1)/(o/(G?.ppm??o));O={originX:l,originY:r,ppm:o,snapDist:c},x()}function te(){return O??G}function Si(e){if(e.ctrlKey||e.metaKey){e.preventDefault();const n=a.getBoundingClientRect(),t=e.deltaY<0?1.12:1/1.12;Qe(e.clientX-n.left,e.clientY-n.top,t)}else if(O!==null){e.preventDefault();const n=te(),t=O.snapDist;O={originX:n.originX-e.deltaX,originY:n.originY-e.deltaY,ppm:n.ppm,snapDist:t},x()}}function Bn(e,n,t){return e>=t.x&&e<t.x+t.w&&n>=t.y&&n<t.y+t.h}function Mi(e){if(kt=!1,e.button!==0||(wi(),!te()))return;a.focus({preventScroll:!0}),a.setPointerCapture(e.pointerId);const n=a.getBoundingClientRect(),t=e.clientX-n.left,i=e.clientY-n.top;if(Oe&&d.legendPosition==="floating"&&Bn(t,i,Oe)){je=!0,st={x:t,y:i},pn={...un};return}if(lt&&U!=="pan"){Ue=!0,Fe=!0,Ge={x:t,y:i},Ot={x:te().originX,y:te().originY},a.style.cursor="grabbing";return}if(U==="zoom"||U==="select"){$e=!0,Y=H={x:t,y:i};return}Fe=!0,Ge={x:t,y:i},Ot={x:te().originX,y:te().originY},a.style.cursor="grabbing"}function Ei(e){const n=a.getBoundingClientRect(),t=e.clientX-n.left,i=e.clientY-n.top;if($e){H={x:t,y:i},En();return}if(je){const p=t-st.x,b=i-st.y;p*p+b*b>16&&(je=!1,ot=!0,a.style.cursor="grabbing")}if(ot){un={x:pn.x+(t-st.x),y:pn.y+(i-st.y)},En();return}if(Fe){const p=te(),b=O?.snapDist??G?.snapDist??1;O={originX:Ot.x+(t-Ge.x),originY:Ot.y+(i-Ge.y),ppm:p.ppm,snapDist:b},En();return}const o=te();if(!o)return;const s=(t-o.originX)/o.ppm,l=(o.originY-i)/o.ppm,c=Ln(s,l,o.snapDist)?.die??null,f=Tt.find(p=>t>=p.x&&t<p.x+p.w&&i>=p.y&&i<p.y+p.h);if(ri(f?f.bin:void 0),f){a.style.cursor="pointer",_&&(_.textContent=f.label??`Bin ${f.bin}`,_.style.display="block",Gi(_,a,e.clientX,e.clientY,{followPointer:!0})),vt?.(null,e);return}U==="pan"&&(a.style.cursor=c?"crosshair":"grab"),_&&(c?(_.innerHTML=Ho(c,g.plotMode,{testDefs:X,hbinDefs:ie,sbinDefs:oe,fallbackFormat:d.fallbackFormat,aggrMethod:g.aggrMethod,lotSize:g.lotSize,metadataFields:hn(),activeTest:g.activeTest,reticleConfig:Dt}),_.style.display="block",Gi(_,a,e.clientX,e.clientY,{followPointer:!0})):_.style.display="none"),vt?.(c,e)}function Bi(e){const n=a.getBoundingClientRect(),t=e.clientX-n.left,i=e.clientY-n.top,o=e.ctrlKey||e.metaKey;if(_&&(t<0||i<0||t>n.width||i>n.height)&&(_.style.display="none"),$e){$e=!1,H={x:t,y:i};const r=t-Y.x,c=i-Y.y,f=te();if(U==="zoom"){if(r*r+c*c<25)Qe(t,i,2);else if(f){const p=Math.min(Y.x,H.x),b=Math.max(Y.x,H.x),R=Math.min(Y.y,H.y),ae=Math.max(Y.y,H.y),v=b-p,k=ae-R;if(v>4&&k>4){const S=a.clientWidth,D=a.clientHeight,q=S/v,L=D/k,re=Math.min(q,L),pt=Ci(f.ppm*re),Q=pt/f.ppm,Tn=(p+b)/2,On=(R+ae)/2;O={originX:S/2-(Tn-f.originX)*Q,originY:D/2-(On-f.originY)*Q,ppm:pt,snapDist:f.snapDist/Q}}}x(),a.style.cursor="crosshair";return}if(r*r+c*c<25)kn(t,i,o,e);else if(f){const p=(Math.min(Y.x,H.x)-f.originX)/f.ppm,b=(Math.max(Y.x,H.x)-f.originX)/f.ppm,R=(f.originY-Math.max(Y.y,H.y))/f.ppm,ae=(f.originY-Math.min(Y.y,H.y))/f.ppm,v=g.hoverPoints,k=[];for(let S=0;S<v.length;S++)if(v[S].x>=p&&v[S].x<=b&&v[S].y>=R&&v[S].y<=ae){const D=g.dies[S];D&&k.push(D)}if(o)for(const S of k){const D=de(S);w.has(D)?w.delete(D):w.add(D)}else w=new Set(k.map(S=>de(S)));Me(),fe?.(We())}x(),a.style.cursor="crosshair";return}if(je){je=!1,kn(t,i,o,e);return}if(ot){ot=!1,a.style.cursor="grab";return}if(!Fe)return;if(Fe=!1,Ue){Ue=!1,a.style.cursor=lt||U==="pan"?"grab":"crosshair";return}a.style.cursor=U==="pan"?"grab":"crosshair";const s=t-Ge.x,l=i-Ge.y;s*s+l*l<25&&kn(t,i,o,e)}function kn(e,n,t,i){for(const r of Tt)if(e>=r.x&&e<r.x+r.w&&n>=r.y&&n<r.y+r.h){Me("legend"),typeof r.bin=="number"?T({highlightBin:no(d.highlightBin,r.bin,t)}):T({highlightMetadataValue:no(d.highlightMetadataValue,r.bin,t)});return}if(Oe&&Bn(e,n,Oe))return;const o=te();if(!o)return;const l=Ln((e-o.originX)/o.ppm,(o.originY-n)/o.ppm,o.snapDist)?.die??null;if(l){so?.(l,i);const r=de(l);t?w.has(r)?w.delete(r):w.add(r):w.size===1&&w.has(r)?w=new Set:w=new Set([r]),Me(),fe?.(We()),x()}else t||(w=new Set,Me(),fe?.([]),x())}function We(){const e=[],n=g.hoverPoints;for(let t=0;t<n.length;t++){const i=g.dies[t];i&&w.has(de(i))&&e.push(i)}return e}function ki(){Bt&&(Bt.style.display=Et()?"flex":"none",Bt.ariaLabel=w.size>0?"Charts and tables for the selected dies (or right-click)":"Charts and tables for this wafer (or right-click)")}function Di(){const e={waferLabel:yt(),testDefs:X,isLotStack:C.isLotStack,wafer:C.wafer,passBins:ne,ringCount:ze(C,"renderWaferMap"),activeTest:d.plotMode==="value"?d.activeTest:void 0};return w.size>0?Ts(We(),e,W):Os(W,e)}function Dn(e,n,t){ye!==e&&n.click(),Pn(t,Z??F??a)}function Do(e,n){if(!Et())return;const t=d.plotMode==="softBin"?"soft":"hard",i=$s(d.highlightBin),o=i.length>1&&i.includes(e)?[...i]:[e],s=[{label:yt()??"this wafer",dies:W,wafer:C.wafer,passBins:ne,ringCount:ze(C,"renderWaferMap")}],l=Ji(s,t,o,X);if(!l)return;const r={...Mt},c=o.length>1?Ji(s,t,[e],X):null;c&&(r.narrower={label:`Only ${t} bin ${e}`,backLabel:"All filtered bins",source:c,ctx:Mt});const f=a;import("./drilldown.js").then(({openDrilldownMenu:p})=>{Xe||(sn=p(n,f,l,r))})}function Po(){const e=new Set;for(const n of g.dies){const t=de(n);w.has(t)||e.add(t)}w=e,Me(),fe?.(We()),x()}function Pn(e,n){if(!Et())return;const t=y.drilldownSourceOverride?.(),i=t?.source??Di(),o={...Mt,...t?.ctx};if(!t&&w.size>0&&(o.onInvertSelection=Po),t?.narrowable){const s=Di(),l=s.items.reduce((r,c)=>r+c.dies.length,0);o.narrower={label:`Only this wafer \u2014 ${l.toLocaleString()} die${l===1?"":"s"}`,source:s,ctx:Mt}}import("./drilldown.js").then(({openDrilldownMenu:s})=>{Xe||(sn=s(e,n,i,o))})}function Pi(e){e.stopPropagation();const n=kt;if(kt=!1,!Et()||ge)return;const t=a.getBoundingClientRect();if(!n){const o=e.clientX-t.left,s=e.clientY-t.top,l=Tt.find(f=>o>=f.x&&o<f.x+f.w&&s>=f.y&&s<f.y+f.h);if(l&&typeof l.bin=="number"&&!C.isLotStack&&(d.plotMode===void 0||d.plotMode==="hardBin"||d.plotMode==="softBin")){e.preventDefault(),Do(l.bin,{x:e.clientX,y:e.clientY});return}if(Oe&&Bn(o,s,Oe))return;const r=te(),c=r?Ln((o-r.originX)/r.ppm,(r.originY-s)/r.ppm,r.snapDist)?.die:void 0;c&&!w.has(de(c))&&(w=new Set([de(c)]),Me(),fe?.(We()),x())}e.preventDefault();const i=n?{x:t.left+t.width/2,y:t.top+t.height/2}:{x:e.clientX,y:e.clientY};Pn(i,a)}function Li(){ri(void 0),_&&Qt(u),vt?.(null,new MouseEvent("mouseleave")),a.style.cursor=U==="pan"?"grab":"crosshair"}function Ti(){Fe=!1,Ue=!1,$e=!1,je=!1,ot=!1,_&&Qt(u),vt?.(null,new MouseEvent("mouseleave")),a.style.cursor=U==="pan"?"grab":"crosshair",x()}function Ln(e,n,t){const i=g.hoverPoints,o=g.rectangles;for(let c=0;c<o.length;c++){const f=o[c];if(Math.abs(e-f.x)<=f.width/2&&Math.abs(n-f.y)<=f.height/2){const p=g.dies[c];return p?{die:p,index:c}:null}}let s=null,l=-1,r=t*t;for(let c=0;c<i.length;c++){const f=i[c].x-e,p=i[c].y-n,b=f*f+p*p;b<r&&(r=b,s=g.dies[c]??null,l=c)}return s?{die:s,index:l}:null}const Oi=new B.ResizeObserver(()=>{G=null,O=null,x()});Oi.observe(a),y.height==null&&oo<=0&&Vn(()=>Vn(()=>{P.clientHeight>0||console.warn("[wafermap] The map container has zero height, so the map cannot render. renderWaferMap fills its container \u2014 give the container a resolved height: an explicit CSS `height` (e.g. 600px), a height-resolved flex/grid parent, or `position:absolute; inset:0`. Alternatively pass `{ height: 600 }` in the render options and the library will size it for you.")}));let ft=B.matchMedia(`(resolution: ${B.devicePixelRatio}dppx)`);const Kt=()=>{ft.removeEventListener("change",Kt),ft=B.matchMedia(`(resolution: ${B.devicePixelRatio}dppx)`),ft.addEventListener("change",Kt),x()};ft.addEventListener("change",Kt);const Fi=B.matchMedia("(prefers-color-scheme: dark)"),Ri=()=>x();Fi.addEventListener("change",Ri);const Ai=()=>{_&&Qt(u)};B.addEventListener("blur",Ai);function Wi(e){if((e.key==="ContextMenu"||e.shiftKey&&e.key==="F10")&&(kt=!0),e.key==="Escape"&&wi(),e.key==="Escape"&&w.size>0&&(w=new Set,Me(),fe?.([]),x()),(e.key==="e"||e.key==="E")&&Gn&&(e.stopPropagation(),($n??bi)()),(e.ctrlKey||e.metaKey)&&(e.key==="="||e.key==="+"?(e.preventDefault(),Qe(a.clientWidth/2,a.clientHeight/2,1.2)):e.key==="-"?(e.preventDefault(),Qe(a.clientWidth/2,a.clientHeight/2,1/1.2)):e.key==="0"&&(e.preventDefault(),ut())),!e.ctrlKey&&!e.metaKey&&!e.shiftKey){const t=te();if(t){const i=O?.snapDist??G?.snapDist??1;let o=0,s=0;e.key==="ArrowLeft"&&(o=20,e.preventDefault()),e.key==="ArrowRight"&&(o=-20,e.preventDefault()),e.key==="ArrowUp"&&(s=20,e.preventDefault()),e.key==="ArrowDown"&&(s=-20,e.preventDefault()),(o||s)&&(O={originX:t.originX+o,originY:t.originY+s,ppm:t.ppm,snapDist:i},x())}e.key===" "&&!lt&&(e.preventDefault(),lt=!0,U!=="pan"&&(a.style.cursor="grab"))}}function Ii(e){e.key===" "&&(lt=!1,Ue&&(Fe=!1,Ue=!1),a.style.cursor=U==="pan"?"grab":"crosshair")}a.style.cursor="crosshair",a.setAttribute("tabindex","0"),a.addEventListener("wheel",Si,{passive:!1}),a.addEventListener("pointerdown",Mi),a.addEventListener("pointermove",Ei),a.addEventListener("pointerup",Bi),a.addEventListener("pointerleave",Li),a.addEventListener("pointercancel",Ti);const Vi=()=>ut();a.addEventListener("dblclick",Vi),a.addEventListener("keydown",Wi),a.addEventListener("keyup",Ii),a.addEventListener("contextmenu",Pi);const zi=e=>{e.stopPropagation()};a.addEventListener("click",zi),a.clientWidth,x(),bt?.();function ut(){G=null,O=null,x()}function jt(e){import("./userGuideHtml.js").then(n=>bs({buildWaferMap:Go,renderWaferMap,renderWaferGallery:void 0,analyzeWaferMap:In},n.USER_GUIDE_HTML,ao,P,e))}const Lo=vs(e=>jt(e));return He(),ke&&J?.filter!==void 0&&nn(),{setResult(e){C=e,$=e.wafer,Ct=e.dies,W=tn(),ie=e.hbinDefs,oe=e.sbinDefs,X=e.testDefs,Ke=e.metadataFields,ni=e.reticles?.length?e.reticles:void 0,Dt=e.reticleConfig,ii=e.dataAxisFlip,ln=e.isLotStack,an=e.aggrMethod,rn=e.lotSize,ho(),at(),x(),ei(),Z&&se()},setOptions(e){vi(e)},getOptions(){return{...d}},resetZoom:ut,setSelection(e){w=new Set(e.map(n=>de(n))),x()},getSelectedDies:()=>We(),clearSelection(){w=new Set,Me(),fe?.([]),x()},setFindingsNotice(e){ui=e,Rt()},setStatsSummary(e){gn(e)},closeSummaryPanel(){Ht(!1)},getExportTitle(){return Nn()},getSaveImageHook(){return ce.onSaveImage},locateDie:Xt,getSaveTextHook(){return ce.onSaveText},drawPendingNow:xi,getBinColors(){return g.binColors},setSummaryVisible(e){gi=e,ct()},setViewControlsVisible(e){j&&(j.style.display=e?"flex":"none")},setExpandVisible(e){Lt(e)},openUserGuide:()=>jt(),setInsightsOpen(e){Ce(e)},destroy(){Xe=!0,Lo(),on.flush();for(const e of dt.values())e.cancel();dt.clear(),Ae?.close(),yi?.()?.remove(),bn&&u.removeEventListener("click",bn,!0),a.removeEventListener("wheel",Si),a.removeEventListener("pointerdown",Mi),a.removeEventListener("pointermove",Ei),a.removeEventListener("pointerup",Bi),a.removeEventListener("pointerleave",Li),a.removeEventListener("pointercancel",Ti),a.removeEventListener("dblclick",Vi),a.removeEventListener("keydown",Wi),a.removeEventListener("keyup",Ii),a.removeEventListener("contextmenu",Pi),sn?.(),a.removeEventListener("click",zi),Oi.disconnect(),Mn?.disconnect(),ft.removeEventListener("change",Kt),Fi.removeEventListener("change",Ri),B.removeEventListener("blur",Ai),po(),_&&Qt(u),le?.remove(),Re&&(Re.parentElement?.insertBefore(M,Re),Re.remove()),be&&(be.parentElement?.insertBefore(M,be),be.remove()),M.remove(),a.style.cursor="",K?.destroy(),ee?.destroy(),Ye.remove()}}}
1
+ import{createViewSwitch as zo}from"./viewSwitch.js";import{createSummaryToggle as Yo}from"./summaryToggle.js";import{buildView as Ho,buildHoverText as _o,findTestDef as Ut,resolveTestNumber as Fn,buildMapTitle as Xo}from"../renderer/buildView.js";import{drawMapCanvas as Ko,BIN_LEGEND_W as _i,BIN_LEGEND_W_COMPACT as No,BIN_LEGEND_MAP_GAP as Rn,BIN_LEGEND_ADAPT_COMPACT as jo,BIN_LEGEND_ADAPT_FLOATING as $o,PATH_SHAPES as Go}from"./toCanvas.js";import{buildWaferMap as Uo,computeCoverage as Xi,computeYield as Ki,defaultBinMode as Zo,getTestPassStatus as qo,isParametricTest as An,isBuiltMap as In}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as Wn}from"../stats/analyzeWaferMap.js";import{SHADOW as Qo,LEADING as Ni,wireControlHover as ji,SPACE as V,EDGE_GUTTER as Jo,RADIUS as $i,FONT as Zt,CLR as A,applyOverlayZ as es,getTooltip as Gi,hideTooltip as qt,positionTooltip as Ui,createToolbarHelpers as ts,buildModeMenuEl as ns,openReparentedModal as is,makePaletteBtn as os,makeLogScaleBtn as ss,makeLegendStyleBtn as ls,makeOverlaysBtn as as,makeOrientationBtn as rs,menuLayerFor as Zi,saveImageBlob as ds,markMenuTrigger as mt,wireMenuA11y as qi,wireExpandToggle as cs,nextFrame as Vn,requestedPassFailDisplay as fs,overlayMenuRows as us,anyOverlayActive as ps,openCompactDiagnostics as hs,roomForPanel as gs,logWmapVersionOnce as ms,buildDataModeEntries as ys,metadataKeyHasData as bs,metadataModeEntry as Qi}from"./toolbar.js";import{openUserGuideWindow as vs,registerGuideOpener as ws}from"./guideWindow.js";import{waferIdentityLabel as xs}from"../core/waferLabel.js";import{metadataDisplayValue as Cs}from"../core/metadata.js";import{withExportContext as Ss}from"./exportName.js";import{testValueNotice as Ms}from"./testValueOffer.js";import{axisPrefsFromOptions as Ji,optionsFromAxisPrefs as Es,CHART_PREF_KEYS as zn}from"./chartPrefs.js";import{createSummaryPanelEl as Yn,wrapWithSummaryPanel as Hn,renderWaferSummaryContentSteps as Bs}from"./summaryPanel.js";import{runChunked as ks}from"./chunked.js";import{collectWarnings as Ds,buildWarningsMenuEl as Ps,severityOf as Ts}from"./warnings.js";import{plotStoreFor as Ls}from"./plotStore.js";import{selectionPopulation as Os,waferPopulation as Fs}from"./chartPopulation.js";import{sourceFromBins as eo}from"./plotItems.js";import{createIdentityHeader as Rs,collapsedLabel as _n}from"./identityHeader.js";import{getDieKey as ce,hasPosition as to,isPositionedDie as As}from"../core/dies.js";import{bandButton as Is}from"./filterButton.js";import{buildDieListSection as Ws}from"./dieList.js";import{buildMaplessSummary as Vs}from"./maplessSummary.js";import{resolveBinColors as zs,binColorWarning as Ys}from"../renderer/binColors.js";import{isPassBin as Hs,requirePassBins as _s}from"../core/passBins.js";import{PAT_MODE_FIELD as Xs,PAT_MODE_KEY as Ks,isPatMode as no,patModeOffered as Ns,withPatField as js,withPatVerdicts as $s}from"./patMode.js";import{requireRingCount as ze}from"../core/ringCount.js";import{asList as Gs,toggleHighlight as io}from"../core/utils.js";import{buildCompactMap as Us,compactLayoutOffered as Zs}from"../core/compact.js";const qs={binColorScheme:!0,valueColorScheme:!0,reverseValueScheme:!0,useDefinedBinColors:!0,showDieLabels:!0,showRingBoundaries:!0,showQuadrantBoundaries:!0,showReticle:!0,showXYIndicator:!0,showAxes:!0,legendPosition:!0,colorbarRangeMode:!0,markFailingDies:!0,fallbackFormat:!0,chartAxisIncludesLimits:!0,chartClipOutliers:!0,chartLimitLines:!0};export const WAFER_PREFERENCE_KEYS=Object.keys(qs);const oo=new Set(WAFER_PREFERENCE_KEYS);export const COLOR_KEYS=["binColorScheme","valueColorScheme","reverseValueScheme","useDefinedBinColors","binColors"];export function classifyChanged(P){const h=P.some(u=>oo.has(u)),y=P.some(u=>!oo.has(u));return h&&y?"mixed":h?"preference":"state"}export function findingBin(P,h,y){const{kind:u,bin:B}=P.variable;if(!(u!=="hardBin"&&u!=="softBin"||B===void 0))return h&&Hs(u,B,h,y)?void 0:B}export function findingPlotMode(P,h,y){const{kind:u}=P.variable;return u==="hardBin"||u==="softBin"?u:h==="hardBin"||h==="softBin"?h:y?"hardBin":"softBin"}export function toPublicViewOptions(P){const{metadataValueOrder:h,binColors:y,lotSize:u,compactMap:B,...Je}=P;return Je}export function renderWaferMap(P,h,y={}){return renderWaferMapCard(P,h,y)}export function renderWaferMapCard(P,h,y={}){ms();const u=P.ownerDocument,B=u.defaultView??window,Je=()=>C.label,yt=()=>xs({label:Je(),wafer:$}),fe=Ss(()=>{const e=Cs($.metadata?.lot);return{prefix:y.downloadFilename,lots:e!==void 0?[e]:[],...C.isLotStack?{stackedWafers:g?.lotSize??!0}:{wafer:yt()}}},y.onSaveImage,y.onSaveText);function Xn(){const e=g.plotMode==="softBin"||g.plotMode==="stackedSoftBins"?se:oe,{primary:n,secondary:t}=Xo(g,d.fallbackFormat,e);return[n,C.isLotStack?"":t].filter(Boolean).join(" ")||"wafer-map"}B.getComputedStyle(P).position==="static"&&(P.style.position="relative");const so=P.clientHeight;y.height!=null&&(P.style.height=typeof y.height=="number"?`${y.height}px`:y.height);const Qt=h.dataCoverage?h.dataCoverage.unpositionedDies:h.dies.filter(e=>!to(e)).length,et=(h.dataCoverage?h.dataCoverage.totalDies:h.dies.length-Qt)===0&&Qt>0,Ye=u.createElement("div");Object.assign(Ye.style,{display:"flex",flexDirection:"column",width:"100%",height:"100%"}),P.appendChild(Ye);const Ee=u.createElement("div");Object.assign(Ee.style,{position:"relative",width:"100%",flex:"1 1 auto",minHeight:"0"});const me=y.chromeInset??Jo,z=u.createElement("div");Object.assign(z.style,{display:"flex",alignItems:"stretch",gap:V.sm,background:A.canvasBg,paddingBottom:V.lg,paddingTop:me,paddingLeft:me,paddingRight:me,flexShrink:"0",minWidth:"0"}),Ye.appendChild(z),Ye.appendChild(Ee);function He(){const e=[...z.children].some(n=>n.style.display!=="none");z.style.display=e?"flex":"none"}const M=u.createElement("div");Object.assign(M.style,{position:"relative",width:"100%",height:"100%"});const a=u.createElement("canvas");Object.assign(a.style,{width:"100%",height:"100%",display:"block"}),M.appendChild(a),Ee.appendChild(M);let bt=null;if(Qt>0){let t=function(){if(n){const l=Ws(e,h.testDefs,{...y.dieList,onSaveText:fe.onSaveText,waferMetadata:$.metadata,metadataFields:Ne,attributes:y.attributes,ownerDocument:u});if(l)return l}const o=Ut(h.testDefs,d.activeTest??0),s=An(o)?d.logScale??o?.logScale??!1:!1;return Vs(e,h.testDefs,{plotMode:d.plotMode??"hardBin",activeTest:d.activeTest,hbinDefs:oe,sbinDefs:se,binColors:g.binColors,valueColorScheme:d.valueColorScheme,reverseValueScheme:d.reverseValueScheme,logScale:s,colorbarRangeMode:d.colorbarRangeMode,valueRangeDies:h.dies})},i=function(o){const s=u.createElement("button");return s.type="button",ji(s),Object.assign(s.style,{fontSize:Zt.body,padding:`${V.xxs} ${V.sm}`,borderRadius:$i.control,flexShrink:"0",border:`1px solid ${A.menuBorder}`,background:A.menuBg,color:A.text,cursor:"pointer"}),s.textContent=n?"View chart":"View die list",s.addEventListener("click",l=>{l.stopPropagation(),n=!n,s.textContent=n?"View chart":"View die list",o()}),s};const e=h.dies.filter(o=>!to(o));let n=!1;if(et){const o=u.createElement("div");Object.assign(o.style,{position:"absolute",inset:"0",background:A.panelBg,padding:V.xl,boxSizing:"border-box",overflow:"hidden",display:"flex",flexDirection:"column",gap:V.md,zIndex:"1"});const s=u.createElement("div");Object.assign(s.style,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:V.md});const l=u.createElement("span");Object.assign(l.style,{fontSize:Zt.body,color:A.label,lineHeight:Ni.base}),l.textContent="No die position data for this wafer.",s.appendChild(l);const r=u.createElement("div");Object.assign(r.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),s.appendChild(i(()=>r.replaceChildren(t()))),o.appendChild(s),o.appendChild(r),M.appendChild(o),bt=()=>{n||r.replaceChildren(t())}}else{const o=u.createElement("div");Object.assign(o.style,{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"3",background:A.panelBg,borderTop:`1px solid ${A.menuBorder}`,fontSize:Zt.body,color:A.text,cursor:"pointer",padding:`${V.xs} ${V.md}`,display:"flex",alignItems:"center",justifyContent:"space-between",gap:V.md}),ji(o,"bare");const s=u.createElement("span");s.textContent=`+${e.length} ${e.length===1?"die":"dies"} without position data`,o.appendChild(s);const l=u.createElement("span");l.textContent="\u25BE",Object.assign(l.style,{fontSize:Zt.body,lineHeight:Ni.none,color:A.label,flexShrink:"0"}),o.appendChild(l),o.setAttribute("aria-expanded","false"),o.setAttribute("aria-label",`${e.length} dies without position data. Click to view.`);let r=null,c=null;cs(o,f=>{if(l.textContent=f?"\u25B4":"\u25BE",o.setAttribute("aria-expanded",String(f)),f){r=u.createElement("div");const p=o.getBoundingClientRect().height||28;Object.assign(r.style,{position:"absolute",left:"0",right:"0",bottom:`${p}px`,top:"20%",zIndex:"2",background:A.panelBg,borderTop:`1px solid ${A.menuBorder}`,padding:V.md,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:V.md}),r.addEventListener("click",R=>R.stopPropagation());const b=u.createElement("div");Object.assign(b.style,{display:"flex",justifyContent:"flex-end"}),b.appendChild(i(()=>{c&&c.replaceChildren(t())})),r.appendChild(b),c=u.createElement("div"),Object.assign(c.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),c.appendChild(t()),r.appendChild(c),M.appendChild(r)}else r&&(r.remove(),r=null,c=null)}),M.appendChild(o),bt=()=>{c&&!n&&c.replaceChildren(t())}}}const{onHover:vt,onClick:lo,onSelect:ue,onViewOptionsChange:Kn,showTooltip:ao=!0,showToolbar:Be=!0,showIdentity:Nn=!0,summaryPanel:tt,showHelpButton:jn=!1,userGuideExtension:ro,onExpand:$n,showExpandButton:Gn=!0,zIndex:co,insights:J,warnings:Un,viewOptions:fo={},..._e}=y,ke=J?.enabled??Be;let nt=null,Xe=null;ke&&(nt=zo(u,"Map","wafer",e=>Ce(e)),Be||(nt.el.style.marginLeft="auto"),z.appendChild(nt.el)),ke&&(Xe=Is(u,"Filter\u2026","wmapMapFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{tn().then(e=>e.openEditor(Xe??P,[St()]))}),Xe.style.order="1",z.appendChild(Xe));const uo=.4,po=20,ne=[..._s(h,"renderWaferMap")],Zn=Un?.display??!0,ho=es(co);let pe=y.statsSummary,De=!1,wt;const ie=()=>De?wt:pe;let we=[],qn=!1,xt=null,Qn=!1;function Jt(){const e=Ds({result:h,statsSummary:ie(),extra:xt?[xt]:[]}),n=e.length!==we.length||e.some((t,i)=>t.code!==we[i]?.code||t.message!==we[i]?.message);we=e,(n||!qn)&&(qn=!0,Un?.onWarning?.(e))}Jt();let C=h,$=h.wafer,Ct=h.dies,I=h.dies,xe=null,Jn=null,Pe=null;const St=()=>({dies:Ct,wafer:$,label:Je()??"Wafer",identity:yt(),waferIndex:0,passBins:ne,testDefs:K,statsSummary:pe});function en(){const e=xe?.get();if(wt=void 0,!xe||!e||e.off)return De=!1,Ct;const n=xe.mark([St()]);De=n.narrowing;const t=n.items[0].dies;if(De&&pe&&In(C)){const i=t.filter(o=>!o.filteredOut);try{wt=i.length===0?void 0:Wn({...C,dies:i,yield:Ki(t,ne,C.yield?.yieldPercentGross!=null?"denominator-only":"exclude"),dataCoverage:Xi(i)},pe.analysisOptions)}catch{wt=void 0}}return t}function ei(){if(!xe||!Pe)return;const e=[St()];Pe.refresh(xe.keep(e).result,e),Pe.el.style.display=xe.get()&&!ge?"":"none"}function ti(){I=en(),ei(),at(),x(),hn(pe)}function tn(){return Jn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const n=e({doc:u,initial:J?.filter,onChange:J?.onFilterChange,savedFilters:J?.savedFilters,onSavedFiltersChange:J?.onSavedFiltersChange,pickFiltersFile:J?.onPickFiltersFile,onSaveText:y.onSaveText,attributes:y.attributes,getRingCount:()=>ze(C,"renderWaferMap")});return xe=n,Pe=n.createBand(()=>[St()],{marginLeft:me,marginRight:me,marginBottom:V.lg}),Ye.insertBefore(Pe.el,Ee),n.subscribe(()=>{Ke||ti()}),n.get()&&!Ke&&ti(),n}),Jn}let w=new Set,Te=null;const nn=J?.plotStore??Ls(J),Mt={plots:nn,getBinColors:()=>g.binColors,attributes:y.attributes,onSaveImage:fe.onSaveImage,onSaveText:fe.onSaveText,onLocateDie:(e,n,t)=>En(e,t)},Et=()=>!et;let on=null,Bt=null,kt=!1,Ke=!1,oe=h.hbinDefs,se=h.sbinDefs,K=h.testDefs,Ne=h.metadataFields,ni=h.reticles?.length?h.reticles:void 0,Dt=h.reticleConfig,ii=h.dataAxisFlip,sn=h.isLotStack??!1,ln=h.aggrMethod,an=h.lotSize,ee=null,he=null,Pt=null;function Tt(e){Pt&&(Pt.style.display=e?"flex":"none",Ze?.())}Nn&&(ee=Rs(_n($.metadata??{},it())??"",$.metadata,{lotStack:it(),ownerDocument:u,attributes:y.attributes}),M.appendChild(ee.metaPanel),ee.metaPanel.style.visibility="visible",ee.isEmpty()||(he=oi(ee.wrap),z.insertBefore(he,z.firstChild),He()));function oi(e){const n=u.createElement("div");return Object.assign(n.style,{display:"flex",alignItems:"center",padding:`${V.sm} ${V.lg}`,flex:"1 1 auto",minWidth:"0",overflow:"hidden",gap:V.sm}),Object.assign(e.style,{flex:"1",minWidth:"0"}),n.appendChild(e),n}function it(){return sn?{lotSize:an??1,aggrMethod:ln}:void 0}function go(){if(!ee)return;ee.update(_n($.metadata??{},it())??"",$.metadata,it());const e=he?.isConnected??!1,n=!ee.isEmpty();!n&&e?(he.remove(),he=null):n&&!e&&(he=oi(ee.wrap),he.style.display="",z.insertBefore(he,z.firstChild),He())}const mo=[...oe??[],...se??[]].some(e=>e.color);let d={plotMode:Zo([h.dies]),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,showReticle:!1,showXYIndicator:!1,compact:!1,rotation:0,flipX:!1,flipY:!1,legendPosition:"default",...fo},N=null,ge=!1,si=null;function li(){return ke?N?Promise.resolve(N):(si??=Promise.all([import("./insightsTab.js"),tn()]).then(([{createInsightsTab:e},n])=>(N=e({pageFilter:n,showFilterButton:!1,initialAxisPrefs:Ji(d),onAxisPrefsChange:t=>{d={...d,...Es(t)};const i=[...zn];Kn?.(d,i,classifyChanged(i))},attributes:y.attributes,getItems:()=>[{wafer:$,dies:Ct,hbinDefs:oe,sbinDefs:se,testDefs:K,label:Je(),passBins:ne,ringCount:ze(C,"renderWaferMap"),statsSummary:pe}],getSynthesisSummary:()=>ie(),getBinColors:()=>g.binColors,getRingCount:()=>ze(C,"renderWaferMap"),onSaveImage:fe.onSaveImage,onSaveText:fe.onSaveText,defaultView:J?.defaultView,plotStore:nn,onPickPlotsFile:J?.onPickPlotsFile,showPatMap:()=>{Ce(!1),T({plotMode:"metadata",activeTest:void 0,activeMetadataKey:Ks,passFailDisplay:"off"})},showOnMap:t=>{if(Ce(!1),t.kind==="test")pi(t.testNumber);else if(t.kind==="finding"){const i=ie()?.findings.find(o=>o.id===t.id);i&&hi(i)}ie()&&Ht(!0)},showMetadataStrip:!1,contentInset:me,onOpenGuide:jn&&!Be?()=>Nt():void 0,focusTest:t=>{T({plotMode:"value",activeTest:t,highlightBin:void 0}),Ce(!1)},locateDie:(t,i,o)=>{Ce(!1),En(t,o)},ownerDocument:u}),Object.assign(N.el.style,{position:"absolute",inset:"0",background:A.canvasBg,overflowY:"auto",paddingTop:"0"}),N.el.style.setProperty("--wmap-sticky-top","0px"),N.el.style.display="none",Ee.appendChild(N.el),N)),si):Promise.resolve(null)}let ai=0;const rn=["wheel","touchstart","pointerdown","keydown"];function yo(e,n){if(n<=0)return;let t=!1;const i=[],o=()=>{t=!0;for(const l of i)B.clearTimeout(l);i.length=0;for(const l of rn)e.removeEventListener(l,o)},s=()=>t||!ge?!0:(e.scrollTop=n,e.scrollTop>=n);if(!s()){for(const l of rn)e.addEventListener(l,o,{passive:!0,once:!0});for(const l of[0,50,150,300,600])i.push(B.setTimeout(()=>{s()},l));i.push(B.setTimeout(()=>{for(const l of rn)e.removeEventListener(l,o)},700))}}function dn(){for(const e of[Z,F])e&&(e.style.visibility=ge?"hidden":"")}function Ce(e){if(!ke)return;const n=ge;ge=e,nt?.setInsightsOpen(e),Pe&&(Pe.el.style.display=xe?.get()&&!e?"":"none"),N&&!e&&n&&(ai=N.el.scrollTop),N&&(N.el.style.display=e?"flex":"none"),M.style.visibility=e?"hidden":"",dn(),X&&(X.style.display=e||et?"none":"flex"),W&&(W.style.display=e?"none":"flex"),Tt(!Ae),ae&&(ae.style.display="flex"),he&&(he.style.display=""),He(),Ze?.(),ee&&e&&ee.collapse(),ct(),e&&li().then(t=>{!t||!ge||(t.el.style.display="flex",t.render(),yo(t.el,ai))})}ke&&J?.defaultOpen&&queueMicrotask(()=>Ce(!0));let g,Le,G=null,O=null,Lt=[],cn;function ri(e){cn!==e&&(cn=e,x())}let Oe=null,fn=_e.legendOffset??{x:0,y:0},ot=!1,je=!1,st={x:0,y:0},un={x:0,y:0},Fe=!1,$e=!1,U="select",Ge={x:0,y:0},Ot={x:0,y:0},Y={x:0,y:0},H={x:0,y:0},lt=!1,Ue=!1;const pn=()=>no(d)?js(Ne):Ne;function at(){const e=d,i=(no(e)?$s(I,K,ne):I).filter(As);g=Ho($,i,{compact:d.compact?d.compactMap??Us(i):void 0,plotMode:e.plotMode,binColorScheme:e.binColorScheme,valueColorScheme:e.valueColorScheme,reverseValueScheme:e.reverseValueScheme,useDefinedBinColors:e.useDefinedBinColors,binColors:e.binColors??zs(I,{passBins:ne,binColorScheme:e.binColorScheme,hbinDefs:oe,sbinDefs:se,useDefinedBinColors:e.useDefinedBinColors}),passBins:ne,showDieLabels:e.showDieLabels,showRingBoundaries:e.showRingBoundaries,showQuadrantBoundaries:e.showQuadrantBoundaries,showReticle:e.showReticle,showXYIndicator:e.showXYIndicator,reticles:ni,ringCount:ze(C,"renderWaferMap"),highlightBin:e.highlightBin,highlightMetadataValue:e.highlightMetadataValue,activeTest:e.activeTest,activeMetadataKey:e.activeMetadataKey,testDefs:K,valueRange:e.valueRange,metadataValueOrder:e.metadataValueOrder,logScale:e.logScale,isLotStack:sn,aggregationMethod:ln??e.aggregationMethod,lotSize:an??e.lotSize,dataAxisFlip:ii,colorbarRangeMode:e.colorbarRangeMode,passFailDisplay:e.passFailDisplay,fallbackFormat:e.fallbackFormat,interactiveTransform:{rotation:e.rotation??0,flipX:e.flipX??!1,flipY:e.flipY??!1}},{hbinDefs:oe,sbinDefs:se,metadataFields:pn()}),Le=void 0;const o=e.binColors?null:Ys(g.binColors,g.plotMode);o?.message!==xt?.message&&(xt=o,Jt(),Qn&&mn())}at();function di(){return d.showAxes??_e.showAxes??O!==null}function bo(){return Zs(I,[Dt])}let Z=null,Re=null,ye=null,Se=null,Ft=null;function ci(){ye===null&&Se===null&&(Ft={plotMode:d.plotMode,activeTest:d.activeTest})}function fi(){T({...Ft??{},highlightBin:void 0}),Ft=null}function hn(e){const n=e!==pe;if(pe=e,n&&De&&(I=en(),at(),x()),Jt(),mn(),Z)le();else if(F)It();else if(e&&!tt?.placement){const t=tt?.defaultOpen??!Be;F=Yn("right",me,u,Dn),F.style.display=t?"block":"none";const i=M.parentElement,o=M.nextSibling;be=Hn(M,F,"right"),i?.insertBefore(be,o),It(),dn()}ct()}function Rt(){Z?le():F&&It()}let ui=y.findingsNotice,rt=!1;const vo=()=>ui??(y.testValueOffer?y.testValueOffer():void 0)??(!y.testValueOffer&&In(C)?Ms(ie()?.stats.testValueAnalysis,1,rt,wo):void 0);function wo(){const e=pe,n=C;if(rt||!e||!In(n))return;rt=!0,Rt();const t=u.defaultView?.requestAnimationFrame?.bind(u.defaultView)??(s=>setTimeout(s,16));let i=!1;const o=()=>{if(i||Ke)return;i=!0;let s;try{s=Wn(n,{...e.analysisOptions,enableTestValueAnalysis:!0})}catch(l){throw rt=!1,Rt(),l}if(rt=!1,C!==n||pe!==e){Rt();return}hn(s),y.onStatsSummaryChange?.(s)};t(()=>t(o)),setTimeout(o,120)}let xo={},F=null,be=null;function Co(e){const{kind:n,index:t}=e.variable;if(n==="test")T({plotMode:"value",activeTest:t??0,highlightBin:void 0});else{const o=I.some(s=>s.hbin!=null);T({plotMode:findingPlotMode(e,d.plotMode,o),highlightBin:findingBin(e,ne,o)})}const i=e.highlight;(i.kind==="bin"||i.kind==="region"||i.kind==="dies")&&Yt(i.dieKeys)}const dt=new Map,gn=new WeakSet;function At(e){if(dt.get(e)?.cancel(),dt.delete(e),e.style.display==="none"){gn.add(e);return}gn.delete(e);const n=ks(Bs(e,{wafer:$,dies:I,yieldSummary:De?Ki(I,ne,C.yield?.yieldPercentGross!=null?"denominator-only":"exclude"):C.yield,dataCoverage:De?Xi(I.filter(t=>!t.filteredOut)):C.dataCoverage,hbinDefs:oe,sbinDefs:se,testDefs:K,statsSummary:ie(),warnings:Zn?we:[],passBins:ne,ringCount:ze(C,"renderWaferMap"),binColors:g.binColors,plotMode:d.plotMode??"hardBin",metadataShownElsewhere:Nn,fallbackFormat:d.fallbackFormat,activeFindingId:ye,findingsFilter:xo,findingsNotice:vo(),onFindingsFilterChange:le,onSaveText:fe.onSaveText,metadataFields:Ne,dieListOptions:y.dieList,onLocateDie:(t,i,o)=>En(t,o),attributes:y.attributes,onClose:Be&&ie()?()=>Ht(!1):void 0,activeTest:Se,onTestClick:t=>{Se===t?(Se=null,Yt([]),fi(),le()):pi(t)},onFindingClick:(t,i)=>{ye===t.id?(ye=null,Yt([]),fi(),le()):hi(t)},onShowChart:ke?t=>{Ce(!0),li().then(i=>i?.showWorthCard(t))}:void 0}));n.done||dt.set(e,n)}function pi(e){ci(),ye=null,Se=e,T({plotMode:"value",activeTest:e,highlightBin:void 0}),Yt(ie()?.stats.testFailures?.[e]?.dieKeys),le()}function hi(e){ci(),Se=null,ye=e.id,Co(e),le()}function le(){Z?At(Z):F&&At(F)}function It(){F&&At(F)}if(tt?.placement){const e=tt.placement;Z=Yn(e,me,u,Dn);const n=M.parentElement,t=M.nextSibling;Re=Hn(M,Z,e),n?.insertBefore(Re,t),le()}else if(ie()){const e=tt?.defaultOpen??!Be;F=Yn("right",me,u,Dn),F.style.display=e?"block":"none";const n=M.parentElement,t=M.nextSibling;be=Hn(M,F,"right"),n?.insertBefore(be,t),It()}dn();const _=ao?Gi(u):null;let ae=null,j=null,Ze=null,X=null,W=null,Wt=null,Vt=null,gi=!0,mi=null,ve=null,zt=null;Qn=!0;function mn(){if(!ve||!zt)return;const e=we.length,n=e>0;if(ve.style.display=n?"flex":"none",zt.style.display=n?"":"none",Ze?.(),!n)return;const t=Ts(we[0]),i=`${e} data ${e===1?"warning":"warnings"}`;ve.style.color=t==="error"?A.errText:A.warnText,ve.ariaLabel=t==="error"?`${i} \u2014 the map may be positionally wrong`:i}let yn=null,yi=null,bn=null,vn=null,wn=null,xn=null;function Me(e="selection"){ye===null&&Se===null||(ye=null,Se=null,Ft=null,e==="selection"?T({highlightBin:void 0}):(w=new Set,ue?.([])),le())}function Yt(e){w=new Set(e??[]),ue&&ue(Ie()),x()}function ct(){if(!Vt)return;Ze?.();const e=Z??F;Vt.sync({visible:gi&&!!ie()&&!!e&&!ge,open:!!e&&e.style.display!=="none",notable:!!ie()?.hasNotableFindings})}function Ht(e){const n=Z??F;if(!n)return;const t=n.style.display!=="none",i=M.getBoundingClientRect().width;if(n.style.display=e?"block":"none",e!==t){const o=i-M.getBoundingClientRect().width;(y.onSummaryPanelChange??_t)?.(e,e?o:0)}e&&gn.has(n)&&At(n),ct()}if(Be){let R=function(L){U=L,i(v,L==="zoom"),i(q,L==="pan"),Wt&&i(Wt,L==="select"),a.style.cursor=L==="pan"?"grab":"crosshair"};ae=u.createElement("div"),ae.dataset.wmapToolbar="single",Object.assign(ae.style,{marginLeft:"auto",flexShrink:"0",display:"flex",flexDirection:"row",alignItems:"center",flexWrap:"wrap-reverse",justifyContent:"flex-end",maxWidth:"100%",background:A.menuBg,border:`1px solid ${A.menuBorder}`,borderRadius:$i.control,boxShadow:Qo.panel,pointerEvents:"auto"});const e=Gi(u),n=ts(e),{makeBtn:t,setActive:i,makeSep:o,syncSeparators:s,syncToolbarVisible:l,makeMenuRow:r,makeMenuSection:c,closeOpenMenu:f,getOpenMenu:p,setOpenMenu:b}=n;Ze=()=>{j&&s(j),ae&&l(ae,"flex"),He()},yn=f,yi=p,u.addEventListener("click",f,!0),X=u.createElement("div"),Object.assign(X.style,{display:et?"none":"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),ae.appendChild(X);const re=t("download","Download PNG",Do);X.appendChild(re),X.appendChild(o());const v=t("zoomMode","Zoom (drag to zoom region)",()=>R("zoom")),k=t("zoomIn","Zoom in",()=>Qe(a.clientWidth/2,a.clientHeight/2,1.2)),S=t("zoomOut","Zoom out",()=>Qe(a.clientWidth/2,a.clientHeight/2,1/1.2)),D=t("reset","Reset zoom (double-click)",()=>ut());X.appendChild(v),X.appendChild(k),X.appendChild(S),X.appendChild(D),X.appendChild(o());const q=t("pan","Pan (drag to move)",()=>R("pan"));X.appendChild(q),Wt=t("boxSelect","Select (drag to select dies)",()=>R("select")),X.appendChild(Wt);{const L=t("drilldown","Chart this wafer",()=>{const de=L.getBoundingClientRect();Pn({x:de.left,y:de.bottom+4},L)});L.setAttribute("aria-haspopup","menu"),Bt=L,Di(),X.appendChild(L)}R(U);{let L=function(m){return m.plotMode!==(d.plotMode??"hardBin")?!1:m.plotMode==="value"?(d.activeTest??0)===(m.activeTest??0):m.plotMode==="metadata"?d.activeMetadataKey===m.activeMetadataKey:!0},de=function(m,E){m.activeTest!==void 0?T({plotMode:m.plotMode,activeTest:m.activeTest,activeMetadataKey:void 0,logScale:m.logScale}):m.activeMetadataKey!==void 0?T({plotMode:m.plotMode,activeTest:void 0,activeMetadataKey:m.activeMetadataKey,passFailDisplay:"off"}):T({plotMode:m.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),b(null),mt(Q,!1)};j=u.createElement("div"),Object.assign(j.style,{display:"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),ae.appendChild(j),W=u.createElement("div"),Object.assign(W.style,{display:"flex",alignItems:"center",gap:"0"}),j.appendChild(W),W.appendChild(o());const pt=()=>{const m=p();m&&(m.remove(),b(null)),mt(Q,!1)},Q=t("mode","Plot mode",()=>{if(p()){pt();return}const m=I,E=g.testDefs,{testEntries:$t,binEntries:We,stackedEntries:ht}=ys(m,E,{includeStacked:g.isLotStack}),Gt=(Ne??[]).filter(Ve=>bs(m,Ve.key)).map(Qi);Ns([{dies:m,testDefs:E}])&&Gt.push(Qi(Xs));const gt=ns(Q.getBoundingClientRect(),$t,We,ht,L,de,{makeMenuRow:r,makeMenuSection:c},d.plotMode??"hardBin",Q.ownerDocument.defaultView??window,Gt);Zi(Q).appendChild(gt),b(gt),mt(Q,!0),qi(gt,Q,pt)});mt(Q,!1);const{btn:Ln,sync:On}=os(n,()=>({...d,plotMode:d.plotMode??"hardBin"}),()=>mo,T);vn=On,vn();const Oo=as(n,()=>{const m=!!g.hasReticle,E=(d.plotMode??"hardBin")==="value",{testNumber:$t}=Fn(d.activeTest??0,g.testDefs),We=Ut(g.testDefs,$t),ht=E&&We!==void 0&&!An(We),Gt=E&&!ht&&(We?.limitLow!==void 0||We?.limitHigh!==void 0),gt=E&&!ht&&g.dies.some(Ve=>qo(Ve,$t,We)!==void 0);return us({...d,showAxes:di()},m,{functionalActive:ht,hasLimits:Gt,hasRecorded:gt,binMode:(d.plotMode??"hardBin")==="hardBin"||(d.plotMode??"hardBin")==="softBin"},Ve=>T(Ve),{on:!!d.compact,offered:bo(),onChange:Ve=>T({compact:Ve}),onDiagnostics:()=>hs(I,[Dt],{anchor:a,onSaveText:fe.onSaveText})})},()=>ps(d)),{btn:Fo,sync:Ro}=ls(n,()=>d,m=>T({legendPosition:m}));bn=Ro,bn();const Hi=()=>{const{testNumber:m}=Fn(d.activeTest??0,K),E=Ut(K,m);return E!==void 0&&!An(E)},{btn:Ao,sync:Io}=ss(n,()=>({...d,functionalActive:Hi()}),m=>T(m));wn=Io,wn();const Wo=()=>{const{testNumber:m}=Fn(d.activeTest??0,K),E=Ut(K,m);return E!==void 0&&(E.limitLow!==void 0||E.limitHigh!==void 0)},jt=t("specRange","Colour bar range: test limits",()=>{const m=d.colorbarRangeMode==="data"?"spec":"data";T({colorbarRangeMode:m})});xn=()=>{const m=d.plotMode==="value"&&Wo()&&fs(d)==="off"&&!Hi();jt.style.display=m?"":"none";const E=(d.colorbarRangeMode??"spec")==="spec";i(jt,E),jt.ariaLabel=E?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"},xn();const Vo=rs(n,()=>d,m=>T(m));W.appendChild(Q),W.appendChild(Ln),W.appendChild(Ao),W.appendChild(jt),et||(W.appendChild(o()),W.appendChild(Oo),W.appendChild(o()),W.appendChild(Fo),W.appendChild(o()),W.appendChild(Vo)),Vt=Yo(u,()=>{const m=Z??F;m&&Ht(m.style.display==="none")}),z.insertBefore(Vt.el,nt?.el??null),ct(),Zn&&(zt=o(),ve=t("warning","Data warnings",()=>{const m=p();if(f(new MouseEvent("click")),m)return;const E=Ps(ve.getBoundingClientRect(),we,B);Zi(Ee).appendChild(E),b(E),qi(E,ve,()=>f(new MouseEvent("click")))}),mt(ve,!1),j.appendChild(zt),j.appendChild(ve),mn()),Gn&&(j.appendChild(o()),Pt=t("expand","Expand (E)",$n??bi),j.appendChild(Pt)),jn&&(j.appendChild(o()),mi=t("help","User guide",()=>Nt()),j.appendChild(mi)),Ze?.()}z.appendChild(ae),Xe&&z.appendChild(Xe),He()}let Ae=null,_t=null;function bi(){Ae&&(Ae.close(),Ae=null);const e=Ee;e.style.flex="1",e.style.minWidth="0",e.style.minHeight="0";const n=_n($.metadata??{},it()),t=z.childElementCount>0?[z,e]:[e],i=is(t,{ownerDocument:u,boxSize:ge?{width:"min(96vw, 1600px)",height:"min(92vh, 1000px)"}:void 0,onClosed:()=>{Ae=null,_t=null,Tt(!0),ge||a.focus({preventScroll:!0})}});if(!i)return;i.box.setAttribute("aria-label",n??"Expanded wafer map"),t.length>1&&(i.contentWrap.style.flexDirection="column"),Ae=i,_t=gs(i);const o=Z??F,s=Re??be;if(o&&s&&o.style.display!=="none"){const l=parseFloat(u.defaultView?.getComputedStyle(s).columnGap??"")||0,r=o.getBoundingClientRect().width+l;r>0&&_t(!0,r)}Tt(!1)}function vi(e){("binColorScheme"in e||"useDefinedBinColors"in e)&&!("binColors"in e)&&d.binColors!==void 0&&(e={...e,binColors:void 0});const n=d.plotMode;d={...d,...e},zn.some(l=>l in e)&&N?.setAxisPrefs(Ji(d));const t=Object.keys(e);if(t.length>0&&t.every(l=>zn.includes(l)))return;("compact"in e||"compactMap"in e)&&(G=null,O=null),e.plotMode!==void 0&&e.plotMode,Object.keys(e).every(l=>l==="legendPosition"||l==="showLegend"||l==="markFailingDies"||l==="showAxes")||at(),bn?.(),vn?.(),wn?.(),xn?.(),x();const o=e.plotMode!==void 0&&e.plotMode!==n,s=COLOR_KEYS.some(l=>l in e);(s||o)&&le(),(s||o||e.activeTest!==void 0||e.logScale!==void 0||e.colorbarRangeMode!==void 0)&&bt?.()}function T(e){vi(e);const n=Object.keys(e);Kn?.(d,n,classifyChanged(n))}let Cn=!1;const Sn=y.drawWhenVisible&&B.IntersectionObserver?new B.IntersectionObserver(e=>{qe=e[e.length-1].isIntersecting,qe&&Xt&&x()},{rootMargin:"25%"}):null;let qe=Sn===null,Xt=!1;Sn?.observe(a);function Mn(){Cn||(Cn=!0,Vn(()=>{Cn=!1,x()},B))}function x(){if(!qe){Xt=!0;return}Xt=!1;const e=O??void 0,n=g.dies[0],t=n?{x:n.width,y:n.height}:_e.diePitchMm,i=Math.floor(a.clientWidth||a.width),o=!!(oe?.length||se?.length||g.dies.some(b=>b.hbin!=null||b.sbin!=null)),s=d.legendPosition??"default",l=d.showLegend??!0,r=s==="default"||s==="compact",c=(_e.colorbarWidth??16)+28,f=o&&r?s!=="default"?Math.max(_i+Rn,c):i<$o?0:i<jo?Math.max(No+Rn,c):Math.max(_i+Rn,c):void 0,p=Ko(a,g,{..._e,minRightReserve:l?f:0,showColorbar:l&&(_e.showColorbar??!0),markFailingDies:d.markFailingDies??!1,legendPosition:s,legendOffset:fn,diePitchMm:t,fallbackFormat:d.fallbackFormat,showAxes:di(),viewport:e,activeBin:d.plotMode==="metadata"?d.highlightMetadataValue:d.highlightBin,hoverBin:cn,afterDies:w.size>0||Te!==null?So:void 0,hbinDefs:oe,sbinDefs:se,metadataFields:pn()});Lt=p.binLegendRows,Oe=p.legendBox??null,O===null&&(G=p.viewport),$e&&ko(),Di()}function So(e,n,t){w.size>0&&Eo(e,n,t),Te!==null&&Mo(e,n,t)}function Mo(e,n,t){Le??=new Map(g.dies.map((b,R)=>[ce(b),R]));const i=Te===null?void 0:Le.get(Te);if(i===void 0)return;const o=g.hoverPoints[i],s=g.rectangles[0],l=s?s.width/2*n.ppm:n.ppm*.5,r=s?s.height/2*n.ppm:n.ppm*.5,c=n.originX+o.x*n.ppm,f=n.originY-o.y*n.ppm,p=Math.max(l,r)*1.25+5;e.save(),e.setLineDash([]),e.beginPath(),e.arc(c,f,p,0,Math.PI*2),e.strokeStyle=t.background,e.lineWidth=6,e.stroke(),e.strokeStyle=t.text,e.lineWidth=3,e.stroke(),e.restore()}function En(e,n){n!==void 0&&T({plotMode:"value",activeTest:n,highlightBin:void 0}),wi(e)}function wi(e){if(Te=e===null?null:ce(e),e!==null&&O!==null){ut();return}x()}function xi(){Te!==null&&(Te=null,x())}function Eo(e,n,t){const i=g.hoverPoints,o=g.rectangles[0],s=o?o.width/2*n.ppm:n.ppm*.5,l=o?o.height/2*n.ppm:n.ppm*.5,r=new Set;w.size>0&&(Le??=new Map(g.dies.map((v,k)=>[ce(v),k])));for(const v of w){const k=Le.get(v);k!==void 0&&r.add(k)}if(!r.size)return;e.save(),e.setLineDash([]),e.fillStyle=t.background,e.globalAlpha=.7;let c=0;e.beginPath();for(let v=0;v<i.length;v++)r.has(v)||(e.rect(n.originX+i[v].x*n.ppm-s,n.originY-i[v].y*n.ppm-l,s*2,l*2),++c===Go&&(e.fill(),e.beginPath(),c=0));c&&e.fill(),e.globalAlpha=1;const{cw:f,ch:p}=Bo(n,s,l),b=new Map,R=v=>Math.round(v*100),re=(v,k,S,D)=>{const q=`${R(v)},${R(k)},${R(S)},${R(D)}`;b.has(q)?b.delete(q):b.set(q,[v,k,S,D])};for(const v of r){const k=n.originX+i[v].x*n.ppm,S=n.originY-i[v].y*n.ppm,D=k-f,q=k+f,L=S-p,de=S+p;re(D,L,q,L),re(D,de,q,de),re(D,L,D,de),re(q,L,q,de)}e.strokeStyle=t.text,e.lineWidth=2,e.lineCap="square",e.beginPath();for(const[v,k,S,D]of b.values())e.moveTo(v,k),e.lineTo(S,D);e.stroke(),e.restore()}function Bo(e,n,t){const i=g.hoverPoints,o=g.dies;let s=0,l=0;for(let r=0;r<o.length&&(!s||!l);r++){const c=o[r];if(!(c.x==null||c.y==null))for(const f of[Le.get(`${c.x+1},${c.y}`),Le.get(`${c.x},${c.y+1}`)]){if(f===void 0)continue;const p=Math.abs(i[f].x-i[r].x)*e.ppm,b=Math.abs(i[f].y-i[r].y)*e.ppm;p>b?s||=p/2:l||=b/2}}return{cw:s||n,ch:l||t}}function ko(){const e=a.getContext("2d"),n=Math.min(Y.x,H.x),t=Math.min(Y.y,H.y),i=Math.abs(H.x-Y.x),o=Math.abs(H.y-Y.y);e.save(),e.fillStyle="rgba(0,0,0,0.08)",e.fillRect(n,t,i,o),e.setLineDash([5,3]),e.strokeStyle="rgba(255,255,255,0.9)",e.lineWidth=3,e.strokeRect(n,t,i,o),e.strokeStyle="rgba(0,0,0,0.9)",e.lineWidth=1.5,e.strokeRect(n,t,i,o),e.restore()}function Ci(){if(!Xt)return;const e=qe;qe=!0,x(),qe=e}function Do(){Ci(),a.toBlob(e=>{e&&ds(e,Xn(),fe.onSaveImage)})}function Si(e){return G?Math.max(G.ppm*uo,Math.min(G.ppm*po,e)):e}function Qe(e,n,t){const i=O??G;if(!i)return;const o=Si(i.ppm*t),s=o/i.ppm,l=e-(e-i.originX)*s,r=n-(n-i.originY)*s,c=(G?.snapDist??1)/(o/(G?.ppm??o));O={originX:l,originY:r,ppm:o,snapDist:c},x()}function te(){return O??G}function Mi(e){if(e.ctrlKey||e.metaKey){e.preventDefault();const n=a.getBoundingClientRect(),t=e.deltaY<0?1.12:1/1.12;Qe(e.clientX-n.left,e.clientY-n.top,t)}else if(O!==null){e.preventDefault();const n=te(),t=O.snapDist;O={originX:n.originX-e.deltaX,originY:n.originY-e.deltaY,ppm:n.ppm,snapDist:t},x()}}function Bn(e,n,t){return e>=t.x&&e<t.x+t.w&&n>=t.y&&n<t.y+t.h}function Ei(e){if(kt=!1,e.button!==0||(xi(),!te()))return;a.focus({preventScroll:!0}),a.setPointerCapture(e.pointerId);const n=a.getBoundingClientRect(),t=e.clientX-n.left,i=e.clientY-n.top;if(Oe&&d.legendPosition==="floating"&&Bn(t,i,Oe)){je=!0,st={x:t,y:i},un={...fn};return}if(lt&&U!=="pan"){Ue=!0,Fe=!0,Ge={x:t,y:i},Ot={x:te().originX,y:te().originY},a.style.cursor="grabbing";return}if(U==="zoom"||U==="select"){$e=!0,Y=H={x:t,y:i};return}Fe=!0,Ge={x:t,y:i},Ot={x:te().originX,y:te().originY},a.style.cursor="grabbing"}function Bi(e){const n=a.getBoundingClientRect(),t=e.clientX-n.left,i=e.clientY-n.top;if($e){H={x:t,y:i},Mn();return}if(je){const p=t-st.x,b=i-st.y;p*p+b*b>16&&(je=!1,ot=!0,a.style.cursor="grabbing")}if(ot){fn={x:un.x+(t-st.x),y:un.y+(i-st.y)},Mn();return}if(Fe){const p=te(),b=O?.snapDist??G?.snapDist??1;O={originX:Ot.x+(t-Ge.x),originY:Ot.y+(i-Ge.y),ppm:p.ppm,snapDist:b},Mn();return}const o=te();if(!o)return;const s=(t-o.originX)/o.ppm,l=(o.originY-i)/o.ppm,c=Tn(s,l,o.snapDist)?.die??null,f=Lt.find(p=>t>=p.x&&t<p.x+p.w&&i>=p.y&&i<p.y+p.h);if(ri(f?f.bin:void 0),f){a.style.cursor="pointer",_&&(_.textContent=f.label??`Bin ${f.bin}`,_.style.display="block",Ui(_,a,e.clientX,e.clientY,{followPointer:!0})),vt?.(null,e);return}U==="pan"&&(a.style.cursor=c?"crosshair":"grab"),_&&(c?(_.innerHTML=_o(c,g.plotMode,{testDefs:K,hbinDefs:oe,sbinDefs:se,fallbackFormat:d.fallbackFormat,aggrMethod:g.aggrMethod,lotSize:g.lotSize,metadataFields:pn(),activeTest:g.activeTest,reticleConfig:Dt}),_.style.display="block",Ui(_,a,e.clientX,e.clientY,{followPointer:!0})):_.style.display="none"),vt?.(c,e)}function ki(e){const n=a.getBoundingClientRect(),t=e.clientX-n.left,i=e.clientY-n.top,o=e.ctrlKey||e.metaKey;if(_&&(t<0||i<0||t>n.width||i>n.height)&&(_.style.display="none"),$e){$e=!1,H={x:t,y:i};const r=t-Y.x,c=i-Y.y,f=te();if(U==="zoom"){if(r*r+c*c<25)Qe(t,i,2);else if(f){const p=Math.min(Y.x,H.x),b=Math.max(Y.x,H.x),R=Math.min(Y.y,H.y),re=Math.max(Y.y,H.y),v=b-p,k=re-R;if(v>4&&k>4){const S=a.clientWidth,D=a.clientHeight,q=S/v,L=D/k,de=Math.min(q,L),pt=Si(f.ppm*de),Q=pt/f.ppm,Ln=(p+b)/2,On=(R+re)/2;O={originX:S/2-(Ln-f.originX)*Q,originY:D/2-(On-f.originY)*Q,ppm:pt,snapDist:f.snapDist/Q}}}x(),a.style.cursor="crosshair";return}if(r*r+c*c<25)kn(t,i,o,e);else if(f){const p=(Math.min(Y.x,H.x)-f.originX)/f.ppm,b=(Math.max(Y.x,H.x)-f.originX)/f.ppm,R=(f.originY-Math.max(Y.y,H.y))/f.ppm,re=(f.originY-Math.min(Y.y,H.y))/f.ppm,v=g.hoverPoints,k=[];for(let S=0;S<v.length;S++)if(v[S].x>=p&&v[S].x<=b&&v[S].y>=R&&v[S].y<=re){const D=g.dies[S];D&&k.push(D)}if(o)for(const S of k){const D=ce(S);w.has(D)?w.delete(D):w.add(D)}else w=new Set(k.map(S=>ce(S)));Me(),ue?.(Ie())}x(),a.style.cursor="crosshair";return}if(je){je=!1,kn(t,i,o,e);return}if(ot){ot=!1,a.style.cursor="grab";return}if(!Fe)return;if(Fe=!1,Ue){Ue=!1,a.style.cursor=lt||U==="pan"?"grab":"crosshair";return}a.style.cursor=U==="pan"?"grab":"crosshair";const s=t-Ge.x,l=i-Ge.y;s*s+l*l<25&&kn(t,i,o,e)}function kn(e,n,t,i){for(const r of Lt)if(e>=r.x&&e<r.x+r.w&&n>=r.y&&n<r.y+r.h){Me("legend"),typeof r.bin=="number"?T({highlightBin:io(d.highlightBin,r.bin,t)}):T({highlightMetadataValue:io(d.highlightMetadataValue,r.bin,t)});return}if(Oe&&Bn(e,n,Oe))return;const o=te();if(!o)return;const l=Tn((e-o.originX)/o.ppm,(o.originY-n)/o.ppm,o.snapDist)?.die??null;if(l){lo?.(l,i);const r=ce(l);t?w.has(r)?w.delete(r):w.add(r):w.size===1&&w.has(r)?w=new Set:w=new Set([r]),Me(),ue?.(Ie()),x()}else t||(w=new Set,Me(),ue?.([]),x())}function Ie(){const e=[],n=g.hoverPoints;for(let t=0;t<n.length;t++){const i=g.dies[t];i&&w.has(ce(i))&&e.push(i)}return e}function Di(){Bt&&(Bt.style.display=Et()?"flex":"none",Bt.ariaLabel=w.size>0?"Charts and tables for the selected dies (or right-click)":"Charts and tables for this wafer (or right-click)")}function Pi(){const e={waferLabel:yt(),testDefs:K,isLotStack:C.isLotStack,wafer:C.wafer,passBins:ne,ringCount:ze(C,"renderWaferMap"),activeTest:d.plotMode==="value"?d.activeTest:void 0};return w.size>0?Os(Ie(),e,I):Fs(I,e)}function Dn(e,n,t){ye!==e&&n.click(),Pn(t,Z??F??a)}function Po(e,n){if(!Et())return;const t=d.plotMode==="softBin"?"soft":"hard",i=Gs(d.highlightBin),o=i.length>1&&i.includes(e)?[...i]:[e],s=[{label:yt()??"this wafer",dies:I,wafer:C.wafer,passBins:ne,ringCount:ze(C,"renderWaferMap")}],l=eo(s,t,o,K);if(!l)return;const r={...Mt},c=o.length>1?eo(s,t,[e],K):null;c&&(r.narrower={label:`Only ${t} bin ${e}`,backLabel:"All filtered bins",source:c,ctx:Mt});const f=a;import("./drilldown.js").then(({openDrilldownMenu:p})=>{Ke||(on=p(n,f,l,r))})}function To(){const e=new Set;for(const n of g.dies){const t=ce(n);w.has(t)||e.add(t)}w=e,Me(),ue?.(Ie()),x()}function Pn(e,n){if(!Et())return;const t=y.drilldownSourceOverride?.(),i=t?.source??Pi(),o={...Mt,...t?.ctx};if(!t&&w.size>0&&(o.onInvertSelection=To),t?.narrowable){const s=Pi(),l=s.items.reduce((r,c)=>r+c.dies.length,0);o.narrower={label:`Only this wafer \u2014 ${l.toLocaleString()} die${l===1?"":"s"}`,source:s,ctx:Mt}}import("./drilldown.js").then(({openDrilldownMenu:s})=>{Ke||(on=s(e,n,i,o))})}function Ti(e){e.stopPropagation();const n=kt;if(kt=!1,!Et()||ge)return;const t=a.getBoundingClientRect();if(!n){const o=e.clientX-t.left,s=e.clientY-t.top,l=Lt.find(f=>o>=f.x&&o<f.x+f.w&&s>=f.y&&s<f.y+f.h);if(l&&typeof l.bin=="number"&&!C.isLotStack&&(d.plotMode===void 0||d.plotMode==="hardBin"||d.plotMode==="softBin")){e.preventDefault(),Po(l.bin,{x:e.clientX,y:e.clientY});return}if(Oe&&Bn(o,s,Oe))return;const r=te(),c=r?Tn((o-r.originX)/r.ppm,(r.originY-s)/r.ppm,r.snapDist)?.die:void 0;c&&!w.has(ce(c))&&(w=new Set([ce(c)]),Me(),ue?.(Ie()),x())}e.preventDefault();const i=n?{x:t.left+t.width/2,y:t.top+t.height/2}:{x:e.clientX,y:e.clientY};Pn(i,a)}function Li(){ri(void 0),_&&qt(u),vt?.(null,new MouseEvent("mouseleave")),a.style.cursor=U==="pan"?"grab":"crosshair"}function Oi(){Fe=!1,Ue=!1,$e=!1,je=!1,ot=!1,_&&qt(u),vt?.(null,new MouseEvent("mouseleave")),a.style.cursor=U==="pan"?"grab":"crosshair",x()}function Tn(e,n,t){const i=g.hoverPoints,o=g.rectangles;for(let c=0;c<o.length;c++){const f=o[c];if(Math.abs(e-f.x)<=f.width/2&&Math.abs(n-f.y)<=f.height/2){const p=g.dies[c];return p?{die:p,index:c}:null}}let s=null,l=-1,r=t*t;for(let c=0;c<i.length;c++){const f=i[c].x-e,p=i[c].y-n,b=f*f+p*p;b<r&&(r=b,s=g.dies[c]??null,l=c)}return s?{die:s,index:l}:null}const Fi=new B.ResizeObserver(()=>{G=null,O=null,x()});Fi.observe(a),y.height==null&&so<=0&&Vn(()=>Vn(()=>{P.clientHeight>0||console.warn("[wafermap] The map container has zero height, so the map cannot render. renderWaferMap fills its container \u2014 give the container a resolved height: an explicit CSS `height` (e.g. 600px), a height-resolved flex/grid parent, or `position:absolute; inset:0`. Alternatively pass `{ height: 600 }` in the render options and the library will size it for you.")}));let ft=B.matchMedia(`(resolution: ${B.devicePixelRatio}dppx)`);const Kt=()=>{ft.removeEventListener("change",Kt),ft=B.matchMedia(`(resolution: ${B.devicePixelRatio}dppx)`),ft.addEventListener("change",Kt),x()};ft.addEventListener("change",Kt);const Ri=B.matchMedia("(prefers-color-scheme: dark)"),Ai=()=>x();Ri.addEventListener("change",Ai);const Ii=()=>{_&&qt(u)};B.addEventListener("blur",Ii);function Wi(e){if((e.key==="ContextMenu"||e.shiftKey&&e.key==="F10")&&(kt=!0),e.key==="Escape"&&xi(),e.key==="Escape"&&w.size>0&&(w=new Set,Me(),ue?.([]),x()),(e.key==="e"||e.key==="E")&&Gn&&(e.stopPropagation(),($n??bi)()),(e.ctrlKey||e.metaKey)&&(e.key==="="||e.key==="+"?(e.preventDefault(),Qe(a.clientWidth/2,a.clientHeight/2,1.2)):e.key==="-"?(e.preventDefault(),Qe(a.clientWidth/2,a.clientHeight/2,1/1.2)):e.key==="0"&&(e.preventDefault(),ut())),!e.ctrlKey&&!e.metaKey&&!e.shiftKey){const t=te();if(t){const i=O?.snapDist??G?.snapDist??1;let o=0,s=0;e.key==="ArrowLeft"&&(o=20,e.preventDefault()),e.key==="ArrowRight"&&(o=-20,e.preventDefault()),e.key==="ArrowUp"&&(s=20,e.preventDefault()),e.key==="ArrowDown"&&(s=-20,e.preventDefault()),(o||s)&&(O={originX:t.originX+o,originY:t.originY+s,ppm:t.ppm,snapDist:i},x())}e.key===" "&&!lt&&(e.preventDefault(),lt=!0,U!=="pan"&&(a.style.cursor="grab"))}}function Vi(e){e.key===" "&&(lt=!1,Ue&&(Fe=!1,Ue=!1),a.style.cursor=U==="pan"?"grab":"crosshair")}a.style.cursor="crosshair",a.setAttribute("tabindex","0"),a.addEventListener("wheel",Mi,{passive:!1}),a.addEventListener("pointerdown",Ei),a.addEventListener("pointermove",Bi),a.addEventListener("pointerup",ki),a.addEventListener("pointerleave",Li),a.addEventListener("pointercancel",Oi);const zi=()=>ut();a.addEventListener("dblclick",zi),a.addEventListener("keydown",Wi),a.addEventListener("keyup",Vi),a.addEventListener("contextmenu",Ti);const Yi=e=>{e.stopPropagation()};a.addEventListener("click",Yi),a.clientWidth,x(),bt?.();function ut(){G=null,O=null,x()}function Nt(e){import("./userGuideHtml.js").then(n=>vs({buildWaferMap:Uo,renderWaferMap,renderWaferGallery:void 0,analyzeWaferMap:Wn},n.USER_GUIDE_HTML,ro,P,e))}const Lo=ws(e=>Nt(e));return He(),ke&&J?.filter!==void 0&&tn(),{setResult(e){C=e,$=e.wafer,Ct=e.dies,I=en(),oe=e.hbinDefs,se=e.sbinDefs,K=e.testDefs,Ne=e.metadataFields,ni=e.reticles?.length?e.reticles:void 0,Dt=e.reticleConfig,ii=e.dataAxisFlip,sn=e.isLotStack,ln=e.aggrMethod,an=e.lotSize,go(),at(),x(),ei(),Z&&le()},setOptions(e){vi(e)},getOptions(){return{...d}},resetZoom:ut,setSelection(e){w=new Set(e.map(n=>ce(n))),x()},getSelectedDies:()=>Ie(),clearSelection(){w=new Set,Me(),ue?.([]),x()},setFindingsNotice(e){ui=e,Rt()},setStatsSummary(e){hn(e)},closeSummaryPanel(){Ht(!1)},getExportTitle(){return Xn()},getSaveImageHook(){return fe.onSaveImage},locateDie:wi,getSaveTextHook(){return fe.onSaveText},drawPendingNow:Ci,getBinColors(){return g.binColors},setSummaryVisible(e){gi=e,ct()},setViewControlsVisible(e){j&&(j.style.display=e?"flex":"none")},setExpandVisible(e){Tt(e)},openUserGuide:()=>Nt(),setInsightsOpen(e){Ce(e)},destroy(){Ke=!0,Lo(),nn.flush();for(const e of dt.values())e.cancel();dt.clear(),Ae?.close(),yi?.()?.remove(),yn&&u.removeEventListener("click",yn,!0),a.removeEventListener("wheel",Mi),a.removeEventListener("pointerdown",Ei),a.removeEventListener("pointermove",Bi),a.removeEventListener("pointerup",ki),a.removeEventListener("pointerleave",Li),a.removeEventListener("pointercancel",Oi),a.removeEventListener("dblclick",zi),a.removeEventListener("keydown",Wi),a.removeEventListener("keyup",Vi),a.removeEventListener("contextmenu",Ti),on?.(),a.removeEventListener("click",Yi),Fi.disconnect(),Sn?.disconnect(),ft.removeEventListener("change",Kt),Ri.removeEventListener("change",Ai),B.removeEventListener("blur",Ii),ho(),_&&qt(u),ae?.remove(),Re&&(Re.parentElement?.insertBefore(M,Re),Re.remove()),be&&(be.parentElement?.insertBefore(M,be),be.remove()),M.remove(),a.style.cursor="",N?.destroy(),ee?.destroy(),Ye.remove()}}}
@@ -540,7 +540,7 @@ export declare function renderWaferSummaryContentSteps(panel: HTMLDivElement, pa
540
540
  /** See `RenderOptions.dieList` — gates the "View die list" link below. */
541
541
  dieListOptions?: DieListDisplayOptions;
542
542
  /** A die row clicked in the Data tables: show that die on its map. */
543
- onLocateDie?: (die: Die, waferIndex: number | undefined) => void;
543
+ onLocateDie?: (die: Die, waferIndex: number | undefined, testNumber?: number) => void;
544
544
  /** The host's wafer attributes (`attributes` on the render options): what the Data tables call each field. */
545
545
  attributes?: Record<string, FacetCuration>;
546
546
  /**
@@ -630,7 +630,7 @@ export declare function renderLotSummaryContentSteps(panel: HTMLDivElement, para
630
630
  /** See `RenderOptions.dieList` — gates the "View die list" link below. */
631
631
  dieListOptions?: DieListDisplayOptions;
632
632
  /** A die row clicked in the Data tables: show that die on its map. */
633
- onLocateDie?: (die: Die, waferIndex: number | undefined) => void;
633
+ onLocateDie?: (die: Die, waferIndex: number | undefined, testNumber?: number) => void;
634
634
  /** The host's wafer attributes (`attributes` on the render options): what the Data tables call each field. */
635
635
  attributes?: Record<string, FacetCuration>;
636
636
  /** Per-wafer findings tally badged onto the Wafer Yield rows — see