@wafertools/wafermap 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +81 -1
  2. package/README.md +20 -13
  3. package/dist/packages/canvas-adapter/chartPopulation.d.ts +8 -3
  4. package/dist/packages/canvas-adapter/chartPopulation.js +1 -1
  5. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +27 -17
  6. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/patCard.d.ts +2 -0
  8. package/dist/packages/canvas-adapter/charts/patCard.js +1 -1
  9. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +0 -7
  10. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  11. package/dist/packages/canvas-adapter/drilldown.d.ts +5 -0
  12. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  13. package/dist/packages/canvas-adapter/index.d.ts +1 -0
  14. package/dist/packages/canvas-adapter/index.js +1 -1
  15. package/dist/packages/canvas-adapter/insightsTab.d.ts +2 -0
  16. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  17. package/dist/packages/canvas-adapter/patMode.d.ts +27 -0
  18. package/dist/packages/canvas-adapter/patMode.js +1 -0
  19. package/dist/packages/canvas-adapter/pinnedTests.d.ts +10 -0
  20. package/dist/packages/canvas-adapter/pinnedTests.js +1 -0
  21. package/dist/packages/canvas-adapter/plotCard.d.ts +1 -1
  22. package/dist/packages/canvas-adapter/plotCard.js +1 -1
  23. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  24. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  25. package/dist/packages/canvas-adapter/summaryPanel.d.ts +3 -3
  26. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  27. package/dist/packages/canvas-adapter/toolbar.d.ts +7 -4
  28. package/dist/packages/canvas-adapter/toolbar.js +2 -2
  29. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  30. package/dist/packages/canvas-adapter/userGuideHtml.js +72 -92
  31. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  32. package/dist/packages/canvas-adapter/version.js +1 -1
  33. package/dist/packages/canvas-adapter/viewSwitch.js +1 -1
  34. package/dist/packages/renderer/buildWaferMap.js +1 -1
  35. package/dist/packages/renderer/derivedTests/apply.d.ts +10 -0
  36. package/dist/packages/renderer/derivedTests/apply.js +1 -1
  37. package/dist/packages/renderer/derivedTests/check.d.ts +35 -0
  38. package/dist/packages/renderer/derivedTests/check.js +1 -0
  39. package/dist/packages/renderer/fmt.d.ts +5 -0
  40. package/dist/packages/renderer/fmt.js +1 -1
  41. package/dist/packages/renderer/index.d.ts +2 -0
  42. package/dist/packages/renderer/index.js +1 -1
  43. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  44. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  45. package/dist/packages/stats/chartCatalogue.js +1 -1
  46. package/dist/packages/stats/clusterDetection.js +1 -1
  47. package/dist/packages/stats/groupCompare.d.ts +1 -1
  48. package/dist/packages/stats/groupCompare.js +1 -1
  49. package/dist/packages/stats/pat.js +1 -1
  50. package/dist/packages/stats/plotData.d.ts +7 -0
  51. package/dist/packages/stats/plotData.js +1 -1
  52. package/dist/packages/stats/reportHtml.js +33 -29
  53. package/dist/packages/stats/synthesis.d.ts +1 -1
  54. package/dist/packages/stats/synthesis.js +1 -1
  55. package/package.json +16 -5
  56. package/dist/packages/canvas-adapter/patMaps.d.ts +0 -26
  57. package/dist/packages/canvas-adapter/patMaps.js +0 -1
