@wafertools/wafermap 0.34.0 → 0.35.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 (104) hide show
  1. package/AGENTS.md +7 -1
  2. package/CHANGELOG.md +189 -1
  3. package/README.md +6 -3
  4. package/dist/packages/canvas-adapter/charts/barPanel.d.ts +1 -1
  5. package/dist/packages/canvas-adapter/charts/binCluster.js +1 -1
  6. package/dist/packages/canvas-adapter/charts/boxplot.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/capability.js +1 -1
  8. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +17 -2
  9. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
  11. package/dist/packages/canvas-adapter/charts/histogram.js +1 -1
  12. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  13. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.d.ts +6 -1
  14. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
  15. package/dist/packages/canvas-adapter/charts/scatter.js +1 -1
  16. package/dist/packages/canvas-adapter/charts/testPassRate.js +1 -1
  17. package/dist/packages/canvas-adapter/dataTab.d.ts +6 -0
  18. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  19. package/dist/packages/canvas-adapter/dieList.js +6 -6
  20. package/dist/packages/canvas-adapter/drilldown.d.ts +3 -0
  21. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  22. package/dist/packages/canvas-adapter/identityHeader.d.ts +4 -1
  23. package/dist/packages/canvas-adapter/identityHeader.js +1 -1
  24. package/dist/packages/canvas-adapter/insightsTab.d.ts +3 -1
  25. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  26. package/dist/packages/canvas-adapter/plotEditor.js +1 -1
  27. package/dist/packages/canvas-adapter/plotTab.d.ts +3 -0
  28. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  29. package/dist/packages/canvas-adapter/renderWaferGallery.d.ts +8 -0
  30. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  31. package/dist/packages/canvas-adapter/renderWaferMap.d.ts +22 -1
  32. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  33. package/dist/packages/canvas-adapter/summaryPanel.d.ts +39 -11
  34. package/dist/packages/canvas-adapter/summaryPanel.js +4 -2
  35. package/dist/packages/canvas-adapter/summaryToggle.d.ts +11 -0
  36. package/dist/packages/canvas-adapter/summaryToggle.js +1 -0
  37. package/dist/packages/canvas-adapter/sweepEditor.js +1 -1
  38. package/dist/packages/canvas-adapter/toolbar.d.ts +8 -0
  39. package/dist/packages/canvas-adapter/toolbar.js +2 -2
  40. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  41. package/dist/packages/canvas-adapter/userGuideHtml.js +57 -27
  42. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  43. package/dist/packages/canvas-adapter/version.js +1 -1
  44. package/dist/packages/canvas-adapter/warnings.js +1 -1
  45. package/dist/packages/core/classify.d.ts +5 -0
  46. package/dist/packages/core/classify.js +1 -1
  47. package/dist/packages/core/dieTable.d.ts +26 -0
  48. package/dist/packages/core/dieTable.js +1 -1
  49. package/dist/packages/core/index.d.ts +1 -1
  50. package/dist/packages/core/index.js +1 -1
  51. package/dist/packages/core/passBins.d.ts +6 -0
  52. package/dist/packages/core/passBins.js +1 -1
  53. package/dist/packages/core/reticle.d.ts +20 -0
  54. package/dist/packages/core/reticle.js +1 -1
  55. package/dist/packages/core/wafer.d.ts +15 -0
  56. package/dist/packages/core/wafer.js +1 -1
  57. package/dist/packages/renderer/buildView.js +1 -1
  58. package/dist/packages/renderer/buildWaferMap.d.ts +32 -1
  59. package/dist/packages/renderer/buildWaferMap.js +1 -1
  60. package/dist/packages/renderer/derivedTests/apply.js +1 -1
  61. package/dist/packages/renderer/derivedTests/evaluate.d.ts +3 -1
  62. package/dist/packages/renderer/derivedTests/evaluate.js +1 -1
  63. package/dist/packages/renderer/derivedTests/parser.d.ts +7 -0
  64. package/dist/packages/renderer/derivedTests/parser.js +2 -2
  65. package/dist/packages/renderer/spec.d.ts +4 -0
  66. package/dist/packages/renderer/spec.js +1 -1
  67. package/dist/packages/renderer/valueFilter.d.ts +55 -0
  68. package/dist/packages/renderer/valueFilter.js +1 -0
  69. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  70. package/dist/packages/stats/analyzeWaferMap.d.ts +44 -3
  71. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  72. package/dist/packages/stats/capability.d.ts +5 -0
  73. package/dist/packages/stats/capability.js +1 -1
  74. package/dist/packages/stats/clusterDetection.js +1 -1
  75. package/dist/packages/stats/connectedComponents.d.ts +19 -0
  76. package/dist/packages/stats/connectedComponents.js +1 -1
  77. package/dist/packages/stats/dieRegions.d.ts +42 -0
  78. package/dist/packages/stats/dieRegions.js +1 -0
  79. package/dist/packages/stats/facets.d.ts +8 -0
  80. package/dist/packages/stats/facets.js +1 -1
  81. package/dist/packages/stats/index.d.ts +2 -1
  82. package/dist/packages/stats/index.js +1 -1
  83. package/dist/packages/stats/lotPattern.js +1 -1
  84. package/dist/packages/stats/math.d.ts +25 -3
  85. package/dist/packages/stats/math.js +1 -1
  86. package/dist/packages/stats/metadataColumns.js +1 -1
  87. package/dist/packages/stats/patternClassification.d.ts +44 -18
  88. package/dist/packages/stats/patternClassification.js +1 -1
  89. package/dist/packages/stats/plotData.d.ts +12 -1
  90. package/dist/packages/stats/plotData.js +1 -1
  91. package/dist/packages/stats/plotSpec.d.ts +1 -1
  92. package/dist/packages/stats/plotSpec.js +1 -1
  93. package/dist/packages/stats/regions.d.ts +15 -0
  94. package/dist/packages/stats/regions.js +1 -1
  95. package/dist/packages/stats/renderSummaryReport.js +33 -33
  96. package/dist/packages/stats/reportHtml.d.ts +7 -6
  97. package/dist/packages/stats/reportHtml.js +39 -37
  98. package/dist/packages/stats/synthesis.d.ts +44 -17
  99. package/dist/packages/stats/synthesis.js +1 -1
  100. package/dist/packages/stats/types.d.ts +12 -0
  101. package/llms.txt +2 -2
  102. package/package.json +1 -1
  103. package/dist/packages/canvas-adapter/summaryRail.d.ts +0 -7
  104. package/dist/packages/canvas-adapter/summaryRail.js +0 -1