@@ -0,0 +1,10 @@
1
+ /** The pinned test numbers, in the order they were pinned. */
2
+ export declare function getPinnedTests(): number[];
3
+ /** Adopt a saved set of pinned tests. Does not call {@link onPinnedTestsChange}: that reports the reader's own changes only. */
4
+ export declare function setPinnedTests(testNumbers: Iterable<number>): void;
5
+ /** Called with the whole set after the reader pins or unpins a test. Returns a function that stops the calls. */
6
+ export declare function onPinnedTestsChange(listener: (testNumbers: number[]) => void): () => void;
7
+ export declare function isTestPinned(testNumber: number): boolean;
8
+ /** The reader's pin or unpin of one test. */
9
+ export declare function toggleTestPinned(testNumber: number): void;
10
+ //# sourceMappingURL=pinnedTests.d.ts.map
@@ -0,0 +1 @@
1
+ const e=new Set,o=new Set;export function getPinnedTests(){return[...e]}export function setPinnedTests(n){e.clear();for(const t of n)Number.isFinite(t)&&e.add(t)}export function onPinnedTestsChange(n){return o.add(n),()=>{o.delete(n)}}export function isTestPinned(n){return e.has(n)}export function toggleTestPinned(n){e.delete(n)||e.add(n);const t=getPinnedTests();for(const i of o)i(t)}
@@ -30,7 +30,7 @@ export interface PlotCardOptions {
30
30
  */
31
31
  drill?: (points: readonly PlotPoint[]) => CardTransform | null;
32
32
  /** What a click on a bar that drills does, in the reader's words ("see its wafers"). */
33
- drillLabel?: string;
33
+ drillLabel?: string | (() => string | undefined);
34
34
  /** Lines the card adds under its statement, for what the plot itself cannot know (two judgements disagreeing). */
35
35
  notes?: (spec: CardSpec) => string[];
36
36
  /** Controls the host owns (a test picker shared across a section, its axis settings), put before the card's own. */
@@ -1 +1 @@
1
- import{resolvePlot as k}from"../stats/plotData.js";import{fillCard as w,freezeCard as y}from"../stats/cardSpec.js";import{newPlotId as B}from"../stats/plotSpec.js";import{renderPlotChart as v}from"./charts/plotChart.js";import{makeBackButton as D,makeSegmented as A}from"./charts/chartShell.js";import{markNoPrint as P}from"./toolbar.js";export function renderPlotCard(e){let i;const f=D(()=>{i?(i=void 0,a()):e.externalBack?.onBack()},e.doc);P(f);const m={ownerDocument:e.doc,waferLabel:t=>e.items[t]?.label??"",...e.chart,onSelectPoints:e.drill||e.chart.onSelectPoints?(t,n,s,c)=>{const r=i?null:e.drill?.(t);if(r){i=r,a();return}e.chart.onSelectPoints?.(t,n,s,c)}:void 0},l=v(m),d="build"in e.spec?e.spec:void 0,p=d?.choices.map(t=>t.current)??[],h=()=>d?d.build(p):e.spec,o=()=>i?i(h()):h(),b=()=>({testDefs:e.ctx.testDefs,groupBy:e.ctx.groupBy,...e.slots?.()});if(e.editAsPlot){const t=e.editAsPlot;l.setMenuRows(()=>{const n=y(o(),{...b(),waferCount:e.items.length},B());return[{label:"Edit as plot",disabledHint:"issue"in n?n.issue:void 0,onClick:()=>{"spec"in n&&t(n.spec,{items:e.items,ctx:e.ctx})}}]})}l.actions.appendChild(f);for(const t of e.extras??[])l.actions.appendChild(t);let u=[],x;const g=()=>{const t=!!i;if(x===t)return;x=t;const n=(d?.choices??[]).map((s,c)=>{const r=A(typeof s.options=="function"?s.options(t):s.options,p[c],C=>{p[c]=C,a()},e.doc);return P(r),r});if(u.length)u.forEach((s,c)=>s.replaceWith(n[c]));else for(const s of n)l.actions.appendChild(s);u=n};function a(){g(),f.style.display=i||e.externalBack?.shown()?"":"none",m.selectActionLabel=e.drill&&!i?e.drillLabel:e.chart.selectActionLabel;const t=w(o(),b()),n="spec"in t?t.spec:{...o(),fields:{}},s=k(n,e.items,e.ctx),c=e.notes?.(o())??[],r=e.unavailable?{...s,marks:void 0,issues:[e.unavailable]}:"issue"in t?{...s,issues:[t.issue]}:c.length?{...s,notes:[...s.notes,...c]}:s;l.setPlot(r),e.onResolved?.(r)}return a(),{card:l.card,current:o,refresh:a,destroy:()=>l.destroy()}}
1
+ import{resolvePlot as k}from"../stats/plotData.js";import{fillCard as y,freezeCard as w}from"../stats/cardSpec.js";import{newPlotId as B}from"../stats/plotSpec.js";import{renderPlotChart as L}from"./charts/plotChart.js";import{makeBackButton as v,makeSegmented as D}from"./charts/chartShell.js";import{markNoPrint as g}from"./toolbar.js";export function renderPlotCard(e){let l;const p=v(()=>{l?(l=void 0,a()):e.externalBack?.onBack()},e.doc);g(p);const h={ownerDocument:e.doc,waferLabel:t=>e.items[t]?.label??"",...e.chart,onSelectPoints:e.drill||e.chart.onSelectPoints?(t,s,i,n)=>{const r=l?null:e.drill?.(t);if(r){l=r,a();return}e.chart.onSelectPoints?.(t,s,i,n)}:void 0},c=L(h),d="build"in e.spec?e.spec:void 0,u=d?.choices.map(t=>t.current)??[],b=()=>d?d.build(u):e.spec,o=()=>l?l(b()):b(),x=()=>({testDefs:e.ctx.testDefs,groupBy:e.ctx.groupBy,...e.slots?.()});if(e.editAsPlot){const t=e.editAsPlot;c.setMenuRows(()=>{const s=w(o(),{...x(),waferCount:e.items.length},B());return[{label:"Edit as plot",disabledHint:"issue"in s?s.issue:void 0,onClick:()=>{"spec"in s&&t(s.spec,{items:e.items,ctx:e.ctx})}}]})}c.actions.appendChild(p);for(const t of e.extras??[])c.actions.appendChild(t);let m=[],P;const C=()=>{const t=!!l;if(P===t)return;P=t;const s=(d?.choices??[]).map((i,n)=>{const r=D(typeof i.options=="function"?i.options(t):i.options,u[n],f=>{u[n]=f,a()},e.doc);return g(r),r});if(m.length)m.forEach((i,n)=>i.replaceWith(s[n]));else for(const i of s)c.actions.appendChild(i);m=s};function a(){C(),p.style.display=l||e.externalBack?.shown()?"":"none";const t=y(o(),x()),s=typeof e.drillLabel=="function"?e.drillLabel():e.drillLabel;h.selectActionLabel=e.drill&&!l&&s?s:e.chart.selectActionLabel;const i="spec"in t?t.spec:{...o(),fields:{}},n=k(i,e.items,e.ctx),r=e.notes?.(o())??[],f=e.unavailable?{...n,marks:void 0,issues:[e.unavailable]}:"issue"in t?{...n,issues:[t.issue]}:r.length?{...n,notes:[...n.notes,...r]}:n;c.setPlot(f),e.onResolved?.(f)}return a(),{card:c.card,current:o,refresh:a,destroy:()=>c.destroy()}}
@@ -1 +1 @@
1
- import{createViewSwitch as fs}from"./viewSwitch.js";import{createSummaryToggle as ps}from"./summaryToggle.js";import{getUniqueTestNumbers as ms,resolveTestNumber as gs,findTestDef as hs,collectMetadataValues as ys}from"../renderer/buildView.js";import{metadataCategoricalValue as bs}from"../core/metadata.js";import{resolveBinColorsForMaps as ws,mergeBinDefs as Ft,binColorWarning as vs,mixedPassBinsWarning as Ss,binColorsEqual as Cs}from"../renderer/binColors.js";import{commonPassBins as Xo,itemPassBins as ut}from"../core/passBins.js";import{requireRingCount as ne}from"../core/ringCount.js";import{NO_DATA_FILL as xs}from"../renderer/colorMap.js";import{metadataValueColor as Ms}from"../renderer/colorMap.js";import{resolveCanvasTheme as ks}from"./canvasTheme.js";import{ICONS as Dn}from"./icons.js";import{SHADOW as Bn,LEADING as Yo,TRACKING as Ds,controlStyle as Bs,wireControlHover as En,SPACE as M,EDGE_GUTTER as oe,MAP_CHROME_INSET as Es,RADIUS as q,FONT as N,CLR as v,sevColor as Uo,MODE_LABELS as Os,BIN_LEGEND_MODES as Zo,STACKED_MODES as ie,applyOverlayZ as Ts,getTooltip as Ls,hideTooltip as Qo,createToolbarHelpers as Ws,buildModeMenuEl as Rs,openDetachWindow as As,openFloatingWindow as Ps,openModal as Fs,copyWmapThemeTokens as $s,syncWmapPopupTheme as Is,makePaletteBtn as Vs,makeLogScaleBtn as Hs,makeLegendStyleBtn as js,makeOverlaysBtn as zs,makeOrientationBtn as Ns,menuLayerFor as Jo,saveImageBlob as Gs,markMenuTrigger as ft,wireMenuA11y as ei,wireTooltip as On,requestedPassFailDisplay as ti,overlayMenuRows as _s,anyOverlayActive as Ks,openCompactDiagnostics as qs,roomForPanel as ni,logWmapVersionOnce as Xs,buildDataModeEntries as Ys,metadataKeyHasData as Us,metadataModeEntry as Zs}from"./toolbar.js";import{openReportModal as Qs,openUserGuideWindow as Js,registerGuideOpener as ea}from"./guideWindow.js";import{waferDisplayLabel as pt,waferIdentityLabel as we}from"../core/waferLabel.js";import{bandButton as ta}from"./filterButton.js";import{metadataDisplayValue as na}from"../core/metadata.js";import{withExportContext as oa}from"./exportName.js";import{sortBinsForDisplay as ia}from"../stats/binPareto.js";import{diePassStatus as sa,isYieldEligibleDie as aa}from"../core/dies.js";import{aggregateValues as la,aggregateBinCounts as oi}from"../core/aggregates.js";import{renderWaferMap as ra,renderWaferMapCard as ii,toPublicViewOptions as $t}from"./renderWaferMap.js";import{waferPopulation as ca,selectionPopulation as da,LOT_STACK_REASON as Tn}from"./chartPopulation.js";import{sourceFromBins as si}from"./plotItems.js";import{plotStoreFor as ua}from"./plotStore.js";import{classifyChanged as Ln,COLOR_KEYS as fa,findingBin as pa,findingPlotMode as ma}from"./renderWaferMap.js";import{findingPatternKey as ai}from"../stats/filterFindings.js";import{synthesisSource as ga}from"../stats/synthesis.js";import{buildWaferMap as ha,computeCoverage as ya,computeYield as ba,defaultBinMode as wa,getTestPassStatus as li,isParametricTest as Wn,getDieTestValue as va,isBuiltMap as Sa}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as Rn}from"../stats/analyzeWaferMap.js";import{lotTestValueStatus as Ca}from"../stats/testValueBudget.js";import{testValueNotice as xa}from"./testValueOffer.js";import{axisPrefsFromOptions as An,optionsFromAxisPrefs as Ma,CHART_PREF_KEYS as Pn}from"./chartPrefs.js";import{collectWarnings as ka,buildWarningsMenuEl as Da,severityOf as Ba}from"./warnings.js";import{asList as Fn,compareNatural as $n,arrayEqual as It,toggleHighlight as ri}from"../core/utils.js";import{buildCompactMap as Ea,compactLayoutOffered as Oa}from"../core/compact.js";import{attachExpandableMetadata as ci}from"./identityHeader.js";import{createSummaryPanelEl as In,buildMetadataStripRow as Ta,metadataEntries as La,renderLotSummaryContentSteps as Wa,reportMapsFromItems as Ra}from"./summaryPanel.js";import{prettyKey as Aa}from"../stats/facets.js";import{testLabel as Pa,markedTestLabel as Fa,derivedFields as $a}from"../renderer/testLabel.js";import{mergeTestDefs as Ia}from"../stats/mergeTestDefs.js";import{getDieKey as Vt,hasPosition as Va}from"../core/dies.js";import{testValue as Ha}from"../core/dieTable.js";import{runChunked as ja}from"./chunked.js";function di(u){if(typeof u!="number"||!Number.isFinite(u))return;const k=Math.round(u);return k>=1?k:void 0}const Vn=12;function za(u,k,d){let z=k;if(k.length>Vn){const D=k.slice(0,Vn-1),E=k.slice(Vn-1),$=E.reduce((F,ce)=>F+ce.count,0);z=[...D,{color:v.label,count:$,label:`Other (${E.length} bins)`}]}const O=u.createElement("div");Object.assign(O.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:q.control,overflow:"hidden",border:`1px solid ${v.menuBorder}`,boxSizing:"border-box",marginTop:M.xs,flexShrink:"0"}),O.setAttribute("role","img"),O.setAttribute("aria-label",`Population split: ${z.map(D=>`${D.label} ${Ht(D.count/d*100)}`).join(", ")}`);for(const D of z){const E=D.count/d*100,$=u.createElement("div");Object.assign($.style,{flex:`${E} 1 0`,minWidth:E>0?"2px":"0",background:D.color}),On($,`${D.label} \xB7 ${D.count.toLocaleString()} dies \xB7 ${Ht(E)}`),O.appendChild($)}return O}function Ht(u){return u>0&&u<.1?"<0.1%":`${u.toFixed(1)}%`}function ui(u,k,d){const z=new Map;let O=0,D=0;for(const E of u){const $=d?new Set(d(E)):void 0;for(const F of E.dies){if(!aa(F))continue;const ce=k(F);ce!==void 0&&(z.set(ce,(z.get(ce)??0)+1),O++,$&&sa(F,$)&&D++)}}return{counts:z,total:O,pass:D}}function fi(u,k){const d=u.ownerDocument.createElement("div");Object.assign(d.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${M.xxs} ${M.xs}`,borderRadius:q.control});const z=u.ownerDocument.createElement("span");Object.assign(z.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:k.color,border:k.isActive?`2px solid ${v.iconActive}`:`1px solid ${v.menuBorder}`,borderRadius:q.control,boxSizing:"border-box"});const O=u.ownerDocument.createElement("span");if(O.textContent=k.label,Object.assign(O.style,{fontWeight:k.isActive?"700":"400",color:k.isActive?v.iconActive:v.text,whiteSpace:"nowrap"}),d.appendChild(z),d.appendChild(O),k.count!==void 0){const D=u.ownerDocument.createElement("span");if(D.textContent=k.count.toLocaleString(),Object.assign(D.style,{color:k.isActive?v.iconActive:v.text,fontWeight:k.isActive?"700":"400",whiteSpace:"nowrap"}),d.appendChild(D),k.percent!==void 0){const E=u.ownerDocument.createElement("span");E.textContent=Ht(k.percent),Object.assign(E.style,{color:v.label,whiteSpace:"nowrap"}),d.appendChild(E)}}if(d.setAttribute("role","button"),d.setAttribute("aria-pressed",k.isActive?"true":"false"),d.tabIndex=0,d.addEventListener("mouseenter",()=>{d.style.background=v.bgHover}),d.addEventListener("mouseleave",()=>{d.style.background="transparent"}),d.addEventListener("focus",()=>{d.style.background=v.bgHover}),d.addEventListener("blur",()=>{d.style.background="transparent"}),d.addEventListener("click",D=>k.onClick(D.ctrlKey||D.metaKey)),d.addEventListener("keydown",D=>{if(D.key==="Enter"||D.key===" ")D.preventDefault(),k.onClick(D.ctrlKey||D.metaKey);else if(k.onMenu&&(D.key==="ContextMenu"||D.key==="F10"&&D.shiftKey)){D.preventDefault();const E=d.getBoundingClientRect();k.onMenu({x:E.left+E.width/2,y:E.bottom},d)}}),k.onMenu){const D=k.onMenu;d.addEventListener("contextmenu",E=>{E.preventDefault(),D({x:E.clientX,y:E.clientY},d)}),On(d,"Right-click: charts and tables for these dies")}u.appendChild(d)}export function renderWaferGallery(u,k,d={}){Xs();const z=6;let O=di(d.columns);const D=d.showHelpButton??!1,E=d.userGuideExtension,$=d.insights?.enabled??!0,F=ua(d.insights),ce={enabled:!1,plotStore:F},pi=Ts(d.zIndex),Oe=d.summaryPanel,ve=e=>[...ut(e)],Hn=()=>V.flatMap(e=>e?[ne(e,"renderWaferGallery")]:[]),mt=()=>Hn()[0];function mi(e){const t=[...new Set(e)].sort((n,o)=>n-o);return t.length<2?null:{code:"ring-count-mixed",severity:"warning",message:`These wafers were built with different ring counts (${t.join(", ")}). Each card and each wafer's findings use their own; the lot's ring yield in the Summary panel, report and Insights uses ${e[0]} rings.`}}let K=d.lotStatsSummary,ze;const se=()=>Se?ze:K;let Ne=d.viewOptions?.legendPosition??"default",gt=d.perCardLegend??!1;function Ge(){const e=a.plotMode??"hardBin";return Zo.has(e)?null:a.colorbarRangeMode==="data"?"Each map has its own value range, so it keeps its own colour bar":"These wafers have no shared colour bar for value mode, so each map keeps its own"}function jn(){const e=gt||Ge()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let a={plotMode:wa(k.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...d.viewOptions},C=[],de=[],Te=[],x=[];const I=oa(()=>{const e=x.filter(n=>n!=null),t=[...new Set(e.map(n=>na(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort($n);return{prefix:d.downloadFilename,lots:t,...e.length===1?{wafer:we(e[0])}:{waferCount:e.length}}},d.onSaveImage,d.onSaveText);let V=k.map(e=>typeof e=="function"?null:e),X=null,zn=null,jt=!1,Le=0,Se=!1,zt=!1;const _e=new WeakSet,Nn=new WeakMap,Ke=()=>{const e=X?.get();return!!e&&!e.off};function Gn(e,t){return{dies:e.dies,wafer:e.wafer,label:pt(e,t),identity:we(e),waferIndex:t,passBins:ut(e),testDefs:e.testDefs,statsSummary:e.statsSummary}}const Nt=new Map;function qe(e,t){if(!X||!Ke())return e;const n=Nn.get(e);if(n&&n.v===Le)return n.item;const o=X.mark([Gn(e,t)]);let i=e;if(o.narrowing){const s=o.items[0].dies,l=s.filter(c=>!c.filteredOut);i={...e,dies:s,statsSummary:Nt.get(e),...e.yield?{yield:ba(s,[...ut(e)],e.yield.yieldPercentGross!=null?"denominator-only":"exclude")}:{},...e.dataCoverage?{dataCoverage:ya(l)}:{}},o.hidden.size&&_e.add(i)}return Nn.set(e,{v:Le,item:i}),i}const _n=new WeakMap;function gi(e,t){if(!X||!Ke())return e;const n=_n.get(e);if(n&&n.v===Le)return n.item;const o=qe(e,t),i=o===e?e:_e.has(o)?null:{...o,dies:o.dies.filter(s=>!s.filteredOut)};return _n.set(e,{v:Le,item:i}),i}function B(){return!X||!Ke()?V:V.map((e,t)=>e?gi(e,t):null)}let ht=0,yt=!1;function hi(){const e=++ht;ze=void 0,Nt.clear();const t=()=>{yt=!1,W(),le()};if(!Se){t();return}const n=Ut();if(!n||!(K||n.some(s=>s.statsSummary))){t();return}const o=B().flatMap((s,l)=>s?[{it:s,i:l}]:[]);if(o.length===0){t();return}yt=!0;const i=K?.analysisOptions??n.find(s=>s.statsSummary)?.statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(async({analyzeWaferLotAsync:s,remapLotWaferIndices:l})=>{const c=await s(o.map(p=>p.it),i);if(e!==ht||jt)return;const r=o.map(p=>p.i);ze=l(c,r),c.perWafer.forEach((p,m)=>Nt.set(V[r[m]],p.summary)),Le++,V.forEach((p,m)=>{if(!p||ie.has(a.plotMode))return;const f=qe(p,m);x[m]=f,C[m]?.setStatsSummary(f.statsSummary)}),De(),t()}).catch(()=>{e===ht&&t()})}const bt=e=>X&&Ke()?e.map((t,n)=>typeof t=="function"?t:qe(t,n)):e;function Gt(){return zn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const t=e({doc:u.ownerDocument,initial:d.insights?.filter,onChange:d.insights?.onFilterChange,savedFilters:d.insights?.savedFilters,onSavedFiltersChange:d.insights?.onSavedFiltersChange,pickFiltersFile:d.insights?.onPickFiltersFile,onSaveText:d.onSaveText,attributes:d.attributes,getRingCount:()=>ne({ringCount:mt()},"the page filter")});return jt||(X=t,ue=t.createBand(()=>Kt(),{marginLeft:oe,marginRight:oe,marginBottom:M.lg}),u.insertBefore(ue.el,U),t.subscribe(qt),t.get()&&qt()),t}),zn}let ue=null,wt=null,_t;const Kt=()=>V.flatMap((e,t)=>e?[Gn(e,t)]:[]);function Kn(){clearTimeout(_t),_t=setTimeout(()=>{if(!X||!ue)return;const e=Kt(),t=X.keep(e);ue.refresh(t.result,e),ue.el.style.display=X.get()&&!it?"":"none"},0)}function qt(){if(Le++,Se=!1,Ue>0){zt=!0,Kn();return}zt=!1;const e=a.plotMode;Se=Ke()&&V.some((t,n)=>t!==null&&qe(t,n)!==t),ze=void 0,yt=Se&&!!K,V.length>0&&(ie.has(e)?(a={...a,...At(e)},Z(Ve(e))):Z(bt(V.filter(t=>t!==null)))),Kn(),hi()}function We(){return Ia(B())}function Xe(){if(B().some(e=>e?.testDefs?.length))return We().defs}let Ye=0,Ue=0;const Q=new Map;let yi=0,vt=null,J=null,fe=null,Re=null;function St(){J===null&&fe===null&&(Re={plotMode:a.plotMode,activeTest:a.activeTest})}function qn(){Re&&R({...Re},{fireCallback:!1}),Re=null}let Xn=new Set,S=null,bi={};function Yn(e){return B()[e]?.statsSummary??se()?.perWafer.find(t=>t.waferIndex===e)?.summary}function Un(){return!!(B().some(e=>e?.statsSummary?.findings.length)||se()?.perWafer.some(e=>e.summary.findings.length))}const wi=Ls(),Ae=Ws(wi),{makeBtn:Pe,setActive:Zn,makeSep:Ce,syncSeparators:Xt,syncToolbarVisible:Yt,makeMenuRow:vi,makeMenuSection:Si,makeDropdown:Qn,closeOpenMenu:Ct,getOpenMenu:Ze,setOpenMenu:Qe}=Ae;u.ownerDocument.addEventListener("click",Ct,!0);const Jn=()=>Qo();window.addEventListener("blur",Jn);let eo=d.findingsNotice,xe=null;function Ut(){const e=V;return e.length>0&&e.every(t=>t!=null&&Sa(t))?e:null}function Ci(){return K?.stats.testValueAnalysis??Ca(B().flatMap(e=>e?.statsSummary?[e.statsSummary]:[]))}const Zt=()=>eo??(Ut()?xa(Ci(),B().length,xe!==null,xi):void 0);function xi(){const e=Ut();if(xe||!e)return;const t=new AbortController;xe=t,W();const n=K?.analysisOptions??e[0].statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(({analyzeWaferLotAsync:o})=>o(e,{...n,enableTestValueAnalysis:!0,signal:t.signal})).then(o=>{if(t.signal.aborted)return;xe=null;const i=o.perWafer.map(s=>s.summary);V=V.map((s,l)=>s&&{...s,statsSummary:i[l]}),ie.has(a.plotMode)||(x=x.map((s,l)=>s&&{...s,statsSummary:i[l]}),C.forEach((s,l)=>s?.setStatsSummary(i[l]))),K=o,De(),W(),le(),d.onStatsSummaryChange?.({summaries:i,lotStatsSummary:o})}).catch(o=>{if(!t.signal.aborted)throw xe=null,W(),o})}function Qt(){xe?.abort(),xe=null}function to(e){Xn=new Set(e);const t=[...P.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=Xn.has(i);o.style.outline=s?`3px solid ${v.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function Jt(){to([])}let xt=!1;function en(){xt=!0;for(const e of C)e&&e.clearSelection();xt=!1}function no(e){return t=>{!xt&&(J!==null||fe!==null)&&(Re=null,ke(),W()),on.set(e,t.length),ae&&!Je&&!xt&&Mi(e,t),e.onSelect?.(t)}}function pe(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),P.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let ae=!1,Je=!1,Me=new Set;function Mi(e,t){Je=!0;try{Me=new Set(t.map(n=>Vt(n))),x.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>Me.has(Vt(s))))})}finally{Je=!1}Ot()}function oo(){Me=new Set,Je=!0;try{for(const e of C)e?.clearSelection()}finally{Je=!1}Ot()}function tn(){if(!ae||Me.size===0)return;const e=[];let t=!1;if(x.forEach((i,s)=>{if(!i)return;const l=i.dies.filter(c=>Me.has(Vt(c)));l.length!==0&&(i.isLotStack&&(t=!0),e.push({label:we(i)??i.label??`Wafer ${s+1}`,dies:l,waferIndex:s,wafer:i.wafer,passBins:ve(i),ringCount:ne(i,"renderWaferGallery")}))}),e.length===0)return;const n=We(),o=a;return{source:{items:e,population:e.length===1?`selected on ${e[0].label}`:`selected at the same die positions on ${e.length} wafers`,testDefs:n.defs,activeTest:o.plotMode==="value"?o.activeTest:void 0,notMeasuredReason:t?Tn:void 0},ctx:{plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,onSaveImage:I.onSaveImage,onSaveText:I.onSaveText,onLocateDie:(i,s)=>pe(s,i)}}}function io(){const e=[];let t=!1;if(x.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:we(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:ve(o),ringCount:ne(o,"renderWaferGallery")}))}),e.length<2)return;const n=a;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:We().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Tn:void 0},ctx:{plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,onSaveImage:I.onSaveImage,onSaveText:I.onSaveText,onLocateDie:(o,i)=>pe(i,o)}}}function ki(e){const t=tn()??lo(e);if(t)return t;const n=io(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function nn(e,t,n){J!==e&&t.click();const o=S;if(!o)return;const i=se()?.findings.find(l=>l.id===e),s=tn()??io()??Bi()??(i?so(ro(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:l})=>{o.isConnected&&l(n,o,s.source,{plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,...s.ctx})})}function Di(e,t,n,o){const i=Fn(a.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],l=[];let c=!1;x.forEach((h,y)=>{h&&(h.isLotStack&&(c=!0),l.push({label:we(h)??h.label??`Wafer ${y+1}`,dies:h.dies,waferIndex:y,wafer:h.wafer,passBins:ve(h),ringCount:ne(h,"renderWaferGallery")}))});const r=We().defs,p=si(l,e,s,r,void 0,c);if(!p)return;const m={plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,onSaveImage:I.onSaveImage,onSaveText:I.onSaveText,onLocateDie:(h,y)=>pe(y,h)},f=s.length>1?si(l,e,[t],r,void 0,c):null,g=f?{...m,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:f,ctx:m}}:m;import("./drilldown.js").then(({openDrilldownMenu:h})=>{o.isConnected&&h(n,o,p,g)})}function so(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((l,c)=>l-c)){const l=x[s];l&&(l.isLotStack&&(o=!0),n.push({label:we(l)??l.label??`Wafer ${s+1}`,dies:l.dies,waferIndex:s,wafer:l.wafer,passBins:ve(l),ringCount:ne(l,"renderWaferGallery")}))}if(n.length===0)return;const i=a;return{source:{items:n,population:n.length===1?`on ${n[0].label}`:`on ${n.length} ${t}wafers`,testDefs:We().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Tn:void 0},ctx:{plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,onSaveImage:I.onSaveImage,onSaveText:I.onSaveText,onLocateDie:(s,l)=>pe(l,s)}}}function Bi(){let e;for(let i=0;i<C.length;i++)if((C[i]?.getSelectedDies().length??0)!==0){if(e!==void 0)return;e=i}const t=e===void 0?void 0:x[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=a;return{source:da(n,{waferLabel:we(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:ve(t),ringCount:ne(t,"renderWaferGallery")}),ctx:{onSaveImage:I.onSaveImage,onSaveText:I.onSaveText,onLocateDie:(i,s)=>pe(s??e,i)}}}function Ei(e){e||oo(),ae=e,Ot()}function Mt(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=x[i],l=C[i];if(!s||!l)continue;const c=s.dies.filter(r=>n.has(Vt(r)));l.setSelection(c)}}const Y=new Set,on=new Map;function ao(){[...P.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=Y.has(o)?`2px solid ${v.iconActive}`:"",n.style.outlineOffset=Y.has(o)?"-2px":""});const t=Y.size;ee.style.display=t>0?"":"none",ee.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,ee.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function Oi(e){e<0||(Y.has(e)?Y.delete(e):Y.add(e),ao())}function Ti(){Y.clear(),ao()}function lo(e){if(!(Y.size===0||!Y.has(e))){for(const t of on.values())if(t>0)return;return so([...Y],"picked ")}}function Li(){const e=[];for(let t=0;t<B().length;t++){const n=B()[t];if(!n)continue;const o=Yn(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 Wi(e){const t=x[e]??B()[e];t&&rt(e,t)}function Ri(e){const t=Yn(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 Ai(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{Qs(e(Ra(B(),mt())),{anchor:u})})}function Pi(){if(!S)return;S.innerHTML="";const e=Li();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:N.body,color:v.label,marginBottom:M.md}),S.appendChild(n)}if(e.length>0){const n=u.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{...Bs("outlined"),marginBottom:M.lg,display:"block",width:"100%",textAlign:"left"}),En(n),n.addEventListener("click",Ai),S.appendChild(n)}if(e.length===0){const n=u.ownerDocument.createElement("div");Object.assign(n.style,{color:v.icon,fontSize:N.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",S.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:l}of e){const c=i?"unusual":s?"notable":"info",r=i+s||l,p=u.ownerDocument.createElement("button");p.type="button",Object.assign(p.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:M.xs,border:"none",borderLeft:`3px solid ${Uo(c)}`,borderRadius:q.control,background:v.bgHover,cursor:"pointer",fontSize:N.body,textAlign:"left",boxSizing:"border-box"}),p.addEventListener("mouseover",()=>{p.style.background=v.bgActive}),p.addEventListener("mouseout",()=>{p.style.background=v.bgHover});const m=u.ownerDocument.createElement("span");m.textContent=pt(o,n),Object.assign(m.style,{color:v.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const f=u.ownerDocument.createElement("span");f.textContent=String(r),p.setAttribute("aria-label",`${pt(o,n)} \u2014 ${r} finding${r===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(f.style,{marginLeft:M.sm,flexShrink:"0",background:Uo(c),color:"#fff",borderRadius:q.container,padding:"1px 5px",fontSize:N.body,fontWeight:"600"}),p.appendChild(m),p.appendChild(f),p.addEventListener("click",()=>rt(n,o)),S.appendChild(p)}const t=u.ownerDocument.createElement("div");t.style.height="12px",S.appendChild(t)}let Fe=null,et=null;function W(){if(!S||Se&&K&&!ze&&yt)return;Fe?.cancel(),Fe=null;const e=se();if(e){const t=Ft(B().map(o=>o?.hbinDefs)),n=Ft(B().map(o=>o?.sbinDefs));Fe=ja(Wa(S,{lotSummary:e,items:B(),hbinDefs:t.length?t:void 0,sbinDefs:n.length?n:void 0,testDefs:Xe(),ringCount:mt(),binColors:a.binColors,plotMode:a.plotMode??"hardBin",fallbackFormat:a.fallbackFormat,activeFindingId:J,warnings:d.warnings?.display??!0?me:[],findingsFilter:bi,findingsNotice:Zt(),onFindingsFilterChange:W,onSaveText:I.onSaveText,attributes:d.attributes,onFindingClick:(o,i)=>{J===o.id?(ke(),qn()):(St(),mo(o,i)),W()},activeTest:fe,onTestClick:o=>{const i=fe===o;i||St(),ke(),i?qn():po(o),W()},onShowChart:$?o=>{st(!0),To().then(i=>i?.showWorthCard(o))}:void 0,onWaferClick:Wi,findingsFor:Ri,dieListOptions:d.dieList,onLocateDie:(o,i)=>pe(i,o),onClose:()=>an(!1)}),{onDone:()=>{const o=et;et=null,o?.()}})}else Pi()}function ro(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let kt=[];function co(){if(kt.length!==0){for(const e of kt)C[e]?.setOptions({plotMode:a.plotMode,activeTest:a.activeTest});kt=[]}}function ke(){J=null,fe=null,Jt(),en(),co(),R({highlightBin:void 0},{fireCallback:!1})}function uo(){J===null&&fe===null||(Re=null,ke(),W())}function fo(e,t){const n=Xe();if(n===void 0||n.some(i=>i.testNumber===e))R({plotMode:"value",activeTest:e,highlightBin:void 0},{fireCallback:!1});else{R({highlightBin:void 0},{fireCallback:!1});const s=ie.has(a.plotMode??"hardBin")?null:t;if(s){for(const l of s)C[l]?.setOptions({plotMode:"value",activeTest:e});kt=[...s]}}}function po(e){fe=e;const t=o=>x[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=x.map((o,i)=>i).filter(o=>t(o)?.length);if(fo(e,n.length?n:null),Jt(),en(),!ie.has(a.plotMode??"hardBin"))for(const o of n)Mt(t(o),[o])}function mo(e,t){if(J===e.id){ke();return}J=e.id,fe=null,t&&(t.style.background=v.bgActive,t.style.fontWeight="600"),co();const{kind:n,index:o}=e.variable;if(n==="test")fo(o??0,ro(e));else{const s=x.some(c=>c?.dies?.some(r=>r.hbin!=null)),l=Xo(x.map(c=>c?ut(c):void 0));R({plotMode:ma(e,a.plotMode,s),highlightBin:pa(e,l,s)},{fireCallback:!1})}Jt(),en();const i=e.highlight;if(i.kind==="wafer"){to(i.waferIndices);const s=ai(e);for(const l of i.waferIndices){const c=i.dieKeysByWafer?void 0:x[l]?.statsSummary?.findings.find(p=>ai(p)===s),r=i.dieKeysByWafer?.[l]??c?.highlight?.dieKeys;r?.length&&Mt(r,[l])}}else i.kind==="bin"?i.dieKeys?.length&&Mt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Mt(i.dieKeys)}function sn(){return!!S&&S.style.display!=="none"}function an(e){!S||e===sn()||(e&&W(),S.style.display=e?"flex":"none",le())}function le(){vt&&(Xt(H),Yt(H,"inline-flex"),vt.sync({visible:!!(K||se()||Un())&&!!S&&!it,open:sn(),notable:!!(se()?.hasNotableFindings||B().some(e=>e?.statsSummary?.hasNotableFindings))}))}const H=u.ownerDocument.createElement("div");H.dataset.wmapToolbar="gallery",Object.assign(H.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:q.control,padding:"0",boxShadow:Bn.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const go=()=>{const e=Ze();e&&(e.remove(),Qe(null)),ft(re,!1)},re=Pe("mode","Plot mode",()=>{if(Ze()){go();return}const e=B().flatMap(w=>w?.dies??[]),t=Xe(),{testEntries:n,binEntries:o,stackedEntries:i}=Ys(e,t,{includeStacked:!0}),s=B().filter(Boolean).length,l=w=>{if(w===void 0)return s;let T=0;for(const A of B())A?.dies?.some(j=>li(j,w)!==void 0||Ha(j,w)!==void 0)&&T++;return T},c=s<2?n:n.map(w=>{const T=l(w.activeTest);return T===s?w:{...w,label:`${w.label} \u2014 ${T} of ${s} wafers`}}),r=a.plotMode??"hardBin",p=a.activeTest??0;function m(w){return w.plotMode!==r?!1:w.plotMode==="value"?p===(w.activeTest??0):w.plotMode==="metadata"?a.activeMetadataKey===w.activeMetadataKey:!0}function f(w,T){w.activeTest!==void 0?R({plotMode:"value",activeTest:w.activeTest,activeMetadataKey:void 0,logScale:w.logScale}):w.activeMetadataKey!==void 0?R({plotMode:w.plotMode,activeTest:void 0,activeMetadataKey:w.activeMetadataKey,passFailDisplay:"off"}):R({plotMode:w.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),T.remove(),Qe(null),ft(re,!1)}const g=new Set,h=B().flatMap(w=>w?.metadataFields??[]).filter(w=>!g.has(w.key)&&g.add(w.key)).filter(w=>Us(e,w.key)).map(Zs),y=Rs(re.getBoundingClientRect(),c,o,i,m,f,{makeMenuRow:vi,makeMenuSection:Si},r,re.ownerDocument.defaultView??window,h);Jo(re).appendChild(y),Qe(y),ft(re,!0),ei(y,re,go)});ft(re,!1);const Fi=()=>x.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:$i,sync:ho}=Vs(Ae,()=>({...a,plotMode:a.plotMode??"hardBin"}),Fi,e=>R(e));ho();const Ii=k.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function Dt(){const e=Xe(),{testNumber:t}=gs(a.activeTest??0,e);return{testNumber:t,td:hs(e,t)}}function yo(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Dt();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function tt(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Dt();return e!==void 0&&!Wn(e)}function Vi(){if((a.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=Dt();return B().some(n=>n?.dies?.some(o=>li(o,e,t)!==void 0))}function Hi(e,t){if(!t||!Wn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((ti(a)==="spec"&&n?"spec":a.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,l=-1/0;for(const c of B())if(c)for(const r of c.dies){const p=va(r,e);p!==void 0&&(p<s&&(s=p),p>l&&(l=p))}if(isFinite(s))return s===l?[s,s+1]:[s,l]}function Bt(e,t,n){const o=a[e];if(o===t||o!=null&&t!=null&&n(o,t))return!1;a={...a,[e]:t};for(const i of C)i&&i.setOptions({[e]:t});return!0}function bo(){if((a.plotMode??"hardBin")!=="metadata")return;const e=a.activeMetadataKey;if(!e)return;const t=new Set;for(const n of B())if(n)for(const o of ys(n.dies,e))t.add(o);return{key:e,values:[...t].sort($n)}}function ln(){Bt("metadataValueOrder",bo(),(e,t)=>e.key===t.key&&It(e.values,t.values))}function rn(){if((a.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=Dt(),n=Hi(e,t);Bt("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const l=p=>Array.isArray(p)?{test:void 0,range:p}:{test:p.test,range:p.range},c=l(i),r=l(s);return c.test===r.test&&It(c.range,r.range)})}let cn=!1;function ji(){if(cn)return;cn=!0,(u.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{cn=!1,rn(),ln(),Co(),So()})}let dn=!1;function zi(){if(dn)return;dn=!0,(u.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{dn=!1,Rt()})}let wo=[];function G(){const{colors:e,mixedHardBins:t}=ws(B().filter(n=>n!=null),{binColorScheme:a.binColorScheme,useDefinedBinColors:a.useDefinedBinColors});return wo=t,e}function un(){return x.filter(e=>e!=null).flatMap(e=>e.dies)}function vo(){return a.compact?Ea(un()):void 0}const Ni=(e,t)=>It(e.columns,t.columns)&&It(e.rows,t.rows);function So(){Bt("compactMap",vo(),Ni)&&Po()}function Gi(){return Oa(un(),x.filter(e=>e!=null).map(e=>e.reticleConfig))}function Co(){Bt("binColors",G(),Cs),De()}const _i=zs(Ae,()=>_s(a,Ii,{functionalActive:tt(),hasLimits:yo()&&!tt(),hasRecorded:Vi()&&!tt(),binMode:(a.plotMode??"hardBin")==="hardBin"||(a.plotMode??"hardBin")==="softBin"},e=>R(e),{on:!!a.compact,offered:Gi(),onChange:e=>R({compact:e}),onDiagnostics:()=>qs(un(),x.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:u,onSaveText:I.onSaveText})}),()=>Ks(a)),{btn:Ki,sync:xo}=js(Ae,()=>({plotMode:a.plotMode,legendPosition:Ne}),e=>{Ne=e;for(const t of C)t&&t.setOptions({legendPosition:Ne})},{get:()=>gt,set:e=>{gt=e,jn()},blockedReason:Ge});xo();const qi=[{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"}],Mo=Qn("aggr","Aggregation method",()=>qi,()=>a.aggregationMethod??"mean",e=>R({aggregationMethod:e}));function ko(){const e=a.plotMode==="stackedValues";Mo.style.display=e?"":"none"}ko();const{btn:Xi,sync:Do}=Hs(Ae,()=>({...a,functionalActive:tt()}),e=>R(e));Do();const Et=Pe("specRange","Colorbar range: test limits",()=>{const e=a.colorbarRangeMode==="data"?"spec":"data";R({colorbarRangeMode:e})});function Bo(){const e=(a.plotMode??"hardBin")==="value"&&yo()&&ti(a)==="off"&&!tt();Et.style.display=e?"":"none";const t=(a.colorbarRangeMode??"spec")==="spec";Zn(Et,t),Et.ariaLabel=t?"Colorbar range: test limits (click for data range)":"Colorbar range: data range (click for test limits)"}Bo();const Yi=Ns(Ae,()=>a,e=>R(e)),Ui=Pe("downloadAll","Download gallery PNG",cs),$e=Pe("boxSelect","Select the same dies on every wafer",()=>{ae&&Me.size>0?oo():Ei(!ae)});$e.style.position="relative";const nt=u.ownerDocument.createElement("span");nt.dataset.wmapSelectAcrossCount="1",Object.assign(nt.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:q.pill,background:v.iconActive,color:v.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),$e.appendChild(nt);function Ot(){Zn($e,ae);const e=ae?Me.size:0;nt.style.display=e>0?"block":"none",nt.textContent=e>99?"99+":String(e),$e.ariaLabel=ae?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)",$e.setAttribute("aria-pressed",String(ae))}const ee=u.ownerDocument.createElement("button");ee.type="button",ee.dataset.wmapPickedWafers="1",Object.assign(ee.style,{display:"none",border:"none",background:v.bgActive,color:v.iconActive,borderRadius:q.control,padding:`${M.xs} ${M.md}`,fontSize:N.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),En(ee,"bare"),ee.addEventListener("click",Ti);const Zi=Qn("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=>Io(e==="auto"?void 0:Number(e))),L=u.ownerDocument.createElement("div");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:"0"}),H.appendChild(L),L.appendChild(re),L.appendChild($i),L.appendChild(Mo),L.appendChild(Xi),L.appendChild(Et),L.appendChild(Ce()),L.appendChild(_i),L.appendChild(Ce()),L.appendChild(Ki),L.appendChild(Ce()),L.appendChild(Yi),L.appendChild(Ce()),L.appendChild(Zi),L.appendChild(Ce()),L.appendChild($e),L.appendChild(ee),L.appendChild(Ui),Ot();let te=null,Tt=null,me=[],Eo=!1;function De(){const e=ka({lotStatsSummary:se(),result:{warnings:[...B().flatMap(n=>n?.warnings??[]),...We().warnings]},extra:[a.binColors&&vs(a.binColors,a.plotMode),Ss(wo),mi(Hn())].filter(n=>!!n)}),t=e.length!==me.length||e.some((n,o)=>n.code!==me[o]?.code||n.message!==me[o]?.message);me=e,(t||!Eo)&&(Eo=!0,d.warnings?.onWarning?.(e)),Qi()}function Qi(){if(!te||!Tt)return;const e=me.length,t=e>0;if(te.style.display=t?"flex":"none",Tt.style.display=t?"":"none",Xt(H),Yt(H,"inline-flex"),!t)return;const n=Ba(me[0]),o=`${e} data ${e===1?"warning":"warnings"}`;te.style.color=n==="error"?v.errText:v.warnText,te.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(d.warnings?.display??!0)&&(Tt=Ce(),te=Pe("warning","Data warnings",()=>{const e=Ze();if(Ct(new MouseEvent("click")),e)return;const t=Da(te.getBoundingClientRect(),me,te.ownerDocument.defaultView??window);Jo(u).appendChild(t),Qe(t),ei(t,te,()=>Ct(new MouseEvent("click")))}),ft(te,!1),H.appendChild(Tt),H.appendChild(te)),De();function fn(e){import("./userGuideHtml.js").then(t=>Js({buildWaferMap:ha,renderWaferMap:ra,renderWaferGallery,analyzeWaferMap:Rn},t.USER_GUIDE_HTML,E,u,e))}const Ji=ea(e=>fn(e));D&&(H.appendChild(Ce()),H.appendChild(Pe("help","User guide",()=>fn())));const Ie=u.ownerDocument.createElement("div");Ie.dataset.wmapGalleryMeta="1",Object.assign(Ie.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${M.sm} ${M.lg}`,fontSize:N.sub,lineHeight:Yo.none,boxSizing:"border-box"});const Be=u.ownerDocument.createElement("div");Object.assign(Be.style,{background:v.canvasBg,display:"flex",alignItems:"stretch",gap:M.lg,paddingBottom:M.lg,minWidth:"0"});const ge=u.ownerDocument.createElement("div");ge.dataset.wmapGalleryLegend="1",Object.assign(ge.style,{display:"flex",flexDirection:"column",gap:M.sm,background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:q.container,padding:`${M.sm} ${M.lg}`,marginBottom:M.lg,boxShadow:Bn.panel,fontSize:N.body,lineHeight:Yo.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const U=u.ownerDocument.createElement("div");Object.assign(U.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let he=null,ot=null,Oo=null;function To(){return $?he?Promise.resolve(he):(Oo??=Promise.all([import("./insightsTab.js"),Gt()]).then(([{createInsightsTab:e},t])=>(he=e({pageFilter:t,showFilterButton:!1,initialAxisPrefs:An(a),onAxisPrefsChange:n=>{a={...a,...Ma(n)};const o=[...Pn];d.onViewOptionsChange?.($t(a),o,Ln(o))},attributes:d.attributes,getItems:()=>V,getLotStats:()=>K,getBinColors:()=>a.binColors??G(),getRingCount:()=>ne({ringCount:mt()},"the Insights tab"),defaultView:d.insights?.defaultView,plotStore:F,onPickPlotsFile:d.insights?.onPickPlotsFile,showOnMap:n=>{if(st(!1),n.kind==="test")St(),ke(),po(n.testNumber);else{const o=se(),i=o?ga(o).findings.find(s=>s.id===n.id):void 0;i&&J!==i.id&&(St(),mo(i))}an(!0),W()},onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:I.onSaveImage,onSaveText:I.onSaveText,ownerDocument:u.ownerDocument,locateDie:(n,o)=>{st(!1),pe(o,n)},openWafer:(n,o,i)=>{const s=B()[n];if(!s)return;let l=null;const c=Fs({title:o,onClose:()=>l?.destroy(),anchor:u});jo(c,o,s.wafer.metadata??void 0),l=Sn(c.contentWrap,s,i,void 0,ni(c))}}),ot=he.el,ot.style.display="none",u.appendChild(ot),he)),Oo):Promise.resolve(null)}let it=!1,pn=null;function st(e){$&&(it=e,pn?.setInsightsOpen(e),ot&&(ot.style.display=e?"flex":"none"),U.style.display=e?"none":"flex",ue&&(ue.el.style.display=X?.get()&&!e?"":"none"),L.style.display=e?"none":"inline-flex",Xt(H),Yt(H,"inline-flex"),H.style.display="inline-flex",le(),Rt(),e&&To().then(t=>{!t||!it||(t.el.style.display="flex",t.render())}))}$&&d.insights?.defaultOpen&&queueMicrotask(()=>st(!0));const Lo=4,Lt=240,mn=480,es=720,ts=1.25;let Ee=mn;function Wo(e){const t=z*2+110+2,n=Ro();if(n)return Math.ceil(n.across*Lo+t);let o=null;for(const i of e){if(i==null||!i.dies?.length)continue;const s=i.dies[0].width;if(!(s>0))continue;const l=i.wafer.radius*2*(Lo/s),c=Math.ceil(l+t);(o==null||c>o)&&(o=c)}return o}function ns(e){const t=Wo(e);return t==null?Lt:Math.min(Ee,Math.max(Lt,t))}function os(e){const t=Wo(e);if(t==null)return!1;const n=Math.min(es,Math.max(mn,t));return n<=Ee?!1:(Ee=n,!0)}function Ro(){const e=a.compact?a.compactMap:void 0,t=x.find(i=>i?.dies?.length)?.dies[0];if(!e||!t||e.columns.length===0||e.rows.length===0||!(t.width>0)||!(t.height>0))return;const n=(a.rotation??0)%180!==0,o=a.showXYIndicator?2.5:0;return{across:(n?e.rows.length:e.columns.length)+o,down:(n?e.columns.length:e.rows.length)+o,cellAspect:n?t.height/t.width:t.width/t.height}}function Ao(e,t){const n=Ro();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 is(){for(const e of de)e?.parentElement&&Ao(e.parentElement,e)}function Po(){Ee=mn,at=Lt,yn(x.map(e=>e??null)),Wt(),is()}function gn(){return Fo()?`${Ee}px`:"none"}function Fo(){return O==null&&!hn}let hn=!1;function Wt(){const e=gn();for(const t of Array.from(P.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let at=Lt,$o=0;function yn(e){if(os(e)&&Wt(),O==null){const n=ns(e);n>at&&(at=n)}wn()}function Io(e){O=di(e),Wt(),wn()}function bn(e){return`repeat(${e}, minmax(0, ${Fo()?`${Ee}px`:"1fr"}))`}function Vo(e){P.style.gridTemplateColumns!==e&&(P.style.gridTemplateColumns=e)}function wn(){if(O!=null){Vo(bn(O));return}const e=Math.max(1,$o),t=12,n=P.clientWidth||0,o=l=>(n-t*(l-1))/l;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const l=Math.min(Ee,at*ts),c=r=>{let p=0;for(;p<e&&o(p+1)>=r;)p++;return p};i=c(l)||c(at)||1}const s=n>0&&i<e;s!==hn&&(hn=s,Wt()),Vo(bn(i))}const P=u.ownerDocument.createElement("div");if(Object.assign(P.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:bn(1),gap:M.xl,paddingLeft:oe,paddingRight:oe,justifyContent:"start",alignContent:"start",isolation:"isolate"}),Oe?.placement){const e=Oe.placement;S=In(e,oe,u.ownerDocument,nn),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.display="flex",S.style.flexDirection="column"}else if(K||se()||Un()){const e=!!Oe?.defaultOpen;S=In("right",oe,u.ownerDocument,nn),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display=e?"flex":"none",W()}le(),(Oe?.placement??"right")==="left"?(S&&U.appendChild(S),U.appendChild(P)):(U.appendChild(P),S&&U.appendChild(S));const lt=u.ownerDocument.createElement("div");Object.assign(lt.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:oe,paddingRight:oe,paddingTop:oe,zIndex:"1",background:v.menuBg}),Be.appendChild(Ie),Be.appendChild(H),vt=ps(u.ownerDocument,()=>an(!sn())),Be.appendChild(vt.el),le(),$&&(pn=fs(u.ownerDocument,"Maps","lot",e=>st(e)),Be.appendChild(pn.el)),$&&(wt=ta(u.ownerDocument,"Filter\u2026","wmapGalleryFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{Gt().then(e=>e.openEditor(wt??u,Kt()))}),wt.style.order="1",Be.appendChild(wt)),lt.appendChild(Be),lt.appendChild(ge),u.appendChild(lt),u.appendChild(U);function Rt(){ge.innerHTML="";const e=a.plotMode??"hardBin",t=!it&&Zo.has(e),n=x.filter(b=>b!=null&&!_e.has(b)),o=n.find(b=>b.isLotStack),i=Ta(n.map(b=>({metadata:b.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:d.attributes}),s=e==="metadata",l=a.activeMetadataKey,c=t&&!s?ui(n,b=>(e==="softBin"?b.sbin:b.hbin)??void 0,ve):{counts:new Map,total:0,pass:0},r=t&&!s?a.binColors??G():void 0,p=r?e==="softBin"?r.pass.soft:r.pass.hard:new Set,m=ia(c.counts.entries(),p).map(([b])=>b),f=t&&s&&l?ui(n,b=>bs(b.metadata?.[l])):{counts:new Map,total:0,pass:0},g=s?bo()?.values:void 0,h=t&&s?(g??[...f.counts.keys()].sort($n)).filter(b=>f.counts.has(b)):[];if(Ie.innerHTML="",i&&Ie.appendChild(i),Ie.style.display=i?"flex":"none",!m.length&&!h.length){ge.style.display="none";return}ge.style.display="flex";const y=u.ownerDocument.createElement("div");Object.assign(y.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${M.sm} ${M.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),ge.appendChild(y);const w=Fn(a.highlightBin),T=x.flatMap(b=>b?.metadataFields??[]).find(b=>b.key===l),A=s?T?.label??(l?Aa(l):"Metadata"):Os[e],j=u.ownerDocument.createElement("span");if(j.textContent=A,Object.assign(j.style,{fontSize:N.body,fontWeight:"700",letterSpacing:Ds,textTransform:"uppercase",color:v.label,flexShrink:"0"}),y.appendChild(j),!s&&c.total>0){const b=c.pass,_=b/c.total*100,ye=u.ownerDocument.createElement("span");ye.textContent=`Yield ${Ht(_)}`,Object.assign(ye.style,{fontSize:N.body,fontWeight:"700",color:v.value,whiteSpace:"nowrap",flexShrink:"0"});const be=u.ownerDocument.createElement("span");be.textContent=`${b.toLocaleString()} / ${c.total.toLocaleString()} dies`,Object.assign(be.style,{fontSize:N.body,color:v.label,whiteSpace:"nowrap",flexShrink:"0"}),y.appendChild(ye),y.appendChild(be)}if(s){const b=Fn(a.highlightMetadataValue);h.forEach((_,ye)=>{const be=b.includes(_),je=T?.values?.find(kn=>kn.value===_),dt=je?.color??Ms(ye),qo=f.counts.get(_)??0;fi(y,{color:dt,isActive:be,label:je?.label??_,count:qo,percent:f.total>0?qo/f.total*100:void 0,onClick:kn=>{const us=ri(a.highlightMetadataValue,_,kn);uo(),R({highlightMetadataValue:us})}})});return}const ct=e==="softBin"?x.flatMap(b=>b?.sbinDefs??[]):x.flatMap(b=>b?.hbinDefs??[]),Go=new Set,xn=[];for(const b of ct)Go.has(b.bin)||(Go.add(b.bin),xn.push(b));const Mn=xn.length>0?new Map(xn.map(b=>[b.bin,b])):null,_o=r??a.binColors??G(),ds=e==="softBin"?_o.soft:_o.hard,Ko=b=>ds.get(b)??xs;for(const b of m){const _=w.includes(b),ye=Mn?.get(b),be=c.counts.get(b)??0;fi(y,{color:Ko(b),isActive:_,label:ye?.name?`${b} \xB7 ${ye.name}`:`Bin ${b}`,count:be,percent:c.total>0?be/c.total*100:void 0,onMenu:(je,dt)=>Di(e==="softBin"?"soft":"hard",b,je,dt),onClick:je=>{const dt=ri(a.highlightBin,b,je);uo(),R({highlightBin:dt})}})}c.total>0&&m.length>1&&ge.appendChild(za(u.ownerDocument,[...c.counts.entries()].sort(([,b],[,_])=>_-b).map(([b,_])=>({color:Ko(b),count:_,label:Mn?.get(b)?.name?`${b} \xB7 ${Mn.get(b).name}`:`Bin ${b}`})),c.total))}function Ve(e){const t=B().filter(f=>f!==null&&!_e.has(f));if(!t.length)return[];const n=t.map(f=>f.dies.filter(Va).filter(g=>!g.filteredOut)),o=t[0].wafer,i=t.length,s=Xo(t.map(f=>ut(f)));if(!s)return[];const l=new Set(t.map(f=>ne(f,"renderWaferGallery")));if(l.size!==1)return[];const c=[...l][0],r=o.metadata?{...o,metadata:(({wafer:f,waferId:g,...h})=>h)(o.metadata)}:o;function p(f,g){return{...f,stats:{...f.stats,isLotStack:!0,aggregationMethod:g,lotSize:i}}}function m(f,g){const h=f.map(y=>({...y,hbin:void 0,sbin:void 0}));return Rn({wafer:r,dies:h,passBins:[...s],ringCount:c,testDefs:[{testNumber:0,name:g}]},{testNumbers:[0]})}if(e==="stackedValues"){const f=Xe();let g=f?.filter(Wn);if(f!==void 0&&g?.length===0)return[];if(f?.length||(g=ms(t.flatMap(w=>w.dies)).map(w=>({testNumber:w,name:Pa(void 0,w)}))),!g?.length)return[];const h=a.aggregationMethod??"mean";return g.map(y=>{const w=la(n,h,y.testNumber),T={testNumber:0,name:y.name,unit:y.unit,...$a(y)};return{wafer:r,dies:w,passBins:[...s],ringCount:c,testDefs:[T],label:`${Fa(y,y.testNumber)} \xB7 ${h}`,isLotStack:!0,aggrMethod:h,lotSize:i,statsSummary:p(Rn({wafer:r,dies:w,passBins:[...s],ringCount:c,testDefs:[T]},{testNumbers:[0]}),h)}})}if(e==="stackedBins"){let f=Ft(t.map(g=>g?.hbinDefs));return(!f||f.length===0)&&(f=[...new Set(t.flatMap(h=>h.dies.map(y=>y.hbin).filter(y=>y!=null)))].sort((h,y)=>h-y).map(h=>({bin:h,name:`Bin ${h}`}))),f.map(g=>{const h=oi(n,g.bin,"hard"),y=[{bin:g.bin,name:g.name}];return{wafer:r,dies:h,passBins:[...s],ringCount:c,hbinDefs:y,label:`${g.bin} \xB7 ${g.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:p(m(h,`Wafers in hard bin ${g.bin}`),"countBin")}})}if(e==="stackedSoftBins"){let f=Ft(t.map(g=>g?.sbinDefs));return(!f||f.length===0)&&(f=[...new Set(t.flatMap(h=>h.dies.map(y=>y.sbin).filter(y=>y!=null)))].sort((h,y)=>h-y).map(h=>({bin:h,name:`Bin ${h}`}))),f.map(g=>{const h=oi(n,g.bin,"soft"),y=[{bin:g.bin,name:g.name}];return{wafer:r,dies:h,passBins:[...s],ringCount:c,sbinDefs:y,label:`${g.bin} \xB7 ${g.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:p(m(h,`Wafers in soft bin ${g.bin}`),"countBin")}})}return t}function At(e){const t=B().length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:a.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function R(e,{fireCallback:t=!0}={}){const n=Object.keys(e);if(n.length>0&&n.every(m=>Pn.includes(m))){a={...a,...e},he?.setAxisPrefs(An(a)),t&&d.onViewOptionsChange?.($t(a),n,Ln(n));return}Pn.some(m=>m in e)&&he?.setAxisPrefs(An({...a,...e}));const o=a.plotMode,i=Ge()!==null;a={...a,...e};const s=a.plotMode,l=ie.has(s),c=o!==void 0&&ie.has(o),r=Ue>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const m=G();a={...a,binColors:m},e={...e,binColors:m}}if("compact"in e){const m=vo();a={...a,compactMap:m},e={...e,compactMap:m}}if(("compact"in e||a.compact&&("rotation"in e||"showXYIndicator"in e))&&Po(),e.plotMode!==void 0)if(l){const m=At(s);if(a={...a,...m},r)for(const f of C)f&&f.setOptions(e);else Z(Ve(s))}else if(c){const{valueRange:m,lotSize:f,aggregationMethod:g,...h}=a;if(a=h,r)for(const y of C)y&&y.setOptions(e);else Z(B().filter(y=>y!==null))}else for(const m of C)m&&m.setOptions(e);else if(e.aggregationMethod!==void 0&&s==="stackedValues")if(r)for(const m of C)m&&m.setOptions(e);else Z(Ve("stackedValues"));else for(const m of C)m&&m.setOptions(e);Ge()!==null!==i&&jn(),Rt(),ko(),xo(),ho();const p=e.plotMode!==void 0&&e.plotMode!==o;(fa.some(m=>m in e)||p)&&W(),De(),Do(),Bo(),rn(),ln(),t&&d.onViewOptionsChange?.($t(a),n,Ln(n))}function Ho(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:N.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=ci(e,o,t,n,d.attributes);return{wrap:o,metaPanel:s}}function jo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||La(n??{}).length===0)return;const i=o.parentElement,s=u.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const l=ci(u.ownerDocument,s,t,n,d.attributes);l&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(l))}function vn(e,t,n){const o=u.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:q.container,boxShadow:Bn.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:gn(),maxHeight:gn()});const i=u.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${v.menuBorder}`,flexShrink:"0",gap:M.sm});const{wrap:s,metaPanel:l}=Ho(document,pt(e,t),e.wafer.metadata??void 0);i.appendChild(s);const c=u.ownerDocument.createElement("button");c.dataset.wmapExpandBtn="1",c.setAttribute("aria-label","Open full view"),On(c),c.innerHTML=Dn.expand,Object.assign(c.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${v.menuBorder}`,borderRadius:q.control,background:v.panelBg,color:v.label,padding:M.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),En(c),i.appendChild(c),i.addEventListener("click",g=>{(g.ctrlKey||g.metaKey)&&(g.preventDefault(),g.stopPropagation(),Oi(x.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),Ao(o,r),l&&r.appendChild(l),P.appendChild(o),o.addEventListener("contextmenu",g=>{if(g.defaultPrevented)return;g.preventDefault();const h=e.viewOptions?{...a,...e.viewOptions}:a,y=tn()??lo(t),w=y?.source??ca(e.dies,{waferLabel:we(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:h.plotMode==="value"?h.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:ve(e),ringCount:ne(e,"renderWaferGallery")}),T={x:g.clientX,y:g.clientY};import("./drilldown.js").then(({openDrilldownMenu:A})=>{o.isConnected&&A(T,o,w,y?{plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,...y.ctx}:{plots:F,getBinColors:()=>a.binColors??G(),attributes:d.attributes,onSaveImage:f.getSaveImageHook(),onSaveText:f.getSaveTextHook(),onLocateDie:j=>pe(t,j)})})});const p=gt||Ge()!==null,m=e.viewOptions?{...a,...e.viewOptions}:a,f=ii(r,e,{viewOptions:{...m,showLegend:p,legendPosition:Ne},showTooltip:!0,padding:z,statsSummary:e.statsSummary,testValueOffer:Zt,onSaveImage:d.onSaveImage,onSaveText:d.onSaveText,downloadFilename:d.downloadFilename,onClick:e.onClick,onSelect:no(e),drilldownSourceOverride:()=>ki(t),insights:ce,onExpand:()=>rt(t,e),showIdentity:!1,chromeInset:Es,drawWhenVisible:!0});return f.setViewControlsVisible(!1),f.setSummaryVisible(!1),c.onclick=()=>rt(t,e),_e.has(e)&&(o.style.display="none"),{card:o,ctrl:f,canvasWrapper:r,expandBtn:c}}function ss(e){const t=Te[e];if(!t)return;const n=[...Q.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Dn.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>ls(n.id)):(t.innerHTML=Dn.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>rt(e,x[e]))}function Z(e){rs(),Ze()?.remove(),Qe(null),ke(),x=[],Y.clear(),on.clear(),ee.style.display="none";for(const r of C)r&&r.destroy();C=[],de=[],Te=[],Ue=0,P.innerHTML="",$o=e.length,yn(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 m=u.ownerDocument.createElement("div");m.className="wmap-gallery-card",Object.assign(m.style,{background:v.menuBg,border:`1px solid ${v.menuBorder}`,borderRadius:q.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const f=u.ownerDocument.createElement("span");f.textContent="\u2026",Object.assign(f.style,{color:v.label,fontSize:"18px"}),m.appendChild(f),P.appendChild(m),x.push(null),C.push(null),de.push(null),Te.push(null),t.push({index:r,factory:p,placeholder:m}),Ue++}else{const{ctrl:m,canvasWrapper:f,expandBtn:g}=vn(p,r,e.length);x.push(p),C.push(m),de.push(f),Te.push(g)}}Co(),Rt(),rn(),ln(),So();const n=++Ye,o=()=>{setTimeout(()=>{n===Ye&&d.onItemsResolved?.()},0)},i=r=>{setTimeout(()=>{n===Ye&&d.onItemResolved?.(r,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let l=0;function c(){if(n!==Ye)return;if(l>=t.length){if(ie.has(a.plotMode)){const A=a.plotMode;Z(Ve(A));return}if(zt){qt();return}et=o,W(),Fe||(et=null,o());return}const{index:r,factory:p,placeholder:m}=t[l++],f=p();V[r]=f;const g=qe(f,r);g!==f&&(Se=!0),x[r]=g,yn([g]);const{card:h,ctrl:y,canvasWrapper:w,expandBtn:T}=vn(g,r,e.length);C[r]=y,de[r]=w,Te[r]=T,Ue--,m.replaceWith(h),i(++s),zi(),ji(),!S&&!Oe?.placement&&g.statsSummary?.findings.length&&(S=In("right",oe,u.ownerDocument,nn),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display="none",(Oe?.placement??"right")==="left"?U.insertBefore(S,P):U.appendChild(S),W(),le()),le(),setTimeout(c,0)}t.length>0?setTimeout(c,0):o()}if(ie.has(a.plotMode)&&B().length>0){const e=At(a.plotMode);a={...a,...e},Z(Ve(a.plotMode))}else Z(bt(k));d.insights?.filter!==void 0&&Gt(),De();let He=0;const zo=new(u.ownerDocument.defaultView??window).ResizeObserver(()=>{if(He)return;He=(u.ownerDocument.defaultView??window).requestAnimationFrame(()=>{He=0,O==null&&wn()})});zo.observe(P),S&&W();function as(e,t){const n=de[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:v.label,fontSize:N.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function rt(e,t){for(const l of Q.values())if(l.cardIndex===e)return;const n=pt(t,e),o=yi++,i=C[e]?.getOptions(),s=As(n);if(s){const l=s.document;l.title=n,Object.assign(l.documentElement.style,{height:"100%"}),Object.assign(l.body.style,{margin:"0",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",fontFamily:N.family}),$s(u,l.documentElement);const c=Is(u,l.documentElement,()=>w.setOptions({})),r=l.createElement("div");r.dataset.wmapWindowBanner="1",r.textContent=n,Object.assign(r.style,{display:"none",padding:`${M.sm} ${M.xl}`,fontSize:N.body,fontWeight:"700",background:v.warnBg,color:v.warnText,borderBottom:`1px solid ${v.warnBorder}`,flexShrink:"0"}),l.body.appendChild(r);const p=l.createElement("div");Object.assign(p.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),l.body.appendChild(p);const{wrap:m,metaPanel:f}=Ho(l,n,t.wafer.metadata??void 0),g=l.createElement("div");Object.assign(g.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${v.menuBorder}`,flexShrink:"0",gap:M.sm}),g.appendChild(m),p.appendChild(g);const h=l.createElement("div");Object.assign(h.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),f&&h.appendChild(f),p.appendChild(h);let y=0;const w=Sn(h,t,void 0,i,(A,j)=>{const ct=A?j:-y;try{s.resizeBy(ct,0),y=A?j:0}catch{}}),T=setInterval(()=>{s.closed&&Pt(o)},400);s.addEventListener("pagehide",()=>Pt(o)),Q.set(o,{id:o,ctrl:w,cardIndex:e,label:n,closePollId:T,stopThemeSync:c,close:()=>{s.closed||s.close()},setTitle:A=>{l.title=A,r.textContent=A,r.style.display="block"}})}else{const l=Ps({title:n,onClose:()=>Pt(o),anchor:u});l.contentWrap.style.flexDirection="column",jo(l,n,t.wafer.metadata??void 0);const c=Sn(l.contentWrap,t,void 0,i,ni(l));Q.set(o,{id:o,ctrl:c,cardIndex:e,label:n,closePollId:null,close:()=>l.close(),setTitle:r=>{const p=l.box.querySelector("[data-wmap-window-title]");p&&(p.textContent=r,p.title=r)}})}C[e]?.destroy(),C[e]=null,as(e,s!==null),ss(e)}function Sn(e,t,n,o,i){const s=t.viewOptions?{...a,...t.viewOptions}:a,l=o?{...s,...o}:s,r={...n!==void 0?{...l,plotMode:"value",activeTest:n}:l,showLegend:!0,legendPosition:Ne},p=ii(e,t,{viewOptions:r,showTooltip:!0,padding:z,statsSummary:t.statsSummary,testValueOffer:Zt,onSaveImage:d.onSaveImage,onSaveText:d.onSaveText,downloadFilename:d.downloadFilename,onClick:t.onClick,onSelect:no(t),insights:ce,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return p.setViewControlsVisible(!0),p.setSummaryVisible(!0),p.setExpandVisible(!1),p}function Pt(e){const t=Q.get(e);if(!t||(Q.delete(e),t.closePollId!=null&&clearInterval(t.closePollId),t.stopThemeSync?.(),t.ctrl.destroy(),t.cardIndex===null))return;const n=t.cardIndex,o=x[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:l,expandBtn:c}=vn(o,n,x.length);de[n]?.parentElement?.replaceWith(i),C[n]=s,de[n]=l,Te[n]=c}function ls(e){const t=Q.get(e);t&&(t.close(),Pt(e))}function rs(){for(const e of Q.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function Cn(){for(const e of C)e?.drawPendingNow()}const No=u.ownerDocument.defaultView??window;No.addEventListener("beforeprint",Cn);function cs(){Cn();const e=[...P.querySelectorAll("canvas")];if(!e.length)return;const t=e.length,n=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/n),i=e[0].width,s=e[0].height,l=8,c=(u.ownerDocument.defaultView??window).devicePixelRatio||1,r=Math.round(26*c),p=Math.round(12*c),m=u.ownerDocument.createElement("canvas");m.width=n*i+(n-1)*l,m.height=o*(s+r)+(o-1)*l;const f=m.getContext("2d"),g=ks(P);f.fillStyle=g.background,f.fillRect(0,0,m.width,m.height),e.forEach((h,y)=>{const w=y%n,T=Math.floor(y/n),A=w*(i+l),j=T*(s+r+l),ct=h.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";f.fillStyle=g.surface,f.fillRect(A,j,i,r),f.fillStyle=g.text,f.font=`700 ${p}px system-ui, sans-serif`,f.textAlign="left",f.textBaseline="middle",f.fillText(ct,A+Math.round(10*c),j+r/2,i-Math.round(20*c)),f.drawImage(h,A,j+r)}),m.toBlob(h=>{if(!h)return;const y=C.find(w=>w!=null)?.getExportTitle();Gs(h,["gallery",y].filter(Boolean).join(" "),I.onSaveImage)})}return{setItems(e){Qt(),V=e.map(n=>typeof n=="function"?null:n);const t=a.plotMode;if(ie.has(t))if(e.some(o=>typeof o=="function"))Z(bt(e));else{const o=At(t);a={...a,...o},Z(Ve(t))}else Z(bt(e))},setOptions(e){R(e,{fireCallback:!1})},getOptions(){return $t(a)},setFindingsNotice(e){eo=e,W()},setColumns(e){Io(e)},getBinColors(){return a.binColors??G()},setLotStatsSummary(e){Qt(),K=e,De(),S&&W(),le()},openUserGuide:()=>fn(),destroy(){Ji(),F.flush(),Qt(),Ye++,No.removeEventListener("beforeprint",Cn),Fe?.cancel(),Fe=null,et=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=[],Ze()?.remove(),zo.disconnect(),He&&((u.ownerDocument.defaultView??window).cancelAnimationFrame(He),He=0),u.ownerDocument.removeEventListener("click",Ct,!0),window.removeEventListener("blur",Jn),pi(),Qo(),lt.remove(),U.remove(),S?.remove(),jt=!0,ht++,clearTimeout(_t),ue?.el.remove(),he?.destroy()}}}
1
+ import{createViewSwitch as xs}from"./viewSwitch.js";import{createSummaryToggle as Ms}from"./summaryToggle.js";import{getUniqueTestNumbers as ks,resolveTestNumber as Ds,findTestDef as Bs,collectMetadataValues as Es}from"../renderer/buildView.js";import{metadataCategoricalValue as Os}from"../core/metadata.js";import{resolveBinColorsForMaps as Ts,mergeBinDefs as Vt,binColorWarning as Ls,mixedPassBinsWarning as Ps,binColorsEqual as Ws}from"../renderer/binColors.js";import{commonPassBins as ni,itemPassBins as Ue}from"../core/passBins.js";import{PAT_MODE_FIELD as Rs,PAT_MODE_KEY as As,PAT_MODE_ORDER as Fs,isPatMode as mt,patModeOffered as $s,withPatField as Is,withPatVerdicts as Vs}from"./patMode.js";import{requireRingCount as ne}from"../core/ringCount.js";import{NO_DATA_FILL as Hs}from"../renderer/colorMap.js";import{metadataValueColor as js}from"../renderer/colorMap.js";import{resolveCanvasTheme as zs}from"./canvasTheme.js";import{ICONS as Tn}from"./icons.js";import{SHADOW as Ln,LEADING as oi,TRACKING as Ns,controlStyle as _s,wireControlHover as Pn,SPACE as M,EDGE_GUTTER as oe,MAP_CHROME_INSET as Ks,RADIUS as Y,FONT as N,CLR as w,sevColor as ii,MODE_LABELS as Gs,BIN_LEGEND_MODES as si,STACKED_MODES as ie,applyOverlayZ as qs,getTooltip as Xs,hideTooltip as ai,createToolbarHelpers as Ys,buildModeMenuEl as Us,openDetachWindow as Zs,openFloatingWindow as Qs,openModal as Js,copyWmapThemeTokens as ea,syncWmapPopupTheme as ta,makePaletteBtn as na,makeLogScaleBtn as oa,makeLegendStyleBtn as ia,makeOverlaysBtn as sa,makeOrientationBtn as aa,menuLayerFor as li,saveImageBlob as la,markMenuTrigger as gt,wireMenuA11y as ri,wireTooltip as Wn,requestedPassFailDisplay as ci,overlayMenuRows as ra,anyOverlayActive as ca,openCompactDiagnostics as da,roomForPanel as di,logWmapVersionOnce as ua,buildDataModeEntries as fa,metadataKeyHasData as pa,metadataModeEntry as ui}from"./toolbar.js";import{openReportModal as ma,openUserGuideWindow as ga,registerGuideOpener as ha}from"./guideWindow.js";import{waferDisplayLabel as ht,waferIdentityLabel as ve}from"../core/waferLabel.js";import{bandButton as ya}from"./filterButton.js";import{metadataDisplayValue as ba}from"../core/metadata.js";import{withExportContext as wa}from"./exportName.js";import{sortBinsForDisplay as va}from"../stats/binPareto.js";import{diePassStatus as Sa,isYieldEligibleDie as Ca}from"../core/dies.js";import{aggregateValues as xa,aggregateBinCounts as fi}from"../core/aggregates.js";import{renderWaferMap as Ma,renderWaferMapCard as pi,toPublicViewOptions as Ht}from"./renderWaferMap.js";import{waferPopulation as ka,selectionPopulation as Da,LOT_STACK_REASON as Rn}from"./chartPopulation.js";import{sourceFromBins as mi}from"./plotItems.js";import{plotStoreFor as Ba}from"./plotStore.js";import{classifyChanged as An,COLOR_KEYS as Ea,findingBin as Oa,findingPlotMode as Ta}from"./renderWaferMap.js";import{findingPatternKey as gi}from"../stats/filterFindings.js";import{synthesisSource as La}from"../stats/synthesis.js";import{buildWaferMap as Pa,computeCoverage as Wa,computeYield as Ra,defaultBinMode as Aa,getTestPassStatus as hi,isParametricTest as Fn,getDieTestValue as Fa,isBuiltMap as $a}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as $n}from"../stats/analyzeWaferMap.js";import{lotTestValueStatus as Ia}from"../stats/testValueBudget.js";import{testValueNotice as Va}from"./testValueOffer.js";import{axisPrefsFromOptions as In,optionsFromAxisPrefs as Ha,CHART_PREF_KEYS as Vn}from"./chartPrefs.js";import{collectWarnings as ja,buildWarningsMenuEl as za,severityOf as Na}from"./warnings.js";import{asList as Hn,compareNatural as jn,arrayEqual as jt,toggleHighlight as yi}from"../core/utils.js";import{buildCompactMap as _a,compactLayoutOffered as Ka}from"../core/compact.js";import{attachExpandableMetadata as bi}from"./identityHeader.js";import{createSummaryPanelEl as zn,buildMetadataStripRow as Ga,metadataEntries as qa,renderLotSummaryContentSteps as Xa,reportMapsFromItems as Ya}from"./summaryPanel.js";import{prettyKey as Ua}from"../stats/facets.js";import{testLabel as Za,markedTestLabel as Qa,derivedFields as Ja}from"../renderer/testLabel.js";import{mergeTestDefs as el}from"../stats/mergeTestDefs.js";import{getDieKey as zt,hasPosition as tl}from"../core/dies.js";import{testValue as nl}from"../core/dieTable.js";import{runChunked as ol}from"./chunked.js";function wi(r){if(typeof r!="number"||!Number.isFinite(r))return;const k=Math.round(r);return k>=1?k:void 0}const Nn=12;function il(r,k,f){let z=k;if(k.length>Nn){const D=k.slice(0,Nn-1),O=k.slice(Nn-1),I=O.reduce(($,de)=>$+de.count,0);z=[...D,{color:w.label,count:I,label:`Other (${O.length} bins)`}]}const T=r.createElement("div");Object.assign(T.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:Y.control,overflow:"hidden",border:`1px solid ${w.menuBorder}`,boxSizing:"border-box",marginTop:M.xs,flexShrink:"0"}),T.setAttribute("role","img"),T.setAttribute("aria-label",`Population split: ${z.map(D=>`${D.label} ${Nt(D.count/f*100)}`).join(", ")}`);for(const D of z){const O=D.count/f*100,I=r.createElement("div");Object.assign(I.style,{flex:`${O} 1 0`,minWidth:O>0?"2px":"0",background:D.color}),Wn(I,`${D.label} \xB7 ${D.count.toLocaleString()} dies \xB7 ${Nt(O)}`),T.appendChild(I)}return T}function Nt(r){return r>0&&r<.1?"<0.1%":`${r.toFixed(1)}%`}function vi(r,k,f){const z=new Map;let T=0,D=0;for(const O of r){const I=f?new Set(f(O)):void 0;for(const $ of O.dies){if(!Ca($))continue;const de=k($);de!==void 0&&(z.set(de,(z.get(de)??0)+1),T++,I&&Sa($,I)&&D++)}}return{counts:z,total:T,pass:D}}function Si(r,k){const f=r.ownerDocument.createElement("div");Object.assign(f.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${M.xxs} ${M.xs}`,borderRadius:Y.control});const z=r.ownerDocument.createElement("span");Object.assign(z.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:k.color,border:k.isActive?`2px solid ${w.iconActive}`:`1px solid ${w.menuBorder}`,borderRadius:Y.control,boxSizing:"border-box"});const T=r.ownerDocument.createElement("span");if(T.textContent=k.label,Object.assign(T.style,{fontWeight:k.isActive?"700":"400",color:k.isActive?w.iconActive:w.text,whiteSpace:"nowrap"}),f.appendChild(z),f.appendChild(T),k.count!==void 0){const D=r.ownerDocument.createElement("span");if(D.textContent=k.count.toLocaleString(),Object.assign(D.style,{color:k.isActive?w.iconActive:w.text,fontWeight:k.isActive?"700":"400",whiteSpace:"nowrap"}),f.appendChild(D),k.percent!==void 0){const O=r.ownerDocument.createElement("span");O.textContent=Nt(k.percent),Object.assign(O.style,{color:w.label,whiteSpace:"nowrap"}),f.appendChild(O)}}if(f.setAttribute("role","button"),f.setAttribute("aria-pressed",k.isActive?"true":"false"),f.tabIndex=0,f.addEventListener("mouseenter",()=>{f.style.background=w.bgHover}),f.addEventListener("mouseleave",()=>{f.style.background="transparent"}),f.addEventListener("focus",()=>{f.style.background=w.bgHover}),f.addEventListener("blur",()=>{f.style.background="transparent"}),f.addEventListener("click",D=>k.onClick(D.ctrlKey||D.metaKey)),f.addEventListener("keydown",D=>{if(D.key==="Enter"||D.key===" ")D.preventDefault(),k.onClick(D.ctrlKey||D.metaKey);else if(k.onMenu&&(D.key==="ContextMenu"||D.key==="F10"&&D.shiftKey)){D.preventDefault();const O=f.getBoundingClientRect();k.onMenu({x:O.left+O.width/2,y:O.bottom},f)}}),k.onMenu){const D=k.onMenu;f.addEventListener("contextmenu",O=>{O.preventDefault(),D({x:O.clientX,y:O.clientY},f)}),Wn(f,"Right-click: charts and tables for these dies")}r.appendChild(f)}export function renderWaferGallery(r,k,f={}){ua();const z=6;let T=wi(f.columns);const D=f.showHelpButton??!1,O=f.userGuideExtension,I=f.insights?.enabled??!0,$=Ba(f.insights),de={enabled:!1,plotStore:$},Ci=qs(f.zIndex),Re=f.summaryPanel,Se=e=>[...Ue(e)],_n=()=>W.flatMap(e=>e?[ne(e,"renderWaferGallery")]:[]),yt=()=>_n()[0];function xi(e){const t=[...new Set(e)].sort((n,o)=>n-o);return t.length<2?null:{code:"ring-count-mixed",severity:"warning",message:`These wafers were built with different ring counts (${t.join(", ")}). Each card and each wafer's findings use their own; the lot's ring yield in the Summary panel, report and Insights uses ${e[0]} rings.`}}let _=f.lotStatsSummary,Ae;const se=()=>ae?Ae:_;let Ze=f.viewOptions?.legendPosition??"default",bt=f.perCardLegend??!1;function Qe(){const e=a.plotMode??"hardBin";return si.has(e)?null:a.colorbarRangeMode==="data"?"Each map has its own value range, so it keeps its own colour bar":"These wafers have no shared colour bar for value mode, so each map keeps its own"}function Kn(){const e=bt||Qe()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let a={plotMode:Aa(k.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...f.viewOptions},C=[],ue=[],Fe=[],x=[];const V=wa(()=>{const e=x.filter(n=>n!=null),t=[...new Set(e.map(n=>ba(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(jn);return{prefix:f.downloadFilename,lots:t,...e.length===1?{wafer:ve(e[0])}:{waferCount:e.length}}},f.onSaveImage,f.onSaveText);let W=k.map(e=>typeof e=="function"?null:e),q=null,Gn=null,_t=!1,Ce=0,ae=!1,wt=!1;const xe=new WeakSet,qn=new WeakMap,Me=()=>{const e=q?.get();return!!e&&!e.off};function Xn(e,t){return{dies:e.dies,wafer:e.wafer,label:ht(e,t),identity:ve(e),waferIndex:t,passBins:Ue(e),testDefs:e.testDefs,statsSummary:e.statsSummary}}const Kt=new Map;function Je(e,t){if(!q||!Me())return e;const n=qn.get(e);if(n&&n.v===Ce)return n.item;const o=q.mark([Xn(e,t)]);let i=e;if(o.narrowing){const s=o.items[0].dies,l=s.filter(u=>!u.filteredOut);i={...e,dies:s,statsSummary:Kt.get(e),...e.yield?{yield:Ra(s,[...Ue(e)],e.yield.yieldPercentGross!=null?"denominator-only":"exclude")}:{},...e.dataCoverage?{dataCoverage:Wa(l)}:{}},o.hidden.size&&xe.add(i)}return qn.set(e,{v:Ce,item:i}),i}const Yn=new WeakMap;function Gt(e,t){const n=Je(e,t);if(!mt(a))return n;const o=Yn.get(n);if(o)return o;const i={...n,dies:Vs(n.dies,n.testDefs,Ue(n)),metadataFields:Is(n.metadataFields)};return xe.has(n)&&xe.add(i),Yn.set(n,i),i}const Un=new WeakMap;function Mi(e,t){if(!q||!Me())return e;const n=Un.get(e);if(n&&n.v===Ce)return n.item;const o=Je(e,t),i=o===e?e:xe.has(o)?null:{...o,dies:o.dies.filter(s=>!s.filteredOut)};return Un.set(e,{v:Ce,item:i}),i}function B(){return!q||!Me()?W:W.map((e,t)=>e?Mi(e,t):null)}let vt=0,et=!1;function Zn(){const e=++vt;Ae=void 0,Kt.clear();const t=()=>{et=!1,R(),re()};if(!ae){t();return}const n=Jt();if(!n||!(_||n.some(s=>s.statsSummary))){t();return}const o=B().flatMap((s,l)=>s?[{it:s,i:l}]:[]);if(o.length===0){t();return}et=!0;const i=_?.analysisOptions??n.find(s=>s.statsSummary)?.statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(async({analyzeWaferLotAsync:s,remapLotWaferIndices:l})=>{const u=await s(o.map(m=>m.it),i);if(e!==vt||_t)return;const d=o.map(m=>m.i);Ae=l(u,d),u.perWafer.forEach((m,v)=>Kt.set(W[d[v]],m.summary)),Ce++,W.forEach((m,v)=>{if(!m||ie.has(a.plotMode))return;const p=Gt(m,v);x[v]=p,C[v]?.setStatsSummary(p.statsSummary)}),Te(),t()}).catch(()=>{e===vt&&t()})}const $e=e=>q&&Me()||mt(a)?e.map((t,n)=>typeof t=="function"?t:Gt(t,n)):e;function qt(){return Gn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const t=e({doc:r.ownerDocument,initial:f.insights?.filter,onChange:f.insights?.onFilterChange,savedFilters:f.insights?.savedFilters,onSavedFiltersChange:f.insights?.onSavedFiltersChange,pickFiltersFile:f.insights?.onPickFiltersFile,onSaveText:f.onSaveText,attributes:f.attributes,getRingCount:()=>ne({ringCount:yt()},"the page filter")});return _t||(q=t,fe=t.createBand(()=>Yt(),{marginLeft:oe,marginRight:oe,marginBottom:M.lg}),r.insertBefore(fe.el,Z),t.subscribe(Ut),t.get()&&Ut()),t}),Gn}let fe=null,St=null,Xt;const Yt=()=>W.flatMap((e,t)=>e?[Xn(e,t)]:[]);function Qn(){clearTimeout(Xt),Xt=setTimeout(()=>{if(!q||!fe)return;const e=Yt(),t=q.keep(e);fe.refresh(t.result,e),fe.el.style.display=q.get()&&!Ke?"":"none"},0)}function Jn(){if(q){if(ke>0){Me()&&(wt=!0);return}Ce++,ae=Me()&&W.some((e,t)=>e!==null&&Je(e,t)!==e),Ae=void 0,et=ae&&!!_,Zn()}}function Ut(){if(Ce++,ae=!1,ke>0){wt=!0,Qn();return}wt=!1;const e=a.plotMode;ae=Me()&&W.some((t,n)=>t!==null&&Je(t,n)!==t),Ae=void 0,et=ae&&!!_,W.length>0&&(ie.has(e)?(a={...a,...$t(e)},X(qe(e))):X($e(W.filter(t=>t!==null)))),Qn(),Zn()}function Ie(){return el(B())}function tt(){if(B().some(e=>e?.testDefs?.length))return Ie().defs}let nt=0,ke=0;const Q=new Map;let ki=0,Ct=null,J=null,pe=null,Ve=null;function xt(){J===null&&pe===null&&(Ve={plotMode:a.plotMode,activeTest:a.activeTest})}function eo(){Ve&&P({...Ve},{fireCallback:!1}),Ve=null}let to=new Set,S=null,Di={};function no(e){return B()[e]?.statsSummary??se()?.perWafer.find(t=>t.waferIndex===e)?.summary}function oo(){return!!(B().some(e=>e?.statsSummary?.findings.length)||se()?.perWafer.some(e=>e.summary.findings.length))}const Bi=Xs(),He=Ys(Bi),{makeBtn:je,setActive:io,makeSep:De,syncSeparators:Zt,syncToolbarVisible:Qt,makeMenuRow:Ei,makeMenuSection:Oi,makeDropdown:so,closeOpenMenu:Mt,getOpenMenu:ot,setOpenMenu:it}=He;r.ownerDocument.addEventListener("click",Mt,!0);const ao=()=>ai();window.addEventListener("blur",ao);let lo=f.findingsNotice,Be=null;function Jt(){const e=W;return e.length>0&&e.every(t=>t!=null&&$a(t))?e:null}function Ti(){return _?.stats.testValueAnalysis??Ia(B().flatMap(e=>e?.statsSummary?[e.statsSummary]:[]))}const en=()=>lo??(Jt()?Va(Ti(),B().length,Be!==null,Li):void 0);function Li(){const e=Jt();if(Be||!e)return;const t=new AbortController;Be=t,R();const n=_?.analysisOptions??e[0].statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(({analyzeWaferLotAsync:o})=>o(e,{...n,enableTestValueAnalysis:!0,signal:t.signal})).then(o=>{if(t.signal.aborted)return;Be=null;const i=o.perWafer.map(s=>s.summary);W=W.map((s,l)=>s&&{...s,statsSummary:i[l]}),ie.has(a.plotMode)||(x=x.map((s,l)=>s&&{...s,statsSummary:i[l]}),C.forEach((s,l)=>s?.setStatsSummary(i[l]))),_=o,Te(),R(),re(),f.onStatsSummaryChange?.({summaries:i,lotStatsSummary:o})}).catch(o=>{if(!t.signal.aborted)throw Be=null,R(),o})}function tn(){Be?.abort(),Be=null}function ro(e){to=new Set(e);const t=[...F.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=to.has(i);o.style.outline=s?`3px solid ${w.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function nn(){ro([])}let kt=!1;function on(){kt=!0;for(const e of C)e&&e.clearSelection();kt=!1}function co(e){return t=>{!kt&&(J!==null||pe!==null)&&(Ve=null,Oe(),R()),ln.set(e,t.length),le&&!st&&!kt&&Pi(e,t),e.onSelect?.(t)}}function me(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),F.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let le=!1,st=!1,Ee=new Set;function Pi(e,t){st=!0;try{Ee=new Set(t.map(n=>zt(n))),x.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>Ee.has(zt(s))))})}finally{st=!1}Lt()}function uo(){Ee=new Set,st=!0;try{for(const e of C)e?.clearSelection()}finally{st=!1}Lt()}function sn(){if(!le||Ee.size===0)return;const e=[];let t=!1;if(x.forEach((i,s)=>{if(!i)return;const l=i.dies.filter(u=>Ee.has(zt(u)));l.length!==0&&(i.isLotStack&&(t=!0),e.push({label:ve(i)??i.label??`Wafer ${s+1}`,dies:l,waferIndex:s,wafer:i.wafer,passBins:Se(i),ringCount:ne(i,"renderWaferGallery")}))}),e.length===0)return;const n=Ie(),o=a;return{source:{items:e,population:e.length===1?`selected on ${e[0].label}`:`selected at the same die positions on ${e.length} wafers`,testDefs:n.defs,activeTest:o.plotMode==="value"?o.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>me(s,i)}}}function fo(){const e=[];let t=!1;if(x.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:ve(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:Se(o),ringCount:ne(o,"renderWaferGallery")}))}),e.length<2)return;const n=a;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:Ie().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(o,i)=>me(i,o)}}}function Wi(e){const t=sn()??go(e);if(t)return t;const n=fo(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function an(e,t,n){J!==e&&t.click();const o=S;if(!o)return;const i=se()?.findings.find(l=>l.id===e),s=sn()??fo()??Ai()??(i?po(ho(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:l})=>{o.isConnected&&l(n,o,s.source,{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...s.ctx})})}function Ri(e,t,n,o){const i=Hn(a.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],l=[];let u=!1;x.forEach((g,h)=>{g&&(g.isLotStack&&(u=!0),l.push({label:ve(g)??g.label??`Wafer ${h+1}`,dies:g.dies,waferIndex:h,wafer:g.wafer,passBins:Se(g),ringCount:ne(g,"renderWaferGallery")}))});const d=Ie().defs,m=mi(l,e,s,d,void 0,u);if(!m)return;const v={plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(g,h)=>me(h,g)},p=s.length>1?mi(l,e,[t],d,void 0,u):null,c=p?{...v,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:p,ctx:v}}:v;import("./drilldown.js").then(({openDrilldownMenu:g})=>{o.isConnected&&g(n,o,m,c)})}function po(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((l,u)=>l-u)){const l=x[s];l&&(l.isLotStack&&(o=!0),n.push({label:ve(l)??l.label??`Wafer ${s+1}`,dies:l.dies,waferIndex:s,wafer:l.wafer,passBins:Se(l),ringCount:ne(l,"renderWaferGallery")}))}if(n.length===0)return;const i=a;return{source:{items:n,population:n.length===1?`on ${n[0].label}`:`on ${n.length} ${t}wafers`,testDefs:Ie().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(s,l)=>me(l,s)}}}function Ai(){let e;for(let i=0;i<C.length;i++)if((C[i]?.getSelectedDies().length??0)!==0){if(e!==void 0)return;e=i}const t=e===void 0?void 0:x[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=a;return{source:Da(n,{waferLabel:ve(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:Se(t),ringCount:ne(t,"renderWaferGallery")}),ctx:{onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>me(s??e,i)}}}function Fi(e){e||uo(),le=e,Lt()}function Dt(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=x[i],l=C[i];if(!s||!l)continue;const u=s.dies.filter(d=>n.has(zt(d)));l.setSelection(u)}}const U=new Set,ln=new Map;function mo(){[...F.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=U.has(o)?`2px solid ${w.iconActive}`:"",n.style.outlineOffset=U.has(o)?"-2px":""});const t=U.size;ee.style.display=t>0?"":"none",ee.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,ee.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function $i(e){e<0||(U.has(e)?U.delete(e):U.add(e),mo())}function Ii(){U.clear(),mo()}function go(e){if(!(U.size===0||!U.has(e))){for(const t of ln.values())if(t>0)return;return po([...U],"picked ")}}function Vi(){const e=[];for(let t=0;t<B().length;t++){const n=B()[t];if(!n)continue;const o=no(t)?.findings??[];o.length&&e.push({index:t,item:n,unusualCount:o.filter(i=>i.severity==="unusual").length,notableCount:o.filter(i=>i.severity==="notable").length,totalCount:o.length})}return e}function Hi(e){const t=x[e]??B()[e];t&&ut(e,t)}function ji(e){const t=no(e)?.findings??[];if(t.length)return{total:t.length,unusual:t.filter(n=>n.severity==="unusual").length,notable:t.filter(n=>n.severity==="notable").length}}function zi(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{ma(e(Ya(B(),yt())),{anchor:r})})}function Ni(){if(!S)return;S.innerHTML="";const e=Vi();if(B().length>0){const n=r.ownerDocument.createElement("div"),o=e.length,i=B().filter(Boolean).length;n.textContent=o===0?`No findings on any of the ${i} wafers`:`${o} of ${i} wafer${i===1?"":"s"} with findings`,Object.assign(n.style,{fontSize:N.body,color:w.label,marginBottom:M.md}),S.appendChild(n)}if(e.length>0){const n=r.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{..._s("outlined"),marginBottom:M.lg,display:"block",width:"100%",textAlign:"left"}),Pn(n),n.addEventListener("click",zi),S.appendChild(n)}if(e.length===0){const n=r.ownerDocument.createElement("div");Object.assign(n.style,{color:w.icon,fontSize:N.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",S.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:l}of e){const u=i?"unusual":s?"notable":"info",d=i+s||l,m=r.ownerDocument.createElement("button");m.type="button",Object.assign(m.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:M.xs,border:"none",borderLeft:`3px solid ${ii(u)}`,borderRadius:Y.control,background:w.bgHover,cursor:"pointer",fontSize:N.body,textAlign:"left",boxSizing:"border-box"}),m.addEventListener("mouseover",()=>{m.style.background=w.bgActive}),m.addEventListener("mouseout",()=>{m.style.background=w.bgHover});const v=r.ownerDocument.createElement("span");v.textContent=ht(o,n),Object.assign(v.style,{color:w.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const p=r.ownerDocument.createElement("span");p.textContent=String(d),m.setAttribute("aria-label",`${ht(o,n)} \u2014 ${d} finding${d===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(p.style,{marginLeft:M.sm,flexShrink:"0",background:ii(u),color:"#fff",borderRadius:Y.container,padding:"1px 5px",fontSize:N.body,fontWeight:"600"}),m.appendChild(v),m.appendChild(p),m.addEventListener("click",()=>ut(n,o)),S.appendChild(m)}const t=r.ownerDocument.createElement("div");t.style.height="12px",S.appendChild(t)}let ze=null,at=null;function R(){if(!S||ae&&_&&!Ae&&et)return;ze?.cancel(),ze=null;const e=se();if(e){const t=Vt(B().map(o=>o?.hbinDefs)),n=Vt(B().map(o=>o?.sbinDefs));ze=ol(Xa(S,{lotSummary:e,items:B(),hbinDefs:t.length?t:void 0,sbinDefs:n.length?n:void 0,testDefs:tt(),ringCount:yt(),binColors:a.binColors,plotMode:a.plotMode??"hardBin",fallbackFormat:a.fallbackFormat,activeFindingId:J,warnings:f.warnings?.display??!0?ge:[],findingsFilter:Di,findingsNotice:en(),onFindingsFilterChange:R,onSaveText:V.onSaveText,attributes:f.attributes,onFindingClick:(o,i)=>{J===o.id?(Oe(),eo()):(xt(),So(o,i)),R()},activeTest:pe,onTestClick:o=>{const i=pe===o;i||xt(),Oe(),i?eo():vo(o),R()},onShowChart:I?o=>{Ge(!0),$o().then(i=>i?.showWorthCard(o))}:void 0,onWaferClick:Hi,findingsFor:ji,dieListOptions:f.dieList,onLocateDie:(o,i)=>me(i,o),onClose:()=>cn(!1)}),{onDone:()=>{const o=at;at=null,o?.()}})}else Ni()}function ho(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let Bt=[];function yo(){if(Bt.length!==0){for(const e of Bt)C[e]?.setOptions({plotMode:a.plotMode,activeTest:a.activeTest});Bt=[]}}function Oe(){J=null,pe=null,nn(),on(),yo(),P({highlightBin:void 0},{fireCallback:!1})}function bo(){J===null&&pe===null||(Ve=null,Oe(),R())}function wo(e,t){const n=tt();if(n===void 0||n.some(i=>i.testNumber===e))P({plotMode:"value",activeTest:e,highlightBin:void 0},{fireCallback:!1});else{P({highlightBin:void 0},{fireCallback:!1});const s=ie.has(a.plotMode??"hardBin")?null:t;if(s){for(const l of s)C[l]?.setOptions({plotMode:"value",activeTest:e});Bt=[...s]}}}function vo(e){pe=e;const t=o=>x[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=x.map((o,i)=>i).filter(o=>t(o)?.length);if(wo(e,n.length?n:null),nn(),on(),!ie.has(a.plotMode??"hardBin"))for(const o of n)Dt(t(o),[o])}function So(e,t){if(J===e.id){Oe();return}J=e.id,pe=null,t&&(t.style.background=w.bgActive,t.style.fontWeight="600"),yo();const{kind:n,index:o}=e.variable;if(n==="test")wo(o??0,ho(e));else{const s=x.some(u=>u?.dies?.some(d=>d.hbin!=null)),l=ni(x.map(u=>u?Ue(u):void 0));P({plotMode:Ta(e,a.plotMode,s),highlightBin:Oa(e,l,s)},{fireCallback:!1})}nn(),on();const i=e.highlight;if(i.kind==="wafer"){ro(i.waferIndices);const s=gi(e);for(const l of i.waferIndices){const u=i.dieKeysByWafer?void 0:x[l]?.statsSummary?.findings.find(m=>gi(m)===s),d=i.dieKeysByWafer?.[l]??u?.highlight?.dieKeys;d?.length&&Dt(d,[l])}}else i.kind==="bin"?i.dieKeys?.length&&Dt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Dt(i.dieKeys)}function rn(){return!!S&&S.style.display!=="none"}function cn(e){!S||e===rn()||(e&&R(),S.style.display=e?"flex":"none",re())}function re(){Ct&&(Zt(H),Qt(H,"inline-flex"),Ct.sync({visible:!!(_||se()||oo())&&!!S&&!Ke,open:rn(),notable:!!(se()?.hasNotableFindings||B().some(e=>e?.statsSummary?.hasNotableFindings))}))}const H=r.ownerDocument.createElement("div");H.dataset.wmapToolbar="gallery",Object.assign(H.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,padding:"0",boxShadow:Ln.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const Co=()=>{const e=ot();e&&(e.remove(),it(null)),gt(ce,!1)},ce=je("mode","Plot mode",()=>{if(ot()){Co();return}const e=B().flatMap(y=>y?.dies??[]),t=tt(),{testEntries:n,binEntries:o,stackedEntries:i}=fa(e,t,{includeStacked:!0}),s=B().filter(Boolean).length,l=y=>{if(y===void 0)return s;let E=0;for(const A of B())A?.dies?.some(j=>hi(j,y)!==void 0||nl(j,y)!==void 0)&&E++;return E},u=s<2?n:n.map(y=>{const E=l(y.activeTest);return E===s?y:{...y,label:`${y.label} \u2014 ${E} of ${s} wafers`}}),d=a.plotMode??"hardBin",m=a.activeTest??0;function v(y){return y.plotMode!==d?!1:y.plotMode==="value"?m===(y.activeTest??0):y.plotMode==="metadata"?a.activeMetadataKey===y.activeMetadataKey:!0}function p(y,E){y.activeTest!==void 0?P({plotMode:"value",activeTest:y.activeTest,activeMetadataKey:void 0,logScale:y.logScale}):y.activeMetadataKey!==void 0?P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:y.activeMetadataKey,passFailDisplay:"off"}):P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),it(null),gt(ce,!1)}const c=new Set,g=B().flatMap(y=>y?.metadataFields??[]).filter(y=>!c.has(y.key)&&c.add(y.key)).filter(y=>pa(e,y.key)).map(ui);ke===0&&$s(B())&&g.push(ui(Rs));const h=Us(ce.getBoundingClientRect(),u,o,i,v,p,{makeMenuRow:Ei,makeMenuSection:Oi},d,ce.ownerDocument.defaultView??window,g);li(ce).appendChild(h),it(h),gt(ce,!0),ri(h,ce,Co)});gt(ce,!1);const _i=()=>x.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:Ki,sync:xo}=na(He,()=>({...a,plotMode:a.plotMode??"hardBin"}),_i,e=>P(e));xo();const Gi=k.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function Et(){const e=tt(),{testNumber:t}=Ds(a.activeTest??0,e);return{testNumber:t,td:Bs(e,t)}}function Mo(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function lt(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&!Fn(e)}function qi(){if((a.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=Et();return B().some(n=>n?.dies?.some(o=>hi(o,e,t)!==void 0))}function Xi(e,t){if(!t||!Fn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((ci(a)==="spec"&&n?"spec":a.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,l=-1/0;for(const u of B())if(u)for(const d of u.dies){const m=Fa(d,e);m!==void 0&&(m<s&&(s=m),m>l&&(l=m))}if(isFinite(s))return s===l?[s,s+1]:[s,l]}function Ot(e,t,n){const o=a[e];if(o===t||o!=null&&t!=null&&n(o,t))return!1;a={...a,[e]:t};for(const i of C)i&&i.setOptions({[e]:t});return!0}function ko(){if((a.plotMode??"hardBin")!=="metadata")return;const e=a.activeMetadataKey;if(!e)return;if(mt(a))return{key:e,values:[...Fs]};const t=new Set;for(const n of B())if(n)for(const o of Es(n.dies,e))t.add(o);return{key:e,values:[...t].sort(jn)}}function dn(){Ot("metadataValueOrder",ko(),(e,t)=>e.key===t.key&&jt(e.values,t.values))}function un(){if((a.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=Et(),n=Xi(e,t);Ot("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const l=m=>Array.isArray(m)?{test:void 0,range:m}:{test:m.test,range:m.range},u=l(i),d=l(s);return u.test===d.test&&jt(u.range,d.range)})}let fn=!1;function Yi(){if(fn)return;fn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{fn=!1,un(),dn(),Oo(),Eo()})}let pn=!1;function Ui(){if(pn)return;pn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{pn=!1,Ft()})}let Do=[];function K(){const{colors:e,mixedHardBins:t}=Ts(B().filter(n=>n!=null),{binColorScheme:a.binColorScheme,useDefinedBinColors:a.useDefinedBinColors});return Do=t,e}function mn(){return x.filter(e=>e!=null).flatMap(e=>e.dies)}function Bo(){return a.compact?_a(mn()):void 0}const Zi=(e,t)=>jt(e.columns,t.columns)&&jt(e.rows,t.rows);function Eo(){Ot("compactMap",Bo(),Zi)&&jo()}function Qi(){return Ka(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig))}function Oo(){Ot("binColors",K(),Ws),Te()}const Ji=sa(He,()=>ra(a,Gi,{functionalActive:lt(),hasLimits:Mo()&&!lt(),hasRecorded:qi()&&!lt(),binMode:(a.plotMode??"hardBin")==="hardBin"||(a.plotMode??"hardBin")==="softBin"},e=>P(e),{on:!!a.compact,offered:Qi(),onChange:e=>P({compact:e}),onDiagnostics:()=>da(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:r,onSaveText:V.onSaveText})}),()=>ca(a)),{btn:es,sync:To}=ia(He,()=>({plotMode:a.plotMode,legendPosition:Ze}),e=>{Ze=e;for(const t of C)t&&t.setOptions({legendPosition:Ze})},{get:()=>bt,set:e=>{bt=e,Kn()},blockedReason:Qe});To();const ts=[{value:"mean",label:"Mean"},{value:"median",label:"Median"},{value:"stddev",label:"Std Dev"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"count",label:"Count"}],Lo=so("aggr","Aggregation method",()=>ts,()=>a.aggregationMethod??"mean",e=>P({aggregationMethod:e}));function Po(){const e=a.plotMode==="stackedValues";Lo.style.display=e?"":"none"}Po();const{btn:ns,sync:Wo}=oa(He,()=>({...a,functionalActive:lt()}),e=>P(e));Wo();const Tt=je("specRange","Colour bar range: test limits",()=>{const e=a.colorbarRangeMode==="data"?"spec":"data";P({colorbarRangeMode:e})});function Ro(){const e=(a.plotMode??"hardBin")==="value"&&Mo()&&ci(a)==="off"&&!lt();Tt.style.display=e?"":"none";const t=(a.colorbarRangeMode??"spec")==="spec";io(Tt,t),Tt.ariaLabel=t?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"}Ro();const os=aa(He,()=>a,e=>P(e)),is=je("downloadAll","Download gallery PNG",vs),Ne=je("boxSelect","Select the same dies on every wafer",()=>{le&&Ee.size>0?uo():Fi(!le)});Ne.style.position="relative";const rt=r.ownerDocument.createElement("span");rt.dataset.wmapSelectAcrossCount="1",Object.assign(rt.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:Y.pill,background:w.iconActive,color:w.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Ne.appendChild(rt);function Lt(){io(Ne,le);const e=le?Ee.size:0;rt.style.display=e>0?"block":"none",rt.textContent=e>99?"99+":String(e),Ne.ariaLabel=le?e>0?`Select the same dies on every wafer: on, ${e.toLocaleString()} die position${e===1?"":"s"} selected (click to clear the selection)`:"Select the same dies on every wafer: on (click to turn off)":"Select the same dies on every wafer: off (click to turn on)",Ne.setAttribute("aria-pressed",String(le))}const ee=r.ownerDocument.createElement("button");ee.type="button",ee.dataset.wmapPickedWafers="1",Object.assign(ee.style,{display:"none",border:"none",background:w.bgActive,color:w.iconActive,borderRadius:Y.control,padding:`${M.xs} ${M.md}`,fontSize:N.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),Pn(ee,"bare"),ee.addEventListener("click",Ii);const ss=so("columns","Columns",()=>[{value:"auto",label:"Auto (0)"},{value:"1",label:"1 column (1)"},{value:"2",label:"2 columns (2)"},{value:"3",label:"3 columns (3)"},{value:"4",label:"4 columns (4)"},{value:"5",label:"5 columns (5)"}],()=>T!=null?String(T):"auto",e=>Sn(e==="auto"?void 0:Number(e))),L=r.ownerDocument.createElement("div");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:"0"}),H.appendChild(L),L.appendChild(ce),L.appendChild(Ki),L.appendChild(Lo),L.appendChild(ns),L.appendChild(Tt),L.appendChild(De()),L.appendChild(Ji),L.appendChild(De()),L.appendChild(es),L.appendChild(De()),L.appendChild(os),L.appendChild(De()),L.appendChild(ss),L.appendChild(De()),L.appendChild(Ne),L.appendChild(ee),L.appendChild(is),Lt();let te=null,Pt=null,ge=[],Ao=!1;function Te(){const e=ja({lotStatsSummary:se(),result:{warnings:[...B().flatMap(n=>n?.warnings??[]),...Ie().warnings]},extra:[a.binColors&&Ls(a.binColors,a.plotMode),Ps(Do),xi(_n())].filter(n=>!!n)}),t=e.length!==ge.length||e.some((n,o)=>n.code!==ge[o]?.code||n.message!==ge[o]?.message);ge=e,(t||!Ao)&&(Ao=!0,f.warnings?.onWarning?.(e)),as()}function as(){if(!te||!Pt)return;const e=ge.length,t=e>0;if(te.style.display=t?"flex":"none",Pt.style.display=t?"":"none",Zt(H),Qt(H,"inline-flex"),!t)return;const n=Na(ge[0]),o=`${e} data ${e===1?"warning":"warnings"}`;te.style.color=n==="error"?w.errText:w.warnText,te.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(f.warnings?.display??!0)&&(Pt=De(),te=je("warning","Data warnings",()=>{const e=ot();if(Mt(new MouseEvent("click")),e)return;const t=za(te.getBoundingClientRect(),ge,te.ownerDocument.defaultView??window);li(r).appendChild(t),it(t),ri(t,te,()=>Mt(new MouseEvent("click")))}),gt(te,!1),H.appendChild(Pt),H.appendChild(te)),Te();function gn(e){import("./userGuideHtml.js").then(t=>ga({buildWaferMap:Pa,renderWaferMap:Ma,renderWaferGallery,analyzeWaferMap:$n},t.USER_GUIDE_HTML,O,r,e))}const ls=ha(e=>gn(e));D&&(H.appendChild(De()),H.appendChild(je("help","User guide",()=>gn())));const _e=r.ownerDocument.createElement("div");_e.dataset.wmapGalleryMeta="1",Object.assign(_e.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${M.sm} ${M.lg}`,fontSize:N.sub,lineHeight:oi.none,boxSizing:"border-box"});const Le=r.ownerDocument.createElement("div");Object.assign(Le.style,{background:w.canvasBg,display:"flex",alignItems:"stretch",gap:M.lg,paddingBottom:M.lg,minWidth:"0"});const he=r.ownerDocument.createElement("div");he.dataset.wmapGalleryLegend="1",Object.assign(he.style,{display:"flex",flexDirection:"column",gap:M.sm,background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,padding:`${M.sm} ${M.lg}`,marginBottom:M.lg,boxShadow:Ln.panel,fontSize:N.body,lineHeight:oi.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const Z=r.ownerDocument.createElement("div");Object.assign(Z.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let ye=null,ct=null,Fo=null;function $o(){return I?ye?Promise.resolve(ye):(Fo??=Promise.all([import("./insightsTab.js"),qt()]).then(([{createInsightsTab:e},t])=>(ye=e({pageFilter:t,showFilterButton:!1,initialAxisPrefs:In(a),onAxisPrefsChange:n=>{a={...a,...Ha(n)};const o=[...Vn];f.onViewOptionsChange?.(Ht(a),o,An(o))},attributes:f.attributes,getItems:()=>W,getLotStats:()=>_,getBinColors:()=>a.binColors??K(),getRingCount:()=>ne({ringCount:yt()},"the Insights tab"),defaultView:f.insights?.defaultView,plotStore:$,onPickPlotsFile:f.insights?.onPickPlotsFile,showPatMap:()=>{Ge(!1),P({plotMode:"metadata",activeTest:void 0,activeMetadataKey:As,passFailDisplay:"off"})},showOnMap:n=>{if(Ge(!1),n.kind==="test")xt(),Oe(),vo(n.testNumber);else{const o=se(),i=o?La(o).findings.find(s=>s.id===n.id):void 0;i&&J!==i.id&&(xt(),So(i))}cn(!0),R()},onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,ownerDocument:r.ownerDocument,locateDie:(n,o)=>{Ge(!1),me(o,n)},openWafer:(n,o,i)=>{const s=B()[n];if(!s)return;let l=null;const u=Js({title:o,onClose:()=>l?.destroy(),anchor:r});qo(u,o,s.wafer.metadata??void 0),l=kn(u.contentWrap,s,i,void 0,di(u))}}),ct=ye.el,ct.style.display="none",r.appendChild(ct),ye)),Fo):Promise.resolve(null)}let Ke=!1,hn=null;function Ge(e){I&&(Ke=e,hn?.setInsightsOpen(e),ct&&(ct.style.display=e?"flex":"none"),Z.style.display=e?"none":"flex",fe&&(fe.el.style.display=q?.get()&&!e?"":"none"),L.style.display=e?"none":"inline-flex",Zt(H),Qt(H,"inline-flex"),H.style.display="inline-flex",re(),Ft(),e&&$o().then(t=>{!t||!Ke||(t.el.style.display="flex",t.render())}))}I&&f.insights?.defaultOpen&&queueMicrotask(()=>Ge(!0));const rs=6,cs=4,Wt=240,yn=480,ds=720,us=1.25;let Pe=yn;function Io(e){const t=z*2+110+2,n=Vo();if(n)return Math.ceil(n.across*cs+t);let o=null;for(const i of e){if(i==null||!i.dies?.length)continue;const s=i.dies[0].width;if(!(s>0))continue;const l=i.wafer.radius*2*(rs/s),u=Math.ceil(l+t);(o==null||u>o)&&(o=u)}return o}function fs(e){const t=Io(e);return t==null?Wt:Math.min(Pe,Math.max(Wt,t))}function ps(e){const t=Io(e);if(t==null)return!1;const n=Math.min(ds,Math.max(yn,t));return n<=Pe?!1:(Pe=n,!0)}function Vo(){const e=a.compact?a.compactMap:void 0,t=x.find(i=>i?.dies?.length)?.dies[0];if(!e||!t||e.columns.length===0||e.rows.length===0||!(t.width>0)||!(t.height>0))return;const n=(a.rotation??0)%180!==0,o=a.showXYIndicator?2.5:0;return{across:(n?e.rows.length:e.columns.length)+o,down:(n?e.columns.length:e.rows.length)+o,cellAspect:n?t.height/t.width:t.width/t.height}}function Ho(e,t){const n=Vo();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 ms(){for(const e of ue)e?.parentElement&&Ho(e.parentElement,e)}function jo(){Pe=yn,dt=Wt,vn(x.map(e=>e??null)),Rt(),ms()}function bn(){return zo()?`${Pe}px`:"none"}function zo(){return T==null&&!wn}let wn=!1;function Rt(){const e=bn();for(const t of Array.from(F.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let dt=Wt,No=0;function vn(e){if(ps(e)&&Rt(),T==null){const n=fs(e);n>dt&&(dt=n)}xn()}function Sn(e){T=wi(e),Rt(),xn()}let At=!1;r.addEventListener("pointerenter",()=>{At=!0}),r.addEventListener("pointermove",()=>{At=!0}),r.addEventListener("pointerleave",()=>{At=!1});const gs=()=>{if(At)return!0;try{return r.matches(":hover")}catch{return!1}},_o=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||Ke||!gs()&&!r.contains(e.target)||!/^[0-5]$/.test(e.key)||r.ownerDocument.querySelector('[role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||(e.preventDefault(),Sn(e.key==="0"?void 0:Number(e.key)))};r.ownerDocument.addEventListener("keydown",_o);function Cn(e){return`repeat(${e}, minmax(0, ${zo()?`${Pe}px`:"1fr"}))`}function Ko(e){F.style.gridTemplateColumns!==e&&(F.style.gridTemplateColumns=e)}function xn(){if(T!=null){Ko(Cn(T));return}const e=Math.max(1,No),t=12,n=F.clientWidth||0,o=l=>(n-t*(l-1))/l;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const l=Math.min(Pe,dt*us),u=d=>{let m=0;for(;m<e&&o(m+1)>=d;)m++;return m};i=u(l)||u(dt)||1}const s=n>0&&i<e;s!==wn&&(wn=s,Rt()),Ko(Cn(i))}const F=r.ownerDocument.createElement("div");if(Object.assign(F.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Cn(1),gap:M.xl,paddingLeft:oe,paddingRight:oe,justifyContent:"start",alignContent:"start",isolation:"isolate"}),Re?.placement){const e=Re.placement;S=zn(e,oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.display="flex",S.style.flexDirection="column"}else if(_||se()||oo()){const e=!!Re?.defaultOpen;S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display=e?"flex":"none",R()}re(),(Re?.placement??"right")==="left"?(S&&Z.appendChild(S),Z.appendChild(F)):(Z.appendChild(F),S&&Z.appendChild(S));const We=r.ownerDocument.createElement("div");Object.assign(We.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:oe,paddingRight:oe,paddingTop:oe,zIndex:"1",background:w.menuBg}),Le.appendChild(_e),Le.appendChild(H),Ct=Ms(r.ownerDocument,()=>cn(!rn())),Le.appendChild(Ct.el),re(),I&&(hn=xs(r.ownerDocument,"Maps","lot",e=>Ge(e)),Le.appendChild(hn.el)),I&&(St=ya(r.ownerDocument,"Filter\u2026","wmapGalleryFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{qt().then(e=>e.openEditor(St??r,Yt()))}),St.style.order="1",Le.appendChild(St)),We.appendChild(Le),We.appendChild(he),r.appendChild(We),r.appendChild(Z);function Ft(){he.innerHTML="";const e=a.plotMode??"hardBin",t=!Ke&&si.has(e),n=x.filter(b=>b!=null&&!xe.has(b)),o=n.find(b=>b.isLotStack),i=Ga(n.map(b=>({metadata:b.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:f.attributes}),s=e==="metadata",l=a.activeMetadataKey,u=t&&!s?vi(n,b=>(e==="softBin"?b.sbin:b.hbin)??void 0,Se):{counts:new Map,total:0,pass:0},d=t&&!s?a.binColors??K():void 0,m=d?e==="softBin"?d.pass.soft:d.pass.hard:new Set,v=va(u.counts.entries(),m).map(([b])=>b),p=t&&s&&l?vi(n,b=>Os(b.metadata?.[l])):{counts:new Map,total:0,pass:0},c=s?ko()?.values:void 0,g=t&&s?(c??[...p.counts.keys()].sort(jn)).filter(b=>p.counts.has(b)):[];if(_e.innerHTML="",i&&_e.appendChild(i),_e.style.display=i?"flex":"none",!v.length&&!g.length){he.style.display="none";return}he.style.display="flex";const h=r.ownerDocument.createElement("div");Object.assign(h.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${M.sm} ${M.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),he.appendChild(h);const y=Hn(a.highlightBin),E=x.flatMap(b=>b?.metadataFields??[]).find(b=>b.key===l),A=s?E?.label??(l?Ua(l):"Metadata"):Gs[e],j=r.ownerDocument.createElement("span");if(j.textContent=A,Object.assign(j.style,{fontSize:N.body,fontWeight:"700",letterSpacing:Ns,textTransform:"uppercase",color:w.label,flexShrink:"0"}),h.appendChild(j),!s&&u.total>0){const b=u.pass,G=b/u.total*100,be=r.ownerDocument.createElement("span");be.textContent=`Yield ${Nt(G)}`,Object.assign(be.style,{fontSize:N.body,fontWeight:"700",color:w.value,whiteSpace:"nowrap",flexShrink:"0"});const we=r.ownerDocument.createElement("span");we.textContent=`${b.toLocaleString()} / ${u.total.toLocaleString()} dies`,Object.assign(we.style,{fontSize:N.body,color:w.label,whiteSpace:"nowrap",flexShrink:"0"}),h.appendChild(be),h.appendChild(we)}if(s){const b=Hn(a.highlightMetadataValue);g.forEach((G,be)=>{const we=b.includes(G),Ye=E?.values?.find(On=>On.value===G),pt=Ye?.color??js(be),ti=p.counts.get(G)??0;Si(h,{color:pt,isActive:we,label:Ye?.label??G,count:ti,percent:p.total>0?ti/p.total*100:void 0,onClick:On=>{const Cs=yi(a.highlightMetadataValue,G,On);bo(),P({highlightMetadataValue:Cs})}})});return}const ft=e==="softBin"?x.flatMap(b=>b?.sbinDefs??[]):x.flatMap(b=>b?.hbinDefs??[]),Qo=new Set,Bn=[];for(const b of ft)Qo.has(b.bin)||(Qo.add(b.bin),Bn.push(b));const En=Bn.length>0?new Map(Bn.map(b=>[b.bin,b])):null,Jo=d??a.binColors??K(),Ss=e==="softBin"?Jo.soft:Jo.hard,ei=b=>Ss.get(b)??Hs;for(const b of v){const G=y.includes(b),be=En?.get(b),we=u.counts.get(b)??0;Si(h,{color:ei(b),isActive:G,label:be?.name?`${b} \xB7 ${be.name}`:`Bin ${b}`,count:we,percent:u.total>0?we/u.total*100:void 0,onMenu:(Ye,pt)=>Ri(e==="softBin"?"soft":"hard",b,Ye,pt),onClick:Ye=>{const pt=yi(a.highlightBin,b,Ye);bo(),P({highlightBin:pt})}})}u.total>0&&v.length>1&&he.appendChild(il(r.ownerDocument,[...u.counts.entries()].sort(([,b],[,G])=>G-b).map(([b,G])=>({color:ei(b),count:G,label:En?.get(b)?.name?`${b} \xB7 ${En.get(b).name}`:`Bin ${b}`})),u.total))}function qe(e){const t=B().filter(p=>p!==null&&!xe.has(p));if(!t.length)return[];const n=t.map(p=>p.dies.filter(tl).filter(c=>!c.filteredOut)),o=t[0].wafer,i=t.length,s=ni(t.map(p=>Ue(p)));if(!s)return[];const l=new Set(t.map(p=>ne(p,"renderWaferGallery")));if(l.size!==1)return[];const u=[...l][0],d=o.metadata?{...o,metadata:(({wafer:p,waferId:c,...g})=>g)(o.metadata)}:o;function m(p,c){return{...p,stats:{...p.stats,isLotStack:!0,aggregationMethod:c,lotSize:i}}}function v(p,c){const g=p.map(h=>({...h,hbin:void 0,sbin:void 0}));return $n({wafer:d,dies:g,passBins:[...s],ringCount:u,testDefs:[{testNumber:0,name:c}]},{testNumbers:[0]})}if(e==="stackedValues"){const p=tt();let c=p?.filter(Fn);if(p!==void 0&&c?.length===0)return[];if(p?.length||(c=ks(t.flatMap(y=>y.dies)).map(y=>({testNumber:y,name:Za(void 0,y)}))),!c?.length)return[];const g=a.aggregationMethod??"mean";return c.map(h=>{const y=xa(n,g,h.testNumber),E={testNumber:0,name:h.name,unit:h.unit,...Ja(h)};return{wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E],label:`${Qa(h,h.testNumber)} \xB7 ${g}`,isLotStack:!0,aggrMethod:g,lotSize:i,statsSummary:m($n({wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E]},{testNumbers:[0]}),g)}})}if(e==="stackedBins"){let p=Vt(t.map(c=>c?.hbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.hbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=fi(n,c.bin,"hard"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,hbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in hard bin ${c.bin}`),"countBin")}})}if(e==="stackedSoftBins"){let p=Vt(t.map(c=>c?.sbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.sbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=fi(n,c.bin,"soft"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,sbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in soft bin ${c.bin}`),"countBin")}})}return t}function $t(e){const t=B().length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:a.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function P(e,{fireCallback:t=!0}={}){const n=Object.keys(e);if(n.length>0&&n.every(c=>Vn.includes(c))){a={...a,...e},ye?.setAxisPrefs(In(a)),t&&f.onViewOptionsChange?.(Ht(a),n,An(n));return}Vn.some(c=>c in e)&&ye?.setAxisPrefs(In({...a,...e}));const o=a.plotMode,i=mt(a),s=Qe()!==null;a={...a,...e};const l=a.plotMode,u=ie.has(l),d=mt(a),m=o!==void 0&&ie.has(o),v=ke>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const c=K();a={...a,binColors:c},e={...e,binColors:c}}if("compact"in e){const c=Bo();a={...a,compactMap:c},e={...e,compactMap:c}}if(("compact"in e||a.compact&&("rotation"in e||"showXYIndicator"in e))&&jo(),e.plotMode!==void 0)if(u){const c=$t(l);if(a={...a,...c},v)for(const g of C)g&&g.setOptions(e);else X(qe(l))}else if(m){const{valueRange:c,lotSize:g,aggregationMethod:h,...y}=a;if(a=y,v)for(const E of C)E&&E.setOptions(e);else X(d?$e(W.filter(E=>E!==null)):B().filter(E=>E!==null))}else if(i!==d&&!v)X($e(W.filter(c=>c!==null)));else for(const c of C)c&&c.setOptions(e);else if(e.aggregationMethod!==void 0&&l==="stackedValues")if(v)for(const c of C)c&&c.setOptions(e);else X(qe("stackedValues"));else for(const c of C)c&&c.setOptions(e);Qe()!==null!==s&&Kn(),Ft(),Po(),To(),xo();const p=e.plotMode!==void 0&&e.plotMode!==o;(Ea.some(c=>c in e)||p)&&R(),Te(),Wo(),Ro(),un(),dn(),t&&f.onViewOptionsChange?.(Ht(a),n,An(n))}function Go(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:N.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=bi(e,o,t,n,f.attributes);return{wrap:o,metaPanel:s}}function qo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||qa(n??{}).length===0)return;const i=o.parentElement,s=r.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const l=bi(r.ownerDocument,s,t,n,f.attributes);l&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(l))}function Mn(e,t,n){const o=r.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,boxShadow:Ln.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:bn(),maxHeight:bn()});const i=r.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm});const{wrap:s,metaPanel:l}=Go(document,ht(e,t),e.wafer.metadata??void 0);i.appendChild(s);const u=r.ownerDocument.createElement("button");u.dataset.wmapExpandBtn="1",u.setAttribute("aria-label","Open full view"),Wn(u),u.innerHTML=Tn.expand,Object.assign(u.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,background:w.panelBg,color:w.label,padding:M.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),Pn(u),i.appendChild(u),i.addEventListener("click",c=>{(c.ctrlKey||c.metaKey)&&(c.preventDefault(),c.stopPropagation(),$i(x.indexOf(e)))},!0),o.appendChild(i);const d=r.ownerDocument.createElement("div");Object.assign(d.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(d),Ho(o,d),l&&d.appendChild(l),F.appendChild(o),o.addEventListener("contextmenu",c=>{if(c.defaultPrevented)return;c.preventDefault();const g=e.viewOptions?{...a,...e.viewOptions}:a,h=sn()??go(t),y=h?.source??ka(e.dies,{waferLabel:ve(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:g.plotMode==="value"?g.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:Se(e),ringCount:ne(e,"renderWaferGallery")}),E={x:c.clientX,y:c.clientY};import("./drilldown.js").then(({openDrilldownMenu:A})=>{o.isConnected&&A(E,o,y,h?{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...h.ctx}:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:p.getSaveImageHook(),onSaveText:p.getSaveTextHook(),onLocateDie:j=>me(t,j)})})});const m=bt||Qe()!==null,v=e.viewOptions?{...a,...e.viewOptions}:a,p=pi(d,e,{viewOptions:{...v,showLegend:m,legendPosition:Ze},showTooltip:!0,padding:z,statsSummary:e.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:e.onClick,onSelect:co(e),drilldownSourceOverride:()=>Wi(t),insights:de,onExpand:()=>ut(t,e),showIdentity:!1,chromeInset:Ks,drawWhenVisible:!0});return p.setViewControlsVisible(!1),p.setSummaryVisible(!1),u.onclick=()=>ut(t,e),xe.has(e)&&(o.style.display="none"),{card:o,ctrl:p,canvasWrapper:d,expandBtn:u}}function hs(e){const t=Fe[e];if(!t)return;const n=[...Q.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Tn.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>bs(n.id)):(t.innerHTML=Tn.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>ut(e,x[e]))}function X(e){ws(),ot()?.remove(),it(null),Oe(),x=[],U.clear(),ln.clear(),ee.style.display="none";for(const d of C)d&&d.destroy();C=[],ue=[],Fe=[],ke=0,F.innerHTML="",No=e.length,vn(e.map(d=>typeof d=="function"?null:d));const t=[];for(let d=0;d<e.length;d++){const m=e[d];if(typeof m=="function"){const v=r.ownerDocument.createElement("div");v.className="wmap-gallery-card",Object.assign(v.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const p=r.ownerDocument.createElement("span");p.textContent="\u2026",Object.assign(p.style,{color:w.label,fontSize:"18px"}),v.appendChild(p),F.appendChild(v),x.push(null),C.push(null),ue.push(null),Fe.push(null),t.push({index:d,factory:m,placeholder:v}),ke++}else{const{ctrl:v,canvasWrapper:p,expandBtn:c}=Mn(m,d,e.length);x.push(m),C.push(v),ue.push(p),Fe.push(c)}}Oo(),Ft(),un(),dn(),Eo();const n=++nt,o=()=>{setTimeout(()=>{n===nt&&f.onItemsResolved?.()},0)},i=d=>{setTimeout(()=>{n===nt&&f.onItemResolved?.(d,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let l=0;function u(){if(n!==nt)return;if(l>=t.length){if(ie.has(a.plotMode)){const A=a.plotMode;X(qe(A));return}if(wt){Ut();return}at=o,R(),ze||(at=null,o());return}const{index:d,factory:m,placeholder:v}=t[l++],p=m();W[d]=p;const c=Gt(p,d);Je(p,d)!==p&&(ae=!0),x[d]=c,vn([c]);const{card:g,ctrl:h,canvasWrapper:y,expandBtn:E}=Mn(c,d,e.length);C[d]=h,ue[d]=y,Fe[d]=E,ke--,v.replaceWith(g),i(++s),Ui(),Yi(),!S&&!Re?.placement&&c.statsSummary?.findings.length&&(S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display="none",(Re?.placement??"right")==="left"?Z.insertBefore(S,F):Z.appendChild(S),R(),re()),re(),setTimeout(u,0)}t.length>0?setTimeout(u,0):o()}if(ie.has(a.plotMode)&&B().length>0){const e=$t(a.plotMode);a={...a,...e},X(qe(a.plotMode))}else X($e(k));f.insights?.filter!==void 0&&qt(),Te();let Xe=0;const Xo=new(r.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Xe)return;Xe=(r.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Xe=0,T==null&&xn()})});Xo.observe(F);const Yo=()=>{r.style.setProperty("--wmap-sticky-top",`${We.offsetHeight}px`)};Yo();const Uo=new(r.ownerDocument.defaultView??window).ResizeObserver(Yo);Uo.observe(We),S&&R();function ys(e,t){const n=ue[e];if(!n)return;n.innerHTML="",Object.assign(n.style,{alignItems:"center",justifyContent:"center"});const o=r.ownerDocument.createElement("span");o.textContent=t?"Opened in its own window":"Opened in the wafer viewer",Object.assign(o.style,{color:w.label,fontSize:N.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function ut(e,t){for(const l of Q.values())if(l.cardIndex===e)return;const n=ht(t,e),o=ki++,i=C[e]?.getOptions(),s=Zs(n);if(s){const l=s.document;l.title=n,Object.assign(l.documentElement.style,{height:"100%"}),Object.assign(l.body.style,{margin:"0",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",fontFamily:N.family}),ea(r,l.documentElement);const u=ta(r,l.documentElement,()=>y.setOptions({})),d=l.createElement("div");d.dataset.wmapWindowBanner="1",d.textContent=n,Object.assign(d.style,{display:"none",padding:`${M.sm} ${M.xl}`,fontSize:N.body,fontWeight:"700",background:w.warnBg,color:w.warnText,borderBottom:`1px solid ${w.warnBorder}`,flexShrink:"0"}),l.body.appendChild(d);const m=l.createElement("div");Object.assign(m.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),l.body.appendChild(m);const{wrap:v,metaPanel:p}=Go(l,n,t.wafer.metadata??void 0),c=l.createElement("div");Object.assign(c.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm}),c.appendChild(v),m.appendChild(c);const g=l.createElement("div");Object.assign(g.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),p&&g.appendChild(p),m.appendChild(g);let h=0;const y=kn(g,t,void 0,i,(A,j)=>{const ft=A?j:-h;try{s.resizeBy(ft,0),h=A?j:0}catch{}}),E=setInterval(()=>{s.closed&&It(o)},400);s.addEventListener("pagehide",()=>It(o)),Q.set(o,{id:o,ctrl:y,cardIndex:e,label:n,closePollId:E,stopThemeSync:u,close:()=>{s.closed||s.close()},setTitle:A=>{l.title=A,d.textContent=A,d.style.display="block"}})}else{const l=Qs({title:n,onClose:()=>It(o),anchor:r});l.contentWrap.style.flexDirection="column",qo(l,n,t.wafer.metadata??void 0);const u=kn(l.contentWrap,t,void 0,i,di(l));Q.set(o,{id:o,ctrl:u,cardIndex:e,label:n,closePollId:null,close:()=>l.close(),setTitle:d=>{const m=l.box.querySelector("[data-wmap-window-title]");m&&(m.textContent=d,m.title=d)}})}C[e]?.destroy(),C[e]=null,ys(e,s!==null),hs(e)}function kn(e,t,n,o,i){const s=t.viewOptions?{...a,...t.viewOptions}:a,l=o?{...s,...o}:s,d={...n!==void 0?{...l,plotMode:"value",activeTest:n}:l,showLegend:!0,legendPosition:Ze},m=pi(e,t,{viewOptions:d,showTooltip:!0,padding:z,statsSummary:t.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:t.onClick,onSelect:co(t),insights:de,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return m.setViewControlsVisible(!0),m.setSummaryVisible(!0),m.setExpandVisible(!1),m}function It(e){const t=Q.get(e);if(!t||(Q.delete(e),t.closePollId!=null&&clearInterval(t.closePollId),t.stopThemeSync?.(),t.ctrl.destroy(),t.cardIndex===null))return;const n=t.cardIndex,o=x[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:l,expandBtn:u}=Mn(o,n,x.length);ue[n]?.parentElement?.replaceWith(i),C[n]=s,ue[n]=l,Fe[n]=u}function bs(e){const t=Q.get(e);t&&(t.close(),It(e))}function ws(){for(const e of Q.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function Dn(){for(const e of C)e?.drawPendingNow()}const Zo=r.ownerDocument.defaultView??window;Zo.addEventListener("beforeprint",Dn);function vs(){Dn();const e=[...F.querySelectorAll("canvas")];if(!e.length)return;const t=e.length,n=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/n),i=e[0].width,s=e[0].height,l=8,u=(r.ownerDocument.defaultView??window).devicePixelRatio||1,d=Math.round(26*u),m=Math.round(12*u),v=r.ownerDocument.createElement("canvas");v.width=n*i+(n-1)*l,v.height=o*(s+d)+(o-1)*l;const p=v.getContext("2d"),c=zs(F);p.fillStyle=c.background,p.fillRect(0,0,v.width,v.height),e.forEach((g,h)=>{const y=h%n,E=Math.floor(h/n),A=y*(i+l),j=E*(s+d+l),ft=g.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";p.fillStyle=c.surface,p.fillRect(A,j,i,d),p.fillStyle=c.text,p.font=`700 ${m}px system-ui, sans-serif`,p.textAlign="left",p.textBaseline="middle",p.fillText(ft,A+Math.round(10*u),j+d/2,i-Math.round(20*u)),p.drawImage(g,A,j+d)}),v.toBlob(g=>{if(!g)return;const h=C.find(y=>y!=null)?.getExportTitle();la(g,["gallery",h].filter(Boolean).join(" "),V.onSaveImage)})}return{setItems(e){tn(),W=e.map(n=>typeof n=="function"?null:n);const t=a.plotMode;if(ie.has(t))if(e.some(o=>typeof o=="function"))X($e(e));else{const o=$t(t);a={...a,...o},X(qe(t))}else X($e(e));Jn()},setOptions(e){P(e,{fireCallback:!1})},getOptions(){return Ht(a)},setFindingsNotice(e){lo=e,R()},setColumns(e){Sn(e)},getBinColors(){return a.binColors??K()},setLotStatsSummary(e){tn(),_=e,Jn(),Te(),S&&R(),re()},openUserGuide:()=>gn(),destroy(){ls(),$.flush(),tn(),nt++,Zo.removeEventListener("beforeprint",Dn),r.ownerDocument.removeEventListener("keydown",_o),ze?.cancel(),ze=null,at=null;for(const e of[...Q.values()])e.closePollId!=null&&clearInterval(e.closePollId),e.close(),e.ctrl.destroy();Q.clear();for(const e of C)e&&e.destroy();C=[],ot()?.remove(),Xo.disconnect(),Uo.disconnect(),Xe&&((r.ownerDocument.defaultView??window).cancelAnimationFrame(Xe),Xe=0),r.ownerDocument.removeEventListener("click",Mt,!0),window.removeEventListener("blur",ao),Ci(),ai(),We.remove(),Z.remove(),S?.remove(),_t=!0,vt++,clearTimeout(Xt),fe?.el.remove(),ye?.destroy()}}}