@@ -1 +1 @@
1
- import{createViewSwitch as bi}from"./viewSwitch.js";import{createSummaryRail as wi}from"./summaryRail.js";import{getUniqueTestNumbers as vi,resolveTestNumber as Si,findTestDef as Ci,collectMetadataValues as xi}from"../renderer/buildView.js";import{metadataCategoricalValue as Mi}from"../core/metadata.js";import{resolveBinColorsForMaps as ki,mergeBinDefs as mt,binColorWarning as Di,mixedPassBinsWarning as Bi,binColorsEqual as Ei}from"../renderer/binColors.js";import{commonPassBins as Oi,itemPassBins as to}from"../core/passBins.js";import{requireRingCount as ne}from"../core/ringCount.js";import{NO_DATA_FILL as Ti}from"../renderer/colorMap.js";import{metadataValueColor as Li}from"../renderer/colorMap.js";import{resolveCanvasTheme as Wi}from"./canvasTheme.js";import{ICONS as _t}from"./icons.js";import{SHADOW as qt,LEADING as no,TRACKING as Ri,controlStyle as $i,wireControlHover as Xt,SPACE as k,EDGE_GUTTER as fe,MAP_CHROME_INSET as Ai,RADIUS as _,FONT as j,CLR as b,sevColor as oo,MODE_LABELS as Ii,BIN_LEGEND_MODES as io,STACKED_MODES as Oe,applyOverlayZ as Pi,getTooltip as Fi,hideTooltip as so,createToolbarHelpers as Hi,buildModeMenuEl as ji,openDetachWindow as Vi,openFloatingWindow as zi,openModal as Ni,copyWmapThemeTokens as Gi,syncWmapPopupTheme as Ki,makePaletteBtn as _i,makeLogScaleBtn as qi,makeLegendStyleBtn as Xi,makeOverlaysBtn as Ui,makeOrientationBtn as Yi,menuLayerFor as ao,saveImageBlob as Zi,markMenuTrigger as Ze,wireMenuA11y as lo,wireTooltip as Ut,requestedPassFailDisplay as ro,overlayMenuRows as Qi,anyOverlayActive as Ji,openCompactDiagnostics as es,roomForPanel as co,logWmapVersionOnce as ts,buildDataModeEntries as ns,metadataKeyHasData as os,metadataModeEntry as is}from"./toolbar.js";import{openReportModal as ss,openUserGuideWindow as as}from"./guideWindow.js";import{waferDisplayLabel as gt,waferIdentityLabel as ye}from"../core/waferLabel.js";import{metadataDisplayValue as ls}from"../core/metadata.js";import{withExportContext as rs}from"./exportName.js";import{sortBinsForDisplay as cs}from"../stats/binPareto.js";import{diePassStatus as ds}from"../core/dies.js";import{aggregateValues as us,aggregateBinCounts as uo}from"../core/aggregates.js";import{renderWaferMap as fs,renderWaferMapCard as fo,toPublicViewOptions as po}from"./renderWaferMap.js";import{waferPopulation as ps,selectionPopulation as ms,LOT_STACK_REASON as Yt}from"./chartPopulation.js";import{sourceFromBins as mo}from"./plotItems.js";import{plotStoreFor as gs}from"./plotStore.js";import{classifyChanged as hs,COLOR_KEYS as ys,findingBin as bs}from"./renderWaferMap.js";import{findingPatternKey as go}from"../stats/filterFindings.js";import{buildWaferMap as ws,getTestPassStatus as ho,isParametricTest as Zt,getDieTestValue as vs}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as ht}from"../stats/analyzeWaferMap.js";import{collectWarnings as Ss,buildWarningsMenuEl as Cs,severityOf as xs}from"./warnings.js";import{asList as Qt,compareNatural as Jt,arrayEqual as yt,toggleHighlight as yo}from"../core/utils.js";import{buildCompactMap as Ms,compactLayoutOffered as ks}from"../core/compact.js";import{attachExpandableMetadata as bo}from"./identityHeader.js";import{createSummaryPanelEl as en,buildMetadataStripRow as Ds,metadataEntries as Bs,renderLotSummaryContentSteps as Es,reportMapsFromItems as Os}from"./summaryPanel.js";import{prettyKey as Ts}from"../stats/facets.js";import{testLabel as Ls,markedTestLabel as Ws,derivedFields as Rs}from"../renderer/testLabel.js";import{mergeTestDefs as $s}from"../stats/mergeTestDefs.js";import{getDieKey as bt,hasPosition as As}from"../core/dies.js";import{testValue as Is}from"../core/dieTable.js";import{runChunked as Ps}from"./chunked.js";function wo(d){if(typeof d!="number"||!Number.isFinite(d))return;const D=Math.round(d);return D>=1?D:void 0}const tn=12;function Fs(d,D,m){let H=D;if(D.length>tn){const x=D.slice(0,tn-1),E=D.slice(tn-1),V=E.reduce((R,oe)=>R+oe.count,0);H=[...x,{color:b.label,count:V,label:`Other (${E.length} bins)`}]}const O=d.createElement("div");Object.assign(O.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:_.control,overflow:"hidden",border:`1px solid ${b.menuBorder}`,boxSizing:"border-box",marginTop:k.xs,flexShrink:"0"}),O.setAttribute("role","img"),O.setAttribute("aria-label",`Population split: ${H.map(x=>`${x.label} ${wt(x.count/m*100)}`).join(", ")}`);for(const x of H){const E=x.count/m*100,V=d.createElement("div");Object.assign(V.style,{flex:`${E} 1 0`,minWidth:E>0?"2px":"0",background:x.color}),Ut(V,`${x.label} \xB7 ${x.count.toLocaleString()} dies \xB7 ${wt(E)}`),O.appendChild(V)}return O}function wt(d){return d>0&&d<.1?"<0.1%":`${d.toFixed(1)}%`}function vo(d,D,m){const H=new Map;let O=0,x=0;for(const E of d){const V=m?new Set(m(E)):void 0;for(const R of E.dies){if(R.partial||R.edgeExcluded)continue;const oe=D(R);oe!==void 0&&(H.set(oe,(H.get(oe)??0)+1),O++,V&&ds(R,V)&&x++)}}return{counts:H,total:O,pass:x}}function So(d,D){const m=d.ownerDocument.createElement("div");Object.assign(m.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${k.xxs} ${k.xs}`,borderRadius:_.control});const H=d.ownerDocument.createElement("span");Object.assign(H.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:D.color,border:D.isActive?`2px solid ${b.iconActive}`:`1px solid ${b.menuBorder}`,borderRadius:_.control,boxSizing:"border-box"});const O=d.ownerDocument.createElement("span");if(O.textContent=D.label,Object.assign(O.style,{fontWeight:D.isActive?"700":"400",color:D.isActive?b.iconActive:b.text,whiteSpace:"nowrap"}),m.appendChild(H),m.appendChild(O),D.count!==void 0){const x=d.ownerDocument.createElement("span");if(x.textContent=D.count.toLocaleString(),Object.assign(x.style,{color:D.isActive?b.iconActive:b.text,fontWeight:D.isActive?"700":"400",whiteSpace:"nowrap"}),m.appendChild(x),D.percent!==void 0){const E=d.ownerDocument.createElement("span");E.textContent=wt(D.percent),Object.assign(E.style,{color:b.label,whiteSpace:"nowrap"}),m.appendChild(E)}}if(m.setAttribute("role","button"),m.setAttribute("aria-pressed",D.isActive?"true":"false"),m.tabIndex=0,m.addEventListener("mouseenter",()=>{m.style.background=b.bgHover}),m.addEventListener("mouseleave",()=>{m.style.background="transparent"}),m.addEventListener("focus",()=>{m.style.background=b.bgHover}),m.addEventListener("blur",()=>{m.style.background="transparent"}),m.addEventListener("click",x=>D.onClick(x.ctrlKey||x.metaKey)),m.addEventListener("keydown",x=>{if(x.key==="Enter"||x.key===" ")x.preventDefault(),D.onClick(x.ctrlKey||x.metaKey);else if(D.onMenu&&(x.key==="ContextMenu"||x.key==="F10"&&x.shiftKey)){x.preventDefault();const E=m.getBoundingClientRect();D.onMenu({x:E.left+E.width/2,y:E.bottom},m)}}),D.onMenu){const x=D.onMenu;m.addEventListener("contextmenu",E=>{E.preventDefault(),x({x:E.clientX,y:E.clientY},m)}),Ut(m,"Right-click: charts and tables for these dies")}d.appendChild(m)}export function renderWaferGallery(d,D,m={}){ts();const H=6;let O=wo(m.columns);const x=m.showHelpButton??!1,E=m.userGuideExtension,V=m.insights?.enabled??!0,R=gs(m.insights),oe={enabled:!1,plotStore:R},Co=Pi(m.zIndex),be=m.summaryPanel,pe=e=>[...to(e)],nn=()=>M.flatMap(e=>e?[ne(e,"renderWaferGallery")]:[]),vt=()=>nn()[0];function xo(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 z=m.lotStatsSummary,Te=m.viewOptions?.legendPosition??"default",Qe=m.perCardLegend??!1;function Le(){const e=l.plotMode??"hardBin";return io.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 on(){const e=Qe||Le()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let l={plotMode:"hardBin",showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...m.viewOptions},C=[],ie=[],we=[],B=[];const P=rs(()=>{const e=B.filter(n=>n!=null),t=[...new Set(e.map(n=>ls(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(Jt);return{prefix:m.downloadFilename,lots:t,...e.length===1?{wafer:ye(e[0])}:{waferCount:e.length}}},m.onSaveImage,m.onSaveText);let M=D.map(e=>typeof e=="function"?null:e);function ve(){return $s(M)}function We(){if(M.some(e=>e?.testDefs?.length))return ve().defs}let Re=0,Je=0;const U=new Map;let Mo=0,$=null,se=null,sn=new Set,w=null,ko={};function an(e){return M[e]?.statsSummary??z?.perWafer.find(t=>t.waferIndex===e)?.summary}function St(){return!!(M.some(e=>e?.statsSummary?.findings.length)||z?.perWafer.some(e=>e.summary.findings.length))}const Do=Fi(),Se=Hi(Do),{makeBtn:ae,setActive:$e,makeSep:Q,makeMenuRow:Bo,makeMenuSection:Eo,makeDropdown:ln,closeOpenMenu:et,getOpenMenu:Ae,setOpenMenu:Ie}=Se;d.ownerDocument.addEventListener("click",et,!0);const rn=()=>so();window.addEventListener("blur",rn);let cn=m.findingsNotice;function dn(e){sn=new Set(e);const t=[...A.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=sn.has(i);o.style.outline=s?`3px solid ${b.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function un(){dn([])}let tt=!1;function fn(){tt=!0;for(const e of C)e&&e.clearSelection();tt=!1}function pn(e){return t=>{!tt&&se!==null&&(He(),N()),kt.set(e,t.length),J&&!Pe&&!tt&&Oo(e,t),e.onSelect?.(t)}}function le(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),A.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let J=!1,Pe=!1,me=new Set;function Oo(e,t){Pe=!0;try{me=new Set(t.map(n=>bt(n))),B.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>me.has(bt(s))))})}finally{Pe=!1}lt()}function mn(){me=new Set,Pe=!0;try{for(const e of C)e?.clearSelection()}finally{Pe=!1}lt()}function Ct(){if(!J||me.size===0)return;const e=[];let t=!1;if(B.forEach((i,s)=>{if(!i)return;const a=i.dies.filter(f=>me.has(bt(f)));a.length!==0&&(i.isLotStack&&(t=!0),e.push({label:ye(i)??i.label??`Wafer ${s+1}`,dies:a,waferIndex:s,wafer:i.wafer,passBins:pe(i),ringCount:ne(i,"renderWaferGallery")}))}),e.length===0)return;const n=ve(),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?Yt:void 0},ctx:{plots:R,onSaveImage:P.onSaveImage,onSaveText:P.onSaveText,onLocateDie:(i,s)=>le(s,i)}}}function gn(){const e=[];let t=!1;if(B.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:ye(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:pe(o),ringCount:ne(o,"renderWaferGallery")}))}),e.length<2)return;const n=l;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:ve().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Yt:void 0},ctx:{plots:R,onSaveImage:P.onSaveImage,onSaveText:P.onSaveText,onLocateDie:(o,i)=>le(i,o)}}}function To(e){const t=Ct()??bn(e);if(t)return t;const n=gn(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function xt(e,t,n){se!==e&&t.click();const o=w;if(!o)return;const i=z?.findings.find(a=>a.id===e),s=Ct()??gn()??Wo()??(i?hn(wn(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:a})=>{o.isConnected&&a(n,o,s.source,{plots:R,...s.ctx})})}function Lo(e,t,n,o){const i=Qt(l.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],a=[];let f=!1;B.forEach((g,S)=>{g&&(g.isLotStack&&(f=!0),a.push({label:ye(g)??g.label??`Wafer ${S+1}`,dies:g.dies,waferIndex:S,wafer:g.wafer,passBins:pe(g),ringCount:ne(g,"renderWaferGallery")}))});const r=ve().defs,p=mo(a,e,s,r,void 0,f);if(!p)return;const c={plots:R,onSaveImage:P.onSaveImage,onSaveText:P.onSaveText,onLocateDie:(g,S)=>le(S,g)},u=s.length>1?mo(a,e,[t],r,void 0,f):null,h=u?{...c,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:u,ctx:c}}:c;import("./drilldown.js").then(({openDrilldownMenu:g})=>{o.isConnected&&g(n,o,p,h)})}function hn(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((a,f)=>a-f)){const a=B[s];a&&(a.isLotStack&&(o=!0),n.push({label:ye(a)??a.label??`Wafer ${s+1}`,dies:a.dies,waferIndex:s,wafer:a.wafer,passBins:pe(a),ringCount:ne(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:ve().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Yt:void 0},ctx:{plots:R,onSaveImage:P.onSaveImage,onSaveText:P.onSaveText,onLocateDie:(s,a)=>le(a,s)}}}function Wo(){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:B[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=l;return{source:ms(n,{waferLabel:ye(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:pe(t),ringCount:ne(t,"renderWaferGallery")}),ctx:{onSaveImage:P.onSaveImage,onSaveText:P.onSaveText,onLocateDie:(i,s)=>le(s??e,i)}}}function Ro(e){e||mn(),J=e,lt()}function Mt(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=B[i],a=C[i];if(!s||!a)continue;const f=s.dies.filter(r=>n.has(bt(r)));a.setSelection(f)}}const q=new Set,kt=new Map;function yn(){[...A.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=q.has(o)?`2px solid ${b.iconActive}`:"",n.style.outlineOffset=q.has(o)?"-2px":""});const t=q.size;Y.style.display=t>0?"":"none",Y.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,Y.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function $o(e){e<0||(q.has(e)?q.delete(e):q.add(e),yn())}function Ao(){q.clear(),yn()}function bn(e){if(!(q.size===0||!q.has(e))){for(const t of kt.values())if(t>0)return;return hn([...q],"picked ")}}function Io(){const e=[];for(let t=0;t<M.length;t++){const n=M[t];if(!n)continue;const o=an(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 Po(e){const t=B[e]??M[e];t&&Xe(e,t)}function Fo(e){const t=an(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 Ho(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{ss(e(Os(M,vt())),{anchor:d})})}function jo(){if(!w)return;w.innerHTML="";const e=Io();if(M.length>0){const n=d.ownerDocument.createElement("div"),o=e.length,i=M.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:j.body,color:b.label,marginBottom:k.md}),w.appendChild(n)}if(e.length>0){const n=d.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{...$i("outlined"),marginBottom:k.lg,display:"block",width:"100%",textAlign:"left"}),Xt(n),n.addEventListener("click",Ho),w.appendChild(n)}if(e.length===0){const n=d.ownerDocument.createElement("div");Object.assign(n.style,{color:b.icon,fontSize:j.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",w.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:a}of e){const f=i?"unusual":s?"notable":"info",r=i+s||a,p=d.ownerDocument.createElement("button");p.type="button",Object.assign(p.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:k.xs,border:"none",borderLeft:`3px solid ${oo(f)}`,borderRadius:_.control,background:b.bgHover,cursor:"pointer",fontSize:j.body,textAlign:"left",boxSizing:"border-box"}),p.addEventListener("mouseover",()=>{p.style.background=b.bgActive}),p.addEventListener("mouseout",()=>{p.style.background=b.bgHover});const c=d.ownerDocument.createElement("span");c.textContent=gt(o,n),Object.assign(c.style,{color:b.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const u=d.ownerDocument.createElement("span");u.textContent=String(r),p.setAttribute("aria-label",`${gt(o,n)} \u2014 ${r} finding${r===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(u.style,{marginLeft:k.sm,flexShrink:"0",background:oo(f),color:"#fff",borderRadius:_.container,padding:"1px 5px",fontSize:j.body,fontWeight:"600"}),p.appendChild(c),p.appendChild(u),p.addEventListener("click",()=>Xe(n,o)),w.appendChild(p)}const t=d.ownerDocument.createElement("div");t.style.height="12px",w.appendChild(t)}let Ce=null,Fe=null;function N(){if(w)if(Ce?.cancel(),Ce=null,z){const e=mt(M.map(n=>n?.hbinDefs)),t=mt(M.map(n=>n?.sbinDefs));Ce=Ps(Es(w,{lotSummary:z,items:M,hbinDefs:e.length?e:void 0,sbinDefs:t.length?t:void 0,testDefs:We(),ringCount:vt(),binColors:l.binColors,plotMode:l.plotMode??"hardBin",fallbackFormat:l.fallbackFormat,activeFindingId:se,warnings:m.warnings?.display??!0?re:[],findingsFilter:ko,findingsNotice:cn,onFindingsFilterChange:N,onSaveText:P.onSaveText,onFindingClick:(n,o)=>{se===n.id?He():Vo(n,o),N()},onWaferClick:Po,findingsFor:Fo,dieListOptions:m.dieList,onLocateDie:(n,o)=>le(o,n)}),{onDone:()=>{const n=Fe;Fe=null,n?.()}})}else jo()}function wn(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let nt=[];function vn(){if(nt.length!==0){for(const e of nt)C[e]?.setOptions({plotMode:l.plotMode,activeTest:l.activeTest});nt=[]}}function He(){se=null,un(),fn(),vn(),I({highlightBin:void 0},{fireCallback:!1})}function Sn(){se!==null&&(He(),N())}function Vo(e,t){if(se===e.id){He();return}se=e.id,t.style.background=b.bgActive,t.style.fontWeight="600",vn();const{kind:n,index:o}=e.variable;if(n==="test"){const s=o??0,a=We();if(a===void 0||a.some(r=>r.testNumber===s))I({plotMode:"value",activeTest:s,highlightBin:void 0},{fireCallback:!1});else{I({highlightBin:void 0},{fireCallback:!1});const p=Oe.has(l.plotMode??"hardBin")?null:wn(e);if(p){for(const c of p)C[c]?.setOptions({plotMode:"value",activeTest:s});nt=[...p]}}}else I({plotMode:n==="softBin"?"softBin":"hardBin",highlightBin:bs(e)},{fireCallback:!1});un(),fn();const i=e.highlight;if(i.kind==="wafer"){dn(i.waferIndices);const s=go(e);for(const a of i.waferIndices){const f=i.dieKeysByWafer?void 0:B[a]?.statsSummary?.findings.find(p=>go(p)===s),r=i.dieKeysByWafer?.[a]??f?.highlight?.dieKeys;r?.length&&Mt(r,[a])}}else i.kind==="bin"?i.dieKeys?.length&&Mt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Mt(i.dieKeys)}let ot=null;function Cn(){if(!ot)return;const e=w?w.style.display!=="none":!0,t=!!$&&$.style.display!=="none",n=!!(z?.hasNotableFindings||M.some(o=>o?.statsSummary?.hasNotableFindings));ot.sync(t&&!e,n)}function ge(){if(!$)return;const e=!!w;$.style.display=(z||St())&&e&&!ct?"flex":"none";const t=w?w.style.display!=="none":!1;(z?.hasNotableFindings||M.some(o=>o?.statsSummary?.hasNotableFindings))&&!t?$.style.color=b.findingIndicator:$.dataset.active||($.style.color=b.icon),Cn()}const G=d.ownerDocument.createElement("div");G.dataset.wmapToolbar="gallery",Object.assign(G.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:_.control,padding:"0",boxShadow:qt.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const xn=()=>{const e=Ae();e&&(e.remove(),Ie(null)),Ze(ee,!1)},ee=ae("mode","Plot mode",()=>{if(Ae()){xn();return}const e=M.flatMap(v=>v?.dies??[]),t=We(),{testEntries:n,binEntries:o,stackedEntries:i}=ns(e,t,{includeStacked:!0}),s=M.filter(Boolean).length,a=v=>{if(v===void 0)return s;let L=0;for(const W of M)W?.dies?.some(F=>ho(F,v)!==void 0||Is(F,v)!==void 0)&&L++;return L},f=s<2?n:n.map(v=>{const L=a(v.activeTest);return L===s?v:{...v,label:`${v.label} \u2014 ${L} of ${s} wafers`}}),r=l.plotMode??"hardBin",p=l.activeTest??0;function c(v){return v.plotMode!==r?!1:v.plotMode==="value"?p===(v.activeTest??0):v.plotMode==="metadata"?l.activeMetadataKey===v.activeMetadataKey:!0}function u(v,L){v.activeTest!==void 0?I({plotMode:"value",activeTest:v.activeTest,activeMetadataKey:void 0,logScale:v.logScale}):v.activeMetadataKey!==void 0?I({plotMode:v.plotMode,activeTest:void 0,activeMetadataKey:v.activeMetadataKey,passFailDisplay:"off"}):I({plotMode:v.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),L.remove(),Ie(null),Ze(ee,!1)}const h=new Set,g=M.flatMap(v=>v?.metadataFields??[]).filter(v=>!h.has(v.key)&&h.add(v.key)).filter(v=>os(e,v.key)).map(is),S=ji(ee.getBoundingClientRect(),f,o,i,c,u,{makeMenuRow:Bo,makeMenuSection:Eo},r,ee.ownerDocument.defaultView??window,g);ao(ee).appendChild(S),Ie(S),Ze(ee,!0),lo(S,ee,xn)});Ze(ee,!1);const zo=()=>B.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:No,sync:Mn}=_i(Se,()=>({...l,plotMode:l.plotMode??"hardBin"}),zo,e=>I(e));Mn();const Go=D.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function it(){const e=We(),{testNumber:t}=Si(l.activeTest??0,e);return{testNumber:t,td:Ci(e,t)}}function kn(){if((l.plotMode??"hardBin")!=="value")return!1;const{td:e}=it();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function je(){if((l.plotMode??"hardBin")!=="value")return!1;const{td:e}=it();return e!==void 0&&!Zt(e)}function Ko(){if((l.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=it();return M.some(n=>n?.dies?.some(o=>ho(o,e,t)!==void 0))}function _o(e,t){if(!t||!Zt(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((ro(l)==="spec"&&n?"spec":l.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,a=-1/0;for(const f of M)if(f)for(const r of f.dies){const p=vs(r,e);p!==void 0&&(p<s&&(s=p),p>a&&(a=p))}if(isFinite(s))return s===a?[s,s+1]:[s,a]}function st(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 Dn(){if((l.plotMode??"hardBin")!=="metadata")return;const e=l.activeMetadataKey;if(!e)return;const t=new Set;for(const n of M)if(n)for(const o of xi(n.dies,e))t.add(o);return{key:e,values:[...t].sort(Jt)}}function Dt(){st("metadataValueOrder",Dn(),(e,t)=>e.key===t.key&&yt(e.values,t.values))}function Bt(){if((l.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=it(),n=_o(e,t);st("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const a=p=>Array.isArray(p)?{test:void 0,range:p}:{test:p.test,range:p.range},f=a(i),r=a(s);return f.test===r.test&&yt(f.range,r.range)})}let Et=!1;function qo(){if(Et)return;Et=!0,(d.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{Et=!1,Bt(),Dt(),Tn(),On()})}let Ot=!1;function Xo(){if(Ot)return;Ot=!0,(d.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{Ot=!1,ft()})}let Bn=[];function xe(){const{colors:e,mixedHardBins:t}=ki(M.filter(n=>n!=null),{binColorScheme:l.binColorScheme,useDefinedBinColors:l.useDefinedBinColors});return Bn=t,e}function Tt(){return B.filter(e=>e!=null).flatMap(e=>e.dies)}function En(){return l.compact?Ms(Tt()):void 0}const Uo=(e,t)=>yt(e.columns,t.columns)&&yt(e.rows,t.rows);function On(){st("compactMap",En(),Uo)&&Nn()}function Yo(){return ks(Tt(),B.filter(e=>e!=null).map(e=>e.reticleConfig))}function Tn(){st("binColors",xe(),Ei),ze()}const Zo=Ui(Se,()=>Qi(l,Go,{functionalActive:je(),hasLimits:kn()&&!je(),hasRecorded:Ko()&&!je(),binMode:(l.plotMode??"hardBin")==="hardBin"||(l.plotMode??"hardBin")==="softBin"},e=>I(e),{on:!!l.compact,offered:Yo(),onChange:e=>I({compact:e}),onDiagnostics:()=>es(Tt(),B.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:d,onSaveText:P.onSaveText})}),()=>Ji(l)),{btn:Qo,sync:Ln}=Xi(Se,()=>({plotMode:l.plotMode,legendPosition:Te}),e=>{Te=e;for(const t of C)t&&t.setOptions({legendPosition:Te})},{get:()=>Qe,set:e=>{Qe=e,on()},blockedReason:Le});Ln();const Jo=[{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"}],Wn=ln("aggr","Aggregation method",()=>Jo,()=>l.aggregationMethod??"mean",e=>I({aggregationMethod:e}));function Rn(){const e=l.plotMode==="stackedValues";Wn.style.display=e?"":"none"}Rn();const{btn:ei,sync:$n}=qi(Se,()=>({...l,functionalActive:je()}),e=>I(e));$n();const at=ae("specRange","Colorbar range: test limits",()=>{const e=l.colorbarRangeMode==="data"?"spec":"data";I({colorbarRangeMode:e})});function An(){const e=(l.plotMode??"hardBin")==="value"&&kn()&&ro(l)==="off"&&!je();at.style.display=e?"":"none";const t=(l.colorbarRangeMode??"spec")==="spec";$e(at,t),at.ariaLabel=t?"Colorbar range: test limits (click for data range)":"Colorbar range: data range (click for test limits)"}An();const ti=Yi(Se,()=>l,e=>I(e)),ni=ae("downloadAll","Download gallery PNG",gi),Me=ae("boxSelect","Select the same dies on every wafer",()=>{J&&me.size>0?mn():Ro(!J)});Me.style.position="relative";const Ve=d.ownerDocument.createElement("span");Ve.dataset.wmapSelectAcrossCount="1",Object.assign(Ve.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:_.pill,background:b.iconActive,color:b.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Me.appendChild(Ve);function lt(){$e(Me,J);const e=J?me.size:0;Ve.style.display=e>0?"block":"none",Ve.textContent=e>99?"99+":String(e),Me.ariaLabel=J?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)",Me.setAttribute("aria-pressed",String(J))}const Y=d.ownerDocument.createElement("button");Y.type="button",Y.dataset.wmapPickedWafers="1",Object.assign(Y.style,{display:"none",border:"none",background:b.bgActive,color:b.iconActive,borderRadius:_.control,padding:`${k.xs} ${k.md}`,fontSize:j.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),Xt(Y,"bare"),Y.addEventListener("click",Ao);const oi=ln("columns","Columns",()=>[{value:"auto",label:"Auto"},{value:"1",label:"1 column"},{value:"2",label:"2 columns"},{value:"3",label:"3 columns"},{value:"4",label:"4 columns"},{value:"5",label:"5 columns"}],()=>O!=null?String(O):"auto",e=>Kn(e==="auto"?void 0:Number(e))),T=d.ownerDocument.createElement("div");Object.assign(T.style,{display:"inline-flex",alignItems:"center",gap:"0"}),G.appendChild(T),T.appendChild(ee),T.appendChild(No),T.appendChild(Wn),T.appendChild(ei),T.appendChild(at),T.appendChild(Q()),T.appendChild(Zo),T.appendChild(Q()),T.appendChild(Qo),T.appendChild(Q()),T.appendChild(ti),T.appendChild(Q()),T.appendChild(oi),T.appendChild(Q()),T.appendChild(Me),T.appendChild(Y),T.appendChild(ni),lt(),(z||St())&&($=ae("findings","Summary panel",()=>{if(!w)return;const e=w.style.display!=="none";e||N(),w.style.display=e?"none":"flex",$e($,!e),ge()}),G.appendChild(Q()),G.appendChild($));let Z=null,rt=null,re=[],In=!1;function ze(){const e=Ss({lotStatsSummary:z,result:{warnings:[...M.flatMap(n=>n?.warnings??[]),...ve().warnings]},extra:[l.binColors&&Di(l.binColors,l.plotMode),Bi(Bn),xo(nn())].filter(n=>!!n)}),t=e.length!==re.length||e.some((n,o)=>n.code!==re[o]?.code||n.message!==re[o]?.message);re=e,(t||!In)&&(In=!0,m.warnings?.onWarning?.(e)),ii()}function ii(){if(!Z||!rt)return;const e=re.length,t=e>0;if(Z.style.display=t?"flex":"none",rt.style.display=t?"":"none",!t)return;const n=xs(re[0]),o=`${e} data ${e===1?"warning":"warnings"}`;Z.style.color=n==="error"?b.errText:b.warnText,Z.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(m.warnings?.display??!0)&&(rt=Q(),Z=ae("warning","Data warnings",()=>{const e=Ae();if(et(new MouseEvent("click")),e)return;const t=Cs(Z.getBoundingClientRect(),re,Z.ownerDocument.defaultView??window);ao(d).appendChild(t),Ie(t),lo(t,Z,()=>et(new MouseEvent("click")))}),Ze(Z,!1),G.appendChild(rt),G.appendChild(Z)),ze();function Pn(){import("./userGuideHtml.js").then(e=>as({buildWaferMap:ws,renderWaferMap:fs,renderWaferGallery,analyzeWaferMap:ht},e.USER_GUIDE_HTML,E,d))}x&&(G.appendChild(Q()),G.appendChild(ae("help","User guide",()=>Pn())));const ke=d.ownerDocument.createElement("div");ke.dataset.wmapGalleryMeta="1",Object.assign(ke.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${k.sm} ${k.lg}`,fontSize:j.sub,lineHeight:no.none,boxSizing:"border-box"});const Ne=d.ownerDocument.createElement("div");Object.assign(Ne.style,{background:b.canvasBg,display:"flex",alignItems:"stretch",gap:k.lg,paddingBottom:k.lg,minWidth:"0"});const ce=d.ownerDocument.createElement("div");ce.dataset.wmapGalleryLegend="1",Object.assign(ce.style,{display:"flex",flexDirection:"column",gap:k.sm,background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:_.container,padding:`${k.sm} ${k.lg}`,marginBottom:k.lg,boxShadow:qt.panel,fontSize:j.body,lineHeight:no.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const X=d.ownerDocument.createElement("div");Object.assign(X.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let De=null,Ge=null,Fn=null;function si(){return V?De?Promise.resolve(De):(Fn??=import("./insightsTab.js").then(({createInsightsTab:e})=>(De=e({getItems:()=>M,getLotStats:()=>z,getBinColors:()=>l.binColors??xe(),getRingCount:()=>ne({ringCount:vt()},"the Insights tab"),defaultView:m.insights?.defaultView,plotStore:R,onPickPlotsFile:m.insights?.onPickPlotsFile,onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:P.onSaveImage,onSaveText:P.onSaveText,ownerDocument:d.ownerDocument,locateDie:(t,n)=>{Wt(!1),le(n,t)},openWafer:(t,n,o)=>{const i=M[t];if(!i)return;let s=null;const a=Ni({title:n,onClose:()=>s?.destroy(),anchor:d});Xn(a,n,i.wafer.metadata??void 0),s=Vt(a.contentWrap,i,o,void 0,co(a))}}),Ge=De.el,Ge.style.display="none",d.appendChild(Ge),De)),Fn):Promise.resolve(null)}let ct=!1,Lt=null;function Wt(e){V&&(ct=e,Lt?.setInsightsOpen(e),Ge&&(Ge.style.display=e?"flex":"none"),X.style.display=e?"none":"flex",T.style.display=e?"none":"inline-flex",G.style.display="inline-flex",ge(),ft(),e&&si().then(t=>{!t||!ct||(t.el.style.display="flex",t.render())}))}V&&m.insights?.defaultOpen&&queueMicrotask(()=>Wt(!0));const Hn=4,dt=240,Rt=480,ai=720,li=1.25;let he=Rt;function jn(e){const t=H*2+110+2,n=Vn();if(n)return Math.ceil(n.across*Hn+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*(Hn/s),f=Math.ceil(a+t);(o==null||f>o)&&(o=f)}return o}function ri(e){const t=jn(e);return t==null?dt:Math.min(he,Math.max(dt,t))}function ci(e){const t=jn(e);if(t==null)return!1;const n=Math.min(ai,Math.max(Rt,t));return n<=he?!1:(he=n,!0)}function Vn(){const e=l.compact?l.compactMap:void 0,t=B.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 zn(e,t){const n=Vn();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 di(){for(const e of ie)e?.parentElement&&zn(e.parentElement,e)}function Nn(){he=Rt,Ke=dt,It(B.map(e=>e??null)),At(),di()}function $t(){return O!=null?"none":`${he}px`}function At(){const e=$t();for(const t of Array.from(A.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let Ke=dt,Gn=0;function It(e){if(ci(e)&&At(),O==null){const n=ri(e);n>Ke&&(Ke=n)}Ft()}function Kn(e){O=wo(e),At(),Ft()}function Pt(e){return`repeat(${e}, minmax(0, ${O!=null?"1fr":`${he}px`}))`}function _n(e){A.style.gridTemplateColumns!==e&&(A.style.gridTemplateColumns=e)}function Ft(){if(O!=null){_n(Pt(O));return}const e=Math.max(1,Gn),t=12,n=A.clientWidth||0,o=s=>(n-t*(s-1))/s;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const s=Math.min(he,Ke*li),a=f=>{let r=0;for(;r<e&&o(r+1)>=f;)r++;return r};i=a(s)||a(Ke)||1}_n(Pt(i))}const A=d.ownerDocument.createElement("div");if(Object.assign(A.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Pt(1),gap:k.xl,paddingLeft:fe,paddingRight:fe,justifyContent:"start",alignContent:"start",isolation:"isolate"}),be?.placement){const e=be.placement;w=en(e,fe,d.ownerDocument,xt),w.style.maxHeight="calc(100vh - 80px)",w.style.position="sticky",w.style.top="8px",w.style.display="flex",w.style.flexDirection="column"}else if(z||St()){const e=!!be?.defaultOpen;w=en("right",fe,d.ownerDocument,xt),w.style.maxHeight="calc(100vh - 80px)",w.style.position="sticky",w.style.top="8px",w.style.flexDirection="column",w.style.display=e?"flex":"none",N()}ge(),w?.style.display!=="none"&&$&&$e($,!0);const ut=be?.placement??"right";ut==="left"?(w&&X.appendChild(w),X.appendChild(A)):(X.appendChild(A),w&&X.appendChild(w)),(ut==="left"||ut==="right")&&(ot=wi(d.ownerDocument,ut,()=>$?.click()),X.appendChild(ot.el),Cn());const _e=d.ownerDocument.createElement("div");Object.assign(_e.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:fe,paddingRight:fe,paddingTop:fe,zIndex:"1",background:b.menuBg}),Ne.appendChild(ke),Ne.appendChild(G),V&&(Lt=bi(d.ownerDocument,"Maps","lot",e=>Wt(e)),Ne.appendChild(Lt.el)),_e.appendChild(Ne),_e.appendChild(ce),d.appendChild(_e),d.appendChild(X);function ft(){ce.innerHTML="";const e=l.plotMode??"hardBin",t=!ct&&io.has(e),n=B.filter(y=>y!=null),o=n.find(y=>y.isLotStack),i=Ds(n.map(y=>({metadata:y.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0),s=e==="metadata",a=l.activeMetadataKey,f=t&&!s?vo(n,y=>(e==="softBin"?y.sbin:y.hbin)??void 0,pe):{counts:new Map,total:0,pass:0},r=t&&!s?l.binColors??xe():void 0,p=r?e==="softBin"?r.pass.soft:r.pass.hard:new Set,c=cs(f.counts.entries(),p).map(([y])=>y),u=t&&s&&a?vo(n,y=>Mi(y.metadata?.[a])):{counts:new Map,total:0,pass:0},h=s?Dn()?.values:void 0,g=t&&s?(h??[...u.counts.keys()].sort(Jt)).filter(y=>u.counts.has(y)):[];if(ke.innerHTML="",i&&ke.appendChild(i),ke.style.display=i?"flex":"none",!c.length&&!g.length){ce.style.display="none";return}ce.style.display="flex";const S=d.ownerDocument.createElement("div");Object.assign(S.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${k.sm} ${k.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),ce.appendChild(S);const v=Qt(l.highlightBin),L=B.flatMap(y=>y?.metadataFields??[]).find(y=>y.key===a),W=s?L?.label??(a?Ts(a):"Metadata"):Ii[e],F=d.ownerDocument.createElement("span");if(F.textContent=W,Object.assign(F.style,{fontSize:j.body,fontWeight:"700",letterSpacing:Ri,textTransform:"uppercase",color:b.label,flexShrink:"0"}),S.appendChild(F),!s&&f.total>0){const y=f.pass,K=y/f.total*100,de=d.ownerDocument.createElement("span");de.textContent=`Yield ${wt(K)}`,Object.assign(de.style,{fontSize:j.body,fontWeight:"700",color:b.value,whiteSpace:"nowrap",flexShrink:"0"});const ue=d.ownerDocument.createElement("span");ue.textContent=`${y.toLocaleString()} / ${f.total.toLocaleString()} dies`,Object.assign(ue.style,{fontSize:j.body,color:b.label,whiteSpace:"nowrap",flexShrink:"0"}),S.appendChild(de),S.appendChild(ue)}if(s){const y=Qt(l.highlightMetadataValue);g.forEach((K,de)=>{const ue=y.includes(K),Ee=L?.values?.find(Kt=>Kt.value===K),Ye=Ee?.color??Li(de),eo=u.counts.get(K)??0;So(S,{color:Ye,isActive:ue,label:Ee?.label??K,count:eo,percent:u.total>0?eo/u.total*100:void 0,onClick:Kt=>{const yi=yo(l.highlightMetadataValue,K,Kt);Sn(),I({highlightMetadataValue:yi})}})});return}const Ue=e==="softBin"?B.flatMap(y=>y?.sbinDefs??[]):B.flatMap(y=>y?.hbinDefs??[]),Zn=new Set,Nt=[];for(const y of Ue)Zn.has(y.bin)||(Zn.add(y.bin),Nt.push(y));const Gt=Nt.length>0?new Map(Nt.map(y=>[y.bin,y])):null,Qn=r??l.binColors??xe(),hi=e==="softBin"?Qn.soft:Qn.hard,Jn=y=>hi.get(y)??Ti;for(const y of c){const K=v.includes(y),de=Gt?.get(y),ue=f.counts.get(y)??0;So(S,{color:Jn(y),isActive:K,label:de?.name?`${y} \xB7 ${de.name}`:`Bin ${y}`,count:ue,percent:f.total>0?ue/f.total*100:void 0,onMenu:(Ee,Ye)=>Lo(e==="softBin"?"soft":"hard",y,Ee,Ye),onClick:Ee=>{const Ye=yo(l.highlightBin,y,Ee);Sn(),I({highlightBin:Ye})}})}f.total>0&&c.length>1&&ce.appendChild(Fs(d.ownerDocument,[...f.counts.entries()].sort(([,y],[,K])=>K-y).map(([y,K])=>({color:Jn(y),count:K,label:Gt?.get(y)?.name?`${y} \xB7 ${Gt.get(y).name}`:`Bin ${y}`})),f.total))}function qe(e){const t=M.filter(c=>c!==null);if(!t.length)return[];const n=t.map(c=>c.dies.filter(As)),o=t[0].wafer,i=t.length,s=Oi(t.map(c=>to(c)));if(!s)return[];const a=new Set(t.map(c=>ne(c,"renderWaferGallery")));if(a.size!==1)return[];const f=[...a][0],r=o.metadata?{...o,metadata:(({wafer:c,waferId:u,...h})=>h)(o.metadata)}:o;function p(c,u){return{...c,stats:{...c.stats,isLotStack:!0,aggregationMethod:u,lotSize:i}}}if(e==="stackedValues"){const c=We();let u=c?.filter(Zt);if(c!==void 0&&u?.length===0)return[];if(c?.length||(u=vi(t.flatMap(S=>S.dies)).map(S=>({testNumber:S,name:Ls(void 0,S)}))),!u?.length)return[];const h=l.aggregationMethod??"mean";return u.map(g=>{const S=us(n,h,g.testNumber),v={testNumber:0,name:g.name,unit:g.unit,...Rs(g)};return{wafer:r,dies:S,passBins:[...s],ringCount:f,testDefs:[v],label:`${Ws(g,g.testNumber)} \xB7 ${h}`,isLotStack:!0,aggrMethod:h,lotSize:i,statsSummary:p(ht({wafer:r,dies:S,passBins:[...s],ringCount:f,testDefs:[v]},{testNumbers:[0]}),h)}})}if(e==="stackedBins"){let c=mt(t.map(u=>u?.hbinDefs));return(!c||c.length===0)&&(c=[...new Set(t.flatMap(h=>h.dies.map(g=>g.hbin).filter(g=>g!=null)))].sort((h,g)=>h-g).map(h=>({bin:h,name:`Bin ${h}`}))),c.map(u=>{const h=uo(n,u.bin,"hard"),g=[{bin:u.bin,name:u.name}];return{wafer:r,dies:h,passBins:[...s],ringCount:f,hbinDefs:g,label:`${u.bin} \xB7 ${u.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:p(ht({wafer:r,dies:h,passBins:[...s],ringCount:f,hbinDefs:g}),"countBin")}})}if(e==="stackedSoftBins"){let c=mt(t.map(u=>u?.sbinDefs));return(!c||c.length===0)&&(c=[...new Set(t.flatMap(h=>h.dies.map(g=>g.sbin).filter(g=>g!=null)))].sort((h,g)=>h-g).map(h=>({bin:h,name:`Bin ${h}`}))),c.map(u=>{const h=uo(n,u.bin,"soft"),g=[{bin:u.bin,name:u.name}];return{wafer:r,dies:h,passBins:[...s],ringCount:f,sbinDefs:g,label:`${u.bin} \xB7 ${u.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:p(ht({wafer:r,dies:h,passBins:[...s],ringCount:f,sbinDefs:g}),"countBin")}})}return t}function Ht(e){const t=M.length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:l.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function I(e,{fireCallback:t=!0}={}){const n=Object.keys(e),o=l.plotMode,i=Le()!==null;l={...l,...e};const s=l.plotMode,a=Oe.has(s),f=o!==void 0&&Oe.has(o),r=Je>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const c=xe();l={...l,binColors:c},e={...e,binColors:c}}if("compact"in e){const c=En();l={...l,compactMap:c},e={...e,compactMap:c}}if(("compact"in e||l.compact&&("rotation"in e||"showXYIndicator"in e))&&Nn(),e.plotMode!==void 0)if(a){const c=Ht(s);if(l={...l,...c},r)for(const u of C)u&&u.setOptions(e);else te(qe(s))}else if(f){const{valueRange:c,lotSize:u,aggregationMethod:h,...g}=l;if(l=g,r)for(const S of C)S&&S.setOptions(e);else te(M.filter(S=>S!==null))}else for(const c of C)c&&c.setOptions(e);else if(e.aggregationMethod!==void 0&&s==="stackedValues")if(r)for(const c of C)c&&c.setOptions(e);else te(qe("stackedValues"));else for(const c of C)c&&c.setOptions(e);Le()!==null!==i&&on(),ft(),Rn(),Ln(),Mn();const p=e.plotMode!==void 0&&e.plotMode!==o;(ys.some(c=>c in e)||p)&&N(),ze(),$n(),An(),Bt(),Dt(),t&&m.onViewOptionsChange?.(po(l),n,hs(n))}function qn(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:k.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:j.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=bo(e,o,t,n);return{wrap:o,metaPanel:s}}function Xn(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||Bs(n??{}).length===0)return;const i=o.parentElement,s=d.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:k.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const a=bo(d.ownerDocument,s,t,n);a&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(a))}function jt(e,t,n){const o=d.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:_.container,boxShadow:qt.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:$t(),maxHeight:$t()});const i=d.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${k.md} ${k.lg} ${k.sm}`,borderBottom:`1px solid ${b.menuBorder}`,flexShrink:"0",gap:k.sm});const{wrap:s,metaPanel:a}=qn(document,gt(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"),Ut(f),f.innerHTML=_t.expand,Object.assign(f.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${b.menuBorder}`,borderRadius:_.control,background:b.panelBg,color:b.label,padding:k.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),Xt(f),i.appendChild(f),i.addEventListener("click",h=>{(h.ctrlKey||h.metaKey)&&(h.preventDefault(),h.stopPropagation(),$o(B.indexOf(e)))},!0),o.appendChild(i);const r=d.ownerDocument.createElement("div");Object.assign(r.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(r),zn(o,r),a&&r.appendChild(a),A.appendChild(o),o.addEventListener("contextmenu",h=>{if(h.defaultPrevented)return;h.preventDefault();const g=e.viewOptions?{...l,...e.viewOptions}:l,S=Ct()??bn(t),v=S?.source??ps(e.dies,{waferLabel:ye(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:g.plotMode==="value"?g.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:pe(e),ringCount:ne(e,"renderWaferGallery")}),L={x:h.clientX,y:h.clientY};import("./drilldown.js").then(({openDrilldownMenu:W})=>{o.isConnected&&W(L,o,v,S?{plots:R,...S.ctx}:{plots:R,onSaveImage:u.getSaveImageHook(),onSaveText:u.getSaveTextHook(),onLocateDie:F=>le(t,F)})})});const p=Qe||Le()!==null,c=e.viewOptions?{...l,...e.viewOptions}:l,u=fo(r,e,{viewOptions:{...c,showLegend:p,legendPosition:Te},showTooltip:!0,padding:H,statsSummary:e.statsSummary,onSaveImage:m.onSaveImage,onSaveText:m.onSaveText,downloadFilename:m.downloadFilename,onClick:e.onClick,onSelect:pn(e),drilldownSourceOverride:()=>To(t),insights:oe,onExpand:()=>Xe(t,e),showIdentity:!1,chromeInset:Ai,drawWhenVisible:!0});return u.setViewControlsVisible(!1),u.setSummaryVisible(!1),f.onclick=()=>Xe(t,e),{card:o,ctrl:u,canvasWrapper:r,expandBtn:f}}function ui(e){const t=we[e];if(!t)return;const n=[...U.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=_t.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>pi(n.id)):(t.innerHTML=_t.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>Xe(e,B[e]))}function te(e){mi(),Ae()?.remove(),Ie(null),He(),B=[],q.clear(),kt.clear(),Y.style.display="none";for(const r of C)r&&r.destroy();C=[],ie=[],we=[],Je=0,A.innerHTML="",Gn=e.length,It(e.map(r=>typeof r=="function"?null:r));const t=[];for(let r=0;r<e.length;r++){const p=e[r];if(typeof p=="function"){const c=d.ownerDocument.createElement("div");c.className="wmap-gallery-card",Object.assign(c.style,{background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:_.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const u=d.ownerDocument.createElement("span");u.textContent="\u2026",Object.assign(u.style,{color:b.label,fontSize:"18px"}),c.appendChild(u),A.appendChild(c),B.push(null),C.push(null),ie.push(null),we.push(null),t.push({index:r,factory:p,placeholder:c}),Je++}else{const{ctrl:c,canvasWrapper:u,expandBtn:h}=jt(p,r,e.length);B.push(p),C.push(c),ie.push(u),we.push(h)}}Tn(),ft(),Bt(),Dt(),On();const n=++Re,o=()=>{setTimeout(()=>{n===Re&&m.onItemsResolved?.()},0)},i=r=>{setTimeout(()=>{n===Re&&m.onItemResolved?.(r,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let a=0;function f(){if(n!==Re)return;if(a>=t.length){if(Oe.has(l.plotMode)){const L=l.plotMode;te(qe(L));return}Fe=o,N(),Ce||(Fe=null,o());return}const{index:r,factory:p,placeholder:c}=t[a++],u=p();B[r]=u,M[r]=u,It([u]);const{card:h,ctrl:g,canvasWrapper:S,expandBtn:v}=jt(u,r,e.length);C[r]=g,ie[r]=S,we[r]=v,Je--,c.replaceWith(h),i(++s),Xo(),qo(),!w&&!be?.placement&&u.statsSummary?.findings.length&&(w=en("right",fe,d.ownerDocument,xt),w.style.maxHeight="calc(100vh - 80px)",w.style.position="sticky",w.style.top="8px",w.style.flexDirection="column",w.style.display="none",(be?.placement??"right")==="left"?X.insertBefore(w,A):X.appendChild(w),N(),$||($=ae("findings","Summary panel",()=>{if(!w)return;const W=w.style.display!=="none";W||N(),w.style.display=W?"none":"flex",$e($,!W),ge()}),G.appendChild(Q()),G.appendChild($)),ge()),ge(),setTimeout(f,0)}t.length>0?setTimeout(f,0):o()}if(Oe.has(l.plotMode)&&M.length>0){const e=Ht(l.plotMode);l={...l,...e},te(qe(l.plotMode))}else te(D);ze();let Be=0;const Un=new(d.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Be)return;Be=(d.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Be=0,O==null&&Ft()})});Un.observe(A),w&&N();function fi(e,t){const n=ie[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:b.label,fontSize:j.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function Xe(e,t){for(const a of U.values())if(a.cardIndex===e)return;const n=gt(t,e),o=Mo++,i=C[e]?.getOptions(),s=Vi(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:j.family}),Gi(d,a.documentElement);const f=Ki(d,a.documentElement,()=>v.setOptions({})),r=a.createElement("div");r.dataset.wmapWindowBanner="1",r.textContent=n,Object.assign(r.style,{display:"none",padding:`${k.sm} ${k.xl}`,fontSize:j.body,fontWeight:"700",background:b.warnBg,color:b.warnText,borderBottom:`1px solid ${b.warnBorder}`,flexShrink:"0"}),a.body.appendChild(r);const p=a.createElement("div");Object.assign(p.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),a.body.appendChild(p);const{wrap:c,metaPanel:u}=qn(a,n,t.wafer.metadata??void 0),h=a.createElement("div");Object.assign(h.style,{display:"flex",alignItems:"center",padding:`${k.md} ${k.lg} ${k.sm}`,borderBottom:`1px solid ${b.menuBorder}`,flexShrink:"0",gap:k.sm}),h.appendChild(c),p.appendChild(h);const g=a.createElement("div");Object.assign(g.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),u&&g.appendChild(u),p.appendChild(g);let S=0;const v=Vt(g,t,void 0,i,(W,F)=>{const Ue=W?F:-S;try{s.resizeBy(Ue,0),S=W?F:0}catch{}}),L=setInterval(()=>{s.closed&&pt(o)},400);s.addEventListener("pagehide",()=>pt(o)),U.set(o,{id:o,ctrl:v,cardIndex:e,label:n,closePollId:L,stopThemeSync:f,close:()=>{s.closed||s.close()},setTitle:W=>{a.title=W,r.textContent=W,r.style.display="block"}})}else{const a=zi({title:n,onClose:()=>pt(o),anchor:d});a.contentWrap.style.flexDirection="column",Xn(a,n,t.wafer.metadata??void 0);const f=Vt(a.contentWrap,t,void 0,i,co(a));U.set(o,{id:o,ctrl:f,cardIndex:e,label:n,closePollId:null,close:()=>a.close(),setTitle:r=>{const p=a.box.querySelector("[data-wmap-window-title]");p&&(p.textContent=r,p.title=r)}})}C[e]?.destroy(),C[e]=null,fi(e,s!==null),ui(e)}function Vt(e,t,n,o,i){const s=t.viewOptions?{...l,...t.viewOptions}:l,a=o?{...s,...o}:s,r={...n!==void 0?{...a,plotMode:"value",activeTest:n}:a,showLegend:!0,legendPosition:Te},p=fo(e,t,{viewOptions:r,showTooltip:!0,padding:H,statsSummary:t.statsSummary,onSaveImage:m.onSaveImage,onSaveText:m.onSaveText,downloadFilename:m.downloadFilename,onClick:t.onClick,onSelect:pn(t),insights:oe,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return p.setViewControlsVisible(!0),p.setSummaryVisible(!0),p.setExpandVisible(!1),p}function pt(e){const t=U.get(e);if(!t||(U.delete(e),t.closePollId!=null&&clearInterval(t.closePollId),t.stopThemeSync?.(),t.ctrl.destroy(),t.cardIndex===null))return;const n=t.cardIndex,o=B[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:a,expandBtn:f}=jt(o,n,B.length);ie[n]?.parentElement?.replaceWith(i),C[n]=s,ie[n]=a,we[n]=f}function pi(e){const t=U.get(e);t&&(t.close(),pt(e))}function mi(){for(const e of U.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function zt(){for(const e of C)e?.drawPendingNow()}const Yn=d.ownerDocument.defaultView??window;Yn.addEventListener("beforeprint",zt);function gi(){zt();const e=[...A.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,r=Math.round(26*f),p=Math.round(12*f),c=d.ownerDocument.createElement("canvas");c.width=n*i+(n-1)*a,c.height=o*(s+r)+(o-1)*a;const u=c.getContext("2d"),h=Wi(A);u.fillStyle=h.background,u.fillRect(0,0,c.width,c.height),e.forEach((g,S)=>{const v=S%n,L=Math.floor(S/n),W=v*(i+a),F=L*(s+r+a),Ue=g.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";u.fillStyle=h.surface,u.fillRect(W,F,i,r),u.fillStyle=h.text,u.font=`700 ${p}px system-ui, sans-serif`,u.textAlign="left",u.textBaseline="middle",u.fillText(Ue,W+Math.round(10*f),F+r/2,i-Math.round(20*f)),u.drawImage(g,W,F+r)}),c.toBlob(g=>{if(!g)return;const S=C.find(v=>v!=null)?.getExportTitle();Zi(g,["gallery",S].filter(Boolean).join(" "),P.onSaveImage)})}return{setItems(e){M=e.map(n=>typeof n=="function"?null:n);const t=l.plotMode;if(Oe.has(t))if(e.some(o=>typeof o=="function"))te(e);else{const o=Ht(t);l={...l,...o},te(qe(t))}else te(e)},setOptions(e){I(e,{fireCallback:!1})},getOptions(){return po(l)},setFindingsNotice(e){cn=e,N()},setColumns(e){Kn(e)},getBinColors(){return l.binColors??xe()},setLotStatsSummary(e){z=e,ze(),w&&N(),ge()},openUserGuide:Pn,destroy(){R.flush(),Re++,Yn.removeEventListener("beforeprint",zt),Ce?.cancel(),Ce=null,Fe=null;for(const e of[...U.values()])e.closePollId!=null&&clearInterval(e.closePollId),e.close(),e.ctrl.destroy();U.clear();for(const e of C)e&&e.destroy();C=[],Ae()?.remove(),Un.disconnect(),Be&&((d.ownerDocument.defaultView??window).cancelAnimationFrame(Be),Be=0),d.ownerDocument.removeEventListener("click",et,!0),window.removeEventListener("blur",rn),Co(),so(),_e.remove(),X.remove(),w?.remove(),De?.destroy()}}}
1
+ import{createViewSwitch as Ei}from"./viewSwitch.js";import{createSummaryToggle as Ti}from"./summaryToggle.js";import{getUniqueTestNumbers as Oi,resolveTestNumber as Li,findTestDef as Wi,collectMetadataValues as Ri}from"../renderer/buildView.js";import{metadataCategoricalValue as $i}from"../core/metadata.js";import{resolveBinColorsForMaps as Ai,mergeBinDefs as mt,binColorWarning as Pi,mixedPassBinsWarning as Ii,binColorsEqual as Fi}from"../renderer/binColors.js";import{commonPassBins as uo,itemPassBins as Yt}from"../core/passBins.js";import{requireRingCount as te}from"../core/ringCount.js";import{NO_DATA_FILL as Hi}from"../renderer/colorMap.js";import{metadataValueColor as ji}from"../renderer/colorMap.js";import{resolveCanvasTheme as Vi}from"./canvasTheme.js";import{ICONS as Zt}from"./icons.js";import{defaultPlotMode as zi,SHADOW as Qt,LEADING as fo,TRACKING as Gi,controlStyle as Ki,wireControlHover as Jt,SPACE as k,EDGE_GUTTER as de,MAP_CHROME_INSET as Ni,RADIUS as K,FONT as j,CLR as b,sevColor as po,MODE_LABELS as _i,BIN_LEGEND_MODES as go,STACKED_MODES as he,applyOverlayZ as qi,getTooltip as Xi,hideTooltip as mo,createToolbarHelpers as Ui,buildModeMenuEl as Yi,openDetachWindow as Zi,openFloatingWindow as Qi,openModal as Ji,copyWmapThemeTokens as es,syncWmapPopupTheme as ts,makePaletteBtn as ns,makeLogScaleBtn as os,makeLegendStyleBtn as is,makeOverlaysBtn as ss,makeOrientationBtn as as,menuLayerFor as ho,saveImageBlob as ls,markMenuTrigger as Ze,wireMenuA11y as yo,wireTooltip as en,requestedPassFailDisplay as bo,overlayMenuRows as rs,anyOverlayActive as cs,openCompactDiagnostics as ds,roomForPanel as wo,logWmapVersionOnce as us,buildDataModeEntries as fs,metadataKeyHasData as ps,metadataModeEntry as gs}from"./toolbar.js";import{openReportModal as ms,openUserGuideWindow as hs}from"./guideWindow.js";import{waferDisplayLabel as ht,waferIdentityLabel as ye}from"../core/waferLabel.js";import{metadataDisplayValue as ys}from"../core/metadata.js";import{withExportContext as bs}from"./exportName.js";import{sortBinsForDisplay as ws}from"../stats/binPareto.js";import{diePassStatus as vs}from"../core/dies.js";import{aggregateValues as Ss,aggregateBinCounts as vo}from"../core/aggregates.js";import{renderWaferMap as Cs,renderWaferMapCard as So,toPublicViewOptions as Co}from"./renderWaferMap.js";import{waferPopulation as xs,selectionPopulation as Ms,LOT_STACK_REASON as tn}from"./chartPopulation.js";import{sourceFromBins as xo}from"./plotItems.js";import{plotStoreFor as ks}from"./plotStore.js";import{classifyChanged as Ds,COLOR_KEYS as Bs,findingBin as Es,findingPlotMode as Ts}from"./renderWaferMap.js";import{findingPatternKey as Mo}from"../stats/filterFindings.js";import{buildWaferMap as Os,getTestPassStatus as ko,isParametricTest as nn,getDieTestValue as Ls}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as yt}from"../stats/analyzeWaferMap.js";import{collectWarnings as Ws,buildWarningsMenuEl as Rs,severityOf as $s}from"./warnings.js";import{asList as on,compareNatural as sn,arrayEqual as bt,toggleHighlight as Do}from"../core/utils.js";import{buildCompactMap as As,compactLayoutOffered as Ps}from"../core/compact.js";import{attachExpandableMetadata as Bo}from"./identityHeader.js";import{createSummaryPanelEl as an,buildMetadataStripRow as Is,metadataEntries as Fs,renderLotSummaryContentSteps as Hs,reportMapsFromItems as js}from"./summaryPanel.js";import{prettyKey as Vs}from"../stats/facets.js";import{testLabel as zs,markedTestLabel as Gs,derivedFields as Ks}from"../renderer/testLabel.js";import{mergeTestDefs as Ns}from"../stats/mergeTestDefs.js";import{getDieKey as wt,hasPosition as _s}from"../core/dies.js";import{testValue as qs}from"../core/dieTable.js";import{runChunked as Xs}from"./chunked.js";function Eo(u){if(typeof u!="number"||!Number.isFinite(u))return;const x=Math.round(u);return x>=1?x:void 0}const ln=12;function Us(u,x,p){let H=x;if(x.length>ln){const M=x.slice(0,ln-1),E=x.slice(ln-1),V=E.reduce((R,ne)=>R+ne.count,0);H=[...M,{color:b.label,count:V,label:`Other (${E.length} bins)`}]}const T=u.createElement("div");Object.assign(T.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:K.control,overflow:"hidden",border:`1px solid ${b.menuBorder}`,boxSizing:"border-box",marginTop:k.xs,flexShrink:"0"}),T.setAttribute("role","img"),T.setAttribute("aria-label",`Population split: ${H.map(M=>`${M.label} ${vt(M.count/p*100)}`).join(", ")}`);for(const M of H){const E=M.count/p*100,V=u.createElement("div");Object.assign(V.style,{flex:`${E} 1 0`,minWidth:E>0?"2px":"0",background:M.color}),en(V,`${M.label} \xB7 ${M.count.toLocaleString()} dies \xB7 ${vt(E)}`),T.appendChild(V)}return T}function vt(u){return u>0&&u<.1?"<0.1%":`${u.toFixed(1)}%`}function To(u,x,p){const H=new Map;let T=0,M=0;for(const E of u){const V=p?new Set(p(E)):void 0;for(const R of E.dies){if(R.partial||R.edgeExcluded)continue;const ne=x(R);ne!==void 0&&(H.set(ne,(H.get(ne)??0)+1),T++,V&&vs(R,V)&&M++)}}return{counts:H,total:T,pass:M}}function Oo(u,x){const p=u.ownerDocument.createElement("div");Object.assign(p.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${k.xxs} ${k.xs}`,borderRadius:K.control});const H=u.ownerDocument.createElement("span");Object.assign(H.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:x.color,border:x.isActive?`2px solid ${b.iconActive}`:`1px solid ${b.menuBorder}`,borderRadius:K.control,boxSizing:"border-box"});const T=u.ownerDocument.createElement("span");if(T.textContent=x.label,Object.assign(T.style,{fontWeight:x.isActive?"700":"400",color:x.isActive?b.iconActive:b.text,whiteSpace:"nowrap"}),p.appendChild(H),p.appendChild(T),x.count!==void 0){const M=u.ownerDocument.createElement("span");if(M.textContent=x.count.toLocaleString(),Object.assign(M.style,{color:x.isActive?b.iconActive:b.text,fontWeight:x.isActive?"700":"400",whiteSpace:"nowrap"}),p.appendChild(M),x.percent!==void 0){const E=u.ownerDocument.createElement("span");E.textContent=vt(x.percent),Object.assign(E.style,{color:b.label,whiteSpace:"nowrap"}),p.appendChild(E)}}if(p.setAttribute("role","button"),p.setAttribute("aria-pressed",x.isActive?"true":"false"),p.tabIndex=0,p.addEventListener("mouseenter",()=>{p.style.background=b.bgHover}),p.addEventListener("mouseleave",()=>{p.style.background="transparent"}),p.addEventListener("focus",()=>{p.style.background=b.bgHover}),p.addEventListener("blur",()=>{p.style.background="transparent"}),p.addEventListener("click",M=>x.onClick(M.ctrlKey||M.metaKey)),p.addEventListener("keydown",M=>{if(M.key==="Enter"||M.key===" ")M.preventDefault(),x.onClick(M.ctrlKey||M.metaKey);else if(x.onMenu&&(M.key==="ContextMenu"||M.key==="F10"&&M.shiftKey)){M.preventDefault();const E=p.getBoundingClientRect();x.onMenu({x:E.left+E.width/2,y:E.bottom},p)}}),x.onMenu){const M=x.onMenu;p.addEventListener("contextmenu",E=>{E.preventDefault(),M({x:E.clientX,y:E.clientY},p)}),en(p,"Right-click: charts and tables for these dies")}u.appendChild(p)}export function renderWaferGallery(u,x,p={}){us();const H=6;let T=Eo(p.columns);const M=p.showHelpButton??!1,E=p.userGuideExtension,V=p.insights?.enabled??!0,R=ks(p.insights),ne={enabled:!1,plotStore:R},Lo=qi(p.zIndex),be=p.summaryPanel,ue=e=>[...Yt(e)],rn=()=>B.flatMap(e=>e?[te(e,"renderWaferGallery")]:[]),St=()=>rn()[0];function Wo(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 N=p.lotStatsSummary,Re=p.viewOptions?.legendPosition??"default",Qe=p.perCardLegend??!1;function $e(){const e=l.plotMode??"hardBin";return go.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 cn(){const e=Qe||$e()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let l={plotMode:zi(x.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...p.viewOptions},C=[],oe=[],we=[],D=[];const A=bs(()=>{const e=D.filter(n=>n!=null),t=[...new Set(e.map(n=>ys(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(sn);return{prefix:p.downloadFilename,lots:t,...e.length===1?{wafer:ye(e[0])}:{waferCount:e.length}}},p.onSaveImage,p.onSaveText);let B=x.map(e=>typeof e=="function"?null:e);function ve(){return Ns(B)}function Ae(){if(B.some(e=>e?.testDefs?.length))return ve().defs}let Pe=0,Je=0;const q=new Map;let Ro=0,et=null,Z=null,ie=null,Se=null;function dn(){Z===null&&ie===null&&(Se={plotMode:l.plotMode,activeTest:l.activeTest})}function un(){Se&&W({...Se},{fireCallback:!1}),Se=null}let fn=new Set,v=null,$o={};function pn(e){return B[e]?.statsSummary??N?.perWafer.find(t=>t.waferIndex===e)?.summary}function gn(){return!!(B.some(e=>e?.statsSummary?.findings.length)||N?.perWafer.some(e=>e.summary.findings.length))}const Ao=Xi(),Ce=Ui(Ao),{makeBtn:xe,setActive:mn,makeSep:fe,syncSeparators:Ct,syncToolbarVisible:xt,makeMenuRow:Po,makeMenuSection:Io,makeDropdown:hn,closeOpenMenu:tt,getOpenMenu:Ie,setOpenMenu:Fe}=Ce;u.ownerDocument.addEventListener("click",tt,!0);const yn=()=>mo();window.addEventListener("blur",yn);let bn=p.findingsNotice;function wn(e){fn=new Set(e);const t=[...$.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=fn.has(i);o.style.outline=s?`3px solid ${b.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function Mt(){wn([])}let nt=!1;function kt(){nt=!0;for(const e of C)e&&e.clearSelection();nt=!1}function vn(e){return t=>{!nt&&(Z!==null||ie!==null)&&(Se=null,ke(),z()),Et.set(e,t.length),Q&&!He&&!nt&&Fo(e,t),e.onSelect?.(t)}}function se(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),$.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let Q=!1,He=!1,pe=new Set;function Fo(e,t){He=!0;try{pe=new Set(t.map(n=>wt(n))),D.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>pe.has(wt(s))))})}finally{He=!1}rt()}function Sn(){pe=new Set,He=!0;try{for(const e of C)e?.clearSelection()}finally{He=!1}rt()}function Dt(){if(!Q||pe.size===0)return;const e=[];let t=!1;if(D.forEach((i,s)=>{if(!i)return;const a=i.dies.filter(d=>pe.has(wt(d)));a.length!==0&&(i.isLotStack&&(t=!0),e.push({label:ye(i)??i.label??`Wafer ${s+1}`,dies:a,waferIndex:s,wafer:i.wafer,passBins:ue(i),ringCount:te(i,"renderWaferGallery")}))}),e.length===0)return;const n=ve(),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?tn:void 0},ctx:{plots:R,attributes:p.attributes,onSaveImage:A.onSaveImage,onSaveText:A.onSaveText,onLocateDie:(i,s)=>se(s,i)}}}function Cn(){const e=[];let t=!1;if(D.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:ye(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:ue(o),ringCount:te(o,"renderWaferGallery")}))}),e.length<2)return;const n=l;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:ve().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?tn:void 0},ctx:{plots:R,attributes:p.attributes,onSaveImage:A.onSaveImage,onSaveText:A.onSaveText,onLocateDie:(o,i)=>se(i,o)}}}function Ho(e){const t=Dt()??kn(e);if(t)return t;const n=Cn(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function Bt(e,t,n){Z!==e&&t.click();const o=v;if(!o)return;const i=N?.findings.find(a=>a.id===e),s=Dt()??Cn()??Vo()??(i?xn(Dn(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:a})=>{o.isConnected&&a(n,o,s.source,{plots:R,attributes:p.attributes,...s.ctx})})}function jo(e,t,n,o){const i=on(l.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],a=[];let d=!1;D.forEach((m,S)=>{m&&(m.isLotStack&&(d=!0),a.push({label:ye(m)??m.label??`Wafer ${S+1}`,dies:m.dies,waferIndex:S,wafer:m.wafer,passBins:ue(m),ringCount:te(m,"renderWaferGallery")}))});const r=ve().defs,g=xo(a,e,s,r,void 0,d);if(!g)return;const c={plots:R,attributes:p.attributes,onSaveImage:A.onSaveImage,onSaveText:A.onSaveText,onLocateDie:(m,S)=>se(S,m)},f=s.length>1?xo(a,e,[t],r,void 0,d):null,h=f?{...c,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:f,ctx:c}}:c;import("./drilldown.js").then(({openDrilldownMenu:m})=>{o.isConnected&&m(n,o,g,h)})}function xn(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((a,d)=>a-d)){const a=D[s];a&&(a.isLotStack&&(o=!0),n.push({label:ye(a)??a.label??`Wafer ${s+1}`,dies:a.dies,waferIndex:s,wafer:a.wafer,passBins:ue(a),ringCount:te(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:ve().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?tn:void 0},ctx:{plots:R,attributes:p.attributes,onSaveImage:A.onSaveImage,onSaveText:A.onSaveText,onLocateDie:(s,a)=>se(a,s)}}}function Vo(){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:D[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=l;return{source:Ms(n,{waferLabel:ye(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:ue(t),ringCount:te(t,"renderWaferGallery")}),ctx:{onSaveImage:A.onSaveImage,onSaveText:A.onSaveText,onLocateDie:(i,s)=>se(s??e,i)}}}function zo(e){e||Sn(),Q=e,rt()}function ot(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=D[i],a=C[i];if(!s||!a)continue;const d=s.dies.filter(r=>n.has(wt(r)));a.setSelection(d)}}const _=new Set,Et=new Map;function Mn(){[...$.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=_.has(o)?`2px solid ${b.iconActive}`:"",n.style.outlineOffset=_.has(o)?"-2px":""});const t=_.size;X.style.display=t>0?"":"none",X.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,X.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function Go(e){e<0||(_.has(e)?_.delete(e):_.add(e),Mn())}function Ko(){_.clear(),Mn()}function kn(e){if(!(_.size===0||!_.has(e))){for(const t of Et.values())if(t>0)return;return xn([..._],"picked ")}}function No(){const e=[];for(let t=0;t<B.length;t++){const n=B[t];if(!n)continue;const o=pn(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 _o(e){const t=D[e]??B[e];t&&Xe(e,t)}function qo(e){const t=pn(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 Xo(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{ms(e(js(B,St())),{anchor:u})})}function Uo(){if(!v)return;v.innerHTML="";const e=No();if(B.length>0){const n=u.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:j.body,color:b.label,marginBottom:k.md}),v.appendChild(n)}if(e.length>0){const n=u.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{...Ki("outlined"),marginBottom:k.lg,display:"block",width:"100%",textAlign:"left"}),Jt(n),n.addEventListener("click",Xo),v.appendChild(n)}if(e.length===0){const n=u.ownerDocument.createElement("div");Object.assign(n.style,{color:b.icon,fontSize:j.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",v.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:a}of e){const d=i?"unusual":s?"notable":"info",r=i+s||a,g=u.ownerDocument.createElement("button");g.type="button",Object.assign(g.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:k.xs,border:"none",borderLeft:`3px solid ${po(d)}`,borderRadius:K.control,background:b.bgHover,cursor:"pointer",fontSize:j.body,textAlign:"left",boxSizing:"border-box"}),g.addEventListener("mouseover",()=>{g.style.background=b.bgActive}),g.addEventListener("mouseout",()=>{g.style.background=b.bgHover});const c=u.ownerDocument.createElement("span");c.textContent=ht(o,n),Object.assign(c.style,{color:b.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const f=u.ownerDocument.createElement("span");f.textContent=String(r),g.setAttribute("aria-label",`${ht(o,n)} \u2014 ${r} finding${r===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(f.style,{marginLeft:k.sm,flexShrink:"0",background:po(d),color:"#fff",borderRadius:K.container,padding:"1px 5px",fontSize:j.body,fontWeight:"600"}),g.appendChild(c),g.appendChild(f),g.addEventListener("click",()=>Xe(n,o)),v.appendChild(g)}const t=u.ownerDocument.createElement("div");t.style.height="12px",v.appendChild(t)}let Me=null,je=null;function z(){if(v)if(Me?.cancel(),Me=null,N){const e=mt(B.map(n=>n?.hbinDefs)),t=mt(B.map(n=>n?.sbinDefs));Me=Xs(Hs(v,{lotSummary:N,items:B,hbinDefs:e.length?e:void 0,sbinDefs:t.length?t:void 0,testDefs:Ae(),ringCount:St(),binColors:l.binColors,plotMode:l.plotMode??"hardBin",fallbackFormat:l.fallbackFormat,activeFindingId:Z,warnings:p.warnings?.display??!0?ae:[],findingsFilter:$o,findingsNotice:bn,onFindingsFilterChange:z,onSaveText:A.onSaveText,onFindingClick:(n,o)=>{Z===n.id?(ke(),un()):(dn(),Zo(n,o)),z()},activeTest:ie,onTestClick:n=>{const o=ie===n;o||dn(),ke(),o?un():Yo(n),z()},onWaferClick:_o,findingsFor:qo,dieListOptions:p.dieList,onLocateDie:(n,o)=>se(o,n),onClose:()=>On(!1)}),{onDone:()=>{const n=je;je=null,n?.()}})}else Uo()}function Dn(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let it=[];function Bn(){if(it.length!==0){for(const e of it)C[e]?.setOptions({plotMode:l.plotMode,activeTest:l.activeTest});it=[]}}function ke(){Z=null,ie=null,Mt(),kt(),Bn(),W({highlightBin:void 0},{fireCallback:!1})}function En(){Z===null&&ie===null||(Se=null,ke(),z())}function Tn(e,t){const n=Ae();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=he.has(l.plotMode??"hardBin")?null:t;if(s){for(const a of s)C[a]?.setOptions({plotMode:"value",activeTest:e});it=[...s]}}}function Yo(e){ie=e;const t=o=>D[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=D.map((o,i)=>i).filter(o=>t(o)?.length);if(Tn(e,n.length?n:null),Mt(),kt(),!he.has(l.plotMode??"hardBin"))for(const o of n)ot(t(o),[o])}function Zo(e,t){if(Z===e.id){ke();return}Z=e.id,ie=null,t.style.background=b.bgActive,t.style.fontWeight="600",Bn();const{kind:n,index:o}=e.variable;if(n==="test")Tn(o??0,Dn(e));else{const s=D.some(d=>d?.dies?.some(r=>r.hbin!=null)),a=uo(D.map(d=>d?Yt(d):void 0));W({plotMode:Ts(e,l.plotMode,s),highlightBin:Es(e,a,s)},{fireCallback:!1})}Mt(),kt();const i=e.highlight;if(i.kind==="wafer"){wn(i.waferIndices);const s=Mo(e);for(const a of i.waferIndices){const d=i.dieKeysByWafer?void 0:D[a]?.statsSummary?.findings.find(g=>Mo(g)===s),r=i.dieKeysByWafer?.[a]??d?.highlight?.dieKeys;r?.length&&ot(r,[a])}}else i.kind==="bin"?i.dieKeys?.length&&ot(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&ot(i.dieKeys)}function Tt(){return!!v&&v.style.display!=="none"}function On(e){!v||e===Tt()||(e&&z(),v.style.display=e?"flex":"none",ge())}function ge(){et&&(Ct(P),xt(P,"inline-flex"),et.sync({visible:!!(N||gn())&&!!v&&!dt,open:Tt(),notable:!!(N?.hasNotableFindings||B.some(e=>e?.statsSummary?.hasNotableFindings))}))}const P=u.ownerDocument.createElement("div");P.dataset.wmapToolbar="gallery",Object.assign(P.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:K.control,padding:"0",boxShadow:Qt.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const Ln=()=>{const e=Ie();e&&(e.remove(),Fe(null)),Ze(J,!1)},J=xe("mode","Plot mode",()=>{if(Ie()){Ln();return}const e=B.flatMap(w=>w?.dies??[]),t=Ae(),{testEntries:n,binEntries:o,stackedEntries:i}=fs(e,t,{includeStacked:!0}),s=B.filter(Boolean).length,a=w=>{if(w===void 0)return s;let L=0;for(const I of B)I?.dies?.some(F=>ko(F,w)!==void 0||qs(F,w)!==void 0)&&L++;return L},d=s<2?n:n.map(w=>{const L=a(w.activeTest);return L===s?w:{...w,label:`${w.label} \u2014 ${L} of ${s} wafers`}}),r=l.plotMode??"hardBin",g=l.activeTest??0;function c(w){return w.plotMode!==r?!1:w.plotMode==="value"?g===(w.activeTest??0):w.plotMode==="metadata"?l.activeMetadataKey===w.activeMetadataKey:!0}function f(w,L){w.activeTest!==void 0?W({plotMode:"value",activeTest:w.activeTest,activeMetadataKey:void 0,logScale:w.logScale}):w.activeMetadataKey!==void 0?W({plotMode:w.plotMode,activeTest:void 0,activeMetadataKey:w.activeMetadataKey,passFailDisplay:"off"}):W({plotMode:w.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),L.remove(),Fe(null),Ze(J,!1)}const h=new Set,m=B.flatMap(w=>w?.metadataFields??[]).filter(w=>!h.has(w.key)&&h.add(w.key)).filter(w=>ps(e,w.key)).map(gs),S=Yi(J.getBoundingClientRect(),d,o,i,c,f,{makeMenuRow:Po,makeMenuSection:Io},r,J.ownerDocument.defaultView??window,m);ho(J).appendChild(S),Fe(S),Ze(J,!0),yo(S,J,Ln)});Ze(J,!1);const Qo=()=>D.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:Jo,sync:Wn}=ns(Ce,()=>({...l,plotMode:l.plotMode??"hardBin"}),Qo,e=>W(e));Wn();const ei=x.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function st(){const e=Ae(),{testNumber:t}=Li(l.activeTest??0,e);return{testNumber:t,td:Wi(e,t)}}function Rn(){if((l.plotMode??"hardBin")!=="value")return!1;const{td:e}=st();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function Ve(){if((l.plotMode??"hardBin")!=="value")return!1;const{td:e}=st();return e!==void 0&&!nn(e)}function ti(){if((l.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=st();return B.some(n=>n?.dies?.some(o=>ko(o,e,t)!==void 0))}function ni(e,t){if(!t||!nn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((bo(l)==="spec"&&n?"spec":l.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,a=-1/0;for(const d of B)if(d)for(const r of d.dies){const g=Ls(r,e);g!==void 0&&(g<s&&(s=g),g>a&&(a=g))}if(isFinite(s))return s===a?[s,s+1]:[s,a]}function at(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 $n(){if((l.plotMode??"hardBin")!=="metadata")return;const e=l.activeMetadataKey;if(!e)return;const t=new Set;for(const n of B)if(n)for(const o of Ri(n.dies,e))t.add(o);return{key:e,values:[...t].sort(sn)}}function Ot(){at("metadataValueOrder",$n(),(e,t)=>e.key===t.key&&bt(e.values,t.values))}function Lt(){if((l.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=st(),n=ni(e,t);at("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const a=g=>Array.isArray(g)?{test:void 0,range:g}:{test:g.test,range:g.range},d=a(i),r=a(s);return d.test===r.test&&bt(d.range,r.range)})}let Wt=!1;function oi(){if(Wt)return;Wt=!0,(u.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{Wt=!1,Lt(),Ot(),Fn(),In()})}let Rt=!1;function ii(){if(Rt)return;Rt=!0,(u.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{Rt=!1,pt()})}let An=[];function De(){const{colors:e,mixedHardBins:t}=Ai(B.filter(n=>n!=null),{binColorScheme:l.binColorScheme,useDefinedBinColors:l.useDefinedBinColors});return An=t,e}function $t(){return D.filter(e=>e!=null).flatMap(e=>e.dies)}function Pn(){return l.compact?As($t()):void 0}const si=(e,t)=>bt(e.columns,t.columns)&&bt(e.rows,t.rows);function In(){at("compactMap",Pn(),si)&&Zn()}function ai(){return Ps($t(),D.filter(e=>e!=null).map(e=>e.reticleConfig))}function Fn(){at("binColors",De(),Fi),Ge()}const li=ss(Ce,()=>rs(l,ei,{functionalActive:Ve(),hasLimits:Rn()&&!Ve(),hasRecorded:ti()&&!Ve(),binMode:(l.plotMode??"hardBin")==="hardBin"||(l.plotMode??"hardBin")==="softBin"},e=>W(e),{on:!!l.compact,offered:ai(),onChange:e=>W({compact:e}),onDiagnostics:()=>ds($t(),D.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:u,onSaveText:A.onSaveText})}),()=>cs(l)),{btn:ri,sync:Hn}=is(Ce,()=>({plotMode:l.plotMode,legendPosition:Re}),e=>{Re=e;for(const t of C)t&&t.setOptions({legendPosition:Re})},{get:()=>Qe,set:e=>{Qe=e,cn()},blockedReason:$e});Hn();const ci=[{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"}],jn=hn("aggr","Aggregation method",()=>ci,()=>l.aggregationMethod??"mean",e=>W({aggregationMethod:e}));function Vn(){const e=l.plotMode==="stackedValues";jn.style.display=e?"":"none"}Vn();const{btn:di,sync:zn}=os(Ce,()=>({...l,functionalActive:Ve()}),e=>W(e));zn();const lt=xe("specRange","Colorbar range: test limits",()=>{const e=l.colorbarRangeMode==="data"?"spec":"data";W({colorbarRangeMode:e})});function Gn(){const e=(l.plotMode??"hardBin")==="value"&&Rn()&&bo(l)==="off"&&!Ve();lt.style.display=e?"":"none";const t=(l.colorbarRangeMode??"spec")==="spec";mn(lt,t),lt.ariaLabel=t?"Colorbar range: test limits (click for data range)":"Colorbar range: data range (click for test limits)"}Gn();const ui=as(Ce,()=>l,e=>W(e)),fi=xe("downloadAll","Download gallery PNG",ki),Be=xe("boxSelect","Select the same dies on every wafer",()=>{Q&&pe.size>0?Sn():zo(!Q)});Be.style.position="relative";const ze=u.ownerDocument.createElement("span");ze.dataset.wmapSelectAcrossCount="1",Object.assign(ze.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:K.pill,background:b.iconActive,color:b.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Be.appendChild(ze);function rt(){mn(Be,Q);const e=Q?pe.size:0;ze.style.display=e>0?"block":"none",ze.textContent=e>99?"99+":String(e),Be.ariaLabel=Q?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)",Be.setAttribute("aria-pressed",String(Q))}const X=u.ownerDocument.createElement("button");X.type="button",X.dataset.wmapPickedWafers="1",Object.assign(X.style,{display:"none",border:"none",background:b.bgActive,color:b.iconActive,borderRadius:K.control,padding:`${k.xs} ${k.md}`,fontSize:j.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),Jt(X,"bare"),X.addEventListener("click",Ko);const pi=hn("columns","Columns",()=>[{value:"auto",label:"Auto"},{value:"1",label:"1 column"},{value:"2",label:"2 columns"},{value:"3",label:"3 columns"},{value:"4",label:"4 columns"},{value:"5",label:"5 columns"}],()=>T!=null?String(T):"auto",e=>eo(e==="auto"?void 0:Number(e))),O=u.ownerDocument.createElement("div");Object.assign(O.style,{display:"inline-flex",alignItems:"center",gap:"0"}),P.appendChild(O),O.appendChild(J),O.appendChild(Jo),O.appendChild(jn),O.appendChild(di),O.appendChild(lt),O.appendChild(fe()),O.appendChild(li),O.appendChild(fe()),O.appendChild(ri),O.appendChild(fe()),O.appendChild(ui),O.appendChild(fe()),O.appendChild(pi),O.appendChild(fe()),O.appendChild(Be),O.appendChild(X),O.appendChild(fi),rt();let U=null,ct=null,ae=[],Kn=!1;function Ge(){const e=Ws({lotStatsSummary:N,result:{warnings:[...B.flatMap(n=>n?.warnings??[]),...ve().warnings]},extra:[l.binColors&&Pi(l.binColors,l.plotMode),Ii(An),Wo(rn())].filter(n=>!!n)}),t=e.length!==ae.length||e.some((n,o)=>n.code!==ae[o]?.code||n.message!==ae[o]?.message);ae=e,(t||!Kn)&&(Kn=!0,p.warnings?.onWarning?.(e)),gi()}function gi(){if(!U||!ct)return;const e=ae.length,t=e>0;if(U.style.display=t?"flex":"none",ct.style.display=t?"":"none",Ct(P),xt(P,"inline-flex"),!t)return;const n=$s(ae[0]),o=`${e} data ${e===1?"warning":"warnings"}`;U.style.color=n==="error"?b.errText:b.warnText,U.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(p.warnings?.display??!0)&&(ct=fe(),U=xe("warning","Data warnings",()=>{const e=Ie();if(tt(new MouseEvent("click")),e)return;const t=Rs(U.getBoundingClientRect(),ae,U.ownerDocument.defaultView??window);ho(u).appendChild(t),Fe(t),yo(t,U,()=>tt(new MouseEvent("click")))}),Ze(U,!1),P.appendChild(ct),P.appendChild(U)),Ge();function Nn(){import("./userGuideHtml.js").then(e=>hs({buildWaferMap:Os,renderWaferMap:Cs,renderWaferGallery,analyzeWaferMap:yt},e.USER_GUIDE_HTML,E,u))}M&&(P.appendChild(fe()),P.appendChild(xe("help","User guide",()=>Nn())));const Ee=u.ownerDocument.createElement("div");Ee.dataset.wmapGalleryMeta="1",Object.assign(Ee.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${k.sm} ${k.lg}`,fontSize:j.sub,lineHeight:fo.none,boxSizing:"border-box"});const Te=u.ownerDocument.createElement("div");Object.assign(Te.style,{background:b.canvasBg,display:"flex",alignItems:"stretch",gap:k.lg,paddingBottom:k.lg,minWidth:"0"});const le=u.ownerDocument.createElement("div");le.dataset.wmapGalleryLegend="1",Object.assign(le.style,{display:"flex",flexDirection:"column",gap:k.sm,background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:K.container,padding:`${k.sm} ${k.lg}`,marginBottom:k.lg,boxShadow:Qt.panel,fontSize:j.body,lineHeight:fo.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const Y=u.ownerDocument.createElement("div");Object.assign(Y.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let Oe=null,Ke=null,_n=null;function mi(){return V?Oe?Promise.resolve(Oe):(_n??=import("./insightsTab.js").then(({createInsightsTab:e})=>(Oe=e({attributes:p.attributes,getItems:()=>B,getLotStats:()=>N,getBinColors:()=>l.binColors??De(),getRingCount:()=>te({ringCount:St()},"the Insights tab"),defaultView:p.insights?.defaultView,plotStore:R,onPickPlotsFile:p.insights?.onPickPlotsFile,onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:A.onSaveImage,onSaveText:A.onSaveText,ownerDocument:u.ownerDocument,locateDie:(t,n)=>{Pt(!1),se(n,t)},openWafer:(t,n,o)=>{const i=B[t];if(!i)return;let s=null;const a=Ji({title:n,onClose:()=>s?.destroy(),anchor:u});oo(a,n,i.wafer.metadata??void 0),s=Nt(a.contentWrap,i,o,void 0,wo(a))}}),Ke=Oe.el,Ke.style.display="none",u.appendChild(Ke),Oe)),_n):Promise.resolve(null)}let dt=!1,At=null;function Pt(e){V&&(dt=e,At?.setInsightsOpen(e),Ke&&(Ke.style.display=e?"flex":"none"),Y.style.display=e?"none":"flex",O.style.display=e?"none":"inline-flex",Ct(P),xt(P,"inline-flex"),P.style.display="inline-flex",ge(),pt(),e&&mi().then(t=>{!t||!dt||(t.el.style.display="flex",t.render())}))}V&&p.insights?.defaultOpen&&queueMicrotask(()=>Pt(!0));const qn=4,ut=240,It=480,hi=720,yi=1.25;let me=It;function Xn(e){const t=H*2+110+2,n=Un();if(n)return Math.ceil(n.across*qn+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*(qn/s),d=Math.ceil(a+t);(o==null||d>o)&&(o=d)}return o}function bi(e){const t=Xn(e);return t==null?ut:Math.min(me,Math.max(ut,t))}function wi(e){const t=Xn(e);if(t==null)return!1;const n=Math.min(hi,Math.max(It,t));return n<=me?!1:(me=n,!0)}function Un(){const e=l.compact?l.compactMap:void 0,t=D.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 Yn(e,t){const n=Un();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 vi(){for(const e of oe)e?.parentElement&&Yn(e.parentElement,e)}function Zn(){me=It,Ne=ut,jt(D.map(e=>e??null)),ft(),vi()}function Ft(){return Qn()?`${me}px`:"none"}function Qn(){return T==null&&!Ht}let Ht=!1;function ft(){const e=Ft();for(const t of Array.from($.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let Ne=ut,Jn=0;function jt(e){if(wi(e)&&ft(),T==null){const n=bi(e);n>Ne&&(Ne=n)}zt()}function eo(e){T=Eo(e),ft(),zt()}function Vt(e){return`repeat(${e}, minmax(0, ${Qn()?`${me}px`:"1fr"}))`}function to(e){$.style.gridTemplateColumns!==e&&($.style.gridTemplateColumns=e)}function zt(){if(T!=null){to(Vt(T));return}const e=Math.max(1,Jn),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(me,Ne*yi),d=r=>{let g=0;for(;g<e&&o(g+1)>=r;)g++;return g};i=d(a)||d(Ne)||1}const s=n>0&&i<e;s!==Ht&&(Ht=s,ft()),to(Vt(i))}const $=u.ownerDocument.createElement("div");if(Object.assign($.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Vt(1),gap:k.xl,paddingLeft:de,paddingRight:de,justifyContent:"start",alignContent:"start",isolation:"isolate"}),be?.placement){const e=be.placement;v=an(e,de,u.ownerDocument,Bt),v.style.maxHeight="calc(100vh - 80px)",v.style.position="sticky",v.style.top="8px",v.style.display="flex",v.style.flexDirection="column"}else if(N||gn()){const e=!!be?.defaultOpen;v=an("right",de,u.ownerDocument,Bt),v.style.maxHeight="calc(100vh - 80px)",v.style.position="sticky",v.style.top="8px",v.style.flexDirection="column",v.style.display=e?"flex":"none",z()}ge(),(be?.placement??"right")==="left"?(v&&Y.appendChild(v),Y.appendChild($)):(Y.appendChild($),v&&Y.appendChild(v));const _e=u.ownerDocument.createElement("div");Object.assign(_e.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:de,paddingRight:de,paddingTop:de,zIndex:"1",background:b.menuBg}),Te.appendChild(Ee),Te.appendChild(P),et=Ti(u.ownerDocument,()=>On(!Tt())),Te.appendChild(et.el),ge(),V&&(At=Ei(u.ownerDocument,"Maps","lot",e=>Pt(e)),Te.appendChild(At.el)),_e.appendChild(Te),_e.appendChild(le),u.appendChild(_e),u.appendChild(Y);function pt(){le.innerHTML="";const e=l.plotMode??"hardBin",t=!dt&&go.has(e),n=D.filter(y=>y!=null),o=n.find(y=>y.isLotStack),i=Is(n.map(y=>({metadata:y.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:p.attributes}),s=e==="metadata",a=l.activeMetadataKey,d=t&&!s?To(n,y=>(e==="softBin"?y.sbin:y.hbin)??void 0,ue):{counts:new Map,total:0,pass:0},r=t&&!s?l.binColors??De():void 0,g=r?e==="softBin"?r.pass.soft:r.pass.hard:new Set,c=ws(d.counts.entries(),g).map(([y])=>y),f=t&&s&&a?To(n,y=>$i(y.metadata?.[a])):{counts:new Map,total:0,pass:0},h=s?$n()?.values:void 0,m=t&&s?(h??[...f.counts.keys()].sort(sn)).filter(y=>f.counts.has(y)):[];if(Ee.innerHTML="",i&&Ee.appendChild(i),Ee.style.display=i?"flex":"none",!c.length&&!m.length){le.style.display="none";return}le.style.display="flex";const S=u.ownerDocument.createElement("div");Object.assign(S.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${k.sm} ${k.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),le.appendChild(S);const w=on(l.highlightBin),L=D.flatMap(y=>y?.metadataFields??[]).find(y=>y.key===a),I=s?L?.label??(a?Vs(a):"Metadata"):_i[e],F=u.ownerDocument.createElement("span");if(F.textContent=I,Object.assign(F.style,{fontSize:j.body,fontWeight:"700",letterSpacing:Gi,textTransform:"uppercase",color:b.label,flexShrink:"0"}),S.appendChild(F),!s&&d.total>0){const y=d.pass,G=y/d.total*100,re=u.ownerDocument.createElement("span");re.textContent=`Yield ${vt(G)}`,Object.assign(re.style,{fontSize:j.body,fontWeight:"700",color:b.value,whiteSpace:"nowrap",flexShrink:"0"});const ce=u.ownerDocument.createElement("span");ce.textContent=`${y.toLocaleString()} / ${d.total.toLocaleString()} dies`,Object.assign(ce.style,{fontSize:j.body,color:b.label,whiteSpace:"nowrap",flexShrink:"0"}),S.appendChild(re),S.appendChild(ce)}if(s){const y=on(l.highlightMetadataValue);m.forEach((G,re)=>{const ce=y.includes(G),We=L?.values?.find(Ut=>Ut.value===G),Ye=We?.color??ji(re),co=f.counts.get(G)??0;Oo(S,{color:Ye,isActive:ce,label:We?.label??G,count:co,percent:f.total>0?co/f.total*100:void 0,onClick:Ut=>{const Bi=Do(l.highlightMetadataValue,G,Ut);En(),W({highlightMetadataValue:Bi})}})});return}const Ue=e==="softBin"?D.flatMap(y=>y?.sbinDefs??[]):D.flatMap(y=>y?.hbinDefs??[]),ao=new Set,qt=[];for(const y of Ue)ao.has(y.bin)||(ao.add(y.bin),qt.push(y));const Xt=qt.length>0?new Map(qt.map(y=>[y.bin,y])):null,lo=r??l.binColors??De(),Di=e==="softBin"?lo.soft:lo.hard,ro=y=>Di.get(y)??Hi;for(const y of c){const G=w.includes(y),re=Xt?.get(y),ce=d.counts.get(y)??0;Oo(S,{color:ro(y),isActive:G,label:re?.name?`${y} \xB7 ${re.name}`:`Bin ${y}`,count:ce,percent:d.total>0?ce/d.total*100:void 0,onMenu:(We,Ye)=>jo(e==="softBin"?"soft":"hard",y,We,Ye),onClick:We=>{const Ye=Do(l.highlightBin,y,We);En(),W({highlightBin:Ye})}})}d.total>0&&c.length>1&&le.appendChild(Us(u.ownerDocument,[...d.counts.entries()].sort(([,y],[,G])=>G-y).map(([y,G])=>({color:ro(y),count:G,label:Xt?.get(y)?.name?`${y} \xB7 ${Xt.get(y).name}`:`Bin ${y}`})),d.total))}function qe(e){const t=B.filter(c=>c!==null);if(!t.length)return[];const n=t.map(c=>c.dies.filter(_s)),o=t[0].wafer,i=t.length,s=uo(t.map(c=>Yt(c)));if(!s)return[];const a=new Set(t.map(c=>te(c,"renderWaferGallery")));if(a.size!==1)return[];const d=[...a][0],r=o.metadata?{...o,metadata:(({wafer:c,waferId:f,...h})=>h)(o.metadata)}:o;function g(c,f){return{...c,stats:{...c.stats,isLotStack:!0,aggregationMethod:f,lotSize:i}}}if(e==="stackedValues"){const c=Ae();let f=c?.filter(nn);if(c!==void 0&&f?.length===0)return[];if(c?.length||(f=Oi(t.flatMap(S=>S.dies)).map(S=>({testNumber:S,name:zs(void 0,S)}))),!f?.length)return[];const h=l.aggregationMethod??"mean";return f.map(m=>{const S=Ss(n,h,m.testNumber),w={testNumber:0,name:m.name,unit:m.unit,...Ks(m)};return{wafer:r,dies:S,passBins:[...s],ringCount:d,testDefs:[w],label:`${Gs(m,m.testNumber)} \xB7 ${h}`,isLotStack:!0,aggrMethod:h,lotSize:i,statsSummary:g(yt({wafer:r,dies:S,passBins:[...s],ringCount:d,testDefs:[w]},{testNumbers:[0]}),h)}})}if(e==="stackedBins"){let c=mt(t.map(f=>f?.hbinDefs));return(!c||c.length===0)&&(c=[...new Set(t.flatMap(h=>h.dies.map(m=>m.hbin).filter(m=>m!=null)))].sort((h,m)=>h-m).map(h=>({bin:h,name:`Bin ${h}`}))),c.map(f=>{const h=vo(n,f.bin,"hard"),m=[{bin:f.bin,name:f.name}];return{wafer:r,dies:h,passBins:[...s],ringCount:d,hbinDefs:m,label:`${f.bin} \xB7 ${f.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:g(yt({wafer:r,dies:h,passBins:[...s],ringCount:d,hbinDefs:m}),"countBin")}})}if(e==="stackedSoftBins"){let c=mt(t.map(f=>f?.sbinDefs));return(!c||c.length===0)&&(c=[...new Set(t.flatMap(h=>h.dies.map(m=>m.sbin).filter(m=>m!=null)))].sort((h,m)=>h-m).map(h=>({bin:h,name:`Bin ${h}`}))),c.map(f=>{const h=vo(n,f.bin,"soft"),m=[{bin:f.bin,name:f.name}];return{wafer:r,dies:h,passBins:[...s],ringCount:d,sbinDefs:m,label:`${f.bin} \xB7 ${f.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:g(yt({wafer:r,dies:h,passBins:[...s],ringCount:d,sbinDefs:m}),"countBin")}})}return t}function Gt(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),o=l.plotMode,i=$e()!==null;l={...l,...e};const s=l.plotMode,a=he.has(s),d=o!==void 0&&he.has(o),r=Je>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const c=De();l={...l,binColors:c},e={...e,binColors:c}}if("compact"in e){const c=Pn();l={...l,compactMap:c},e={...e,compactMap:c}}if(("compact"in e||l.compact&&("rotation"in e||"showXYIndicator"in e))&&Zn(),e.plotMode!==void 0)if(a){const c=Gt(s);if(l={...l,...c},r)for(const f of C)f&&f.setOptions(e);else ee(qe(s))}else if(d){const{valueRange:c,lotSize:f,aggregationMethod:h,...m}=l;if(l=m,r)for(const S of C)S&&S.setOptions(e);else ee(B.filter(S=>S!==null))}else for(const c of C)c&&c.setOptions(e);else if(e.aggregationMethod!==void 0&&s==="stackedValues")if(r)for(const c of C)c&&c.setOptions(e);else ee(qe("stackedValues"));else for(const c of C)c&&c.setOptions(e);$e()!==null!==i&&cn(),pt(),Vn(),Hn(),Wn();const g=e.plotMode!==void 0&&e.plotMode!==o;(Bs.some(c=>c in e)||g)&&z(),Ge(),zn(),Gn(),Lt(),Ot(),t&&p.onViewOptionsChange?.(Co(l),n,Ds(n))}function no(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:k.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:j.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=Bo(e,o,t,n,p.attributes);return{wrap:o,metaPanel:s}}function oo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||Fs(n??{}).length===0)return;const i=o.parentElement,s=u.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:k.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const a=Bo(u.ownerDocument,s,t,n,p.attributes);a&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(a))}function Kt(e,t,n){const o=u.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:K.container,boxShadow:Qt.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:Ft(),maxHeight:Ft()});const i=u.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${k.md} ${k.lg} ${k.sm}`,borderBottom:`1px solid ${b.menuBorder}`,flexShrink:"0",gap:k.sm});const{wrap:s,metaPanel:a}=no(document,ht(e,t),e.wafer.metadata??void 0);i.appendChild(s);const d=u.ownerDocument.createElement("button");d.dataset.wmapExpandBtn="1",d.setAttribute("aria-label","Open full view"),en(d),d.innerHTML=Zt.expand,Object.assign(d.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${b.menuBorder}`,borderRadius:K.control,background:b.panelBg,color:b.label,padding:k.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),Jt(d),i.appendChild(d),i.addEventListener("click",h=>{(h.ctrlKey||h.metaKey)&&(h.preventDefault(),h.stopPropagation(),Go(D.indexOf(e)))},!0),o.appendChild(i);const r=u.ownerDocument.createElement("div");Object.assign(r.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(r),Yn(o,r),a&&r.appendChild(a),$.appendChild(o),o.addEventListener("contextmenu",h=>{if(h.defaultPrevented)return;h.preventDefault();const m=e.viewOptions?{...l,...e.viewOptions}:l,S=Dt()??kn(t),w=S?.source??xs(e.dies,{waferLabel:ye(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:m.plotMode==="value"?m.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:ue(e),ringCount:te(e,"renderWaferGallery")}),L={x:h.clientX,y:h.clientY};import("./drilldown.js").then(({openDrilldownMenu:I})=>{o.isConnected&&I(L,o,w,S?{plots:R,attributes:p.attributes,...S.ctx}:{plots:R,attributes:p.attributes,onSaveImage:f.getSaveImageHook(),onSaveText:f.getSaveTextHook(),onLocateDie:F=>se(t,F)})})});const g=Qe||$e()!==null,c=e.viewOptions?{...l,...e.viewOptions}:l,f=So(r,e,{viewOptions:{...c,showLegend:g,legendPosition:Re},showTooltip:!0,padding:H,statsSummary:e.statsSummary,onSaveImage:p.onSaveImage,onSaveText:p.onSaveText,downloadFilename:p.downloadFilename,onClick:e.onClick,onSelect:vn(e),drilldownSourceOverride:()=>Ho(t),insights:ne,onExpand:()=>Xe(t,e),showIdentity:!1,chromeInset:Ni,drawWhenVisible:!0});return f.setViewControlsVisible(!1),f.setSummaryVisible(!1),d.onclick=()=>Xe(t,e),{card:o,ctrl:f,canvasWrapper:r,expandBtn:d}}function Si(e){const t=we[e];if(!t)return;const n=[...q.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Zt.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>xi(n.id)):(t.innerHTML=Zt.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>Xe(e,D[e]))}function ee(e){Mi(),Ie()?.remove(),Fe(null),ke(),D=[],_.clear(),Et.clear(),X.style.display="none";for(const r of C)r&&r.destroy();C=[],oe=[],we=[],Je=0,$.innerHTML="",Jn=e.length,jt(e.map(r=>typeof r=="function"?null:r));const t=[];for(let r=0;r<e.length;r++){const g=e[r];if(typeof g=="function"){const c=u.ownerDocument.createElement("div");c.className="wmap-gallery-card",Object.assign(c.style,{background:b.menuBg,border:`1px solid ${b.menuBorder}`,borderRadius:K.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const f=u.ownerDocument.createElement("span");f.textContent="\u2026",Object.assign(f.style,{color:b.label,fontSize:"18px"}),c.appendChild(f),$.appendChild(c),D.push(null),C.push(null),oe.push(null),we.push(null),t.push({index:r,factory:g,placeholder:c}),Je++}else{const{ctrl:c,canvasWrapper:f,expandBtn:h}=Kt(g,r,e.length);D.push(g),C.push(c),oe.push(f),we.push(h)}}Fn(),pt(),Lt(),Ot(),In();const n=++Pe,o=()=>{setTimeout(()=>{n===Pe&&p.onItemsResolved?.()},0)},i=r=>{setTimeout(()=>{n===Pe&&p.onItemResolved?.(r,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let a=0;function d(){if(n!==Pe)return;if(a>=t.length){if(he.has(l.plotMode)){const L=l.plotMode;ee(qe(L));return}je=o,z(),Me||(je=null,o());return}const{index:r,factory:g,placeholder:c}=t[a++],f=g();D[r]=f,B[r]=f,jt([f]);const{card:h,ctrl:m,canvasWrapper:S,expandBtn:w}=Kt(f,r,e.length);C[r]=m,oe[r]=S,we[r]=w,Je--,c.replaceWith(h),i(++s),ii(),oi(),!v&&!be?.placement&&f.statsSummary?.findings.length&&(v=an("right",de,u.ownerDocument,Bt),v.style.maxHeight="calc(100vh - 80px)",v.style.position="sticky",v.style.top="8px",v.style.flexDirection="column",v.style.display="none",(be?.placement??"right")==="left"?Y.insertBefore(v,$):Y.appendChild(v),z(),ge()),ge(),setTimeout(d,0)}t.length>0?setTimeout(d,0):o()}if(he.has(l.plotMode)&&B.length>0){const e=Gt(l.plotMode);l={...l,...e},ee(qe(l.plotMode))}else ee(x);Ge();let Le=0;const io=new(u.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Le)return;Le=(u.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Le=0,T==null&&zt()})});io.observe($),v&&z();function Ci(e,t){const n=oe[e];if(!n)return;n.innerHTML="",Object.assign(n.style,{alignItems:"center",justifyContent:"center"});const o=u.ownerDocument.createElement("span");o.textContent=t?"Opened in its own window":"Opened in the wafer viewer",Object.assign(o.style,{color:b.label,fontSize:j.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function Xe(e,t){for(const a of q.values())if(a.cardIndex===e)return;const n=ht(t,e),o=Ro++,i=C[e]?.getOptions(),s=Zi(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:j.family}),es(u,a.documentElement);const d=ts(u,a.documentElement,()=>w.setOptions({})),r=a.createElement("div");r.dataset.wmapWindowBanner="1",r.textContent=n,Object.assign(r.style,{display:"none",padding:`${k.sm} ${k.xl}`,fontSize:j.body,fontWeight:"700",background:b.warnBg,color:b.warnText,borderBottom:`1px solid ${b.warnBorder}`,flexShrink:"0"}),a.body.appendChild(r);const g=a.createElement("div");Object.assign(g.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),a.body.appendChild(g);const{wrap:c,metaPanel:f}=no(a,n,t.wafer.metadata??void 0),h=a.createElement("div");Object.assign(h.style,{display:"flex",alignItems:"center",padding:`${k.md} ${k.lg} ${k.sm}`,borderBottom:`1px solid ${b.menuBorder}`,flexShrink:"0",gap:k.sm}),h.appendChild(c),g.appendChild(h);const m=a.createElement("div");Object.assign(m.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),f&&m.appendChild(f),g.appendChild(m);let S=0;const w=Nt(m,t,void 0,i,(I,F)=>{const Ue=I?F:-S;try{s.resizeBy(Ue,0),S=I?F:0}catch{}}),L=setInterval(()=>{s.closed&&gt(o)},400);s.addEventListener("pagehide",()=>gt(o)),q.set(o,{id:o,ctrl:w,cardIndex:e,label:n,closePollId:L,stopThemeSync:d,close:()=>{s.closed||s.close()},setTitle:I=>{a.title=I,r.textContent=I,r.style.display="block"}})}else{const a=Qi({title:n,onClose:()=>gt(o),anchor:u});a.contentWrap.style.flexDirection="column",oo(a,n,t.wafer.metadata??void 0);const d=Nt(a.contentWrap,t,void 0,i,wo(a));q.set(o,{id:o,ctrl:d,cardIndex:e,label:n,closePollId:null,close:()=>a.close(),setTitle:r=>{const g=a.box.querySelector("[data-wmap-window-title]");g&&(g.textContent=r,g.title=r)}})}C[e]?.destroy(),C[e]=null,Ci(e,s!==null),Si(e)}function Nt(e,t,n,o,i){const s=t.viewOptions?{...l,...t.viewOptions}:l,a=o?{...s,...o}:s,r={...n!==void 0?{...a,plotMode:"value",activeTest:n}:a,showLegend:!0,legendPosition:Re},g=So(e,t,{viewOptions:r,showTooltip:!0,padding:H,statsSummary:t.statsSummary,onSaveImage:p.onSaveImage,onSaveText:p.onSaveText,downloadFilename:p.downloadFilename,onClick:t.onClick,onSelect:vn(t),insights:ne,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return g.setViewControlsVisible(!0),g.setSummaryVisible(!0),g.setExpandVisible(!1),g}function gt(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=D[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:a,expandBtn:d}=Kt(o,n,D.length);oe[n]?.parentElement?.replaceWith(i),C[n]=s,oe[n]=a,we[n]=d}function xi(e){const t=q.get(e);t&&(t.close(),gt(e))}function Mi(){for(const e of q.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function _t(){for(const e of C)e?.drawPendingNow()}const so=u.ownerDocument.defaultView??window;so.addEventListener("beforeprint",_t);function ki(){_t();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,d=(u.ownerDocument.defaultView??window).devicePixelRatio||1,r=Math.round(26*d),g=Math.round(12*d),c=u.ownerDocument.createElement("canvas");c.width=n*i+(n-1)*a,c.height=o*(s+r)+(o-1)*a;const f=c.getContext("2d"),h=Vi($);f.fillStyle=h.background,f.fillRect(0,0,c.width,c.height),e.forEach((m,S)=>{const w=S%n,L=Math.floor(S/n),I=w*(i+a),F=L*(s+r+a),Ue=m.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";f.fillStyle=h.surface,f.fillRect(I,F,i,r),f.fillStyle=h.text,f.font=`700 ${g}px system-ui, sans-serif`,f.textAlign="left",f.textBaseline="middle",f.fillText(Ue,I+Math.round(10*d),F+r/2,i-Math.round(20*d)),f.drawImage(m,I,F+r)}),c.toBlob(m=>{if(!m)return;const S=C.find(w=>w!=null)?.getExportTitle();ls(m,["gallery",S].filter(Boolean).join(" "),A.onSaveImage)})}return{setItems(e){B=e.map(n=>typeof n=="function"?null:n);const t=l.plotMode;if(he.has(t))if(e.some(o=>typeof o=="function"))ee(e);else{const o=Gt(t);l={...l,...o},ee(qe(t))}else ee(e)},setOptions(e){W(e,{fireCallback:!1})},getOptions(){return Co(l)},setFindingsNotice(e){bn=e,z()},setColumns(e){eo(e)},getBinColors(){return l.binColors??De()},setLotStatsSummary(e){N=e,Ge(),v&&z(),ge()},openUserGuide:Nn,destroy(){R.flush(),Pe++,so.removeEventListener("beforeprint",_t),Me?.cancel(),Me=null,je=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=[],Ie()?.remove(),io.disconnect(),Le&&((u.ownerDocument.defaultView??window).cancelAnimationFrame(Le),Le=0),u.ownerDocument.removeEventListener("click",tt,!0),window.removeEventListener("blur",yn),Lo(),mo(),_e.remove(),Y.remove(),v?.remove(),Oe?.destroy()}}}
@@ -8,6 +8,7 @@ import { type UserGuideExtension } from './guideWindow.js';
8
8
  import type { SummaryPanelOptions, FindingsNotice } from './summaryPanel.js';
9
9
  import { type WarningsOptions } from './warnings.js';
10
10
  import type { InsightsOptions } from './insightsTab.js';
11
+ import type { WaferAttributeDef } from '../stats/facets.js';
11
12
  import type { DrilldownContext } from './drilldown.js';
12
13
  import { type DrilldownSource } from './chartPopulation.js';
13
14
  import { type DieListDisplayOptions } from './dieList.js';
@@ -326,6 +327,13 @@ export interface RenderOptions extends ForwardedDrawOptions {
326
327
  * group by).
327
328
  */
328
329
  insights?: InsightsOptions;
330
+ /**
331
+ * What the host calls its wafer attributes (lot, product, temperature, your own columns), over the defaults: a label, whether it
332
+ * is a Group by and Compare by choice (`facet: false` keeps a low-value field like a program revision out of those lists, while
333
+ * it still shows on the header strip, in the Wafers table and in reports), and whether it is a date (grouped by day). One entry
334
+ * per metadata key, so the strip, Group by, the plot fields, the Wafers table and the reports all name an attribute the same way.
335
+ */
336
+ attributes?: Record<string, WaferAttributeDef>;
329
337
  /**
330
338
  * Built-in surfacing of the library's own data warnings (see `WarningsOptions`).
331
339
  *
@@ -509,7 +517,20 @@ export interface CardController extends WaferMapController {
509
517
  /** @internal The public view of a card's options: everything but the gallery's shared state. */
510
518
  /** The bin a finding is about — what the legend filter shows while the finding
511
519
  * is active — or `undefined` for a yield, test or functional finding. */
512
- export declare function findingBin(finding: StatsFinding): number | undefined;
520
+ /**
521
+ * The bin a finding highlights on the map, or `undefined` for none. A pass bin that fell in a region is that
522
+ * region's pass rate, so it is shown as a yield finding is, as the region's dies: highlighting the passing
523
+ * dies would point at the dies the finding is not about. `passBins` are the population's own; without one set
524
+ * for it (wafers judged differently) no bin is taken for a pass bin.
525
+ */
526
+ export declare function findingBin(finding: StatsFinding, passBins: readonly number[] | undefined, hasHardBins: boolean): number | undefined;
527
+ /**
528
+ * The bin mode a finding is shown in. A bin finding takes its own bin type. Any other (a yield region,
529
+ * a spatial pattern) is about which dies, not which bin, so the map keeps the bin mode it is in, and
530
+ * from another mode takes a bin type the dies carry: a soft-bin-only lot switched to hard bins draws
531
+ * every die as no data. One rule for the single map and the gallery.
532
+ */
533
+ export declare function findingPlotMode(finding: StatsFinding, current: PlotMode | undefined, hasHardBins: boolean): PlotMode;
513
534
  export declare function toPublicViewOptions(opts: CardViewOptions): WaferViewOptions;
514
535
  export type RenderableWaferMap = Pick<WaferMapResult, 'wafer' | 'dies'> & Partial<Omit<WaferMapResult, 'wafer' | 'dies'>>;
515
536
  export declare function renderWaferMap(container: HTMLElement, result: RenderableWaferMap, options?: RenderOptions): WaferMapController;
@@ -1 +1 @@
1
- import{createViewSwitch as Ji}from"./viewSwitch.js";import{createSummaryRail as eo}from"./summaryRail.js";import{buildView as to,buildHoverText as no,findTestDef as Lt,resolveTestNumber as gn,buildMapTitle as io}from"../renderer/buildView.js";import{drawMapCanvas as oo,BIN_LEGEND_W as pi,BIN_LEGEND_W_COMPACT as lo,BIN_LEGEND_ADAPT_COMPACT as so,BIN_LEGEND_ADAPT_FLOATING as ao,PATH_SHAPES as ro}from"./toCanvas.js";import{buildWaferMap as co,getTestPassStatus as fo,isParametricTest as mn}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as po}from"../stats/analyzeWaferMap.js";import{SHADOW as uo,LEADING as ui,wireControlHover as hi,SPACE as X,EDGE_GUTTER as ho,RADIUS as gi,FONT as Pt,CLR as k,applyOverlayZ as go,getTooltip as mi,hideTooltip as Tt,positionTooltip as yi,createToolbarHelpers as mo,buildModeMenuEl as yo,openReparentedModal as bo,makePaletteBtn as vo,makeLogScaleBtn as xo,makeLegendStyleBtn as wo,makeOverlaysBtn as Co,makeOrientationBtn as So,menuLayerFor as bi,saveImageBlob as Mo,markMenuTrigger as it,wireMenuA11y as vi,wireExpandToggle as Eo,nextFrame as yn,requestedPassFailDisplay as Do,overlayMenuRows as ko,anyOverlayActive as Bo,openCompactDiagnostics as Lo,roomForPanel as Po,logWmapVersionOnce as To,buildDataModeEntries as Oo,metadataKeyHasData as Ro,metadataModeEntry as Wo}from"./toolbar.js";import{openUserGuideWindow as Io}from"./guideWindow.js";import{waferIdentityLabel as Fo}from"../core/waferLabel.js";import{metadataDisplayValue as Ao}from"../core/metadata.js";import{withExportContext as zo}from"./exportName.js";import{createSummaryPanelEl as bn,wrapWithSummaryPanel as vn,renderWaferSummaryContentSteps as Ho}from"./summaryPanel.js";import{runChunked as Vo}from"./chunked.js";import{collectWarnings as Yo,buildWarningsMenuEl as Xo,severityOf as No}from"./warnings.js";import{plotStoreFor as $o}from"./plotStore.js";import{selectionPopulation as jo,waferPopulation as Ko}from"./chartPopulation.js";import{sourceFromBins as xi}from"./plotItems.js";import{createIdentityHeader as _o,collapsedLabel as xn}from"./identityHeader.js";import{getDieKey as re,hasPosition as wi,isPositionedDie as Go}from"../core/dies.js";import{buildDieListSection as Uo}from"./dieList.js";import{buildMaplessSummary as Zo}from"./maplessSummary.js";import{resolveBinColors as Qo,binColorWarning as qo}from"../renderer/binColors.js";import{requirePassBins as Jo}from"../core/passBins.js";import{requireRingCount as ot}from"../core/ringCount.js";import{asList as el,toggleHighlight as Ci}from"../core/utils.js";import{buildCompactMap as tl,compactLayoutOffered as nl}from"../core/compact.js";const Si=new Set(["binColorScheme","valueColorScheme","reverseValueScheme","useDefinedBinColors","rotation","flipX","flipY","showDieLabels","showRingBoundaries","showQuadrantBoundaries","showReticle","showXYIndicator","compact","showAxes","legendPosition","logScale","colorbarRangeMode","markFailingDies","fallbackFormat"]);export const COLOR_KEYS=["binColorScheme","valueColorScheme","reverseValueScheme","useDefinedBinColors","binColors"];export function classifyChanged(P){const m=P.some(p=>Si.has(p)),S=P.some(p=>!Si.has(p));return m&&S?"mixed":m?"preference":"state"}export function findingBin(P){const{kind:m,bin:S}=P.variable;return m==="hardBin"||m==="softBin"?S:void 0}export function toPublicViewOptions(P){const{metadataValueOrder:m,binColors:S,lotSize:p,compactMap:T,...lt}=P;return lt}export function renderWaferMap(P,m,S={}){return renderWaferMapCard(P,m,S)}export function renderWaferMapCard(P,m,S={}){To();const p=P.ownerDocument,T=p.defaultView??window,lt=()=>F.label,Ot=()=>Fo({label:lt(),wafer:U}),oe=zo(()=>{const e=Ao(U.metadata?.lot);return{prefix:S.downloadFilename,lots:e!==void 0?[e]:[],...F.isLotStack?{stackedWafers:g?.lotSize??!0}:{wafer:Ot()}}},S.onSaveImage,S.onSaveText);function wn(){const e=g.plotMode==="softBin"||g.plotMode==="stackedSoftBins"?te:ee,{primary:t,secondary:n}=io(g,c.fallbackFormat,e);return[t,F.isLotStack?"":n].filter(Boolean).join(" ")||"wafer-map"}T.getComputedStyle(P).position==="static"&&(P.style.position="relative");const Mi=P.clientHeight;S.height!=null&&(P.style.height=typeof S.height=="number"?`${S.height}px`:S.height);const Rt=m.dataCoverage?m.dataCoverage.unpositionedDies:m.dies.filter(e=>!wi(e)).length,Ye=(m.dataCoverage?m.dataCoverage.totalDies:m.dies.length-Rt)===0&&Rt>0,Xe=p.createElement("div");Object.assign(Xe.style,{display:"flex",flexDirection:"column",width:"100%",height:"100%"}),P.appendChild(Xe);const Le=p.createElement("div");Object.assign(Le.style,{position:"relative",width:"100%",flex:"1 1 auto",minHeight:"0"});const be=S.chromeInset??ho,G=p.createElement("div");Object.assign(G.style,{display:"flex",alignItems:"stretch",gap:X.sm,background:k.canvasBg,paddingBottom:X.lg,paddingTop:be,paddingLeft:be,paddingRight:be,flexShrink:"0",minWidth:"0"}),Xe.appendChild(G),Xe.appendChild(Le);function Ne(){const e=[...G.children].some(t=>t.style.display!=="none");G.style.display=e?"flex":"none"}const M=p.createElement("div");Object.assign(M.style,{position:"relative",width:"100%",height:"100%"});const a=p.createElement("canvas");Object.assign(a.style,{width:"100%",height:"100%",display:"block"}),M.appendChild(a),Le.appendChild(M);let st=null;if(Rt>0){let n=function(){if(t){const d=Uo(e,m.testDefs,{...S.dieList,onSaveText:oe.onSaveText,waferMetadata:U.metadata,metadataFields:xe,ownerDocument:p});if(d)return d}const o=Lt(m.testDefs,c.activeTest??0),l=mn(o)?c.logScale??o?.logScale??!1:!1;return Zo(e,m.testDefs,{plotMode:c.plotMode??"hardBin",activeTest:c.activeTest,hbinDefs:ee,sbinDefs:te,binColors:g.binColors,valueColorScheme:c.valueColorScheme,reverseValueScheme:c.reverseValueScheme,logScale:l,colorbarRangeMode:c.colorbarRangeMode,valueRangeDies:m.dies})},i=function(o){const l=p.createElement("button");return l.type="button",hi(l),Object.assign(l.style,{fontSize:Pt.body,padding:`${X.xxs} ${X.sm}`,borderRadius:gi.control,flexShrink:"0",border:`1px solid ${k.menuBorder}`,background:k.menuBg,color:k.text,cursor:"pointer"}),l.textContent=t?"View chart":"View die list",l.addEventListener("click",d=>{d.stopPropagation(),t=!t,l.textContent=t?"View chart":"View die list",o()}),l};const e=m.dies.filter(o=>!wi(o));let t=!1;if(Ye){const o=p.createElement("div");Object.assign(o.style,{position:"absolute",inset:"0",background:k.panelBg,padding:X.xl,boxSizing:"border-box",overflow:"hidden",display:"flex",flexDirection:"column",gap:X.md,zIndex:"1"});const l=p.createElement("div");Object.assign(l.style,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:X.md});const d=p.createElement("span");Object.assign(d.style,{fontSize:Pt.body,color:k.label,lineHeight:ui.base}),d.textContent="No die position data for this wafer.",l.appendChild(d);const s=p.createElement("div");Object.assign(s.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),l.appendChild(i(()=>s.replaceChildren(n()))),o.appendChild(l),o.appendChild(s),M.appendChild(o),st=()=>{t||s.replaceChildren(n())}}else{const o=p.createElement("div");Object.assign(o.style,{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"3",background:k.panelBg,borderTop:`1px solid ${k.menuBorder}`,fontSize:Pt.body,color:k.text,cursor:"pointer",padding:`${X.xs} ${X.md}`,display:"flex",alignItems:"center",justifyContent:"space-between",gap:X.md}),hi(o,"bare");const l=p.createElement("span");l.textContent=`+${e.length} ${e.length===1?"die":"dies"} without position data`,o.appendChild(l);const d=p.createElement("span");d.textContent="\u25BE",Object.assign(d.style,{fontSize:Pt.body,lineHeight:ui.none,color:k.label,flexShrink:"0"}),o.appendChild(d),o.setAttribute("aria-expanded","false"),o.setAttribute("aria-label",`${e.length} dies without position data. Click to view.`);let s=null,r=null;Eo(o,f=>{if(d.textContent=f?"\u25B4":"\u25BE",o.setAttribute("aria-expanded",String(f)),f){s=p.createElement("div");const u=o.getBoundingClientRect().height||28;Object.assign(s.style,{position:"absolute",left:"0",right:"0",bottom:`${u}px`,top:"20%",zIndex:"2",background:k.panelBg,borderTop:`1px solid ${k.menuBorder}`,padding:X.md,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:X.md}),s.addEventListener("click",W=>W.stopPropagation());const b=p.createElement("div");Object.assign(b.style,{display:"flex",justifyContent:"flex-end"}),b.appendChild(i(()=>{r&&r.replaceChildren(n())})),s.appendChild(b),r=p.createElement("div"),Object.assign(r.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),r.appendChild(n()),s.appendChild(r),M.appendChild(s)}else s&&(s.remove(),s=null,r=null)}),M.appendChild(o),st=()=>{r&&!t&&r.replaceChildren(n())}}}const{onHover:at,onClick:Ei,onSelect:de,onViewOptionsChange:Di,showTooltip:ki=!0,showToolbar:Pe=!0,showIdentity:Cn=!0,summaryPanel:$e,showHelpButton:Sn=!1,userGuideExtension:Bi,onExpand:Mn,showExpandButton:En=!0,zIndex:Li,insights:Te,warnings:Dn,viewOptions:Pi={},...Oe}=S,rt=Te?.enabled??Pe;let dt=null;rt&&(dt=Ji(p,"Map","wafer",e=>Ke(e)),Pe||(dt.el.style.marginLeft="auto"),G.appendChild(dt.el));const Ti=.4,Oi=20,Re=[...Jo(m,"renderWaferMap")],kn=Dn?.display??!0,Ri=go(Li);let ce=S.statsSummary,he=[],Bn=!1,ct=null,Ln=!1;function Wt(){const e=Yo({result:m,statsSummary:ce,extra:ct?[ct]:[]}),t=e.length!==he.length||e.some((n,i)=>n.code!==he[i]?.code||n.message!==he[i]?.message);he=e,(t||!Bn)&&(Bn=!0,Dn?.onWarning?.(e))}Wt();let F=m,U=m.wafer,le=m.dies,x=new Set,ve=null;const It=Te?.plotStore??$o(Te),ft={plots:It,onSaveImage:oe.onSaveImage,onSaveText:oe.onSaveText,onLocateDie:e=>Mt(e)},pt=()=>!Ye;let Ft=null,ut=null,ht=!1,At=!1,ee=m.hbinDefs,te=m.sbinDefs,Z=m.testDefs,xe=m.metadataFields,Pn=m.reticles?.length?m.reticles:void 0,gt=m.reticleConfig,Tn=m.dataAxisFlip,zt=m.isLotStack??!1,Ht=m.aggrMethod,Vt=m.lotSize,Q=null,se=null,ae=null;Cn&&(Q=_o(xn(U.metadata??{},je())??"",U.metadata,{lotStack:je(),ownerDocument:p}),M.appendChild(Q.metaPanel),Q.metaPanel.style.visibility="visible",Q.isEmpty()||(se=On(Q.wrap),G.insertBefore(se,G.firstChild),Ne()));function On(e){const t=p.createElement("div");return Object.assign(t.style,{display:"flex",alignItems:"center",padding:`${X.sm} ${X.lg}`,flex:"1 1 auto",minWidth:"0",overflow:"hidden",gap:X.sm}),Object.assign(e.style,{flex:"1",minWidth:"0"}),t.appendChild(e),t}function je(){return zt?{lotSize:Vt??1,aggrMethod:Ht}:void 0}function Wi(){if(!Q)return;Q.update(xn(U.metadata??{},je())??"",U.metadata,je());const e=se?.isConnected??!1,t=!Q.isEmpty();!t&&e?(se.remove(),se=null):t&&!e&&(se=On(Q.wrap),se.style.display="",G.insertBefore(se,G.firstChild),Ne())}const Ii=[...ee??[],...te??[]].some(e=>e.color);let c={plotMode:"hardBin",showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,showReticle:!1,showXYIndicator:!1,compact:!1,rotation:0,flipX:!1,flipY:!1,legendPosition:"default",...Pi},q=null,ge=!1,Rn=null;function Fi(){return rt?q?Promise.resolve(q):(Rn??=import("./insightsTab.js").then(({createInsightsTab:e})=>(q=e({getItems:()=>[{wafer:U,dies:le,hbinDefs:ee,sbinDefs:te,testDefs:Z,label:lt(),passBins:Re,statsSummary:ce}],getBinColors:()=>g.binColors,getRingCount:()=>ot(F,"renderWaferMap"),onSaveImage:oe.onSaveImage,onSaveText:oe.onSaveText,defaultView:Te?.defaultView,plotStore:It,onPickPlotsFile:Te?.onPickPlotsFile,showMetadataStrip:!1,contentInset:be,onOpenGuide:Sn&&!Pe?()=>fn():void 0,focusTest:t=>{O({plotMode:"value",activeTest:t,highlightBin:void 0}),Ke(!1)},locateDie:t=>{Ke(!1),Mt(t)},ownerDocument:p}),Object.assign(q.el.style,{position:"absolute",inset:"0",background:k.canvasBg,overflowY:"auto",paddingTop:"0"}),q.el.style.display="none",Le.appendChild(q.el),q)),Rn):Promise.resolve(null)}let Wn=0;const Yt=["wheel","touchstart","pointerdown","keydown"];function Ai(e,t){if(t<=0)return;let n=!1;const i=[],o=()=>{n=!0;for(const d of i)T.clearTimeout(d);i.length=0;for(const d of Yt)e.removeEventListener(d,o)},l=()=>n||!ge?!0:(e.scrollTop=t,e.scrollTop>=t);if(!l()){for(const d of Yt)e.addEventListener(d,o,{passive:!0,once:!0});for(const d of[0,50,150,300,600])i.push(T.setTimeout(()=>{l()},d));i.push(T.setTimeout(()=>{for(const d of Yt)e.removeEventListener(d,o)},700))}}function Ke(e){if(!rt)return;const t=ge;ge=e,dt?.setInsightsOpen(e),q&&!e&&t&&(Wn=q.el.scrollTop),q&&(q.el.style.display=e?"flex":"none"),M.style.visibility=e?"hidden":"",V&&(V.style.display=e||Ye?"none":"flex"),R&&(R.style.display=e?"none":"flex"),ae&&(ae.style.display=De?"none":"flex"),fe&&(fe.style.display="flex"),se&&(se.style.display=""),Ne(),Q&&e&&Q.collapse(),wt(),e&&Fi().then(n=>{!n||!ge||(n.el.style.display="flex",n.render(),Ai(n.el,Wn))})}rt&&Te?.defaultOpen&&queueMicrotask(()=>Ke(!0));let g,we,K=null,B=null,mt=[],Xt;function In(e){Xt!==e&&(Xt=e,w())}let Ce=null,Nt=Oe.legendOffset??{x:0,y:0},_e=!1,We=!1,Ge={x:0,y:0},$t={x:0,y:0},Se=!1,Ie=!1,_="select",Fe={x:0,y:0},yt={x:0,y:0},A={x:0,y:0},z={x:0,y:0},Ue=!1,Ae=!1;function jt(){const e=c,t=le.filter(Go);g=to(U,t,{compact:c.compact?c.compactMap??tl(t):void 0,plotMode:e.plotMode,binColorScheme:e.binColorScheme,valueColorScheme:e.valueColorScheme,reverseValueScheme:e.reverseValueScheme,useDefinedBinColors:e.useDefinedBinColors,binColors:e.binColors??Qo(le,{passBins:Re,binColorScheme:e.binColorScheme,hbinDefs:ee,sbinDefs:te,useDefinedBinColors:e.useDefinedBinColors}),passBins:Re,showDieLabels:e.showDieLabels,showRingBoundaries:e.showRingBoundaries,showQuadrantBoundaries:e.showQuadrantBoundaries,showReticle:e.showReticle,showXYIndicator:e.showXYIndicator,reticles:Pn,ringCount:ot(F,"renderWaferMap"),highlightBin:e.highlightBin,highlightMetadataValue:e.highlightMetadataValue,activeTest:e.activeTest,activeMetadataKey:e.activeMetadataKey,testDefs:Z,valueRange:e.valueRange,metadataValueOrder:e.metadataValueOrder,logScale:e.logScale,isLotStack:zt,aggregationMethod:Ht??e.aggregationMethod,lotSize:Vt??e.lotSize,dataAxisFlip:Tn,colorbarRangeMode:e.colorbarRangeMode,passFailDisplay:e.passFailDisplay,fallbackFormat:e.fallbackFormat,interactiveTransform:{rotation:e.rotation??0,flipX:e.flipX??!1,flipY:e.flipY??!1}},{hbinDefs:ee,sbinDefs:te,metadataFields:xe}),we=void 0;const n=e.binColors?null:qo(g.binColors,g.plotMode);n?.message!==ct?.message&&(ct=n,Wt(),Ln&&Ut())}jt();function Fn(){return c.showAxes??Oe.showAxes??B!==null}function zi(){return nl(le,[gt])}let N=null,me=null,Me=null,An=S.findingsNotice,Hi={},L=null,ne=null;function Vi(e){const{kind:t,index:n}=e.variable;O(t==="test"?{plotMode:"value",activeTest:n??0,highlightBin:void 0}:{plotMode:t==="softBin"?"softBin":"hardBin",highlightBin:findingBin(e)});const i=e.highlight;(i.kind==="bin"||i.kind==="region"||i.kind==="dies")&&Yn(i.dieKeys)}const Ze=new Map,Kt=new WeakSet;function _t(e){if(Ze.get(e)?.cancel(),Ze.delete(e),e.style.display==="none"){Kt.add(e);return}Kt.delete(e);const t=Vo(Ho(e,{wafer:U,dies:le,yieldSummary:F.yield,dataCoverage:F.dataCoverage,hbinDefs:ee,sbinDefs:te,testDefs:Z,statsSummary:ce,warnings:kn?he:[],passBins:Re,ringCount:ot(F,"renderWaferMap"),binColors:g.binColors,plotMode:c.plotMode??"hardBin",metadataShownElsewhere:Cn,fallbackFormat:c.fallbackFormat,activeFindingId:Me,findingsFilter:Hi,findingsNotice:An,onFindingsFilterChange:ye,onSaveText:oe.onSaveText,metadataFields:xe,dieListOptions:S.dieList,onLocateDie:n=>Mt(n),onFindingClick:(n,i)=>{Me===n.id?(Me=null,Yn([]),O({highlightBin:void 0})):(Me=n.id,Vi(n)),ye()}}));t.done||Ze.set(e,t)}function ye(){N&&_t(N)}function Qe(){L&&_t(L)}let bt=null;function Gt(e,t){t!=="right"&&t!=="left"||(bt=eo(p,t,()=>tn(!0)),e.appendChild(bt.el))}function zn(){if(!bt)return;const e=N??L,t=e?e.style.display!=="none":!0,n=!!j&&j.style.display!=="none";bt.sync(n&&!t,!!ce?.hasNotableFindings)}if($e?.placement){const e=$e.placement;N=bn(e,be,p,rn);const t=M.parentElement,n=M.nextSibling;me=vn(M,N,e),Gt(me,e),t?.insertBefore(me,n),ye()}else if(ce){const e=$e?.defaultOpen??!Pe;L=bn("right",be,p,rn),L.style.display=e?"block":"none";const t=M.parentElement,n=M.nextSibling;ne=vn(M,L,"right"),Gt(ne,"right"),t?.insertBefore(ne,n),Qe()}const H=ki?mi(p):null;let fe=null,$=null,V=null,R=null,vt=null,j=null,Hn=null,pe=null,xt=null;Ln=!0;function Ut(){if(!pe||!xt)return;const e=he.length,t=e>0;if(pe.style.display=t?"flex":"none",xt.style.display=t?"":"none",!t)return;const n=No(he[0]),i=`${e} data ${e===1?"warning":"warnings"}`;pe.style.color=n==="error"?k.errText:k.warnText,pe.ariaLabel=n==="error"?`${i} \u2014 the map may be positionally wrong`:i}let Zt=null,Vn=null,Qt=null,qt=null,Jt=null,en=null;function Ee(e="selection"){Me!==null&&(Me=null,e==="selection"?O({highlightBin:void 0}):(x=new Set,de?.([])),ye())}function Yn(e){x=new Set(e??[]),de&&de(Ve()),w()}function wt(){if(!j)return;const e=!!(N??L);j.style.display=ce&&e&&!ge?"flex":"none";const t=N??L,n=t?t.style.display!=="none":!1;ce?.hasNotableFindings&&!n?j.style.color=k.findingIndicator:j.dataset.active||(j.style.color=k.icon),zn()}let Xn=null;function tn(e){const t=N??L;if(!t)return;const n=t.style.display!=="none",i=M.getBoundingClientRect().width;if(t.style.display=e?"block":"none",e!==n){const o=i-M.getBoundingClientRect().width;(S.onSummaryPanelChange??Ct)?.(e,e?o:0)}e&&Kt.has(t)&&_t(t),j&&Xn?.(j,e),wt()}if(Pe){let u=function(y){_=y,i(W,y==="zoom"),i(C,y==="pan"),vt&&i(vt,y==="select"),a.style.cursor=y==="pan"?"grab":"crosshair"};fe=p.createElement("div"),fe.dataset.wmapToolbar="single",Object.assign(fe.style,{marginLeft:"auto",flexShrink:"0",display:"flex",flexDirection:"row",alignItems:"center",flexWrap:"wrap-reverse",justifyContent:"flex-end",maxWidth:"100%",background:k.menuBg,border:`1px solid ${k.menuBorder}`,borderRadius:gi.control,boxShadow:uo.panel,pointerEvents:"auto"});const e=mi(p),t=mo(e),{makeBtn:n,setActive:i,makeSep:o,makeMenuRow:l,makeMenuSection:d,closeOpenMenu:s,getOpenMenu:r,setOpenMenu:f}=t;Xn=i,Zt=s,Vn=r,p.addEventListener("click",s,!0),V=p.createElement("div"),Object.assign(V.style,{display:Ye?"none":"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),fe.appendChild(V);const b=n("download","Download PNG",Ki);V.appendChild(b),V.appendChild(o());const W=n("zoomMode","Zoom (drag to zoom region)",()=>u("zoom")),ie=n("zoomIn","Zoom in",()=>He(a.clientWidth/2,a.clientHeight/2,1.2)),v=n("zoomOut","Zoom out",()=>He(a.clientWidth/2,a.clientHeight/2,1/1.2)),E=n("reset","Reset zoom (double-click)",()=>Je());V.appendChild(W),V.appendChild(ie),V.appendChild(v),V.appendChild(E),V.appendChild(o());const C=n("pan","Pan (drag to move)",()=>u("pan"));V.appendChild(C),vt=n("boxSelect","Select (drag to select dies)",()=>u("select")),V.appendChild(vt);{const y=n("drilldown","Chart this wafer",()=>{const Y=y.getBoundingClientRect();dn({x:Y.left,y:Y.bottom+4},y)});y.setAttribute("aria-haspopup","menu"),ut=y,qn(),V.appendChild(y)}u(_);{let y=function(h){return h.plotMode!==(c.plotMode??"hardBin")?!1:h.plotMode==="value"?(c.activeTest??0)===(h.activeTest??0):h.plotMode==="metadata"?c.activeMetadataKey===h.activeMetadataKey:!0},Y=function(h,D){h.activeTest!==void 0?O({plotMode:h.plotMode,activeTest:h.activeTest,activeMetadataKey:void 0,logScale:h.logScale}):h.activeMetadataKey!==void 0?O({plotMode:h.plotMode,activeTest:void 0,activeMetadataKey:h.activeMetadataKey,passFailDisplay:"off"}):O({plotMode:h.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),D.remove(),f(null),it(I,!1)};$=p.createElement("div"),Object.assign($.style,{display:"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),fe.appendChild($),R=p.createElement("div"),Object.assign(R.style,{display:"flex",alignItems:"center",gap:"0"}),$.appendChild(R),R.appendChild(o());const ue=()=>{const h=r();h&&(h.remove(),f(null)),it(I,!1)},I=n("mode","Plot mode",()=>{if(r()){ue();return}const h=le,D=g.testDefs,{testEntries:Bt,binEntries:ke,stackedEntries:tt}=Oo(h,D,{includeStacked:g.isLotStack}),hn=(xe??[]).filter(Be=>Ro(h,Be.key)).map(Wo),nt=yo(I.getBoundingClientRect(),Bt,ke,tt,y,Y,{makeMenuRow:l,makeMenuSection:d},c.plotMode??"hardBin",I.ownerDocument.defaultView??window,hn);bi(I).appendChild(nt),f(nt),it(I,!0),vi(nt,I,ue)});it(I,!1);const{btn:Dt,sync:et}=vo(t,()=>({...c,plotMode:c.plotMode??"hardBin"}),()=>Ii,O);qt=et,qt();const pn=Co(t,()=>{const h=!!g.hasReticle,D=(c.plotMode??"hardBin")==="value",{testNumber:Bt}=gn(c.activeTest??0,g.testDefs),ke=Lt(g.testDefs,Bt),tt=D&&ke!==void 0&&!mn(ke),hn=D&&!tt&&(ke?.limitLow!==void 0||ke?.limitHigh!==void 0),nt=D&&!tt&&g.dies.some(Be=>fo(Be,Bt,ke)!==void 0);return ko({...c,showAxes:Fn()},h,{functionalActive:tt,hasLimits:hn,hasRecorded:nt,binMode:(c.plotMode??"hardBin")==="hardBin"||(c.plotMode??"hardBin")==="softBin"},Be=>O(Be),{on:!!c.compact,offered:zi(),onChange:Be=>O({compact:Be}),onDiagnostics:()=>Lo(le,[gt],{anchor:a,onSaveText:oe.onSaveText})})},()=>Bo(c)),{btn:un,sync:Gi}=wo(t,()=>c,h=>O({legendPosition:h}));Qt=Gi,Qt();const fi=()=>{const{testNumber:h}=gn(c.activeTest??0,Z),D=Lt(Z,h);return D!==void 0&&!mn(D)},{btn:Ui,sync:Zi}=xo(t,()=>({...c,functionalActive:fi()}),h=>O(h));Jt=Zi,Jt();const Qi=()=>{const{testNumber:h}=gn(c.activeTest??0,Z),D=Lt(Z,h);return D!==void 0&&(D.limitLow!==void 0||D.limitHigh!==void 0)},kt=n("specRange","Colorbar range: test limits",()=>{const h=c.colorbarRangeMode==="data"?"spec":"data";O({colorbarRangeMode:h})});en=()=>{const h=c.plotMode==="value"&&Qi()&&Do(c)==="off"&&!fi();kt.style.display=h?"":"none";const D=(c.colorbarRangeMode??"spec")==="spec";i(kt,D),kt.ariaLabel=D?"Colorbar range: test limits (click for data range)":"Colorbar range: data range (click for test limits)"},en();const qi=So(t,()=>c,h=>O(h));R.appendChild(I),R.appendChild(Dt),R.appendChild(Ui),R.appendChild(kt),Ye||(R.appendChild(o()),R.appendChild(pn),R.appendChild(o()),R.appendChild(un),R.appendChild(o()),R.appendChild(qi)),ce&&(j=n("findings","Summary panel",()=>{const h=N??L;h&&tn(h.style.display==="none")}),$.appendChild(o()),$.appendChild(j),L?.style.display!=="none"&&i(j,!0),wt()),kn&&(xt=o(),pe=n("warning","Data warnings",()=>{const h=r();if(s(new MouseEvent("click")),h)return;const D=Xo(pe.getBoundingClientRect(),he,T);bi(Le).appendChild(D),f(D),vi(D,pe,()=>s(new MouseEvent("click")))}),it(pe,!1),$.appendChild(xt),$.appendChild(pe),Ut()),En&&($.appendChild(o()),ae=n("expand","Expand (E)",Mn??Nn),$.appendChild(ae)),Sn&&($.appendChild(o()),Hn=n("help","User guide",()=>fn()),$.appendChild(Hn))}G.appendChild(fe),Ne()}let De=null,Ct=null;function Nn(){De&&(De.close(),De=null);const e=Le;e.style.flex="1",e.style.minWidth="0",e.style.minHeight="0";const t=xn(U.metadata??{},je()),n=G.childElementCount>0?[G,e]:[e],i=bo(n,{ownerDocument:p,boxSize:ge?{width:"min(96vw, 1600px)",height:"min(92vh, 1000px)"}:void 0,onClosed:()=>{De=null,Ct=null,ae&&(ae.style.display="flex"),ge||a.focus({preventScroll:!0})}});if(!i)return;i.box.setAttribute("aria-label",t??"Expanded wafer map"),n.length>1&&(i.contentWrap.style.flexDirection="column"),De=i,Ct=Po(i);const o=N??L,l=me??ne;if(o&&l&&o.style.display!=="none"){const d=parseFloat(p.defaultView?.getComputedStyle(l).columnGap??"")||0,s=o.getBoundingClientRect().width+d;s>0&&Ct(!0,s)}ae&&(ae.style.display="none")}function $n(e){("binColorScheme"in e||"useDefinedBinColors"in e)&&!("binColors"in e)&&c.binColors!==void 0&&(e={...e,binColors:void 0});const t=c.plotMode;c={...c,...e},("compact"in e||"compactMap"in e)&&(K=null,B=null),e.plotMode!==void 0&&e.plotMode,Object.keys(e).every(l=>l==="legendPosition"||l==="showLegend"||l==="markFailingDies"||l==="showAxes")||jt(),Qt?.(),qt?.(),Jt?.(),en?.(),w();const i=e.plotMode!==void 0&&e.plotMode!==t,o=COLOR_KEYS.some(l=>l in e);(o||i)&&(ye(),Qe()),(o||i||e.activeTest!==void 0||e.logScale!==void 0||e.colorbarRangeMode!==void 0)&&st?.()}function O(e){$n(e);const t=Object.keys(e);Di?.(c,t,classifyChanged(t))}let nn=!1;const on=S.drawWhenVisible&&T.IntersectionObserver?new T.IntersectionObserver(e=>{ze=e[e.length-1].isIntersecting,ze&&St&&w()},{rootMargin:"25%"}):null;let ze=on===null,St=!1;on?.observe(a);function ln(){nn||(nn=!0,yn(()=>{nn=!1,w()},T))}function w(){if(!ze){St=!0;return}St=!1;const e=B??void 0,t=g.dies[0],n=t?{x:t.width,y:t.height}:Oe.diePitchMm,i=Math.floor(a.clientWidth||a.width),o=!!(ee?.length||te?.length||g.dies.some(b=>b.hbin!=null||b.sbin!=null)),l=c.legendPosition??"default",d=c.showLegend??!0,s=l==="default"||l==="compact",r=(Oe.colorbarWidth??16)+28,f=o&&s?l!=="default"?Math.max(pi,r):i<ao?0:i<so?Math.max(lo,r):Math.max(pi,r):void 0,u=oo(a,g,{...Oe,minRightReserve:d?f:0,showColorbar:d&&(Oe.showColorbar??!0),markFailingDies:c.markFailingDies??!1,legendPosition:l,legendOffset:Nt,diePitchMm:n,fallbackFormat:c.fallbackFormat,showAxes:Fn(),viewport:e,activeBin:c.plotMode==="metadata"?c.highlightMetadataValue:c.highlightBin,hoverBin:Xt,afterDies:x.size>0||ve!==null?Yi:void 0,hbinDefs:ee,sbinDefs:te,metadataFields:xe});mt=u.binLegendRows,Ce=u.legendBox??null,B===null&&(K=u.viewport),Ie&&ji(),qn()}function Yi(e,t,n){x.size>0&&Ni(e,t,n),ve!==null&&Xi(e,t,n)}function Xi(e,t,n){we??=new Map(g.dies.map((b,W)=>[re(b),W]));const i=ve===null?void 0:we.get(ve);if(i===void 0)return;const o=g.hoverPoints[i],l=g.rectangles[0],d=l?l.width/2*t.ppm:t.ppm*.5,s=l?l.height/2*t.ppm:t.ppm*.5,r=t.originX+o.x*t.ppm,f=t.originY-o.y*t.ppm,u=Math.max(d,s)*1.25+5;e.save(),e.setLineDash([]),e.beginPath(),e.arc(r,f,u,0,Math.PI*2),e.strokeStyle=n.background,e.lineWidth=6,e.stroke(),e.strokeStyle=n.text,e.lineWidth=3,e.stroke(),e.restore()}function Mt(e){if(ve=e===null?null:re(e),e!==null&&B!==null){Je();return}w()}function jn(){ve!==null&&(ve=null,w())}function Ni(e,t,n){const i=g.hoverPoints,o=g.rectangles[0],l=o?o.width/2*t.ppm:t.ppm*.5,d=o?o.height/2*t.ppm:t.ppm*.5,s=new Set;x.size>0&&(we??=new Map(g.dies.map((v,E)=>[re(v),E])));for(const v of x){const E=we.get(v);E!==void 0&&s.add(E)}if(!s.size)return;e.save(),e.setLineDash([]),e.fillStyle=n.background,e.globalAlpha=.7;let r=0;e.beginPath();for(let v=0;v<i.length;v++)s.has(v)||(e.rect(t.originX+i[v].x*t.ppm-l,t.originY-i[v].y*t.ppm-d,l*2,d*2),++r===ro&&(e.fill(),e.beginPath(),r=0));r&&e.fill(),e.globalAlpha=1;const{cw:f,ch:u}=$i(t,l,d),b=new Map,W=v=>Math.round(v*100),ie=(v,E,C,y)=>{const Y=`${W(v)},${W(E)},${W(C)},${W(y)}`;b.has(Y)?b.delete(Y):b.set(Y,[v,E,C,y])};for(const v of s){const E=t.originX+i[v].x*t.ppm,C=t.originY-i[v].y*t.ppm,y=E-f,Y=E+f,ue=C-u,I=C+u;ie(y,ue,Y,ue),ie(y,I,Y,I),ie(y,ue,y,I),ie(Y,ue,Y,I)}e.strokeStyle=n.text,e.lineWidth=2,e.lineCap="square",e.beginPath();for(const[v,E,C,y]of b.values())e.moveTo(v,E),e.lineTo(C,y);e.stroke(),e.restore()}function $i(e,t,n){const i=g.hoverPoints,o=g.dies;let l=0,d=0;for(let s=0;s<o.length&&(!l||!d);s++){const r=o[s];if(!(r.x==null||r.y==null))for(const f of[we.get(`${r.x+1},${r.y}`),we.get(`${r.x},${r.y+1}`)]){if(f===void 0)continue;const u=Math.abs(i[f].x-i[s].x)*e.ppm,b=Math.abs(i[f].y-i[s].y)*e.ppm;u>b?l||=u/2:d||=b/2}}return{cw:l||t,ch:d||n}}function ji(){const e=a.getContext("2d"),t=Math.min(A.x,z.x),n=Math.min(A.y,z.y),i=Math.abs(z.x-A.x),o=Math.abs(z.y-A.y);e.save(),e.fillStyle="rgba(0,0,0,0.08)",e.fillRect(t,n,i,o),e.setLineDash([5,3]),e.strokeStyle="rgba(255,255,255,0.9)",e.lineWidth=3,e.strokeRect(t,n,i,o),e.strokeStyle="rgba(0,0,0,0.9)",e.lineWidth=1.5,e.strokeRect(t,n,i,o),e.restore()}function Kn(){if(!St)return;const e=ze;ze=!0,w(),ze=e}function Ki(){Kn(),a.toBlob(e=>{e&&Mo(e,wn(),oe.onSaveImage)})}function _n(e){return K?Math.max(K.ppm*Ti,Math.min(K.ppm*Oi,e)):e}function He(e,t,n){const i=B??K;if(!i)return;const o=_n(i.ppm*n),l=o/i.ppm,d=e-(e-i.originX)*l,s=t-(t-i.originY)*l,r=(K?.snapDist??1)/(o/(K?.ppm??o));B={originX:d,originY:s,ppm:o,snapDist:r},w()}function J(){return B??K}function Gn(e){if(e.ctrlKey||e.metaKey){e.preventDefault();const t=a.getBoundingClientRect(),n=e.deltaY<0?1.12:1/1.12;He(e.clientX-t.left,e.clientY-t.top,n)}else if(B!==null){e.preventDefault();const t=J(),n=B.snapDist;B={originX:t.originX-e.deltaX,originY:t.originY-e.deltaY,ppm:t.ppm,snapDist:n},w()}}function sn(e,t,n){return e>=n.x&&e<n.x+n.w&&t>=n.y&&t<n.y+n.h}function Un(e){if(ht=!1,e.button!==0||(jn(),!J()))return;a.focus({preventScroll:!0}),a.setPointerCapture(e.pointerId);const t=a.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top;if(Ce&&c.legendPosition==="floating"&&sn(n,i,Ce)){We=!0,Ge={x:n,y:i},$t={...Nt};return}if(Ue&&_!=="pan"){Ae=!0,Se=!0,Fe={x:n,y:i},yt={x:J().originX,y:J().originY},a.style.cursor="grabbing";return}if(_==="zoom"||_==="select"){Ie=!0,A=z={x:n,y:i};return}Se=!0,Fe={x:n,y:i},yt={x:J().originX,y:J().originY},a.style.cursor="grabbing"}function Zn(e){const t=a.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top;if(Ie){z={x:n,y:i},ln();return}if(We){const u=n-Ge.x,b=i-Ge.y;u*u+b*b>16&&(We=!1,_e=!0,a.style.cursor="grabbing")}if(_e){Nt={x:$t.x+(n-Ge.x),y:$t.y+(i-Ge.y)},ln();return}if(Se){const u=J(),b=B?.snapDist??K?.snapDist??1;B={originX:yt.x+(n-Fe.x),originY:yt.y+(i-Fe.y),ppm:u.ppm,snapDist:b},ln();return}const o=J();if(!o)return;const l=(n-o.originX)/o.ppm,d=(o.originY-i)/o.ppm,r=cn(l,d,o.snapDist)?.die??null,f=mt.find(u=>n>=u.x&&n<u.x+u.w&&i>=u.y&&i<u.y+u.h);if(In(f?f.bin:void 0),f){a.style.cursor="pointer",H&&(H.textContent=f.label??`Bin ${f.bin}`,H.style.display="block",yi(H,a,e.clientX,e.clientY,{followPointer:!0})),at?.(null,e);return}_==="pan"&&(a.style.cursor=r?"crosshair":"grab"),H&&(r?(H.innerHTML=no(r,g.plotMode,{testDefs:Z,hbinDefs:ee,sbinDefs:te,fallbackFormat:c.fallbackFormat,aggrMethod:g.aggrMethod,lotSize:g.lotSize,metadataFields:xe,activeTest:g.activeTest,reticleConfig:gt}),H.style.display="block",yi(H,a,e.clientX,e.clientY,{followPointer:!0})):H.style.display="none"),at?.(r,e)}function Qn(e){const t=a.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top,o=e.ctrlKey||e.metaKey;if(H&&(n<0||i<0||n>t.width||i>t.height)&&(H.style.display="none"),Ie){Ie=!1,z={x:n,y:i};const s=n-A.x,r=i-A.y,f=J();if(_==="zoom"){if(s*s+r*r<25)He(n,i,2);else if(f){const u=Math.min(A.x,z.x),b=Math.max(A.x,z.x),W=Math.min(A.y,z.y),ie=Math.max(A.y,z.y),v=b-u,E=ie-W;if(v>4&&E>4){const C=a.clientWidth,y=a.clientHeight,Y=C/v,ue=y/E,I=Math.min(Y,ue),Dt=_n(f.ppm*I),et=Dt/f.ppm,pn=(u+b)/2,un=(W+ie)/2;B={originX:C/2-(pn-f.originX)*et,originY:y/2-(un-f.originY)*et,ppm:Dt,snapDist:f.snapDist/et}}}w(),a.style.cursor="crosshair";return}if(s*s+r*r<25)an(n,i,o,e);else if(f){const u=(Math.min(A.x,z.x)-f.originX)/f.ppm,b=(Math.max(A.x,z.x)-f.originX)/f.ppm,W=(f.originY-Math.max(A.y,z.y))/f.ppm,ie=(f.originY-Math.min(A.y,z.y))/f.ppm,v=g.hoverPoints,E=[];for(let C=0;C<v.length;C++)if(v[C].x>=u&&v[C].x<=b&&v[C].y>=W&&v[C].y<=ie){const y=g.dies[C];y&&E.push(y)}if(o)for(const C of E){const y=re(C);x.has(y)?x.delete(y):x.add(y)}else x=new Set(E.map(C=>re(C)));Ee(),de?.(Ve())}w(),a.style.cursor="crosshair";return}if(We){We=!1,an(n,i,o,e);return}if(_e){_e=!1,a.style.cursor="grab";return}if(!Se)return;if(Se=!1,Ae){Ae=!1,a.style.cursor=Ue||_==="pan"?"grab":"crosshair";return}a.style.cursor=_==="pan"?"grab":"crosshair";const l=n-Fe.x,d=i-Fe.y;l*l+d*d<25&&an(n,i,o,e)}function an(e,t,n,i){for(const s of mt)if(e>=s.x&&e<s.x+s.w&&t>=s.y&&t<s.y+s.h){Ee("legend"),typeof s.bin=="number"?O({highlightBin:Ci(c.highlightBin,s.bin,n)}):O({highlightMetadataValue:Ci(c.highlightMetadataValue,s.bin,n)});return}if(Ce&&sn(e,t,Ce))return;const o=J();if(!o)return;const d=cn((e-o.originX)/o.ppm,(o.originY-t)/o.ppm,o.snapDist)?.die??null;if(d){Ei?.(d,i);const s=re(d);n?x.has(s)?x.delete(s):x.add(s):x.size===1&&x.has(s)?x=new Set:x=new Set([s]),Ee(),de?.(Ve()),w()}else n||(x=new Set,Ee(),de?.([]),w())}function Ve(){const e=[],t=g.hoverPoints;for(let n=0;n<t.length;n++){const i=g.dies[n];i&&x.has(re(i))&&e.push(i)}return e}function qn(){ut&&(ut.style.display=pt()?"flex":"none",ut.ariaLabel=x.size>0?"Charts and tables for the selected dies (or right-click)":"Charts and tables for this wafer (or right-click)")}function Jn(){const e={waferLabel:Ot(),testDefs:Z,isLotStack:F.isLotStack,wafer:F.wafer,passBins:Re,ringCount:ot(F,"renderWaferMap"),activeTest:c.plotMode==="value"?c.activeTest:void 0};return x.size>0?jo(Ve(),e):Ko(le,e)}function rn(e,t,n){Me!==e&&t.click(),dn(n,N??L??a)}function _i(e,t){if(!pt())return;const n=c.plotMode==="softBin"?"soft":"hard",i=el(c.highlightBin),o=i.length>1&&i.includes(e)?[...i]:[e],l=[{label:Ot()??"this wafer",dies:le,wafer:F.wafer,passBins:Re,ringCount:ot(F,"renderWaferMap")}],d=xi(l,n,o,Z);if(!d)return;const s={...ft},r=o.length>1?xi(l,n,[e],Z):null;r&&(s.narrower={label:`Only ${n} bin ${e}`,backLabel:"All filtered bins",source:r,ctx:ft});const f=a;import("./drilldown.js").then(({openDrilldownMenu:u})=>{At||(Ft=u(t,f,d,s))})}function dn(e,t){if(!pt())return;const n=S.drilldownSourceOverride?.(),i=n?.source??Jn(),o={...ft,...n?.ctx};if(n?.narrowable){const l=Jn(),d=l.items.reduce((s,r)=>s+r.dies.length,0);o.narrower={label:`Only this wafer \u2014 ${d.toLocaleString()} die${d===1?"":"s"}`,source:l,ctx:ft}}import("./drilldown.js").then(({openDrilldownMenu:l})=>{At||(Ft=l(e,t,i,o))})}function ei(e){e.stopPropagation();const t=ht;if(ht=!1,!pt()||ge)return;const n=a.getBoundingClientRect();if(!t){const o=e.clientX-n.left,l=e.clientY-n.top,d=mt.find(f=>o>=f.x&&o<f.x+f.w&&l>=f.y&&l<f.y+f.h);if(d&&typeof d.bin=="number"&&!F.isLotStack&&(c.plotMode===void 0||c.plotMode==="hardBin"||c.plotMode==="softBin")){e.preventDefault(),_i(d.bin,{x:e.clientX,y:e.clientY});return}if(Ce&&sn(o,l,Ce))return;const s=J(),r=s?cn((o-s.originX)/s.ppm,(s.originY-l)/s.ppm,s.snapDist)?.die:void 0;r&&!x.has(re(r))&&(x=new Set([re(r)]),Ee(),de?.(Ve()),w())}e.preventDefault();const i=t?{x:n.left+n.width/2,y:n.top+n.height/2}:{x:e.clientX,y:e.clientY};dn(i,a)}function ti(){In(void 0),H&&Tt(p),at?.(null,new MouseEvent("mouseleave")),a.style.cursor=_==="pan"?"grab":"crosshair"}function ni(){Se=!1,Ae=!1,Ie=!1,We=!1,_e=!1,H&&Tt(p),at?.(null,new MouseEvent("mouseleave")),a.style.cursor=_==="pan"?"grab":"crosshair",w()}function cn(e,t,n){const i=g.hoverPoints,o=g.rectangles;for(let r=0;r<o.length;r++){const f=o[r];if(Math.abs(e-f.x)<=f.width/2&&Math.abs(t-f.y)<=f.height/2){const u=g.dies[r];return u?{die:u,index:r}:null}}let l=null,d=-1,s=n*n;for(let r=0;r<i.length;r++){const f=i[r].x-e,u=i[r].y-t,b=f*f+u*u;b<s&&(s=b,l=g.dies[r]??null,d=r)}return l?{die:l,index:d}:null}const ii=new T.ResizeObserver(()=>{K=null,B=null,w()});ii.observe(a),S.height==null&&Mi<=0&&yn(()=>yn(()=>{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 qe=T.matchMedia(`(resolution: ${T.devicePixelRatio}dppx)`);const Et=()=>{qe.removeEventListener("change",Et),qe=T.matchMedia(`(resolution: ${T.devicePixelRatio}dppx)`),qe.addEventListener("change",Et),w()};qe.addEventListener("change",Et);const oi=T.matchMedia("(prefers-color-scheme: dark)"),li=()=>w();oi.addEventListener("change",li);const si=()=>{H&&Tt(p)};T.addEventListener("blur",si);function ai(e){if((e.key==="ContextMenu"||e.shiftKey&&e.key==="F10")&&(ht=!0),e.key==="Escape"&&jn(),e.key==="Escape"&&x.size>0&&(x=new Set,Ee(),de?.([]),w()),(e.key==="e"||e.key==="E")&&En&&(e.stopPropagation(),(Mn??Nn)()),(e.ctrlKey||e.metaKey)&&(e.key==="="||e.key==="+"?(e.preventDefault(),He(a.clientWidth/2,a.clientHeight/2,1.2)):e.key==="-"?(e.preventDefault(),He(a.clientWidth/2,a.clientHeight/2,1/1.2)):e.key==="0"&&(e.preventDefault(),Je())),!e.ctrlKey&&!e.metaKey&&!e.shiftKey){const n=J();if(n){const i=B?.snapDist??K?.snapDist??1;let o=0,l=0;e.key==="ArrowLeft"&&(o=20,e.preventDefault()),e.key==="ArrowRight"&&(o=-20,e.preventDefault()),e.key==="ArrowUp"&&(l=20,e.preventDefault()),e.key==="ArrowDown"&&(l=-20,e.preventDefault()),(o||l)&&(B={originX:n.originX+o,originY:n.originY+l,ppm:n.ppm,snapDist:i},w())}e.key===" "&&!Ue&&(e.preventDefault(),Ue=!0,_!=="pan"&&(a.style.cursor="grab"))}}function ri(e){e.key===" "&&(Ue=!1,Ae&&(Se=!1,Ae=!1),a.style.cursor=_==="pan"?"grab":"crosshair")}a.style.cursor="crosshair",a.setAttribute("tabindex","0"),a.addEventListener("wheel",Gn,{passive:!1}),a.addEventListener("pointerdown",Un),a.addEventListener("pointermove",Zn),a.addEventListener("pointerup",Qn),a.addEventListener("pointerleave",ti),a.addEventListener("pointercancel",ni);const di=()=>Je();a.addEventListener("dblclick",di),a.addEventListener("keydown",ai),a.addEventListener("keyup",ri),a.addEventListener("contextmenu",ei);const ci=e=>{e.stopPropagation()};a.addEventListener("click",ci),a.clientWidth,w(),st?.();function Je(){K=null,B=null,w()}function fn(){import("./userGuideHtml.js").then(e=>Io({buildWaferMap:co,renderWaferMap,renderWaferGallery:void 0,analyzeWaferMap:po},e.USER_GUIDE_HTML,Bi,P))}return Ne(),{setResult(e){F=e,U=e.wafer,le=e.dies,ee=e.hbinDefs,te=e.sbinDefs,Z=e.testDefs,xe=e.metadataFields,Pn=e.reticles?.length?e.reticles:void 0,gt=e.reticleConfig,Tn=e.dataAxisFlip,zt=e.isLotStack,Ht=e.aggrMethod,Vt=e.lotSize,Wi(),jt(),w(),N&&ye()},setOptions(e){$n(e)},getOptions(){return{...c}},resetZoom:Je,setSelection(e){x=new Set(e.map(t=>re(t))),w()},getSelectedDies:()=>Ve(),clearSelection(){x=new Set,Ee(),de?.([]),w()},setFindingsNotice(e){An=e,N?ye():L&&Qe()},setStatsSummary(e){if(ce=e,Wt(),Ut(),N)ye();else if(L)Qe();else if(e&&!$e?.placement){const t=$e?.defaultOpen??!Pe;L=bn("right",be,p,rn),L.style.display=t?"block":"none";const n=M.parentElement,i=M.nextSibling;ne=vn(M,L,"right"),Gt(ne,"right"),n?.insertBefore(ne,i),Qe()}wt()},closeSummaryPanel(){tn(!1)},getExportTitle(){return wn()},getSaveImageHook(){return oe.onSaveImage},locateDie:Mt,getSaveTextHook(){return oe.onSaveText},drawPendingNow:Kn,getBinColors(){return g.binColors},setSummaryVisible(e){j&&(j.style.display=e?"flex":"none"),zn()},setViewControlsVisible(e){$&&($.style.display=e?"flex":"none")},setExpandVisible(e){ae&&(ae.style.display=e?"flex":"none")},openUserGuide:fn,setInsightsOpen(e){Ke(e)},destroy(){At=!0,It.flush();for(const e of Ze.values())e.cancel();Ze.clear(),De?.close(),Vn?.()?.remove(),Zt&&p.removeEventListener("click",Zt,!0),a.removeEventListener("wheel",Gn),a.removeEventListener("pointerdown",Un),a.removeEventListener("pointermove",Zn),a.removeEventListener("pointerup",Qn),a.removeEventListener("pointerleave",ti),a.removeEventListener("pointercancel",ni),a.removeEventListener("dblclick",di),a.removeEventListener("keydown",ai),a.removeEventListener("keyup",ri),a.removeEventListener("contextmenu",ei),Ft?.(),a.removeEventListener("click",ci),ii.disconnect(),on?.disconnect(),qe.removeEventListener("change",Et),oi.removeEventListener("change",li),T.removeEventListener("blur",si),Ri(),H&&Tt(p),fe?.remove(),me&&(me.parentElement?.insertBefore(M,me),me.remove()),ne&&(ne.parentElement?.insertBefore(M,ne),ne.remove()),M.remove(),a.style.cursor="",q?.destroy(),Q?.destroy(),Xe.remove()}}}
1
+ import{createViewSwitch as oo}from"./viewSwitch.js";import{createSummaryToggle as lo}from"./summaryToggle.js";import{buildView as so,buildHoverText as ao,findTestDef as Wt,resolveTestNumber as bn,buildMapTitle as ro}from"../renderer/buildView.js";import{drawMapCanvas as co,BIN_LEGEND_W as gi,BIN_LEGEND_W_COMPACT as fo,BIN_LEGEND_ADAPT_COMPACT as uo,BIN_LEGEND_ADAPT_FLOATING as po,PATH_SHAPES as ho}from"./toCanvas.js";import{buildWaferMap as go,getTestPassStatus as mo,isParametricTest as vn}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as yo}from"../stats/analyzeWaferMap.js";import{defaultPlotMode as bo,SHADOW as vo,LEADING as mi,wireControlHover as yi,SPACE as Y,EDGE_GUTTER as xo,RADIUS as bi,FONT as Ft,CLR as W,applyOverlayZ as wo,getTooltip as vi,hideTooltip as It,positionTooltip as xi,createToolbarHelpers as Co,buildModeMenuEl as So,openReparentedModal as Mo,makePaletteBtn as Eo,makeLogScaleBtn as Bo,makeLegendStyleBtn as ko,makeOverlaysBtn as Do,makeOrientationBtn as Lo,menuLayerFor as wi,saveImageBlob as To,markMenuTrigger as lt,wireMenuA11y as Ci,wireExpandToggle as Po,nextFrame as xn,requestedPassFailDisplay as Oo,overlayMenuRows as Ro,anyOverlayActive as Wo,openCompactDiagnostics as Fo,roomForPanel as Io,logWmapVersionOnce as Ao,buildDataModeEntries as Vo,metadataKeyHasData as zo,metadataModeEntry as Ho}from"./toolbar.js";import{openUserGuideWindow as Yo}from"./guideWindow.js";import{waferIdentityLabel as Xo}from"../core/waferLabel.js";import{metadataDisplayValue as $o}from"../core/metadata.js";import{withExportContext as Ko}from"./exportName.js";import{createSummaryPanelEl as wn,wrapWithSummaryPanel as Cn,renderWaferSummaryContentSteps as jo}from"./summaryPanel.js";import{runChunked as No}from"./chunked.js";import{collectWarnings as _o,buildWarningsMenuEl as Go,severityOf as Uo}from"./warnings.js";import{plotStoreFor as Zo}from"./plotStore.js";import{selectionPopulation as Qo,waferPopulation as qo}from"./chartPopulation.js";import{sourceFromBins as Si}from"./plotItems.js";import{createIdentityHeader as Jo,collapsedLabel as Sn}from"./identityHeader.js";import{getDieKey as re,hasPosition as Mi,isPositionedDie as el}from"../core/dies.js";import{buildDieListSection as tl}from"./dieList.js";import{buildMaplessSummary as nl}from"./maplessSummary.js";import{resolveBinColors as il,binColorWarning as ol}from"../renderer/binColors.js";import{isPassBin as ll,requirePassBins as sl}from"../core/passBins.js";import{requireRingCount as st}from"../core/ringCount.js";import{asList as al,toggleHighlight as Ei}from"../core/utils.js";import{buildCompactMap as rl,compactLayoutOffered as dl}from"../core/compact.js";const Bi=new Set(["binColorScheme","valueColorScheme","reverseValueScheme","useDefinedBinColors","rotation","flipX","flipY","showDieLabels","showRingBoundaries","showQuadrantBoundaries","showReticle","showXYIndicator","compact","showAxes","legendPosition","logScale","colorbarRangeMode","markFailingDies","fallbackFormat"]);export const COLOR_KEYS=["binColorScheme","valueColorScheme","reverseValueScheme","useDefinedBinColors","binColors"];export function classifyChanged(L){const h=L.some(u=>Bi.has(u)),v=L.some(u=>!Bi.has(u));return h&&v?"mixed":h?"preference":"state"}export function findingBin(L,h,v){const{kind:u,bin:M}=L.variable;if(!(u!=="hardBin"&&u!=="softBin"||M===void 0))return h&&ll(u,M,h,v)?void 0:M}export function findingPlotMode(L,h,v){const{kind:u}=L.variable;return u==="hardBin"||u==="softBin"?u:h==="hardBin"||h==="softBin"?h:v?"hardBin":"softBin"}export function toPublicViewOptions(L){const{metadataValueOrder:h,binColors:v,lotSize:u,compactMap:M,...at}=L;return at}export function renderWaferMap(L,h,v={}){return renderWaferMapCard(L,h,v)}export function renderWaferMapCard(L,h,v={}){Ao();const u=L.ownerDocument,M=u.defaultView??window,at=()=>I.label,At=()=>Xo({label:at(),wafer:G}),se=Ko(()=>{const e=$o(G.metadata?.lot);return{prefix:v.downloadFilename,lots:e!==void 0?[e]:[],...I.isLotStack?{stackedWafers:m?.lotSize??!0}:{wafer:At()}}},v.onSaveImage,v.onSaveText);function Mn(){const e=m.plotMode==="softBin"||m.plotMode==="stackedSoftBins"?ne:te,{primary:t,secondary:n}=ro(m,d.fallbackFormat,e);return[t,I.isLotStack?"":n].filter(Boolean).join(" ")||"wafer-map"}M.getComputedStyle(L).position==="static"&&(L.style.position="relative");const ki=L.clientHeight;v.height!=null&&(L.style.height=typeof v.height=="number"?`${v.height}px`:v.height);const Vt=h.dataCoverage?h.dataCoverage.unpositionedDies:h.dies.filter(e=>!Mi(e)).length,$e=(h.dataCoverage?h.dataCoverage.totalDies:h.dies.length-Vt)===0&&Vt>0,Ke=u.createElement("div");Object.assign(Ke.style,{display:"flex",flexDirection:"column",width:"100%",height:"100%"}),L.appendChild(Ke);const Pe=u.createElement("div");Object.assign(Pe.style,{position:"relative",width:"100%",flex:"1 1 auto",minHeight:"0"});const be=v.chromeInset??xo,$=u.createElement("div");Object.assign($.style,{display:"flex",alignItems:"stretch",gap:Y.sm,background:W.canvasBg,paddingBottom:Y.lg,paddingTop:be,paddingLeft:be,paddingRight:be,flexShrink:"0",minWidth:"0"}),Ke.appendChild($),Ke.appendChild(Pe);function Oe(){const e=[...$.children].some(t=>t.style.display!=="none");$.style.display=e?"flex":"none"}const S=u.createElement("div");Object.assign(S.style,{position:"relative",width:"100%",height:"100%"});const s=u.createElement("canvas");Object.assign(s.style,{width:"100%",height:"100%",display:"block"}),S.appendChild(s),Pe.appendChild(S);let rt=null;if(Vt>0){let n=function(){if(t){const r=tl(e,h.testDefs,{...v.dieList,onSaveText:se.onSaveText,waferMetadata:G.metadata,metadataFields:Ce,ownerDocument:u});if(r)return r}const o=Wt(h.testDefs,d.activeTest??0),l=vn(o)?d.logScale??o?.logScale??!1:!1;return nl(e,h.testDefs,{plotMode:d.plotMode??"hardBin",activeTest:d.activeTest,hbinDefs:te,sbinDefs:ne,binColors:m.binColors,valueColorScheme:d.valueColorScheme,reverseValueScheme:d.reverseValueScheme,logScale:l,colorbarRangeMode:d.colorbarRangeMode,valueRangeDies:h.dies})},i=function(o){const l=u.createElement("button");return l.type="button",yi(l),Object.assign(l.style,{fontSize:Ft.body,padding:`${Y.xxs} ${Y.sm}`,borderRadius:bi.control,flexShrink:"0",border:`1px solid ${W.menuBorder}`,background:W.menuBg,color:W.text,cursor:"pointer"}),l.textContent=t?"View chart":"View die list",l.addEventListener("click",r=>{r.stopPropagation(),t=!t,l.textContent=t?"View chart":"View die list",o()}),l};const e=h.dies.filter(o=>!Mi(o));let t=!1;if($e){const o=u.createElement("div");Object.assign(o.style,{position:"absolute",inset:"0",background:W.panelBg,padding:Y.xl,boxSizing:"border-box",overflow:"hidden",display:"flex",flexDirection:"column",gap:Y.md,zIndex:"1"});const l=u.createElement("div");Object.assign(l.style,{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:Y.md});const r=u.createElement("span");Object.assign(r.style,{fontSize:Ft.body,color:W.label,lineHeight:mi.base}),r.textContent="No die position data for this wafer.",l.appendChild(r);const a=u.createElement("div");Object.assign(a.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),l.appendChild(i(()=>a.replaceChildren(n()))),o.appendChild(l),o.appendChild(a),S.appendChild(o),rt=()=>{t||a.replaceChildren(n())}}else{const o=u.createElement("div");Object.assign(o.style,{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"3",background:W.panelBg,borderTop:`1px solid ${W.menuBorder}`,fontSize:Ft.body,color:W.text,cursor:"pointer",padding:`${Y.xs} ${Y.md}`,display:"flex",alignItems:"center",justifyContent:"space-between",gap:Y.md}),yi(o,"bare");const l=u.createElement("span");l.textContent=`+${e.length} ${e.length===1?"die":"dies"} without position data`,o.appendChild(l);const r=u.createElement("span");r.textContent="\u25BE",Object.assign(r.style,{fontSize:Ft.body,lineHeight:mi.none,color:W.label,flexShrink:"0"}),o.appendChild(r),o.setAttribute("aria-expanded","false"),o.setAttribute("aria-label",`${e.length} dies without position data. Click to view.`);let a=null,c=null;Po(o,f=>{if(r.textContent=f?"\u25B4":"\u25BE",o.setAttribute("aria-expanded",String(f)),f){a=u.createElement("div");const p=o.getBoundingClientRect().height||28;Object.assign(a.style,{position:"absolute",left:"0",right:"0",bottom:`${p}px`,top:"20%",zIndex:"2",background:W.panelBg,borderTop:`1px solid ${W.menuBorder}`,padding:Y.md,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:Y.md}),a.addEventListener("click",O=>O.stopPropagation());const y=u.createElement("div");Object.assign(y.style,{display:"flex",justifyContent:"flex-end"}),y.appendChild(i(()=>{c&&c.replaceChildren(n())})),a.appendChild(y),c=u.createElement("div"),Object.assign(c.style,{flex:"1",minHeight:"0",overflow:"auto",display:"flex",flexDirection:"column"}),c.appendChild(n()),a.appendChild(c),S.appendChild(a)}else a&&(a.remove(),a=null,c=null)}),S.appendChild(o),rt=()=>{c&&!t&&c.replaceChildren(n())}}}const{onHover:dt,onClick:Di,onSelect:de,onViewOptionsChange:Li,showTooltip:Ti=!0,showToolbar:ve=!0,showIdentity:En=!0,summaryPanel:je,showHelpButton:Bn=!1,userGuideExtension:Pi,onExpand:kn,showExpandButton:Dn=!0,zIndex:Oi,insights:Re,warnings:Ln,viewOptions:Ri={},...We}=v,ct=Re?.enabled??ve;let Ne=null;ct&&(Ne=oo(u,"Map","wafer",e=>Ge(e)),ve||(Ne.el.style.marginLeft="auto"),$.appendChild(Ne.el));const Wi=.4,Fi=20,xe=[...sl(h,"renderWaferMap")],Tn=Ln?.display??!0,Ii=wo(Oi);let ce=v.statsSummary,ge=[],Pn=!1,ft=null,On=!1;function zt(){const e=_o({result:h,statsSummary:ce,extra:ft?[ft]:[]}),t=e.length!==ge.length||e.some((n,i)=>n.code!==ge[i]?.code||n.message!==ge[i]?.message);ge=e,(t||!Pn)&&(Pn=!0,Ln?.onWarning?.(e))}zt();let I=h,G=h.wafer,ee=h.dies,x=new Set,we=null;const Ht=Re?.plotStore??Zo(Re),ut={plots:Ht,attributes:v.attributes,onSaveImage:se.onSaveImage,onSaveText:se.onSaveText,onLocateDie:e=>Tt(e)},pt=()=>!$e;let Yt=null,ht=null,gt=!1,Xt=!1,te=h.hbinDefs,ne=h.sbinDefs,U=h.testDefs,Ce=h.metadataFields,Rn=h.reticles?.length?h.reticles:void 0,mt=h.reticleConfig,Wn=h.dataAxisFlip,$t=h.isLotStack??!1,Kt=h.aggrMethod,jt=h.lotSize,Z=null,ae=null,yt=null;function bt(e){yt&&(yt.style.display=e?"flex":"none",ze?.())}En&&(Z=Jo(Sn(G.metadata??{},_e())??"",G.metadata,{lotStack:_e(),ownerDocument:u,attributes:v.attributes}),S.appendChild(Z.metaPanel),Z.metaPanel.style.visibility="visible",Z.isEmpty()||(ae=Fn(Z.wrap),$.insertBefore(ae,$.firstChild),Oe()));function Fn(e){const t=u.createElement("div");return Object.assign(t.style,{display:"flex",alignItems:"center",padding:`${Y.sm} ${Y.lg}`,flex:"1 1 auto",minWidth:"0",overflow:"hidden",gap:Y.sm}),Object.assign(e.style,{flex:"1",minWidth:"0"}),t.appendChild(e),t}function _e(){return $t?{lotSize:jt??1,aggrMethod:Kt}:void 0}function Ai(){if(!Z)return;Z.update(Sn(G.metadata??{},_e())??"",G.metadata,_e());const e=ae?.isConnected??!1,t=!Z.isEmpty();!t&&e?(ae.remove(),ae=null):t&&!e&&(ae=Fn(Z.wrap),ae.style.display="",$.insertBefore(ae,$.firstChild),Oe())}const Vi=[...te??[],...ne??[]].some(e=>e.color);let d={plotMode:bo([h.dies]),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,showReticle:!1,showXYIndicator:!1,compact:!1,rotation:0,flipX:!1,flipY:!1,legendPosition:"default",...Ri},Q=null,me=!1,In=null;function zi(){return ct?Q?Promise.resolve(Q):(In??=import("./insightsTab.js").then(({createInsightsTab:e})=>(Q=e({attributes:v.attributes,getItems:()=>[{wafer:G,dies:ee,hbinDefs:te,sbinDefs:ne,testDefs:U,label:at(),passBins:xe,statsSummary:ce}],getBinColors:()=>m.binColors,getRingCount:()=>st(I,"renderWaferMap"),onSaveImage:se.onSaveImage,onSaveText:se.onSaveText,defaultView:Re?.defaultView,plotStore:Ht,onPickPlotsFile:Re?.onPickPlotsFile,showMetadataStrip:!1,contentInset:be,onOpenGuide:Bn&&!ve?()=>hn():void 0,focusTest:t=>{P({plotMode:"value",activeTest:t,highlightBin:void 0}),Ge(!1)},locateDie:t=>{Ge(!1),Tt(t)},ownerDocument:u}),Object.assign(Q.el.style,{position:"absolute",inset:"0",background:W.canvasBg,overflowY:"auto",paddingTop:"0"}),Q.el.style.display="none",Pe.appendChild(Q.el),Q)),In):Promise.resolve(null)}let An=0;const Nt=["wheel","touchstart","pointerdown","keydown"];function Hi(e,t){if(t<=0)return;let n=!1;const i=[],o=()=>{n=!0;for(const r of i)M.clearTimeout(r);i.length=0;for(const r of Nt)e.removeEventListener(r,o)},l=()=>n||!me?!0:(e.scrollTop=t,e.scrollTop>=t);if(!l()){for(const r of Nt)e.addEventListener(r,o,{passive:!0,once:!0});for(const r of[0,50,150,300,600])i.push(M.setTimeout(()=>{l()},r));i.push(M.setTimeout(()=>{for(const r of Nt)e.removeEventListener(r,o)},700))}}function Ge(e){if(!ct)return;const t=me;me=e,Ne?.setInsightsOpen(e),Q&&!e&&t&&(An=Q.el.scrollTop),Q&&(Q.el.style.display=e?"flex":"none"),S.style.visibility=e?"hidden":"",H&&(H.style.display=e||$e?"none":"flex"),F&&(F.style.display=e?"none":"flex"),bt(!De),ie&&(ie.style.display="flex"),ae&&(ae.style.display=""),Oe(),ze?.(),Z&&e&&Z.collapse(),Je(),e&&zi().then(n=>{!n||!me||(n.el.style.display="flex",n.render(),Hi(n.el,An))})}ct&&Re?.defaultOpen&&queueMicrotask(()=>Ge(!0));let m,Se,K=null,T=null,vt=[],_t;function Vn(e){_t!==e&&(_t=e,w())}let Me=null,Gt=We.legendOffset??{x:0,y:0},Ue=!1,Fe=!1,Ze={x:0,y:0},Ut={x:0,y:0},Ee=!1,Ie=!1,j="select",Ae={x:0,y:0},xt={x:0,y:0},A={x:0,y:0},V={x:0,y:0},Qe=!1,Ve=!1;function Zt(){const e=d,t=ee.filter(el);m=so(G,t,{compact:d.compact?d.compactMap??rl(t):void 0,plotMode:e.plotMode,binColorScheme:e.binColorScheme,valueColorScheme:e.valueColorScheme,reverseValueScheme:e.reverseValueScheme,useDefinedBinColors:e.useDefinedBinColors,binColors:e.binColors??il(ee,{passBins:xe,binColorScheme:e.binColorScheme,hbinDefs:te,sbinDefs:ne,useDefinedBinColors:e.useDefinedBinColors}),passBins:xe,showDieLabels:e.showDieLabels,showRingBoundaries:e.showRingBoundaries,showQuadrantBoundaries:e.showQuadrantBoundaries,showReticle:e.showReticle,showXYIndicator:e.showXYIndicator,reticles:Rn,ringCount:st(I,"renderWaferMap"),highlightBin:e.highlightBin,highlightMetadataValue:e.highlightMetadataValue,activeTest:e.activeTest,activeMetadataKey:e.activeMetadataKey,testDefs:U,valueRange:e.valueRange,metadataValueOrder:e.metadataValueOrder,logScale:e.logScale,isLotStack:$t,aggregationMethod:Kt??e.aggregationMethod,lotSize:jt??e.lotSize,dataAxisFlip:Wn,colorbarRangeMode:e.colorbarRangeMode,passFailDisplay:e.passFailDisplay,fallbackFormat:e.fallbackFormat,interactiveTransform:{rotation:e.rotation??0,flipX:e.flipX??!1,flipY:e.flipY??!1}},{hbinDefs:te,sbinDefs:ne,metadataFields:Ce}),Se=void 0;const n=e.binColors?null:ol(m.binColors,m.plotMode);n?.message!==ft?.message&&(ft=n,zt(),On&&qt())}Zt();function zn(){return d.showAxes??We.showAxes??T!==null}function Yi(){return dl(ee,[mt])}let q=null,Be=null,fe=null,ye=null,wt=null;function Hn(){fe===null&&ye===null&&(wt={plotMode:d.plotMode,activeTest:d.activeTest})}function Yn(){P({...wt??{},highlightBin:void 0}),wt=null}let Xn=v.findingsNotice,Xi={},R=null,ue=null;function $i(e){const{kind:t,index:n}=e.variable;if(t==="test")P({plotMode:"value",activeTest:n??0,highlightBin:void 0});else{const o=ee.some(l=>l.hbin!=null);P({plotMode:findingPlotMode(e,d.plotMode,o),highlightBin:findingBin(e,xe,o)})}const i=e.highlight;(i.kind==="bin"||i.kind==="region"||i.kind==="dies")&&kt(i.dieKeys)}const qe=new Map,Qt=new WeakSet;function Ct(e){if(qe.get(e)?.cancel(),qe.delete(e),e.style.display==="none"){Qt.add(e);return}Qt.delete(e);const t=No(jo(e,{wafer:G,dies:ee,yieldSummary:I.yield,dataCoverage:I.dataCoverage,hbinDefs:te,sbinDefs:ne,testDefs:U,statsSummary:ce,warnings:Tn?ge:[],passBins:xe,ringCount:st(I,"renderWaferMap"),binColors:m.binColors,plotMode:d.plotMode??"hardBin",metadataShownElsewhere:En,fallbackFormat:d.fallbackFormat,activeFindingId:fe,findingsFilter:Xi,findingsNotice:Xn,onFindingsFilterChange:pe,onSaveText:se.onSaveText,metadataFields:Ce,dieListOptions:v.dieList,onLocateDie:n=>Tt(n),onClose:ve&&ce?()=>ln(!1):void 0,activeTest:ye,onTestClick:n=>{ye===n?(ye=null,kt([]),Yn()):(Hn(),fe=null,ye=n,P({plotMode:"value",activeTest:n,highlightBin:void 0}),kt(ce?.stats.testFailures?.[n]?.dieKeys)),pe()},onFindingClick:(n,i)=>{fe===n.id?(fe=null,kt([]),Yn()):(Hn(),ye=null,fe=n.id,$i(n)),pe()}}));t.done||qe.set(e,t)}function pe(){q?Ct(q):R&&Ct(R)}function St(){R&&Ct(R)}if(je?.placement){const e=je.placement;q=wn(e,be,u,fn);const t=S.parentElement,n=S.nextSibling;Be=Cn(S,q,e),t?.insertBefore(Be,n),pe()}else if(ce){const e=je?.defaultOpen??!ve;R=wn("right",be,u,fn),R.style.display=e?"block":"none";const t=S.parentElement,n=S.nextSibling;ue=Cn(S,R,"right"),t?.insertBefore(ue,n),St()}const z=Ti?vi(u):null;let ie=null,X=null,ze=null,H=null,F=null,Mt=null,Et=null,$n=!0,Kn=null,he=null,Bt=null;On=!0;function qt(){if(!he||!Bt)return;const e=ge.length,t=e>0;if(he.style.display=t?"flex":"none",Bt.style.display=t?"":"none",ze?.(),!t)return;const n=Uo(ge[0]),i=`${e} data ${e===1?"warning":"warnings"}`;he.style.color=n==="error"?W.errText:W.warnText,he.ariaLabel=n==="error"?`${i} \u2014 the map may be positionally wrong`:i}let Jt=null,jn=null,en=null,tn=null,nn=null,on=null;function ke(e="selection"){fe===null&&ye===null||(fe=null,ye=null,wt=null,e==="selection"?P({highlightBin:void 0}):(x=new Set,de?.([])),pe())}function kt(e){x=new Set(e??[]),de&&de(Xe()),w()}function Je(){if(!Et)return;ze?.();const e=q??R;Et.sync({visible:$n&&!!ce&&!!e&&!me,open:!!e&&e.style.display!=="none",notable:!!ce?.hasNotableFindings})}function ln(e){const t=q??R;if(!t)return;const n=t.style.display!=="none",i=S.getBoundingClientRect().width;if(t.style.display=e?"block":"none",e!==n){const o=i-S.getBoundingClientRect().width;(v.onSummaryPanelChange??Dt)?.(e,e?o:0)}e&&Qt.has(t)&&Ct(t),Je()}if(ve){let O=function(D){j=D,i(b,D==="zoom"),i(N,D==="pan"),Mt&&i(Mt,D==="select"),s.style.cursor=D==="pan"?"grab":"crosshair"};ie=u.createElement("div"),ie.dataset.wmapToolbar="single",Object.assign(ie.style,{marginLeft:"auto",flexShrink:"0",display:"flex",flexDirection:"row",alignItems:"center",flexWrap:"wrap-reverse",justifyContent:"flex-end",maxWidth:"100%",background:W.menuBg,border:`1px solid ${W.menuBorder}`,borderRadius:bi.control,boxShadow:vo.panel,pointerEvents:"auto"});const e=vi(u),t=Co(e),{makeBtn:n,setActive:i,makeSep:o,syncSeparators:l,syncToolbarVisible:r,makeMenuRow:a,makeMenuSection:c,closeOpenMenu:f,getOpenMenu:p,setOpenMenu:y}=t;ze=()=>{X&&l(X),ie&&r(ie,"flex"),Oe()},Jt=f,jn=p,u.addEventListener("click",f,!0),H=u.createElement("div"),Object.assign(H.style,{display:$e?"none":"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),ie.appendChild(H);const oe=n("download","Download PNG",Ui);H.appendChild(oe),H.appendChild(o());const b=n("zoomMode","Zoom (drag to zoom region)",()=>O("zoom")),E=n("zoomIn","Zoom in",()=>Ye(s.clientWidth/2,s.clientHeight/2,1.2)),C=n("zoomOut","Zoom out",()=>Ye(s.clientWidth/2,s.clientHeight/2,1/1.2)),B=n("reset","Reset zoom (double-click)",()=>tt());H.appendChild(b),H.appendChild(E),H.appendChild(C),H.appendChild(B),H.appendChild(o());const N=n("pan","Pan (drag to move)",()=>O("pan"));H.appendChild(N),Mt=n("boxSelect","Select (drag to select dies)",()=>O("select")),H.appendChild(Mt);{const D=n("drilldown","Chart this wafer",()=>{const le=D.getBoundingClientRect();un({x:le.left,y:le.bottom+4},D)});D.setAttribute("aria-haspopup","menu"),ht=D,ti(),H.appendChild(D)}O(j);{let D=function(g){return g.plotMode!==(d.plotMode??"hardBin")?!1:g.plotMode==="value"?(d.activeTest??0)===(g.activeTest??0):g.plotMode==="metadata"?d.activeMetadataKey===g.activeMetadataKey:!0},le=function(g,k){g.activeTest!==void 0?P({plotMode:g.plotMode,activeTest:g.activeTest,activeMetadataKey:void 0,logScale:g.logScale}):g.activeMetadataKey!==void 0?P({plotMode:g.plotMode,activeTest:void 0,activeMetadataKey:g.activeMetadataKey,passFailDisplay:"off"}):P({plotMode:g.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),k.remove(),y(null),lt(_,!1)};X=u.createElement("div"),Object.assign(X.style,{display:"flex",alignItems:"center",gap:"0",flexWrap:"wrap",justifyContent:"flex-end"}),ie.appendChild(X),F=u.createElement("div"),Object.assign(F.style,{display:"flex",alignItems:"center",gap:"0"}),X.appendChild(F),F.appendChild(o());const nt=()=>{const g=p();g&&(g.remove(),y(null)),lt(_,!1)},_=n("mode","Plot mode",()=>{if(p()){nt();return}const g=ee,k=m.testDefs,{testEntries:Rt,binEntries:Le,stackedEntries:it}=Vo(g,k,{includeStacked:m.isLotStack}),yn=(Ce??[]).filter(Te=>zo(g,Te.key)).map(Ho),ot=So(_.getBoundingClientRect(),Rt,Le,it,D,le,{makeMenuRow:a,makeMenuSection:c},d.plotMode??"hardBin",_.ownerDocument.defaultView??window,yn);wi(_).appendChild(ot),y(ot),lt(_,!0),Ci(ot,_,nt)});lt(_,!1);const{btn:gn,sync:mn}=Eo(t,()=>({...d,plotMode:d.plotMode??"hardBin"}),()=>Vi,P);tn=mn,tn();const Qi=Do(t,()=>{const g=!!m.hasReticle,k=(d.plotMode??"hardBin")==="value",{testNumber:Rt}=bn(d.activeTest??0,m.testDefs),Le=Wt(m.testDefs,Rt),it=k&&Le!==void 0&&!vn(Le),yn=k&&!it&&(Le?.limitLow!==void 0||Le?.limitHigh!==void 0),ot=k&&!it&&m.dies.some(Te=>mo(Te,Rt,Le)!==void 0);return Ro({...d,showAxes:zn()},g,{functionalActive:it,hasLimits:yn,hasRecorded:ot,binMode:(d.plotMode??"hardBin")==="hardBin"||(d.plotMode??"hardBin")==="softBin"},Te=>P(Te),{on:!!d.compact,offered:Yi(),onChange:Te=>P({compact:Te}),onDiagnostics:()=>Fo(ee,[mt],{anchor:s,onSaveText:se.onSaveText})})},()=>Wo(d)),{btn:qi,sync:Ji}=ko(t,()=>d,g=>P({legendPosition:g}));en=Ji,en();const hi=()=>{const{testNumber:g}=bn(d.activeTest??0,U),k=Wt(U,g);return k!==void 0&&!vn(k)},{btn:eo,sync:to}=Bo(t,()=>({...d,functionalActive:hi()}),g=>P(g));nn=to,nn();const no=()=>{const{testNumber:g}=bn(d.activeTest??0,U),k=Wt(U,g);return k!==void 0&&(k.limitLow!==void 0||k.limitHigh!==void 0)},Ot=n("specRange","Colorbar range: test limits",()=>{const g=d.colorbarRangeMode==="data"?"spec":"data";P({colorbarRangeMode:g})});on=()=>{const g=d.plotMode==="value"&&no()&&Oo(d)==="off"&&!hi();Ot.style.display=g?"":"none";const k=(d.colorbarRangeMode??"spec")==="spec";i(Ot,k),Ot.ariaLabel=k?"Colorbar range: test limits (click for data range)":"Colorbar range: data range (click for test limits)"},on();const io=Lo(t,()=>d,g=>P(g));F.appendChild(_),F.appendChild(gn),F.appendChild(eo),F.appendChild(Ot),$e||(F.appendChild(o()),F.appendChild(Qi),F.appendChild(o()),F.appendChild(qi),F.appendChild(o()),F.appendChild(io)),Et=lo(u,()=>{const g=q??R;g&&ln(g.style.display==="none")}),$.insertBefore(Et.el,Ne?.el??null),Je(),Tn&&(Bt=o(),he=n("warning","Data warnings",()=>{const g=p();if(f(new MouseEvent("click")),g)return;const k=Go(he.getBoundingClientRect(),ge,M);wi(Pe).appendChild(k),y(k),Ci(k,he,()=>f(new MouseEvent("click")))}),lt(he,!1),X.appendChild(Bt),X.appendChild(he),qt()),Dn&&(X.appendChild(o()),yt=n("expand","Expand (E)",kn??Nn),X.appendChild(yt)),Bn&&(X.appendChild(o()),Kn=n("help","User guide",()=>hn()),X.appendChild(Kn)),ze?.()}$.appendChild(ie),Oe()}let De=null,Dt=null;function Nn(){De&&(De.close(),De=null);const e=Pe;e.style.flex="1",e.style.minWidth="0",e.style.minHeight="0";const t=Sn(G.metadata??{},_e()),n=$.childElementCount>0?[$,e]:[e],i=Mo(n,{ownerDocument:u,boxSize:me?{width:"min(96vw, 1600px)",height:"min(92vh, 1000px)"}:void 0,onClosed:()=>{De=null,Dt=null,bt(!0),me||s.focus({preventScroll:!0})}});if(!i)return;i.box.setAttribute("aria-label",t??"Expanded wafer map"),n.length>1&&(i.contentWrap.style.flexDirection="column"),De=i,Dt=Io(i);const o=q??R,l=Be??ue;if(o&&l&&o.style.display!=="none"){const r=parseFloat(u.defaultView?.getComputedStyle(l).columnGap??"")||0,a=o.getBoundingClientRect().width+r;a>0&&Dt(!0,a)}bt(!1)}function _n(e){("binColorScheme"in e||"useDefinedBinColors"in e)&&!("binColors"in e)&&d.binColors!==void 0&&(e={...e,binColors:void 0});const t=d.plotMode;d={...d,...e},("compact"in e||"compactMap"in e)&&(K=null,T=null),e.plotMode!==void 0&&e.plotMode,Object.keys(e).every(l=>l==="legendPosition"||l==="showLegend"||l==="markFailingDies"||l==="showAxes")||Zt(),en?.(),tn?.(),nn?.(),on?.(),w();const i=e.plotMode!==void 0&&e.plotMode!==t,o=COLOR_KEYS.some(l=>l in e);(o||i)&&pe(),(o||i||e.activeTest!==void 0||e.logScale!==void 0||e.colorbarRangeMode!==void 0)&&rt?.()}function P(e){_n(e);const t=Object.keys(e);Li?.(d,t,classifyChanged(t))}let sn=!1;const an=v.drawWhenVisible&&M.IntersectionObserver?new M.IntersectionObserver(e=>{He=e[e.length-1].isIntersecting,He&&Lt&&w()},{rootMargin:"25%"}):null;let He=an===null,Lt=!1;an?.observe(s);function rn(){sn||(sn=!0,xn(()=>{sn=!1,w()},M))}function w(){if(!He){Lt=!0;return}Lt=!1;const e=T??void 0,t=m.dies[0],n=t?{x:t.width,y:t.height}:We.diePitchMm,i=Math.floor(s.clientWidth||s.width),o=!!(te?.length||ne?.length||m.dies.some(y=>y.hbin!=null||y.sbin!=null)),l=d.legendPosition??"default",r=d.showLegend??!0,a=l==="default"||l==="compact",c=(We.colorbarWidth??16)+28,f=o&&a?l!=="default"?Math.max(gi,c):i<po?0:i<uo?Math.max(fo,c):Math.max(gi,c):void 0,p=co(s,m,{...We,minRightReserve:r?f:0,showColorbar:r&&(We.showColorbar??!0),markFailingDies:d.markFailingDies??!1,legendPosition:l,legendOffset:Gt,diePitchMm:n,fallbackFormat:d.fallbackFormat,showAxes:zn(),viewport:e,activeBin:d.plotMode==="metadata"?d.highlightMetadataValue:d.highlightBin,hoverBin:_t,afterDies:x.size>0||we!==null?Ki:void 0,hbinDefs:te,sbinDefs:ne,metadataFields:Ce});vt=p.binLegendRows,Me=p.legendBox??null,T===null&&(K=p.viewport),Ie&&Gi(),ti()}function Ki(e,t,n){x.size>0&&Ni(e,t,n),we!==null&&ji(e,t,n)}function ji(e,t,n){Se??=new Map(m.dies.map((y,O)=>[re(y),O]));const i=we===null?void 0:Se.get(we);if(i===void 0)return;const o=m.hoverPoints[i],l=m.rectangles[0],r=l?l.width/2*t.ppm:t.ppm*.5,a=l?l.height/2*t.ppm:t.ppm*.5,c=t.originX+o.x*t.ppm,f=t.originY-o.y*t.ppm,p=Math.max(r,a)*1.25+5;e.save(),e.setLineDash([]),e.beginPath(),e.arc(c,f,p,0,Math.PI*2),e.strokeStyle=n.background,e.lineWidth=6,e.stroke(),e.strokeStyle=n.text,e.lineWidth=3,e.stroke(),e.restore()}function Tt(e){if(we=e===null?null:re(e),e!==null&&T!==null){tt();return}w()}function Gn(){we!==null&&(we=null,w())}function Ni(e,t,n){const i=m.hoverPoints,o=m.rectangles[0],l=o?o.width/2*t.ppm:t.ppm*.5,r=o?o.height/2*t.ppm:t.ppm*.5,a=new Set;x.size>0&&(Se??=new Map(m.dies.map((b,E)=>[re(b),E])));for(const b of x){const E=Se.get(b);E!==void 0&&a.add(E)}if(!a.size)return;e.save(),e.setLineDash([]),e.fillStyle=n.background,e.globalAlpha=.7;let c=0;e.beginPath();for(let b=0;b<i.length;b++)a.has(b)||(e.rect(t.originX+i[b].x*t.ppm-l,t.originY-i[b].y*t.ppm-r,l*2,r*2),++c===ho&&(e.fill(),e.beginPath(),c=0));c&&e.fill(),e.globalAlpha=1;const{cw:f,ch:p}=_i(t,l,r),y=new Map,O=b=>Math.round(b*100),oe=(b,E,C,B)=>{const N=`${O(b)},${O(E)},${O(C)},${O(B)}`;y.has(N)?y.delete(N):y.set(N,[b,E,C,B])};for(const b of a){const E=t.originX+i[b].x*t.ppm,C=t.originY-i[b].y*t.ppm,B=E-f,N=E+f,D=C-p,le=C+p;oe(B,D,N,D),oe(B,le,N,le),oe(B,D,B,le),oe(N,D,N,le)}e.strokeStyle=n.text,e.lineWidth=2,e.lineCap="square",e.beginPath();for(const[b,E,C,B]of y.values())e.moveTo(b,E),e.lineTo(C,B);e.stroke(),e.restore()}function _i(e,t,n){const i=m.hoverPoints,o=m.dies;let l=0,r=0;for(let a=0;a<o.length&&(!l||!r);a++){const c=o[a];if(!(c.x==null||c.y==null))for(const f of[Se.get(`${c.x+1},${c.y}`),Se.get(`${c.x},${c.y+1}`)]){if(f===void 0)continue;const p=Math.abs(i[f].x-i[a].x)*e.ppm,y=Math.abs(i[f].y-i[a].y)*e.ppm;p>y?l||=p/2:r||=y/2}}return{cw:l||t,ch:r||n}}function Gi(){const e=s.getContext("2d"),t=Math.min(A.x,V.x),n=Math.min(A.y,V.y),i=Math.abs(V.x-A.x),o=Math.abs(V.y-A.y);e.save(),e.fillStyle="rgba(0,0,0,0.08)",e.fillRect(t,n,i,o),e.setLineDash([5,3]),e.strokeStyle="rgba(255,255,255,0.9)",e.lineWidth=3,e.strokeRect(t,n,i,o),e.strokeStyle="rgba(0,0,0,0.9)",e.lineWidth=1.5,e.strokeRect(t,n,i,o),e.restore()}function Un(){if(!Lt)return;const e=He;He=!0,w(),He=e}function Ui(){Un(),s.toBlob(e=>{e&&To(e,Mn(),se.onSaveImage)})}function Zn(e){return K?Math.max(K.ppm*Wi,Math.min(K.ppm*Fi,e)):e}function Ye(e,t,n){const i=T??K;if(!i)return;const o=Zn(i.ppm*n),l=o/i.ppm,r=e-(e-i.originX)*l,a=t-(t-i.originY)*l,c=(K?.snapDist??1)/(o/(K?.ppm??o));T={originX:r,originY:a,ppm:o,snapDist:c},w()}function J(){return T??K}function Qn(e){if(e.ctrlKey||e.metaKey){e.preventDefault();const t=s.getBoundingClientRect(),n=e.deltaY<0?1.12:1/1.12;Ye(e.clientX-t.left,e.clientY-t.top,n)}else if(T!==null){e.preventDefault();const t=J(),n=T.snapDist;T={originX:t.originX-e.deltaX,originY:t.originY-e.deltaY,ppm:t.ppm,snapDist:n},w()}}function dn(e,t,n){return e>=n.x&&e<n.x+n.w&&t>=n.y&&t<n.y+n.h}function qn(e){if(gt=!1,e.button!==0||(Gn(),!J()))return;s.focus({preventScroll:!0}),s.setPointerCapture(e.pointerId);const t=s.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top;if(Me&&d.legendPosition==="floating"&&dn(n,i,Me)){Fe=!0,Ze={x:n,y:i},Ut={...Gt};return}if(Qe&&j!=="pan"){Ve=!0,Ee=!0,Ae={x:n,y:i},xt={x:J().originX,y:J().originY},s.style.cursor="grabbing";return}if(j==="zoom"||j==="select"){Ie=!0,A=V={x:n,y:i};return}Ee=!0,Ae={x:n,y:i},xt={x:J().originX,y:J().originY},s.style.cursor="grabbing"}function Jn(e){const t=s.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top;if(Ie){V={x:n,y:i},rn();return}if(Fe){const p=n-Ze.x,y=i-Ze.y;p*p+y*y>16&&(Fe=!1,Ue=!0,s.style.cursor="grabbing")}if(Ue){Gt={x:Ut.x+(n-Ze.x),y:Ut.y+(i-Ze.y)},rn();return}if(Ee){const p=J(),y=T?.snapDist??K?.snapDist??1;T={originX:xt.x+(n-Ae.x),originY:xt.y+(i-Ae.y),ppm:p.ppm,snapDist:y},rn();return}const o=J();if(!o)return;const l=(n-o.originX)/o.ppm,r=(o.originY-i)/o.ppm,c=pn(l,r,o.snapDist)?.die??null,f=vt.find(p=>n>=p.x&&n<p.x+p.w&&i>=p.y&&i<p.y+p.h);if(Vn(f?f.bin:void 0),f){s.style.cursor="pointer",z&&(z.textContent=f.label??`Bin ${f.bin}`,z.style.display="block",xi(z,s,e.clientX,e.clientY,{followPointer:!0})),dt?.(null,e);return}j==="pan"&&(s.style.cursor=c?"crosshair":"grab"),z&&(c?(z.innerHTML=ao(c,m.plotMode,{testDefs:U,hbinDefs:te,sbinDefs:ne,fallbackFormat:d.fallbackFormat,aggrMethod:m.aggrMethod,lotSize:m.lotSize,metadataFields:Ce,activeTest:m.activeTest,reticleConfig:mt}),z.style.display="block",xi(z,s,e.clientX,e.clientY,{followPointer:!0})):z.style.display="none"),dt?.(c,e)}function ei(e){const t=s.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top,o=e.ctrlKey||e.metaKey;if(z&&(n<0||i<0||n>t.width||i>t.height)&&(z.style.display="none"),Ie){Ie=!1,V={x:n,y:i};const a=n-A.x,c=i-A.y,f=J();if(j==="zoom"){if(a*a+c*c<25)Ye(n,i,2);else if(f){const p=Math.min(A.x,V.x),y=Math.max(A.x,V.x),O=Math.min(A.y,V.y),oe=Math.max(A.y,V.y),b=y-p,E=oe-O;if(b>4&&E>4){const C=s.clientWidth,B=s.clientHeight,N=C/b,D=B/E,le=Math.min(N,D),nt=Zn(f.ppm*le),_=nt/f.ppm,gn=(p+y)/2,mn=(O+oe)/2;T={originX:C/2-(gn-f.originX)*_,originY:B/2-(mn-f.originY)*_,ppm:nt,snapDist:f.snapDist/_}}}w(),s.style.cursor="crosshair";return}if(a*a+c*c<25)cn(n,i,o,e);else if(f){const p=(Math.min(A.x,V.x)-f.originX)/f.ppm,y=(Math.max(A.x,V.x)-f.originX)/f.ppm,O=(f.originY-Math.max(A.y,V.y))/f.ppm,oe=(f.originY-Math.min(A.y,V.y))/f.ppm,b=m.hoverPoints,E=[];for(let C=0;C<b.length;C++)if(b[C].x>=p&&b[C].x<=y&&b[C].y>=O&&b[C].y<=oe){const B=m.dies[C];B&&E.push(B)}if(o)for(const C of E){const B=re(C);x.has(B)?x.delete(B):x.add(B)}else x=new Set(E.map(C=>re(C)));ke(),de?.(Xe())}w(),s.style.cursor="crosshair";return}if(Fe){Fe=!1,cn(n,i,o,e);return}if(Ue){Ue=!1,s.style.cursor="grab";return}if(!Ee)return;if(Ee=!1,Ve){Ve=!1,s.style.cursor=Qe||j==="pan"?"grab":"crosshair";return}s.style.cursor=j==="pan"?"grab":"crosshair";const l=n-Ae.x,r=i-Ae.y;l*l+r*r<25&&cn(n,i,o,e)}function cn(e,t,n,i){for(const a of vt)if(e>=a.x&&e<a.x+a.w&&t>=a.y&&t<a.y+a.h){ke("legend"),typeof a.bin=="number"?P({highlightBin:Ei(d.highlightBin,a.bin,n)}):P({highlightMetadataValue:Ei(d.highlightMetadataValue,a.bin,n)});return}if(Me&&dn(e,t,Me))return;const o=J();if(!o)return;const r=pn((e-o.originX)/o.ppm,(o.originY-t)/o.ppm,o.snapDist)?.die??null;if(r){Di?.(r,i);const a=re(r);n?x.has(a)?x.delete(a):x.add(a):x.size===1&&x.has(a)?x=new Set:x=new Set([a]),ke(),de?.(Xe()),w()}else n||(x=new Set,ke(),de?.([]),w())}function Xe(){const e=[],t=m.hoverPoints;for(let n=0;n<t.length;n++){const i=m.dies[n];i&&x.has(re(i))&&e.push(i)}return e}function ti(){ht&&(ht.style.display=pt()?"flex":"none",ht.ariaLabel=x.size>0?"Charts and tables for the selected dies (or right-click)":"Charts and tables for this wafer (or right-click)")}function ni(){const e={waferLabel:At(),testDefs:U,isLotStack:I.isLotStack,wafer:I.wafer,passBins:xe,ringCount:st(I,"renderWaferMap"),activeTest:d.plotMode==="value"?d.activeTest:void 0};return x.size>0?Qo(Xe(),e):qo(ee,e)}function fn(e,t,n){fe!==e&&t.click(),un(n,q??R??s)}function Zi(e,t){if(!pt())return;const n=d.plotMode==="softBin"?"soft":"hard",i=al(d.highlightBin),o=i.length>1&&i.includes(e)?[...i]:[e],l=[{label:At()??"this wafer",dies:ee,wafer:I.wafer,passBins:xe,ringCount:st(I,"renderWaferMap")}],r=Si(l,n,o,U);if(!r)return;const a={...ut},c=o.length>1?Si(l,n,[e],U):null;c&&(a.narrower={label:`Only ${n} bin ${e}`,backLabel:"All filtered bins",source:c,ctx:ut});const f=s;import("./drilldown.js").then(({openDrilldownMenu:p})=>{Xt||(Yt=p(t,f,r,a))})}function un(e,t){if(!pt())return;const n=v.drilldownSourceOverride?.(),i=n?.source??ni(),o={...ut,...n?.ctx};if(n?.narrowable){const l=ni(),r=l.items.reduce((a,c)=>a+c.dies.length,0);o.narrower={label:`Only this wafer \u2014 ${r.toLocaleString()} die${r===1?"":"s"}`,source:l,ctx:ut}}import("./drilldown.js").then(({openDrilldownMenu:l})=>{Xt||(Yt=l(e,t,i,o))})}function ii(e){e.stopPropagation();const t=gt;if(gt=!1,!pt()||me)return;const n=s.getBoundingClientRect();if(!t){const o=e.clientX-n.left,l=e.clientY-n.top,r=vt.find(f=>o>=f.x&&o<f.x+f.w&&l>=f.y&&l<f.y+f.h);if(r&&typeof r.bin=="number"&&!I.isLotStack&&(d.plotMode===void 0||d.plotMode==="hardBin"||d.plotMode==="softBin")){e.preventDefault(),Zi(r.bin,{x:e.clientX,y:e.clientY});return}if(Me&&dn(o,l,Me))return;const a=J(),c=a?pn((o-a.originX)/a.ppm,(a.originY-l)/a.ppm,a.snapDist)?.die:void 0;c&&!x.has(re(c))&&(x=new Set([re(c)]),ke(),de?.(Xe()),w())}e.preventDefault();const i=t?{x:n.left+n.width/2,y:n.top+n.height/2}:{x:e.clientX,y:e.clientY};un(i,s)}function oi(){Vn(void 0),z&&It(u),dt?.(null,new MouseEvent("mouseleave")),s.style.cursor=j==="pan"?"grab":"crosshair"}function li(){Ee=!1,Ve=!1,Ie=!1,Fe=!1,Ue=!1,z&&It(u),dt?.(null,new MouseEvent("mouseleave")),s.style.cursor=j==="pan"?"grab":"crosshair",w()}function pn(e,t,n){const i=m.hoverPoints,o=m.rectangles;for(let c=0;c<o.length;c++){const f=o[c];if(Math.abs(e-f.x)<=f.width/2&&Math.abs(t-f.y)<=f.height/2){const p=m.dies[c];return p?{die:p,index:c}:null}}let l=null,r=-1,a=n*n;for(let c=0;c<i.length;c++){const f=i[c].x-e,p=i[c].y-t,y=f*f+p*p;y<a&&(a=y,l=m.dies[c]??null,r=c)}return l?{die:l,index:r}:null}const si=new M.ResizeObserver(()=>{K=null,T=null,w()});si.observe(s),v.height==null&&ki<=0&&xn(()=>xn(()=>{L.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 et=M.matchMedia(`(resolution: ${M.devicePixelRatio}dppx)`);const Pt=()=>{et.removeEventListener("change",Pt),et=M.matchMedia(`(resolution: ${M.devicePixelRatio}dppx)`),et.addEventListener("change",Pt),w()};et.addEventListener("change",Pt);const ai=M.matchMedia("(prefers-color-scheme: dark)"),ri=()=>w();ai.addEventListener("change",ri);const di=()=>{z&&It(u)};M.addEventListener("blur",di);function ci(e){if((e.key==="ContextMenu"||e.shiftKey&&e.key==="F10")&&(gt=!0),e.key==="Escape"&&Gn(),e.key==="Escape"&&x.size>0&&(x=new Set,ke(),de?.([]),w()),(e.key==="e"||e.key==="E")&&Dn&&(e.stopPropagation(),(kn??Nn)()),(e.ctrlKey||e.metaKey)&&(e.key==="="||e.key==="+"?(e.preventDefault(),Ye(s.clientWidth/2,s.clientHeight/2,1.2)):e.key==="-"?(e.preventDefault(),Ye(s.clientWidth/2,s.clientHeight/2,1/1.2)):e.key==="0"&&(e.preventDefault(),tt())),!e.ctrlKey&&!e.metaKey&&!e.shiftKey){const n=J();if(n){const i=T?.snapDist??K?.snapDist??1;let o=0,l=0;e.key==="ArrowLeft"&&(o=20,e.preventDefault()),e.key==="ArrowRight"&&(o=-20,e.preventDefault()),e.key==="ArrowUp"&&(l=20,e.preventDefault()),e.key==="ArrowDown"&&(l=-20,e.preventDefault()),(o||l)&&(T={originX:n.originX+o,originY:n.originY+l,ppm:n.ppm,snapDist:i},w())}e.key===" "&&!Qe&&(e.preventDefault(),Qe=!0,j!=="pan"&&(s.style.cursor="grab"))}}function fi(e){e.key===" "&&(Qe=!1,Ve&&(Ee=!1,Ve=!1),s.style.cursor=j==="pan"?"grab":"crosshair")}s.style.cursor="crosshair",s.setAttribute("tabindex","0"),s.addEventListener("wheel",Qn,{passive:!1}),s.addEventListener("pointerdown",qn),s.addEventListener("pointermove",Jn),s.addEventListener("pointerup",ei),s.addEventListener("pointerleave",oi),s.addEventListener("pointercancel",li);const ui=()=>tt();s.addEventListener("dblclick",ui),s.addEventListener("keydown",ci),s.addEventListener("keyup",fi),s.addEventListener("contextmenu",ii);const pi=e=>{e.stopPropagation()};s.addEventListener("click",pi),s.clientWidth,w(),rt?.();function tt(){K=null,T=null,w()}function hn(){import("./userGuideHtml.js").then(e=>Yo({buildWaferMap:go,renderWaferMap,renderWaferGallery:void 0,analyzeWaferMap:yo},e.USER_GUIDE_HTML,Pi,L))}return Oe(),{setResult(e){I=e,G=e.wafer,ee=e.dies,te=e.hbinDefs,ne=e.sbinDefs,U=e.testDefs,Ce=e.metadataFields,Rn=e.reticles?.length?e.reticles:void 0,mt=e.reticleConfig,Wn=e.dataAxisFlip,$t=e.isLotStack,Kt=e.aggrMethod,jt=e.lotSize,Ai(),Zt(),w(),q&&pe()},setOptions(e){_n(e)},getOptions(){return{...d}},resetZoom:tt,setSelection(e){x=new Set(e.map(t=>re(t))),w()},getSelectedDies:()=>Xe(),clearSelection(){x=new Set,ke(),de?.([]),w()},setFindingsNotice(e){Xn=e,q?pe():R&&St()},setStatsSummary(e){if(ce=e,zt(),qt(),q)pe();else if(R)St();else if(e&&!je?.placement){const t=je?.defaultOpen??!ve;R=wn("right",be,u,fn),R.style.display=t?"block":"none";const n=S.parentElement,i=S.nextSibling;ue=Cn(S,R,"right"),n?.insertBefore(ue,i),St()}Je()},closeSummaryPanel(){ln(!1)},getExportTitle(){return Mn()},getSaveImageHook(){return se.onSaveImage},locateDie:Tt,getSaveTextHook(){return se.onSaveText},drawPendingNow:Un,getBinColors(){return m.binColors},setSummaryVisible(e){$n=e,Je()},setViewControlsVisible(e){X&&(X.style.display=e?"flex":"none")},setExpandVisible(e){bt(e)},openUserGuide:hn,setInsightsOpen(e){Ge(e)},destroy(){Xt=!0,Ht.flush();for(const e of qe.values())e.cancel();qe.clear(),De?.close(),jn?.()?.remove(),Jt&&u.removeEventListener("click",Jt,!0),s.removeEventListener("wheel",Qn),s.removeEventListener("pointerdown",qn),s.removeEventListener("pointermove",Jn),s.removeEventListener("pointerup",ei),s.removeEventListener("pointerleave",oi),s.removeEventListener("pointercancel",li),s.removeEventListener("dblclick",ui),s.removeEventListener("keydown",ci),s.removeEventListener("keyup",fi),s.removeEventListener("contextmenu",ii),Yt?.(),s.removeEventListener("click",pi),si.disconnect(),an?.disconnect(),et.removeEventListener("change",Pt),ai.removeEventListener("change",ri),M.removeEventListener("blur",di),Ii(),z&&It(u),ie?.remove(),Be&&(Be.parentElement?.insertBefore(S,Be),Be.remove()),ue&&(ue.parentElement?.insertBefore(S,ue),ue.remove()),S.remove(),s.style.cursor="",Q?.destroy(),Z?.destroy(),Ke.remove()}}}