@wafertools/wafermap 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +79 -3
  2. package/README.md +4 -3
  3. package/dist/packages/canvas-adapter/cellShade.d.ts +21 -0
  4. package/dist/packages/canvas-adapter/cellShade.js +1 -0
  5. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +19 -3
  6. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/commonality.js +4 -1
  8. package/dist/packages/canvas-adapter/charts/correlation.d.ts +11 -0
  9. package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/divergingScale.d.ts +23 -0
  11. package/dist/packages/canvas-adapter/charts/divergingScale.js +1 -0
  12. package/dist/packages/canvas-adapter/charts/groupComparison.js +1 -1
  13. package/dist/packages/canvas-adapter/charts/palette.d.ts +10 -3
  14. package/dist/packages/canvas-adapter/charts/palette.js +1 -1
  15. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +8 -0
  16. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  17. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
  18. package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
  19. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  20. package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +1 -0
  21. package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
  22. package/dist/packages/canvas-adapter/filterJson.d.ts +25 -0
  23. package/dist/packages/canvas-adapter/filterJson.js +5 -0
  24. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  25. package/dist/packages/canvas-adapter/pageFilter.js +2 -2
  26. package/dist/packages/canvas-adapter/plotEditor.js +10 -1
  27. package/dist/packages/canvas-adapter/plotJsonComplete.d.ts +46 -0
  28. package/dist/packages/canvas-adapter/plotJsonComplete.js +4 -0
  29. package/dist/packages/canvas-adapter/plotJsonHistory.d.ts +12 -0
  30. package/dist/packages/canvas-adapter/plotJsonHistory.js +1 -0
  31. package/dist/packages/canvas-adapter/plotJsonSuggest.d.ts +16 -0
  32. package/dist/packages/canvas-adapter/plotJsonSuggest.js +1 -0
  33. package/dist/packages/canvas-adapter/plotModal.js +1 -1
  34. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  35. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  36. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  37. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  38. package/dist/packages/canvas-adapter/sweepEditor.js +1 -1
  39. package/dist/packages/canvas-adapter/toCanvas.d.ts +1 -0
  40. package/dist/packages/canvas-adapter/toCanvas.js +1 -1
  41. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  42. package/dist/packages/canvas-adapter/userGuideHtml.js +81 -43
  43. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  44. package/dist/packages/canvas-adapter/version.js +1 -1
  45. package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -0
  46. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  47. package/dist/packages/core/compact.js +2 -2
  48. package/dist/packages/core/dieTable.js +1 -1
  49. package/dist/packages/core/utils.d.ts +6 -0
  50. package/dist/packages/core/utils.js +1 -1
  51. package/dist/packages/renderer/fmt.js +1 -1
  52. package/dist/packages/stats/chartCatalogue.js +1 -1
  53. package/dist/packages/stats/coFailure.d.ts +11 -0
  54. package/dist/packages/stats/coFailure.js +1 -0
  55. package/dist/packages/stats/commonality.d.ts +37 -4
  56. package/dist/packages/stats/commonality.js +1 -1
  57. package/dist/packages/stats/correlation.d.ts +7 -0
  58. package/dist/packages/stats/correlation.js +1 -1
  59. package/dist/packages/stats/dieRegions.d.ts +2 -0
  60. package/dist/packages/stats/dieRegions.js +1 -1
  61. package/dist/packages/stats/differenceMap.d.ts +2 -0
  62. package/dist/packages/stats/differenceMap.js +1 -1
  63. package/dist/packages/stats/examplePicks.d.ts +6 -0
  64. package/dist/packages/stats/examplePicks.js +1 -1
  65. package/dist/packages/stats/groupEffects.d.ts +66 -0
  66. package/dist/packages/stats/groupEffects.js +1 -0
  67. package/dist/packages/stats/plotData.d.ts +11 -2
  68. package/dist/packages/stats/plotData.js +1 -1
  69. package/dist/packages/stats/plotSpec.d.ts +31 -2
  70. package/dist/packages/stats/plotSpec.js +4 -4
  71. package/dist/packages/stats/plotTable.d.ts +18 -0
  72. package/dist/packages/stats/plotTable.js +1 -0
  73. package/dist/packages/stats/renderFindingsReport.js +1 -1
  74. package/dist/packages/stats/renderSummaryReport.js +7 -7
  75. package/dist/packages/stats/reportHtml.js +18 -13
  76. package/dist/packages/stats/sweep.d.ts +3 -3
  77. package/dist/packages/stats/sweepXFromName.js +1 -1
  78. package/dist/packages/stats/synthesis.d.ts +19 -0
  79. package/dist/packages/stats/synthesis.js +1 -1
  80. package/dist/packages/stats/testsByWafer.d.ts +11 -0
  81. package/dist/packages/stats/testsByWafer.js +1 -0
  82. package/package.json +1 -1
@@ -0,0 +1,46 @@
1
+ import { type PlotField } from '../stats/plotSpec.js';
2
+ export interface CompletionSource {
3
+ /** The lot's tests, for the number of a `test` or `passRate` field. */
4
+ tests?: ReadonlyArray<{
5
+ number: number;
6
+ name?: string;
7
+ }>;
8
+ /** The values a condition on `field` can name in its `values` list: what the lot holds for that field. */
9
+ conditionValues?: (field: PlotField) => readonly string[];
10
+ /** The lot's wafer fields, for a `meta` field: the key, and the name the field list shows for it. */
11
+ metaKeys?: ReadonlyArray<{
12
+ key: string;
13
+ label?: string;
14
+ }>;
15
+ /** The gradients a plot's colours can take, by name and the name to show. */
16
+ gradients?: ReadonlyArray<{
17
+ name: string;
18
+ label?: string;
19
+ }>;
20
+ /** One line about a word a setting can take (a chart, an aggregate), shown beside it. */
21
+ describe?: (setting: string, value: string) => string | undefined;
22
+ }
23
+ export interface CompletionItem {
24
+ /** What the list shows. */
25
+ label: string;
26
+ /** What replaces the range: with its quotes, and the colon after a key, as it is written in the text. */
27
+ insert: string;
28
+ detail?: string;
29
+ }
30
+ export interface Completion {
31
+ /** The text from `from` to `to` is replaced by the chosen item's `insert`. */
32
+ from: number;
33
+ to: number;
34
+ items: CompletionItem[];
35
+ /** What the reader has typed of the word being completed (empty at a bare position): the list is for that word. */
36
+ typed: string;
37
+ }
38
+ /**
39
+ * What could be written at `caret`, or undefined for nothing. `force` (Ctrl+Space) also answers where nothing has been
40
+ * typed yet; otherwise a suggestion needs the reader to be inside a string, or to have started a number.
41
+ */
42
+ export declare function completionsAt(text: string, caret: number, source?: CompletionSource, o?: {
43
+ force?: boolean;
44
+ as?: 'filter';
45
+ }): Completion | undefined;
46
+ //# sourceMappingURL=plotJsonComplete.d.ts.map
@@ -0,0 +1,4 @@
1
+ import{PLOT_BIN_BY as O,PLOT_BUILTINS as j,PLOT_CHOICES as k,PLOT_JUDGES as _}from"../stats/plotSpec.js";const x=["x","y","color","rows","facet"],v=[["test","A measured test, by number"],["name","The test\u2019s name when the plot was made"],["builtin","A built-in field: wafer, ring, bin\u2026"],["meta","A wafer field of the lot: a split, a lot"],["passRate","A test\u2019s pass rate, by number"],["judge","Judge a pass rate by limits or by the tester flag"],["tests","A set of tests, as numbers or ranges"],["names","The names of the tests of a set"],["binned","Put a value into ranges"],["bins","How many ranges"],["by","Ranges of equal count or equal width"]],I=["label","scale","min","max","reverse","includeLimits","clip","references"],K=["chart","title","fields","level","aggregate","normalize","axes","where","limits","bins","stack","sort","top","barNorm","histNorm","orientation","valueLabels","cumulative","spread","fit","identity","normalCurve","whatIf","baseline","probabilityAxis","sweep","colorGradient","colorReverse"],R=["series","xLabel","xUnit","yLabel","xScale","crossing","separationAt"],C=["label","tests","xValues","xFromName","testNames"],N=new Set(["valueLabels","cumulative","identity","normalCurve","not","off","reverse","includeLimits","clip","crossing","colorReverse"]),g=/[A-Za-z0-9_.+-]/;function P(e,n){const o=[],l=()=>o[o.length-1],r=()=>{const i=l();i&&(i.expect="comma")};let t=0;for(;t<n;){const i=e[t];if(i===" "||i===`
2
+ `||i==="\r"||i===" "){t++;continue}if(i==='"'){let s=t+1;for(;s<e.length&&e[s]!=='"'&&e[s]!==`
3
+ `;)s+=e[s]==="\\"?2:1;if(s>=n||s>=e.length||e[s]!=='"')return{frames:o,string:{start:t,prefix:e.slice(t+1,n)}};const d=l();d?.kind==="object"&&d.expect==="key"?(d.current=e.slice(t+1,s),d.seen.add(d.current),d.expect="colon"):r(),t=s+1;continue}if(i==="{"||i==="["){const s=l();o.push({start:t,kind:i==="{"?"object":"array",key:s?s.kind==="array"?"[]":s.current:void 0,expect:i==="{"?"key":"value",seen:new Set}),t++;continue}if(i==="}"||i==="]"){o.pop(),r(),t++;continue}if(i===":"){const s=l();s&&(s.expect="value"),t++;continue}if(i===","){const s=l();s&&(s.expect=s.kind==="object"?"key":"value"),t++;continue}if(g.test(i)){let s=t;for(;s<e.length&&g.test(e[s]);)s++;if(s>=n)return{frames:o,bare:{start:t,prefix:e.slice(t,n)}};r(),t=s;continue}return}return{frames:o}}const Y=e=>e.slice(1).map(n=>n.key??"");function B(e){const n=e.join("/");if(n==="")return K.map(l=>[l,void 0]);if(n==="fields")return x.map(l=>[l,void 0]);const o=e[e.length-1];if(e[0]==="fields"&&(e.length===2||e.length===3&&o==="[]"||o==="binned"))return[...e[1]==="color"?[["follow","Follow Group by"],["none","A single colour"]]:[],...v];if(n==="axes")return[["x",void 0],["y",void 0]];if(e[0]==="axes"&&e.length===2)return I.map(l=>[l,void 0]);if(n==="where")return[["conditions",void 0],["off",void 0]];if(n==="where/conditions/[]")return[["field",void 0],["values",void 0],["min",void 0],["max",void 0],["not",void 0]];if(n==="where/conditions/[]/field")return v;if(n==="whatIf")return[["lo",void 0],["hi",void 0]];if(n==="sweep")return R.map(l=>[l,void 0]);if(n==="sweep/series/[]")return C.map(l=>[l,void 0])}const D=e=>{const n=e.join("/"),o=e[e.length-1];return e[0]==="fields"&&(e.length===2||e.length===3&&o==="[]"||o==="binned")||n==="where/conditions/[]/field"};function F(e,n,o,l,r){const t=(i,s=n)=>i.map(d=>({word:d,detail:o.describe?.(s,d)}));if(l&&n==="values"&&e.join("/")==="where/conditions/[]"&&o.conditionValues&&r){const i=/"meta"\s*:\s*"([^"]+)"/.exec(r),s=/"builtin"\s*:\s*"([^"]+)"/.exec(r),d=/"test"\s*:\s*(\d+)/.exec(r),a=i?{meta:i[1]}:s?{builtin:s[1]}:d?{test:Number(d[1])}:void 0,f=a?o.conditionValues(a):[];return f.length?{kind:"string",words:f.map(m=>({word:m}))}:void 0}if(e.length===0&&n in k)return{kind:"string",words:t(k[n])};if(e.length===0&&n==="colorGradient")return o.gradients?.length?{kind:"string",words:o.gradients.map(i=>({word:i.name,detail:i.label&&i.label!==i.name?i.label:void 0}))}:void 0;if(D(e)){if(n==="builtin")return{kind:"string",words:j.map(i=>({word:i,detail:o.describe?.("builtin",i)}))};if(n==="meta")return o.metaKeys?.length?{kind:"string",words:o.metaKeys.map(i=>({word:i.key,detail:i.label&&i.label!==i.key?i.label:void 0}))}:void 0;if(n==="judge")return{kind:"string",words:t(_)};if(n==="by")return{kind:"string",words:t(O)};if((n==="test"||n==="passRate"||n==="tests"&&l)&&o.tests?.length)return{kind:"number",words:o.tests.map(i=>({word:String(i.number),detail:i.name}))}}if(e[0]==="axes"&&e.length===2&&n==="scale"||e.length===1&&e[0]==="sweep"&&n==="xScale")return{kind:"string",words:t(["linear","log"])};if(n==="follow")return{kind:"string",words:t(["groupBy"])};if(N.has(n)||n==="none"&&e[0]==="fields")return{kind:"boolean",words:[{word:"true"},{word:"false"}]}}function L(e,n){const o=n.toLowerCase();if(e.some(t=>t.label===n))return[];const l=e.filter(t=>t.label.toLowerCase().startsWith(o)),r=e.filter(t=>!t.label.toLowerCase().startsWith(o)&&t.label.toLowerCase().includes(o));return[...l,...r]}export function completionsAt(e,n,o={},l={}){const r=P(e,n),t=r?.frames[r.frames.length-1];if(!r||!t)return;const i=[...l.as==="filter"?["where"]:[],...Y(r.frames)],s=r.string?r.string.prefix:r.bare?r.bare.prefix:"";if(!r.string&&!r.bare&&!l.force)return;let d=n,a=n;if(r.string){d=r.string.start;const u=e.indexOf('"',n),b=e.indexOf(`
4
+ `,n);a=u>=0&&(b<0||u<b)?u+1:n}else if(r.bare)for(d=r.bare.start,a=n;a<e.length&&g.test(e[a]);)a++;if(t.kind==="object"&&t.expect==="key"){const u=(B(i)??[]).filter(([w])=>!t.seen.has(w));if(!u.length)return;const b=/^\s*:/.test(e.slice(a))?"":/^\s/.test(e.slice(a))?":":": ",y=L(u.map(([w,A])=>({label:w,insert:`"${w}"${b}`,detail:A})),s);return y.length?{from:d,to:a,items:y,typed:s}:void 0}const f=t.kind==="array",m=f?t.key??"":t.current;if(m===void 0||t.kind==="object"&&t.expect!=="value")return;const S=f?i.slice(0,-1):i,h=r.frames[r.frames.length-2],c=F(S,m,o,f,f&&h?e.slice(h.start,n):void 0);if(!c||r.string&&c.kind!=="string"||c.kind==="number"&&r.bare&&!/^\d*$/.test(s))return;const E=!r.string&&!r.bare&&e.slice(0,d).endsWith(":")?" ":"",p=L(c.words.map(u=>({label:u.word,detail:u.detail,insert:E+(c.kind==="string"?`"${u.word}"`:u.word)})),s);return p.length?{from:d,to:a,items:p,typed:s}:void 0}
@@ -0,0 +1,12 @@
1
+ export interface TextHistory {
2
+ /** Step back; false when there is nothing earlier. */
3
+ undo(): boolean;
4
+ /** Step forward again; false when nothing has been undone. */
5
+ redo(): boolean;
6
+ readonly canUndo: boolean;
7
+ readonly canRedo: boolean;
8
+ }
9
+ export declare function createTextHistory(area: HTMLTextAreaElement, now?: () => number): TextHistory;
10
+ /** Copy `text` to the clipboard and say which way it went; false when the host does not allow it. */
11
+ export declare function copyText(doc: Document, text: string, done: (ok: boolean) => void): void;
12
+ //# sourceMappingURL=plotJsonHistory.d.ts.map
@@ -0,0 +1 @@
1
+ const g=300,T=900;export function createTextHistory(n,i=()=>Date.now()){const e=[{value:n.value,start:n.selectionStart,end:n.selectionEnd}];let t=0,c=!1,d,a=0;const v=()=>({value:n.value,start:n.selectionStart,end:n.selectionEnd});n.addEventListener("input",o=>{if(c)return;const s=o.inputType??"",l=o.data??"",r=i(),p=s==="insertText"&&l.length===1&&!/[\s,:{}[\]]/.test(l)||s==="deleteContentBackward"||s==="deleteContentForward",h=p&&s===d&&r-a<900&&t===e.length-1&&t>0;d=p?s:void 0,a=r;const u=v();if(u.value===e[t].value){e[t]=u;return}if(h){e[t]=u;return}e.length=t+1,e.push(u),e.length>300&&e.shift(),t=e.length-1});function f(o,s){t=o,d=void 0;const l=e[o];c=!0;try{n.value=l.value,n.setSelectionRange(l.start,l.end);const r=n.ownerDocument.defaultView?.InputEvent;n.dispatchEvent(r?new r("input",{bubbles:!0,inputType:s}):new Event("input",{bubbles:!0}))}finally{c=!1}}return{undo(){return t<=0?!1:(f(t-1,"historyUndo"),!0)},redo(){return t>=e.length-1?!1:(f(t+1,"historyRedo"),!0)},get canUndo(){return t>0},get canRedo(){return t<e.length-1}}}export function copyText(n,i,e){const t=n.defaultView?.navigator;t?.clipboard?.writeText?t.clipboard.writeText(i).then(()=>e(!0),()=>e(!1)):e(!1)}
@@ -0,0 +1,16 @@
1
+ import { type CompletionSource } from './plotJsonComplete.js';
2
+ export interface JsonSuggestHandle {
3
+ /** The list, to place under the textarea. */
4
+ el: HTMLElement;
5
+ close(): void;
6
+ /** Open the list at the caret as if Ctrl/Cmd+Space were pressed; false when there is nothing to suggest there. */
7
+ show(): boolean;
8
+ }
9
+ export declare function attachJsonSuggestions(o: {
10
+ doc: Document;
11
+ area: HTMLTextAreaElement;
12
+ source: () => CompletionSource;
13
+ /** The text is a filter, not a plot: its keys and values are a filter's. */
14
+ as?: 'filter';
15
+ }): JsonSuggestHandle;
16
+ //# sourceMappingURL=plotJsonSuggest.d.ts.map
@@ -0,0 +1 @@
1
+ import{completionsAt as C}from"./plotJsonComplete.js";import{CLR as p,FONT as D,RADIUS as L,SPACE as A}from"./toolbar.js";const k=100;let $=0;export function attachJsonSuggestions(f){const{doc:l,area:t}=f,y=`wmap-json-suggest-${++$}`,s=l.createElement("div");s.id=y,s.setAttribute("role","listbox"),s.setAttribute("aria-label","Suggestions"),Object.assign(s.style,{display:"none",maxHeight:"11.5em",overflowY:"auto",border:`1px solid ${p.controlBorder}`,borderRadius:L.control,background:p.menuBg,boxSizing:"border-box",width:"100%",fontSize:D.sub}),t.setAttribute("aria-autocomplete","list"),t.setAttribute("aria-haspopup","listbox"),t.setAttribute("aria-controls",y),t.setAttribute("aria-expanded","false"),t.setAttribute("aria-keyshortcuts","Control+Space Meta+Space");let u,i=0,b=!1,g=!1;const w=e=>`${y}-${e}`;function a(){u=void 0,s.style.display="none",s.replaceChildren(),t.setAttribute("aria-expanded","false"),t.removeAttribute("aria-activedescendant")}function m(){[...s.children].forEach((e,r)=>{const n=r===i;e.setAttribute("aria-selected",String(n)),e.style.background=n?p.menuActive:"transparent",n&&e.scrollIntoView?.({block:"nearest"})}),t.setAttribute("aria-activedescendant",w(i))}function x(e,r){u=e,i=0,b=r||e.typed.length>0,s.replaceChildren(),e.items.slice(0,k).forEach((n,v)=>{const o=l.createElement("div");o.id=w(v),o.setAttribute("role","option"),o.dataset.wmapPlotJsonSuggestion=n.label,Object.assign(o.style,{display:"flex",gap:A.md,padding:`${A.xs} ${A.md}`,cursor:"pointer",color:p.text});const h=l.createElement("span");if(h.textContent=n.label,h.style.fontFamily="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",o.appendChild(h),n.detail){const d=l.createElement("span");d.textContent=n.detail,Object.assign(d.style,{color:p.label,minWidth:"0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(d)}o.addEventListener("mouseenter",()=>{i=v,m()}),o.addEventListener("mousedown",d=>{d.preventDefault(),E(v)}),s.appendChild(o)}),s.style.display="block",t.setAttribute("aria-expanded","true"),m()}function c(e,r=!1){if(t.selectionStart!==t.selectionEnd)return a(),!1;const n=C(t.value,t.selectionStart,f.source(),{force:e,...f.as?{as:f.as}:{}});return n?x(n,r):a(),!!n}const S=()=>/[{,:[]$/.test(t.value.slice(0,t.selectionStart).trimEnd());function E(e){const r=u,n=r?.items[e];if(!(!r||!n)){a(),t.focus(),g=!0;try{t.setSelectionRange(r.from,r.to),l.execCommand?.("insertText",!1,n.insert)||(t.setRangeText(n.insert,r.from,r.to,"end"),t.dispatchEvent(new Event("input",{bubbles:!0})))}finally{g=!1}/:\s?$/.test(n.insert)&&c(!0,!0)}}return t.addEventListener("input",e=>{if(g)return;const r=e.inputType??"";if(r.startsWith("delete")||r.startsWith("history")){a();return}S()?c(!0):c(!1)}),t.addEventListener("keydown",e=>{const r=e.ctrlKey||e.metaKey;if(r&&e.key===" "){e.preventDefault(),c(!0,!0);return}if(!u||e.altKey||e.shiftKey||r)return;const n=Math.min(u.items.length,k);e.key==="ArrowDown"?(e.preventDefault(),b=!0,i=(i+1)%n,m()):e.key==="ArrowUp"?(e.preventDefault(),b=!0,i=(i+n-1)%n,m()):e.key==="Tab"||e.key==="Enter"&&b?(e.preventDefault(),e.stopPropagation(),E(i)):e.key==="Enter"?a():e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),a()):(e.key==="ArrowLeft"||e.key==="ArrowRight"||e.key==="Home"||e.key==="End"||e.key==="PageUp"||e.key==="PageDown")&&a()}),t.addEventListener("blur",a),t.addEventListener("mousedown",a),{el:s,close:a,show:()=>(t.focus(),c(!0,!0))}}
@@ -1 +1 @@
1
- import{fieldCatalogue as z,fieldValues as H,fieldExtent as I,resolvePlot as $,plotTitle as F}from"../stats/plotData.js";import{plotToSweep as J}from"../stats/plotSpec.js";import{renderPlotChart as M}from"./charts/plotChart.js";import{renderSweepPanel as Y}from"./charts/sweep.js";import{createPlotEditor as V}from"./plotEditor.js";import{createSweepEditor as q}from"./sweepEditor.js";import{CLR as b,FONT as T,SPACE as i,controlStyle as B,openReparentedModal as G,wireControlHover as L}from"./toolbar.js";export function openPlotEditor(e){const{doc:o,store:c}=e;let n=e.plot,a=!e.draft;const W=z(e.items,e.ctx),h=t=>$(t,e.items,e.ctx),p=o.createElement("div");p.dataset.wmapPlotWindow="1",Object.assign(p.style,{display:"flex",flexWrap:"wrap",gap:i.xxl,alignItems:"flex-start",width:"100%",boxSizing:"border-box",padding:i.xl});const f=o.createElement("div");if(Object.assign(f.style,{flex:"3 1 420px",minWidth:"0",display:"flex",flexDirection:"column",gap:i.md,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto"}),e.population){const t=o.createElement("div");t.textContent=`Population: ${e.population}`,t.dataset.wmapPopulation="1",Object.assign(t.style,{color:b.label,fontSize:T.body}),f.appendChild(t)}const w=n.chart==="sweep";let r;if(w){const t=Y({spec:J(n),dies:e.items.flatMap(l=>l.dies),testDefs:e.ctx.testDefs?[...e.ctx.testDefs]:void 0,population:e.rawPopulation??e.population,onSaveImage:e.chart.onSaveImage,onSelectPoint:e.onSelectLevel,ownerDocument:o});r={card:t.card,setPlot:l=>t.setSpec(J(l)),destroy:()=>t.destroy()}}else{const t=M({...e.chart,ownerDocument:o,waferLabel:l=>e.items[l]?.label??""});r={card:t.card,setPlot:l=>t.setPlot(h(l)),destroy:()=>t.destroy()}}r.card.style.alignSelf="stretch",f.appendChild(r.card);const m=o.createElement("div");Object.assign(m.style,{flex:"1 1 300px",minWidth:"260px",maxWidth:"420px",display:"flex",flexDirection:"column",gap:i.lg,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto",paddingRight:i.sm});const C=t=>{n=t,a&&c.upsert(t),y()},u=w?{...q({doc:o,plot:n,testDefs:e.ctx.testDefs,onChange:C}),refreshAuto:()=>{}}:V({doc:o,plot:n,catalogue:W,followLabel:()=>e.groupLabel??(e.items.length>1?"a colour per wafer":void 0),autoText:()=>{const t=h(n);return{title:t.autoTitle,x:t.x?.label,y:t.y?.label}},onChange:C,valuesOf:t=>H(t,e.items,e.ctx),extentOf:t=>I(t,e.items,e.ctx),testDefs:e.ctx.testDefs,attributes:e.ctx.curation});m.appendChild(u.el);const x=o.createElement("div");Object.assign(x.style,{display:"flex",flexDirection:"column",gap:i.sm,color:b.label,fontSize:T.body,position:"sticky",bottom:"0",background:b.menuBg,borderTop:`1px solid ${b.menuBorder}`,paddingTop:i.sm,paddingBottom:i.md});const P=o.createElement("div");x.appendChild(P);const s=o.createElement("button");s.type="button",s.textContent="Add to my plots",s.dataset.wmapPlotAdd="1",Object.assign(s.style,{...B("outlined"),alignSelf:"flex-start"}),L(s),s.addEventListener("click",()=>{a=!0,c.upsert(n),N()});const O=JSON.parse(JSON.stringify(e.plot)),E=(t,l,R)=>{const d=o.createElement("button");return d.type="button",d.textContent=t,d.dataset[l]="1",Object.assign(d.style,B("outlined")),L(d),d.addEventListener("click",R),d},g=E("Reset","wmapPlotReset",()=>D()),k=E("Cancel","wmapPlotCancel",()=>{D(),v?.close()}),S=o.createElement("div");Object.assign(S.style,{display:"flex",gap:i.md,flexWrap:"wrap"}),S.append(g,k,s),x.appendChild(S),m.appendChild(x);const A=()=>JSON.stringify(n)!==JSON.stringify(O);function D(){n=JSON.parse(JSON.stringify(O)),a&&c.upsert(n),u.setPlot(n),y()}function N(){P.textContent=a?`Changes are saved to \u201C${w?n.title??"Sweep":F(h(n))}\u201D.`:"This is a draft: it is not kept until you add it to your plots.",s.style.display=a?"none":"",g.disabled=!A(),g.style.opacity=g.disabled?"0.5":"1"}function y(){r.setPlot(n),u.refreshAuto(),N()}y(),p.append(f,m);const j=c.subscribe(()=>{if(!a)return;const t=c.get().find(l=>l.id===n.id);if(!t){v?.close();return}JSON.stringify(t)!==JSON.stringify(n)&&(n=t,u.setPlot(t),y())}),v=G([p],{title:e.title??(a?"Edit plot":"New plot"),anchor:e.anchor,ownerDocument:o,boxSize:{width:"min(96vw, 1180px)",height:"min(92vh, 800px)"},onClosed:()=>{j(),r.destroy(),e.onClosed?.()}});v||(j(),r.destroy())}
1
+ import{fieldCatalogue as H,fieldValues as I,fieldExtent as $,resolvePlot as F,plotTitle as M}from"../stats/plotData.js";import{plotToSweep as T}from"../stats/plotSpec.js";import{renderPlotChart as Y}from"./charts/plotChart.js";import{renderSweepPanel as V}from"./charts/sweep.js";import{createPlotEditor as q}from"./plotEditor.js";import{CLR as b,FONT as B,SPACE as r,controlStyle as L,openReparentedModal as G,wireControlHover as W}from"./toolbar.js";export function openPlotEditor(t){const{doc:o,store:p}=t;let n=t.plot,d=!t.draft;const k=H(t.items,t.ctx),w=e=>F(e,t.items,t.ctx),f=o.createElement("div");f.dataset.wmapPlotWindow="1",Object.assign(f.style,{display:"flex",flexWrap:"wrap",gap:r.xxl,alignItems:"flex-start",width:"100%",boxSizing:"border-box",padding:r.xl});const u=o.createElement("div");if(Object.assign(u.style,{flex:"3 1 420px",minWidth:"0",display:"flex",flexDirection:"column",gap:r.md,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto"}),t.population){const e=o.createElement("div");e.textContent=`Population: ${t.population}`,e.dataset.wmapPopulation="1",Object.assign(e.style,{color:b.label,fontSize:B.body}),u.appendChild(e)}const P=e=>{if(e){const a=V({spec:T(n),dies:t.items.flatMap(l=>l.dies),testDefs:t.ctx.testDefs?[...t.ctx.testDefs]:void 0,population:t.rawPopulation??t.population,onSaveImage:t.chart.onSaveImage,onSelectPoint:t.onSelectLevel,ownerDocument:o});return{card:a.card,setPlot:l=>a.setSpec(T(l)),destroy:()=>a.destroy()}}const i=Y({...t.chart,ownerDocument:o,waferLabel:a=>t.items[a]?.label??""});return{card:i.card,setPlot:a=>i.setPlot(w(a)),destroy:()=>i.destroy()}};let S=n.chart==="sweep",s=P(S);s.card.style.alignSelf="stretch",u.appendChild(s.card);function R(){const e=n.chart==="sweep";if(e===S)return;const i=s;s=P(e),S=e,s.card.style.alignSelf="stretch",i.card.replaceWith(s.card),i.destroy()}const m=o.createElement("div");Object.assign(m.style,{flex:"1 1 300px",minWidth:"260px",maxWidth:"420px",display:"flex",flexDirection:"column",gap:r.lg,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto",paddingRight:r.sm});const x=q({doc:o,plot:n,catalogue:k,followLabel:()=>t.groupLabel??(t.items.length>1?"a colour per wafer":void 0),autoText:()=>{if(n.chart==="sweep")return{title:"Sweep"};const e=w(n);return{title:e.autoTitle,x:e.x?.label,y:e.y?.label}},onChange:e=>{n=e,d&&p.upsert(e),h()},valuesOf:e=>I(e,t.items,t.ctx),extentOf:e=>$(e,t.items,t.ctx),testDefs:t.ctx.testDefs,attributes:t.ctx.curation});m.appendChild(x.el);const g=o.createElement("div");Object.assign(g.style,{display:"flex",flexDirection:"column",gap:r.sm,color:b.label,fontSize:B.body,position:"sticky",bottom:"0",background:b.menuBg,borderTop:`1px solid ${b.menuBorder}`,paddingTop:r.sm,paddingBottom:r.md});const O=o.createElement("div");g.appendChild(O);const c=o.createElement("button");c.type="button",c.textContent="Add to my plots",c.dataset.wmapPlotAdd="1",Object.assign(c.style,{...L("outlined"),alignSelf:"flex-start"}),W(c),c.addEventListener("click",()=>{d=!0,p.upsert(n),j()});const E=JSON.parse(JSON.stringify(t.plot)),D=(e,i,a)=>{const l=o.createElement("button");return l.type="button",l.textContent=e,l.dataset[i]="1",Object.assign(l.style,L("outlined")),W(l),l.addEventListener("click",a),l},y=D("Reset","wmapPlotReset",()=>N()),z=D("Cancel","wmapPlotCancel",()=>{N(),C?.close()}),v=o.createElement("div");Object.assign(v.style,{display:"flex",gap:r.md,flexWrap:"wrap"}),v.append(y,z,c),g.appendChild(v),m.appendChild(g);const A=()=>JSON.stringify(n)!==JSON.stringify(E);function N(){n=JSON.parse(JSON.stringify(E)),d&&p.upsert(n),x.setPlot(n),h()}function j(){O.textContent=d?`Changes are saved to \u201C${n.chart==="sweep"?n.title??"Sweep":M(w(n))}\u201D.`:"This is a draft: it is not kept until you add it to your plots.",c.style.display=d?"none":"",y.disabled=!A(),y.style.opacity=y.disabled?"0.5":"1"}function h(){R(),s.setPlot(n),x.refreshAuto(),j()}h(),f.append(u,m);const J=p.subscribe(()=>{if(!d)return;const e=p.get().find(i=>i.id===n.id);if(!e){C?.close();return}JSON.stringify(e)!==JSON.stringify(n)&&(n=e,x.setPlot(e),h())}),C=G([f],{title:t.title??(d?"Edit plot":"New plot"),anchor:t.anchor,ownerDocument:o,boxSize:{width:"min(96vw, 1180px)",height:"min(92vh, 800px)"},onClosed:()=>{J(),s.destroy(),t.onClosed?.()}});C||(J(),s.destroy())}
@@ -1 +1 @@
1
- import{defaultPlot as te,defaultSweep as oe,describeTitleDrift as ne,examplePlots as se,fieldCatalogue as re,resolvePlot as le,titleDrift as ae}from"../stats/plotData.js";import{addPlots as ie,newPlotId as T,readPlotsFile as ce,writePlotsFile as pe}from"../stats/plotSpec.js";import{buildFilterStrip as de}from"./filterEditor.js";import{isYieldEligibleDie as fe}from"../core/dies.js";import{testValue as ue}from"../core/dieTable.js";import{sweepAppliesTo as me}from"../stats/sweep.js";import{plotToSweep as F}from"../stats/plotSpec.js";import{renderPlotChart as he}from"./charts/plotChart.js";import{renderSweepPanel as ge}from"./charts/sweep.js";import{makeChartGridWrap as we}from"./charts/chartShell.js";import{confirmDialog as ye}from"./confirmDialog.js";import{openDrilldownMenu as L}from"./drilldown.js";import{openPlotEditor as be}from"./plotModal.js";import{sourceFromDies as xe,sourceFromPoints as ve,toPlotItems as Pe}from"./plotItems.js";import{CLR as g,FONT as C,RADIUS as O,SPACE as u,controlStyle as De,markNoPrint as E,saveTextFile as Se,wireControlHover as Ce,wireTooltip as Ee}from"./toolbar.js";const W=1e4;export function createPlotSection(r){const{doc:i,store:l}=r,p=Pe(r.items.map(e=>({label:e.identity??e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:r.ringCount}))),b={testDefs:r.testDefs,groupBy:r.groupBy,curation:r.attributes},M=e=>le(e,p,b),x=re(p,b),m=i.createElement("div");m.dataset.wmapPlotTab="1",Object.assign(m.style,{display:"flex",flexDirection:"column",gap:u.lg,width:"100%"});const v=i.createElement("div");Object.assign(v.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const f=(e,t,n,o)=>{const s=i.createElement("button");return s.type="button",s.textContent=e,s.dataset[t]="1",Object.assign(s.style,{...De("outlined"),fontSize:C.body}),Ce(s),Ee(s,n),s.addEventListener("click",o),s},P=f("Delete all plots\u2026","wmapPlotDeleteAll","Remove every plot and sweep. You are asked first, and Undo brings them back for ten seconds",()=>{X()});v.append(f("+ New plot","wmapPlotNew","Start a chart of your own: choose its type, what goes on each axis and how it is coloured",()=>z()),f("+ New sweep","wmapPlotNewSweep","Read an ordered run of tests as a response curve, and measure where two curves cross",()=>U()),f("Add examples","wmapPlotExamples","Draw one example of each chart type this lot can show, to edit or delete",()=>Y()),f("Import plots\u2026","wmapPlotImport","Add the plots from a file written by Export plots\u2026",()=>{Z()}),f("Export plots\u2026","wmapPlotExport","Save all your plots to a file, to share or to keep a copy",()=>q()),P),E(v),m.appendChild(v);const d=i.createElement("div");d.setAttribute("role","status"),Object.assign(d.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",padding:`${u.sm} ${u.md}`,background:g.menuBg,border:`1px solid ${g.menuBorder}`,borderRadius:O.container,color:g.text,fontSize:C.body}),E(d),m.appendChild(d);let h;function w(e,t,n=[]){h!==void 0&&clearTimeout(h),d.replaceChildren();const o=i.createElement("span");if(o.textContent=e,d.appendChild(o),t){const s=f(t.label,"wmapPlotNoticeAction",t.label==="Undo"?"Put back what was just removed":t.label,()=>{t.run(),I()});d.appendChild(s)}for(const s of n){const a=i.createElement("div");a.textContent=s,Object.assign(a.style,{flexBasis:"100%",color:g.label}),d.appendChild(a)}d.style.display="flex",h=setTimeout(I,t?W:W*2)}function I(){h!==void 0&&(clearTimeout(h),h=void 0),d.style.display="none",d.replaceChildren()}const D=i.createElement("div");D.textContent="No plots yet. A plot is any measured value against another, or a distribution, that you choose: New plot starts one, and it is kept for the next lot. Add examples draws one of each chart type from this lot to start from.",Object.assign(D.style,{color:g.label,fontSize:C.body,padding:`${u.lg} 0`});const S=we(i);m.append(D,S);const y=new Map,A=()=>({onSaveImage:r.onSaveImage,binColors:r.getBinColors?.(),onWaferMenu:r.waferMenu?(e,t,n)=>r.waferMenu(p[e].waferIndex??e,t,n):void 0,onOpenWafer:r.openWafer?(e,t)=>r.openWafer(p[e].waferIndex??e,p[e].label,t):r.focusTest&&p.length===1?(e,t)=>{t!==void 0&&r.focusTest(t)}:void 0,openActionLabel:!r.openWafer&&r.focusTest&&p.length===1?"show this test on the map":void 0,onSelectPoints:(e,t,n)=>R(e,t,n)}),$=()=>({plots:l,getBinColors:r.getBinColors,onSaveImage:r.onSaveImage,onSaveText:r.onSaveText,onLocateDie:r.locateDie});function R(e,t,n){const o=ve(e,p,r.testDefs);o&&L(t,n,o,$())}function k(e,t=!1){be({doc:i,anchor:m,store:l,plot:e,draft:t,items:p,ctx:b,groupLabel:r.groupLabel,chart:A(),onSelectLevel:j})}function U(){const e=oe(r.testDefs,T());l.upsert(e),k(e)}function j(e,t){const n=s=>e.testNumbers.some(a=>{const c=ue(s,a);return c!==void 0&&Number.isFinite(c)}),o=xe(p,`measured at ${e.label}`,s=>fe(s)&&n(s),r.testDefs,e.testNumbers[0]);o&&L({x:t.clientX,y:t.clientY},t.target,o,$())}function z(){const e=te(x,T());l.upsert(e),k(e)}function Y(){const e=o=>JSON.stringify([o.chart,o.fields,o.aggregate??null,o.sweep??null,o.fit??null,o.normalCurve??null,o.spread??null,o.normalize??null,o.sort??null,o.cumulative??null,o.stack??null]),t=new Set(l.get().map(e)),n=se(x,p.length,T,{items:p,ctx:b}).filter(o=>!t.has(e(o)));if(n.length===0){w(x.some(o=>o.group==="Tests")?"The examples for this lot are already in your plots.":"There are no measured values in this lot to draw examples from.");return}for(const o of n)l.upsert(o);w(`Added ${n.length} example plot${n.length===1?"":"s"}: ${[...new Set(n.map(o=>o.chart))].join(", ")}. Edit one to make it yours, or Delete what you do not need.`)}function B(e,t){const n=(o,s,a,c)=>e.appendChild(f(o,s,a,c));n("Edit","wmapPlotEdit","Change this plot\u2019s type, fields, titles, limits and axes",()=>{const o=l.get().find(s=>s.id===t.id);o&&k(o)}),n("Duplicate","wmapPlotDuplicate","Make a copy of this plot to vary",()=>{l.duplicate(t.id)}),n("Delete","wmapPlotDelete","Remove this plot. Undo brings it back for ten seconds",()=>{const o=l.remove(t.id);o&&w(`Deleted \u201C${o.plot.title??"plot"}\u201D.`,{label:"Undo",run:()=>l.insertAt(o.index,o.plot)})})}function _(e){return e.chart==="sweep"?J(e):H(e)}function H(e){const t=he({ownerDocument:i,waferLabel:a=>p[a]?.label??"",...A()});t.card.dataset.wmapPlotId=e.id,E(t.actions),B(t.actions,e);const n=i.createElement("div");n.dataset.wmapPlotTitleDrift="1",Object.assign(n.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",flexBasis:"100%",padding:`${u.xs} ${u.md}`,background:g.warnBg,border:`1px solid ${g.warnBorder}`,borderRadius:O.control,color:g.warnText,fontSize:C.body});const o=i.createElement("div");o.style.flexBasis="100%",t.actions.append(o,n);const s={card:t.card,actions:t.actions,json:"",driftNote:n,destroy:()=>t.destroy(),update:a=>{const c=M(a);t.setPlot(c),G(o,a),t.card.style.opacity=c.issues.length?"0.7":"1",K(n,a)}};return y.set(e.id,s),s}function J(e){const t=F(e),n=p.flatMap(a=>a.dies),o=ge({spec:t,dies:n,testDefs:r.testDefs,onSaveImage:r.onSaveImage,ownerDocument:i,onSelectPoint:j});o.card.dataset.wmapPlotId=e.id,o.card.dataset.wmapSweepPlot="1",E(o.actions),B(o.actions,e);const s={card:o.card,actions:o.actions,json:"",destroy:()=>o.destroy(),update:a=>{const c=F(a);o.setSpec(c),o.card.style.opacity=me(c,r.testDefs)?"1":"0.7"}};return y.set(e.id,s),s}function G(e,t){const n=t.where;e.replaceChildren(),n&&e.appendChild(de({doc:i,filter:n,testDefs:r.testDefs,attributes:r.attributes,label:"Filter",onToggle:o=>{const s=l.get().find(ee=>ee.id===t.id),a=s?.where;if(!s||!a)return;const c={...a};o?delete c.off:c.off=!0,l.upsert({...s,where:c})}}))}function K(e,t){const n=ne(ae(t,x));if(e.replaceChildren(),e.style.display=n?"flex":"none",!n)return;const o=i.createElement("span");o.textContent=n,e.append(o,f("Use the automatic title","wmapPlotAutoTitle","Replace the title you typed with the one written from the plot\u2019s settings",()=>{const s=l.get().find(c=>c.id===t.id);if(!s)return;const a={...s};delete a.title,l.upsert(a)}))}function N(){const e=l.get();for(const[t,n]of y)e.some(o=>o.id===t)||(n.destroy(),n.card.remove(),y.delete(t));e.forEach((t,n)=>{const o=y.get(t.id)??_(t),s=JSON.stringify(t);o.json!==s&&(o.json=s,o.update(t)),S.children[n]!==o.card&&S.insertBefore(o.card,S.children[n]??null)}),D.style.display=e.length===0?"":"none",P.disabled=e.length===0,P.style.opacity=e.length===0?"0.5":"1",P.style.cursor=e.length===0?"default":"pointer"}const V=l.subscribe(N);N();async function X(){const e=l.get().slice();if(e.length===0)return;const t=e.length;if(!await ye({doc:i,anchor:m,title:"Delete all plots",message:t===1?"Delete your 1 saved plot? It is kept on this computer for the next lot, so it will not be there for the next file either. Export plots\u2026 first to keep a copy.":`Delete all ${t} saved plots, sweeps included? They are kept on this computer for the next lot, so they will not be there for the next file either. Export plots\u2026 first to keep a copy.`,confirmLabel:t===1?"Delete 1 plot":`Delete ${t} plots`}))return;const o=l.get().slice();o.length!==0&&(l.replaceAll([]),w(`Deleted ${o.length===1?"1 plot":`all ${o.length} plots`}.`,{label:"Undo",run:()=>l.replaceAll(o)}))}function q(){const e=l.get();if(e.length===0){w("There are no plots to export yet.");return}Se(pe(e),"wafermap-plots.json","application/json",r.onSaveText)}async function Q(){return r.pickPlotsFile?r.pickPlotsFile():new Promise(e=>{const t=i.createElement("input");t.type="file",t.accept=".json,application/json",t.addEventListener("change",()=>{const n=t.files?.[0];if(!n){e(null);return}n.text().then(e,()=>e(null))}),t.addEventListener("cancel",()=>e(null)),t.click()})}async function Z(){const e=await Q();if(e===null)return;const t=ce(e);if(t.error){w(`Could not import: ${t.error}`);return}const{plots:n,copies:o}=ie(l.get(),t.plots);l.replaceAll(n);const s=[...t.warnings,...o.length?[`Kept as copies, since a plot with the same id already existed: ${o.join(", ")}`]:[]];w(`Imported ${t.plots.length} plot${t.plots.length===1?"":"s"}.`,void 0,s)}return{card:m,destroy:()=>{V(),h!==void 0&&clearTimeout(h);for(const e of y.values())e.destroy();y.clear(),l.flush()}}}
1
+ import{defaultPlot as Pe,describeTitleDrift as Ee,examplePlots as Se,fieldCatalogue as De,resolvePlot as Ce,titleDrift as Ae}from"../stats/plotData.js";import{addPlots as ke,newPlotId as V,readPlotsFile as Te,writePlotsFile as Ie}from"../stats/plotSpec.js";import{buildFilterStrip as $e}from"./filterEditor.js";import{isYieldEligibleDie as je}from"../core/dies.js";import{testValue as Be}from"../core/dieTable.js";import{sweepAppliesTo as Oe}from"../stats/sweep.js";import{plotToSweep as Y}from"../stats/plotSpec.js";import{renderPlotChart as ee}from"./charts/plotChart.js";import{renderSweepPanel as te}from"./charts/sweep.js";import{makeChartGridWrap as oe,makeSegmented as Le}from"./charts/chartShell.js";import{confirmDialog as Me}from"./confirmDialog.js";import{openDrilldownMenu as ne}from"./drilldown.js";import{openPlotEditor as Ne}from"./plotModal.js";import{sourceFromDies as Fe,sourceFromPoints as We,toPlotItems as Re}from"./plotItems.js";import{CLR as h,FONT as D,RADIUS as W,SPACE as u,controlStyle as Ue,markNoPrint as I,saveTextFile as ze,wireControlHover as Ve,wireTooltip as Ye}from"./toolbar.js";const se=1e4;export function createPlotSection(l){const{doc:r,store:a}=l,p=Re(l.items.map(e=>({label:e.identity??e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:l.ringCount}))),$={testDefs:l.testDefs,groupBy:l.groupBy,curation:l.attributes},q=e=>Ce(e,p,$),j=De(p,$),g=r.createElement("div");g.dataset.wmapPlotTab="1",Object.assign(g.style,{display:"flex",flexDirection:"column",gap:u.lg,width:"100%"});const B=r.createElement("div");Object.assign(B.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const w=(e,t,n,o)=>{const s=r.createElement("button");return s.type="button",s.textContent=e,s.dataset[t]="1",Object.assign(s.style,{...Ue("outlined"),fontSize:D.body}),Ve(s),Ye(s,n),s.addEventListener("click",o),s},O=w("Delete all plots\u2026","wmapPlotDeleteAll","Remove every plot and sweep. You are asked first, and Undo brings them back for ten seconds",()=>{ye()});let E="plots";const C=Le([["plots","My plots","Your own plots, kept for the next lot"],["examples","Examples","One example of each chart type this lot can show, drawn from its own tests. They are not your plots until you add them"]],E,e=>ie(e),r);C.dataset.wmapPlotViews="1",C.setAttribute("aria-label","Plots shown");for(const e of Array.from(C.querySelectorAll("label")))e.querySelector("input")?.value==="examples"&&(e.dataset.wmapPlotExamples="1");B.append(C,w("+ New plot","wmapPlotNew","Start a chart of your own: choose its type (a sweep reads runs of tests as response curves), what goes on each axis and how it is coloured",()=>ae()),w("Import plots\u2026","wmapPlotImport","Add the plots from a file written by Export plots\u2026",()=>{be()}),w("Export plots\u2026","wmapPlotExport","Save all your plots to a file, to share or to keep a copy",()=>ge()),O),I(B),g.appendChild(B);const y=r.createElement("div");y.setAttribute("role","status"),Object.assign(y.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",padding:`${u.sm} ${u.md}`,background:h.menuBg,border:`1px solid ${h.menuBorder}`,borderRadius:W.container,color:h.text,fontSize:D.body}),I(y),g.appendChild(y);let b;function S(e,t,n=[]){b!==void 0&&clearTimeout(b),y.replaceChildren();const o=r.createElement("span");if(o.textContent=e,y.appendChild(o),t){const s=w(t.label,"wmapPlotNoticeAction",t.label==="Undo"?"Put back what was just removed":t.label,()=>{t.run(),G()});y.appendChild(s)}for(const s of n){const i=r.createElement("div");i.textContent=s,Object.assign(i.style,{flexBasis:"100%",color:h.label}),y.appendChild(i)}y.style.display="flex",b=setTimeout(G,t?se:se*2)}function G(){b!==void 0&&(clearTimeout(b),b=void 0),y.style.display="none",y.replaceChildren()}const x=r.createElement("div");x.dataset.wmapPlotGallery="1",Object.assign(x.style,{display:"none",flexDirection:"column",gap:u.md,padding:u.md,border:`1px solid ${h.menuBorder}`,borderRadius:W.container}),I(x),g.appendChild(x);let L=[];const _=()=>{for(const e of L)e.destroy();L=[],x.replaceChildren(),x.style.display="none"},A=r.createElement("div");A.textContent="No plots yet. A plot is any measured value against another, or a distribution, that you choose: New plot starts one, and it is kept for the next lot. Examples shows one of each chart type from this lot, to look at and to add the ones you want.",Object.assign(A.style,{color:h.label,fontSize:D.body,padding:`${u.lg} 0`});const k=oe(r);g.append(A,k);const v=new Map,R=()=>({onSaveImage:l.onSaveImage,onSaveText:l.onSaveText,binColors:l.getBinColors?.(),onWaferMenu:l.waferMenu?(e,t,n)=>l.waferMenu(p[e].waferIndex??e,t,n):void 0,onOpenWafer:l.openWafer?(e,t)=>l.openWafer(p[e].waferIndex??e,p[e].label,t):l.focusTest&&p.length===1?(e,t)=>{t!==void 0&&l.focusTest(t)}:void 0,openActionLabel:!l.openWafer&&l.focusTest&&p.length===1?"show this test on the map":void 0,onSelectPoints:(e,t,n)=>le(e,t,n)}),H=()=>({plots:a,getBinColors:l.getBinColors,onSaveImage:l.onSaveImage,onSaveText:l.onSaveText,onLocateDie:l.locateDie});function le(e,t,n){const o=We(e,p,l.testDefs);o&&ne(t,n,o,H())}function J(e,t=!1){Ne({doc:r,anchor:g,store:a,plot:e,draft:t,items:p,ctx:$,groupLabel:l.groupLabel,chart:R(),onSelectLevel:U})}function U(e,t){const n=s=>e.testNumbers.some(i=>{const d=Be(s,i);return d!==void 0&&Number.isFinite(d)}),o=Fe(p,`measured at ${e.label}`,s=>je(s)&&n(s),l.testDefs,e.testNumbers[0]);o&&ne({x:t.clientX,y:t.clientY},t.target,o,H())}function ae(){N("plots");const e=Pe(j,V());a.upsert(e),J(e)}const M=e=>JSON.stringify([e.chart,e.fields,e.aggregate??null,e.sweep??null,e.fit??null,e.normalCurve??null,e.spread??null,e.normalize??null,e.sort??null,e.cumulative??null,e.stack??null]);function N(e){const t=C.querySelector(`input[value="${e}"]`);!t||t.checked||(t.checked=!0,t.dispatchEvent(new(r.defaultView??window).Event("change")))}function re(){k.style.display=E==="plots"?"grid":"none",A.style.display=E==="plots"&&a.get().length===0?"":"none",x.style.display=E==="examples"?"flex":"none"}function ie(e){if(e!==E){if(E=e,e==="examples"){if(!ce()){N("plots");return}}else _();re()}}function ce(){const e=Se(j,p.length,V,{items:p,ctx:$});if(e.length===0)return S(j.some(c=>c.group==="Tests")?"There are no examples this lot can draw.":"There are no measured values in this lot to draw examples from."),!1;const t=r.createElement("div");Object.assign(t.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const n=r.createElement("div");Object.assign(n.style,{color:h.text,fontSize:D.body,flex:"1 1 auto"});const o=[],s=w("Add all","wmapPlotExamplesAddAll","Add every example you do not have yet to My plots",()=>{const c=o.map(f=>f.add()).filter(f=>f!==void 0);c.length!==0&&(N("plots"),S(`Added ${c.length} plot${c.length===1?"":"s"} to My plots.`,{label:"Undo",run:()=>{const f=new Set(c);a.replaceAll(a.get().filter(P=>!f.has(P.id)))}}))});t.append(n,s);const i=oe(r);x.append(t,i);const d=[],F=()=>{const c=o.filter(f=>a.get().some(P=>M(P)===M(f.example))).length;n.textContent=`${e.length} examples from this lot, drawn for you. They are not your plots until you add them${c?` (${c} added)`:""}; edit them under My plots.`,s.disabled=c===e.length,s.style.opacity=c===e.length?"0.6":"1"};for(const c of e){let f;if(c.chart==="sweep")f=te({spec:Y(c),dies:p.flatMap(z=>z.dies),testDefs:l.testDefs,onSaveImage:l.onSaveImage,ownerDocument:r,onSelectPoint:U});else{const m=ee({ownerDocument:r,waferLabel:z=>p[z]?.label??"",...R()});m.setPlot(q(c)),f=m}f.card.dataset.wmapPlotExample=c.chart;const P=r.createElement("span");P.textContent="Example",P.dataset.wmapPlotExampleBadge="1",Object.assign(P.style,{fontSize:D.sub,color:h.label,border:`1px dashed ${h.menuBorder}`,borderRadius:W.control,padding:`0 ${u.sm}`});const T=w("Add to my plots","wmapPlotExampleAdd","Add this example to My plots, where you can edit it",()=>{}),Q=()=>a.get().some(m=>M(m)===M(c)),ve=()=>{const m=Q();T.textContent=m?"In your plots":"Add to my plots",T.disabled=m,T.style.opacity=m?"0.6":"1"},Z=()=>{if(Q())return;const m=V();return a.upsert({...c,id:m}),m};T.addEventListener("click",()=>{Z()}),o.push({example:c,add:Z}),d.push(ve),f.actions.append(P,T),i.appendChild(f.card),L.push(f)}const xe=a.subscribe(()=>{for(const c of d)c();F()});L.push({card:t,destroy:xe});for(const c of d)c();return F(),!0}function K(e,t){const n=(o,s,i,d)=>e.appendChild(w(o,s,i,d));n("Edit","wmapPlotEdit","Change this plot\u2019s type, fields, titles, limits and axes",()=>{const o=a.get().find(s=>s.id===t.id);o&&J(o)}),n("Duplicate","wmapPlotDuplicate","Make a copy of this plot to vary",()=>{a.duplicate(t.id)}),n("Delete","wmapPlotDelete","Remove this plot. Undo brings it back for ten seconds",()=>{const o=a.remove(t.id);o&&S(`Deleted \u201C${o.plot.title??"plot"}\u201D.`,{label:"Undo",run:()=>a.insertAt(o.index,o.plot)})})}function de(e){return e.chart==="sweep"?fe(e):pe(e)}function pe(e){const t=ee({ownerDocument:r,waferLabel:i=>p[i]?.label??"",...R()});t.card.dataset.wmapPlotId=e.id,I(t.actions),K(t.actions,e);const n=r.createElement("div");n.dataset.wmapPlotTitleDrift="1",Object.assign(n.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",flexBasis:"100%",padding:`${u.xs} ${u.md}`,background:h.warnBg,border:`1px solid ${h.warnBorder}`,borderRadius:W.control,color:h.warnText,fontSize:D.body});const o=r.createElement("div");o.style.flexBasis="100%",t.actions.append(o,n);const s={sweep:!1,card:t.card,actions:t.actions,json:"",driftNote:n,destroy:()=>t.destroy(),update:i=>{const d=q(i);t.setPlot(d),ue(o,i),t.card.style.opacity=d.issues.length?"0.7":"1",me(n,i)}};return v.set(e.id,s),s}function fe(e){const t=Y(e),n=p.flatMap(i=>i.dies),o=te({spec:t,dies:n,testDefs:l.testDefs,onSaveImage:l.onSaveImage,ownerDocument:r,onSelectPoint:U});o.card.dataset.wmapPlotId=e.id,o.card.dataset.wmapSweepPlot="1",I(o.actions),K(o.actions,e);const s={sweep:!0,card:o.card,actions:o.actions,json:"",destroy:()=>o.destroy(),update:i=>{const d=Y(i);o.setSpec(d),o.card.style.opacity=Oe(d,l.testDefs)?"1":"0.7"}};return v.set(e.id,s),s}function ue(e,t){const n=t.where;e.replaceChildren(),n&&e.appendChild($e({doc:r,filter:n,testDefs:l.testDefs,attributes:l.attributes,label:"Filter",onToggle:o=>{const s=a.get().find(F=>F.id===t.id),i=s?.where;if(!s||!i)return;const d={...i};o?delete d.off:d.off=!0,a.upsert({...s,where:d})}}))}function me(e,t){const n=Ee(Ae(t,j));if(e.replaceChildren(),e.style.display=n?"flex":"none",!n)return;const o=r.createElement("span");o.textContent=n,e.append(o,w("Use the automatic title","wmapPlotAutoTitle","Replace the title you typed with the one written from the plot\u2019s settings",()=>{const s=a.get().find(d=>d.id===t.id);if(!s)return;const i={...s};delete i.title,a.upsert(i)}))}function X(){const e=a.get();for(const[t,n]of v)e.some(o=>o.id===t)||(n.destroy(),n.card.remove(),v.delete(t));e.forEach((t,n)=>{let o=v.get(t.id);o&&o.sweep!==(t.chart==="sweep")&&(o.destroy(),o.card.remove(),v.delete(t.id),o=void 0),o??=de(t);const s=JSON.stringify(t);o.json!==s&&(o.json=s,o.update(t)),k.children[n]!==o.card&&k.insertBefore(o.card,k.children[n]??null)}),A.style.display=E==="plots"&&e.length===0?"":"none",O.disabled=e.length===0,O.style.opacity=e.length===0?"0.5":"1",O.style.cursor=e.length===0?"default":"pointer"}const he=a.subscribe(X);X();async function ye(){const e=a.get().slice();if(e.length===0)return;const t=e.length;if(!await Me({doc:r,anchor:g,title:"Delete all plots",message:t===1?"Delete your 1 saved plot? It is kept on this computer for the next lot, so it will not be there for the next file either. Export plots\u2026 first to keep a copy.":`Delete all ${t} saved plots, sweeps included? They are kept on this computer for the next lot, so they will not be there for the next file either. Export plots\u2026 first to keep a copy.`,confirmLabel:t===1?"Delete 1 plot":`Delete ${t} plots`}))return;const o=a.get().slice();o.length!==0&&(a.replaceAll([]),S(`Deleted ${o.length===1?"1 plot":`all ${o.length} plots`}.`,{label:"Undo",run:()=>a.replaceAll(o)}))}function ge(){const e=a.get();if(e.length===0){S("There are no plots to export yet.");return}ze(Ie(e),"wafermap-plots.json","application/json",l.onSaveText)}async function we(){return l.pickPlotsFile?l.pickPlotsFile():new Promise(e=>{const t=r.createElement("input");t.type="file",t.accept=".json,application/json",t.addEventListener("change",()=>{const n=t.files?.[0];if(!n){e(null);return}n.text().then(e,()=>e(null))}),t.addEventListener("cancel",()=>e(null)),t.click()})}async function be(){const e=await we();if(e===null)return;const t=Te(e);if(t.error){S(`Could not import: ${t.error}`);return}const{plots:n,copies:o}=ke(a.get(),t.plots);a.replaceAll(n),N("plots");const s=[...t.warnings,...o.length?[`Kept as copies, since a plot with the same id already existed: ${o.join(", ")}`]:[]];S(`Imported ${t.plots.length} plot${t.plots.length===1?"":"s"}.`,void 0,s)}return{card:g,destroy:()=>{he(),b!==void 0&&clearTimeout(b),_();for(const e of v.values())e.destroy();v.clear(),a.flush()}}}
@@ -1 +1 @@
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()}}}
1
+ import{createViewSwitch as Ms}from"./viewSwitch.js";import{createSummaryToggle as ks}from"./summaryToggle.js";import{getUniqueTestNumbers as Ds,resolveTestNumber as Bs,findTestDef as Es,collectMetadataValues as Os}from"../renderer/buildView.js";import{metadataCategoricalValue as Ts}from"../core/metadata.js";import{resolveBinColorsForMaps as Ls,mergeBinDefs as Vt,binColorWarning as Ps,mixedPassBinsWarning as Ws,binColorsEqual as Rs}from"../renderer/binColors.js";import{commonPassBins as oi,itemPassBins as Ue}from"../core/passBins.js";import{PAT_MODE_FIELD as As,PAT_MODE_KEY as Fs,PAT_MODE_ORDER as $s,isPatMode as mt,patModeOffered as Is,withPatField as Vs,withPatVerdicts as Hs}from"./patMode.js";import{requireRingCount as ne}from"../core/ringCount.js";import{NO_DATA_FILL as js}from"../renderer/colorMap.js";import{metadataValueColor as zs}from"../renderer/colorMap.js";import{resolveCanvasTheme as Ns}from"./canvasTheme.js";import{ICONS as Tn}from"./icons.js";import{SHADOW as Ln,LEADING as ii,TRACKING as _s,controlStyle as Ks,wireControlHover as Pn,SPACE as M,EDGE_GUTTER as oe,MAP_CHROME_INSET as Gs,RADIUS as Y,FONT as N,CLR as w,sevColor as si,MODE_LABELS as qs,BIN_LEGEND_MODES as ai,STACKED_MODES as ie,applyOverlayZ as Xs,getTooltip as Ys,hideTooltip as li,createToolbarHelpers as Us,buildModeMenuEl as Zs,openDetachWindow as Qs,openFloatingWindow as Js,openModal as ea,copyWmapThemeTokens as ta,syncWmapPopupTheme as na,makePaletteBtn as oa,makeLogScaleBtn as ia,makeLegendStyleBtn as sa,makeOverlaysBtn as aa,makeOrientationBtn as la,menuLayerFor as ri,saveImageBlob as ra,markMenuTrigger as gt,wireMenuA11y as ci,wireTooltip as Wn,requestedPassFailDisplay as di,overlayMenuRows as ca,anyOverlayActive as da,openCompactDiagnostics as ua,roomForPanel as ui,logWmapVersionOnce as fa,buildDataModeEntries as pa,metadataKeyHasData as ma,metadataModeEntry as fi}from"./toolbar.js";import{openReportModal as ga,openUserGuideWindow as ha,registerGuideOpener as ya}from"./guideWindow.js";import{waferDisplayLabel as ht,waferIdentityLabel as Se}from"../core/waferLabel.js";import{bandButton as ba}from"./filterButton.js";import{metadataDisplayValue as wa}from"../core/metadata.js";import{withExportContext as va}from"./exportName.js";import{sortBinsForDisplay as Sa}from"../stats/binPareto.js";import{diePassStatus as Ca,isYieldEligibleDie as xa}from"../core/dies.js";import{aggregateValues as Ma,aggregateBinCounts as pi}from"../core/aggregates.js";import{renderWaferMap as ka,renderWaferMapCard as mi,toPublicViewOptions as Ht}from"./renderWaferMap.js";import{waferPopulation as Da,selectionPopulation as Ba,LOT_STACK_REASON as Rn}from"./chartPopulation.js";import{sourceFromBins as gi}from"./plotItems.js";import{plotStoreFor as Ea}from"./plotStore.js";import{classifyChanged as An,COLOR_KEYS as Oa,findingBin as Ta,findingPlotMode as La}from"./renderWaferMap.js";import{findingPatternKey as hi}from"../stats/filterFindings.js";import{synthesisSource as Pa}from"../stats/synthesis.js";import{buildWaferMap as Wa,computeCoverage as Ra,computeYield as Aa,defaultBinMode as Fa,getTestPassStatus as yi,isParametricTest as Fn,getDieTestValue as $a,isBuiltMap as Ia}from"../renderer/buildWaferMap.js";import{analyzeWaferMap as $n}from"../stats/analyzeWaferMap.js";import{lotTestValueStatus as Va}from"../stats/testValueBudget.js";import{testValueNotice as Ha}from"./testValueOffer.js";import{axisPrefsFromOptions as In,optionsFromAxisPrefs as ja,CHART_PREF_KEYS as Vn}from"./chartPrefs.js";import{collectWarnings as za,buildWarningsMenuEl as Na,severityOf as _a}from"./warnings.js";import{asList as Hn,compareNatural as jn,arrayEqual as jt,toggleHighlight as bi}from"../core/utils.js";import{buildCompactMap as Ka,compactLayoutOffered as Ga}from"../core/compact.js";import{attachExpandableMetadata as wi}from"./identityHeader.js";import{createSummaryPanelEl as zn,buildMetadataStripRow as qa,metadataEntries as Xa,renderLotSummaryContentSteps as Ya,reportMapsFromItems as Ua}from"./summaryPanel.js";import{prettyKey as Za}from"../stats/facets.js";import{testLabel as Qa,markedTestLabel as Ja,derivedFields as el}from"../renderer/testLabel.js";import{mergeTestDefs as tl}from"../stats/mergeTestDefs.js";import{getDieKey as zt,hasPosition as nl}from"../core/dies.js";import{testValue as ol}from"../core/dieTable.js";import{runChunked as il}from"./chunked.js";function vi(r){if(typeof r!="number"||!Number.isFinite(r))return;const k=Math.round(r);return k>=1?k:void 0}const Nn=12;function sl(r,k,f){let z=k;if(k.length>Nn){const D=k.slice(0,Nn-1),T=k.slice(Nn-1),I=T.reduce(($,de)=>$+de.count,0);z=[...D,{color:w.label,count:I,label:`Other (${T.length} bins)`}]}const O=r.createElement("div");Object.assign(O.style,{display:"flex",columnGap:"1px",width:"100%",height:"8px",borderRadius:Y.control,overflow:"hidden",border:`1px solid ${w.menuBorder}`,boxSizing:"border-box",marginTop:M.xs,flexShrink:"0"}),O.setAttribute("role","img"),O.setAttribute("aria-label",`Population split: ${z.map(D=>`${D.label} ${Nt(D.count/f*100)}`).join(", ")}`);for(const D of z){const T=D.count/f*100,I=r.createElement("div");Object.assign(I.style,{flex:`${T} 1 0`,minWidth:T>0?"2px":"0",background:D.color}),Wn(I,`${D.label} \xB7 ${D.count.toLocaleString()} dies \xB7 ${Nt(T)}`),O.appendChild(I)}return O}function Nt(r){return r>0&&r<.1?"<0.1%":`${r.toFixed(1)}%`}function Si(r,k,f){const z=new Map;let O=0,D=0;for(const T of r){const I=f?new Set(f(T)):void 0;for(const $ of T.dies){if(!xa($))continue;const de=k($);de!==void 0&&(z.set(de,(z.get(de)??0)+1),O++,I&&Ca($,I)&&D++)}}return{counts:z,total:O,pass:D}}function Ci(r,k){const f=r.ownerDocument.createElement("div");Object.assign(f.style,{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer",userSelect:"none",padding:`${M.xxs} ${M.xs}`,borderRadius:Y.control});const z=r.ownerDocument.createElement("span");Object.assign(z.style,{display:"inline-block",width:"13px",height:"13px",flexShrink:"0",background:k.color,border:k.isActive?`2px solid ${w.iconActive}`:`1px solid ${w.menuBorder}`,borderRadius:Y.control,boxSizing:"border-box"});const O=r.ownerDocument.createElement("span");if(O.textContent=k.label,Object.assign(O.style,{fontWeight:k.isActive?"700":"400",color:k.isActive?w.iconActive:w.text,whiteSpace:"nowrap"}),f.appendChild(z),f.appendChild(O),k.count!==void 0){const D=r.ownerDocument.createElement("span");if(D.textContent=k.count.toLocaleString(),Object.assign(D.style,{color:k.isActive?w.iconActive:w.text,fontWeight:k.isActive?"700":"400",whiteSpace:"nowrap"}),f.appendChild(D),k.percent!==void 0){const T=r.ownerDocument.createElement("span");T.textContent=Nt(k.percent),Object.assign(T.style,{color:w.label,whiteSpace:"nowrap"}),f.appendChild(T)}}if(f.setAttribute("role","button"),f.setAttribute("aria-pressed",k.isActive?"true":"false"),f.tabIndex=0,f.addEventListener("mouseenter",()=>{f.style.background=w.bgHover}),f.addEventListener("mouseleave",()=>{f.style.background="transparent"}),f.addEventListener("focus",()=>{f.style.background=w.bgHover}),f.addEventListener("blur",()=>{f.style.background="transparent"}),f.addEventListener("click",D=>k.onClick(D.ctrlKey||D.metaKey)),f.addEventListener("keydown",D=>{if(D.key==="Enter"||D.key===" ")D.preventDefault(),k.onClick(D.ctrlKey||D.metaKey);else if(k.onMenu&&(D.key==="ContextMenu"||D.key==="F10"&&D.shiftKey)){D.preventDefault();const T=f.getBoundingClientRect();k.onMenu({x:T.left+T.width/2,y:T.bottom},f)}}),k.onMenu){const D=k.onMenu;f.addEventListener("contextmenu",T=>{T.preventDefault(),D({x:T.clientX,y:T.clientY},f)}),Wn(f,"Right-click: charts and tables for these dies")}r.appendChild(f)}export function renderWaferGallery(r,k,f={}){fa();const z=6;let O=vi(f.columns);const D=f.showHelpButton??!1,T=f.userGuideExtension,I=f.insights?.enabled??!0,$=Ea(f.insights),de={enabled:!1,plotStore:$},xi=Xs(f.zIndex),Re=f.summaryPanel,Ce=e=>[...Ue(e)],_n=()=>W.flatMap(e=>e?[ne(e,"renderWaferGallery")]:[]),yt=()=>_n()[0];function Mi(e){const t=[...new Set(e)].sort((n,o)=>n-o);return t.length<2?null:{code:"ring-count-mixed",severity:"warning",message:`These wafers were built with different ring counts (${t.join(", ")}). Each card and each wafer's findings use their own; the lot's ring yield in the Summary panel, report and Insights uses ${e[0]} rings.`}}let _=f.lotStatsSummary,Ae;const se=()=>ae?Ae:_;let Ze=f.viewOptions?.legendPosition??"default",bt=f.perCardLegend??!1;function Qe(){const e=a.plotMode??"hardBin";return ai.has(e)?null:a.colorbarRangeMode==="data"?"Each map has its own value range, so it keeps its own colour bar":"These wafers have no shared colour bar for value mode, so each map keeps its own"}function Kn(){const e=bt||Qe()!==null;for(const t of C)t&&t.setOptions({showLegend:e})}let a={plotMode:Fa(k.flatMap(e=>typeof e=="function"?[]:[e.dies??[]])),showDieLabels:!1,showRingBoundaries:!1,showQuadrantBoundaries:!1,rotation:0,flipX:!1,flipY:!1,...f.viewOptions},C=[],ue=[],Fe=[],x=[];const V=va(()=>{const e=x.filter(n=>n!=null),t=[...new Set(e.map(n=>wa(n.wafer.metadata?.lot)).filter(n=>n!==void 0))].sort(jn);return{prefix:f.downloadFilename,lots:t,...e.length===1?{wafer:Se(e[0])}:{waferCount:e.length}}},f.onSaveImage,f.onSaveText);let W=k.map(e=>typeof e=="function"?null:e),q=null,Gn=null,_t=!1,xe=0,ae=!1,wt=!1;const fe=new WeakSet,qn=new WeakMap,Me=()=>{const e=q?.get();return!!e&&!e.off};function Xn(e,t){return{dies:e.dies,wafer:e.wafer,label:ht(e,t),identity:Se(e),waferIndex:t,passBins:Ue(e),testDefs:e.testDefs,statsSummary:e.statsSummary}}const Kt=new Map;function Je(e,t){if(!q||!Me())return e;const n=qn.get(e);if(n&&n.v===xe)return n.item;const o=q.mark([Xn(e,t)]);let i=e;if(o.narrowing){const s=o.items[0].dies,l=s.filter(u=>!u.filteredOut);i={...e,dies:s,statsSummary:Kt.get(e),...e.yield?{yield:Aa(s,[...Ue(e)],e.yield.yieldPercentGross!=null?"denominator-only":"exclude")}:{},...e.dataCoverage?{dataCoverage:Ra(l)}:{}},o.hidden.size&&fe.add(i)}return qn.set(e,{v:xe,item:i}),i}const Yn=new WeakMap;function Gt(e,t){const n=Je(e,t);if(!mt(a))return n;const o=Yn.get(n);if(o)return o;const i={...n,dies:Hs(n.dies,n.testDefs,Ue(n)),metadataFields:Vs(n.metadataFields)};return fe.has(n)&&fe.add(i),Yn.set(n,i),i}const Un=new WeakMap;function ki(e,t){if(!q||!Me())return e;const n=Un.get(e);if(n&&n.v===xe)return n.item;const o=Je(e,t),i=o===e?e:fe.has(o)?null:{...o,dies:o.dies.filter(s=>!s.filteredOut)};return Un.set(e,{v:xe,item:i}),i}function B(){return!q||!Me()?W:W.map((e,t)=>e?ki(e,t):null)}let vt=0,et=!1;function Zn(){const e=++vt;Ae=void 0,Kt.clear();const t=()=>{et=!1,R(),re()};if(!ae){t();return}const n=Jt();if(!n||!(_||n.some(s=>s.statsSummary))){t();return}const o=B().flatMap((s,l)=>s?[{it:s,i:l}]:[]);if(o.length===0){t();return}et=!0;const i=_?.analysisOptions??n.find(s=>s.statsSummary)?.statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(async({analyzeWaferLotAsync:s,remapLotWaferIndices:l})=>{const u=await s(o.map(m=>m.it),i);if(e!==vt||_t)return;const d=o.map(m=>m.i);Ae=l(u,d),u.perWafer.forEach((m,v)=>Kt.set(W[d[v]],m.summary)),xe++,W.forEach((m,v)=>{if(!m||ie.has(a.plotMode))return;const p=Gt(m,v);x[v]=p,C[v]?.setStatsSummary(p.statsSummary)}),Te(),t()}).catch(()=>{e===vt&&t()})}const $e=e=>q&&Me()||mt(a)?e.map((t,n)=>typeof t=="function"?t:Gt(t,n)):e;function qt(){return Gn??=import("./pageFilter.js").then(({createPageFilter:e})=>{const t=e({doc:r.ownerDocument,initial:f.insights?.filter,onChange:f.insights?.onFilterChange,savedFilters:f.insights?.savedFilters,onSavedFiltersChange:f.insights?.onSavedFiltersChange,pickFiltersFile:f.insights?.onPickFiltersFile,onSaveText:f.onSaveText,attributes:f.attributes,getRingCount:()=>ne({ringCount:yt()},"the page filter")});return _t||(q=t,pe=t.createBand(()=>Yt(),{marginLeft:oe,marginRight:oe,marginBottom:M.lg}),r.insertBefore(pe.el,Z),t.subscribe(Ut),t.get()&&Ut()),t}),Gn}let pe=null,St=null,Xt;const Yt=()=>W.flatMap((e,t)=>e?[Xn(e,t)]:[]);function Qn(){clearTimeout(Xt),Xt=setTimeout(()=>{if(!q||!pe)return;const e=Yt(),t=q.keep(e);pe.refresh(t.result,e),pe.el.style.display=q.get()&&!Ke?"":"none"},0)}function Jn(){if(q){if(ke>0){Me()&&(wt=!0);return}xe++,ae=Me()&&W.some((e,t)=>e!==null&&Je(e,t)!==e),Ae=void 0,et=ae&&!!_,Zn()}}function Ut(){if(xe++,ae=!1,ke>0){wt=!0,Qn();return}wt=!1;const e=a.plotMode;ae=Me()&&W.some((t,n)=>t!==null&&Je(t,n)!==t),Ae=void 0,et=ae&&!!_,W.length>0&&(ie.has(e)?(a={...a,...$t(e)},X(qe(e))):X($e(W.filter(t=>t!==null)))),Qn(),Zn()}function Ie(){return tl(B())}function tt(){if(B().some(e=>e?.testDefs?.length))return Ie().defs}let nt=0,ke=0;const Q=new Map;let Di=0,Ct=null,J=null,me=null,Ve=null;function xt(){J===null&&me===null&&(Ve={plotMode:a.plotMode,activeTest:a.activeTest})}function eo(){Ve&&P({...Ve},{fireCallback:!1}),Ve=null}let to=new Set,S=null,Bi={};function no(e){return B()[e]?.statsSummary??se()?.perWafer.find(t=>t.waferIndex===e)?.summary}function oo(){return!!(B().some(e=>e?.statsSummary?.findings.length)||se()?.perWafer.some(e=>e.summary.findings.length))}const Ei=Ys(),He=Us(Ei),{makeBtn:je,setActive:io,makeSep:De,syncSeparators:Zt,syncToolbarVisible:Qt,makeMenuRow:Oi,makeMenuSection:Ti,makeDropdown:so,closeOpenMenu:Mt,getOpenMenu:ot,setOpenMenu:it}=He;r.ownerDocument.addEventListener("click",Mt,!0);const ao=()=>li();window.addEventListener("blur",ao);let lo=f.findingsNotice,Be=null;function Jt(){const e=W;return e.length>0&&e.every(t=>t!=null&&Ia(t))?e:null}function Li(){return _?.stats.testValueAnalysis??Va(B().flatMap(e=>e?.statsSummary?[e.statsSummary]:[]))}const en=()=>lo??(Jt()?Ha(Li(),B().length,Be!==null,Pi):void 0);function Pi(){const e=Jt();if(Be||!e)return;const t=new AbortController;Be=t,R();const n=_?.analysisOptions??e[0].statsSummary?.analysisOptions??{};import("../stats/analyzeWaferLot.js").then(({analyzeWaferLotAsync:o})=>o(e,{...n,enableTestValueAnalysis:!0,signal:t.signal})).then(o=>{if(t.signal.aborted)return;Be=null;const i=o.perWafer.map(s=>s.summary);W=W.map((s,l)=>s&&{...s,statsSummary:i[l]}),ie.has(a.plotMode)||(x=x.map((s,l)=>s&&{...s,statsSummary:i[l]}),C.forEach((s,l)=>s?.setStatsSummary(i[l]))),_=o,Te(),R(),re(),f.onStatsSummaryChange?.({summaries:i,lotStatsSummary:o})}).catch(o=>{if(!t.signal.aborted)throw Be=null,R(),o})}function tn(){Be?.abort(),Be=null}function ro(e){to=new Set(e);const t=[...F.querySelectorAll(".wmap-gallery-card")];let n;t.forEach((o,i)=>{const s=to.has(i);o.style.outline=s?`3px solid ${w.findingHighlight}`:"",o.style.outlineOffset=s?"-3px":"",s&&n===void 0&&(n=o)}),n?.scrollIntoView?.({behavior:"smooth",block:"nearest"})}function nn(){ro([])}let kt=!1;function on(){kt=!0;for(const e of C)e&&e.clearSelection();kt=!1}function co(e){return t=>{!kt&&(J!==null||me!==null)&&(Ve=null,Oe(),R()),ln.set(e,t.length),le&&!st&&!kt&&Wi(e,t),e.onSelect?.(t)}}function ge(e,t){e!==void 0&&(C.forEach((n,o)=>{n&&o!==e&&n.locateDie(null)}),C[e]?.locateDie(t),F.querySelectorAll(".wmap-gallery-card")[e]?.scrollIntoView?.({block:"center",behavior:"smooth"}))}let le=!1,st=!1,Ee=new Set;function Wi(e,t){st=!0;try{Ee=new Set(t.map(n=>zt(n))),x.forEach((n,o)=>{const i=C[o];!i||!n||n===e||i.setSelection(n.dies.filter(s=>Ee.has(zt(s))))})}finally{st=!1}Lt()}function uo(){Ee=new Set,st=!0;try{for(const e of C)e?.clearSelection()}finally{st=!1}Lt()}function sn(){if(!le||Ee.size===0)return;const e=[];let t=!1;if(x.forEach((i,s)=>{if(!i)return;const l=i.dies.filter(u=>Ee.has(zt(u)));l.length!==0&&(i.isLotStack&&(t=!0),e.push({label:Se(i)??i.label??`Wafer ${s+1}`,dies:l,waferIndex:s,wafer:i.wafer,passBins:Ce(i),ringCount:ne(i,"renderWaferGallery")}))}),e.length===0)return;const n=Ie(),o=a;return{source:{items:e,population:e.length===1?`selected on ${e[0].label}`:`selected at the same die positions on ${e.length} wafers`,testDefs:n.defs,activeTest:o.plotMode==="value"?o.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>ge(s,i)}}}function fo(){const e=[];let t=!1;if(x.forEach((o,i)=>{const s=o?C[i]?.getSelectedDies()??[]:[];!o||s.length===0||(o.isLotStack&&(t=!0),e.push({label:Se(o)??o.label??`Wafer ${i+1}`,dies:s,waferIndex:i,wafer:o.wafer,passBins:Ce(o),ringCount:ne(o,"renderWaferGallery")}))}),e.length<2)return;const n=a;return{source:{items:e,population:`selected on ${e.length} wafers`,testDefs:Ie().defs,activeTest:n.plotMode==="value"?n.activeTest:void 0,notMeasuredReason:t?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(o,i)=>ge(i,o)}}}function Ri(e){const t=sn()??go(e);if(t)return t;const n=fo(),o=n?.source.items.some(i=>i.waferIndex===e);return n&&o?{...n,narrowable:!0}:void 0}function an(e,t,n){J!==e&&t.click();const o=S;if(!o)return;const i=se()?.findings.find(l=>l.id===e),s=sn()??fo()??Fi()??(i?po(ho(i)):void 0);s&&import("./drilldown.js").then(({openDrilldownMenu:l})=>{o.isConnected&&l(n,o,s.source,{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...s.ctx})})}function Ai(e,t,n,o){const i=Hn(a.highlightBin),s=i.length>1&&i.includes(t)?[...i]:[t],l=[];let u=!1;x.forEach((g,h)=>{g&&(g.isLotStack&&(u=!0),l.push({label:Se(g)??g.label??`Wafer ${h+1}`,dies:g.dies,waferIndex:h,wafer:g.wafer,passBins:Ce(g),ringCount:ne(g,"renderWaferGallery")}))});const d=Ie().defs,m=gi(l,e,s,d,void 0,u);if(!m)return;const v={plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(g,h)=>ge(h,g)},p=s.length>1?gi(l,e,[t],d,void 0,u):null,c=p?{...v,narrower:{label:`Only ${e} bin ${t}`,backLabel:"All filtered bins",source:p,ctx:v}}:v;import("./drilldown.js").then(({openDrilldownMenu:g})=>{o.isConnected&&g(n,o,m,c)})}function po(e,t=""){const n=[];let o=!1;for(const s of[...e??[]].sort((l,u)=>l-u)){const l=x[s];l&&(l.isLotStack&&(o=!0),n.push({label:Se(l)??l.label??`Wafer ${s+1}`,dies:l.dies,waferIndex:s,wafer:l.wafer,passBins:Ce(l),ringCount:ne(l,"renderWaferGallery")}))}if(n.length===0)return;const i=a;return{source:{items:n,population:n.length===1?`on ${n[0].label}`:`on ${n.length} ${t}wafers`,testDefs:Ie().defs,activeTest:i.plotMode==="value"?i.activeTest:void 0,notMeasuredReason:o?Rn:void 0},ctx:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(s,l)=>ge(l,s)}}}function Fi(){let e;for(let i=0;i<C.length;i++)if((C[i]?.getSelectedDies().length??0)!==0){if(e!==void 0)return;e=i}const t=e===void 0?void 0:x[e];if(e===void 0||!t)return;const n=C[e].getSelectedDies(),o=a;return{source:Ba(n,{waferLabel:Se(t),testDefs:t.testDefs,isLotStack:t.isLotStack,activeTest:o.plotMode==="value"?o.activeTest:void 0,waferIndex:e,wafer:t.wafer,passBins:Ce(t),ringCount:ne(t,"renderWaferGallery")}),ctx:{onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,onLocateDie:(i,s)=>ge(s??e,i)}}}function $i(e){e||uo(),le=e,Lt()}function Dt(e,t){const n=new Set(e),o=t??C.map((i,s)=>s);for(const i of o){const s=x[i],l=C[i];if(!s||!l)continue;const u=s.dies.filter(d=>n.has(zt(d)));l.setSelection(u)}}const U=new Set,ln=new Map;function mo(){[...F.querySelectorAll(".wmap-gallery-card")].forEach((n,o)=>{n.style.outline=U.has(o)?`2px solid ${w.iconActive}`:"",n.style.outlineOffset=U.has(o)?"-2px":""});const t=U.size;ee.style.display=t>0?"":"none",ee.textContent=`${t} wafer${t===1?"":"s"} picked \u2715`,ee.ariaLabel=`${t} wafer${t===1?"":"s"} picked. Click to clear.`}function Ii(e){e<0||(U.has(e)?U.delete(e):U.add(e),mo())}function Vi(){U.clear(),mo()}function go(e){if(!(U.size===0||!U.has(e))){for(const t of ln.values())if(t>0)return;return po([...U],"picked ")}}function Hi(){const e=[];for(let t=0;t<B().length;t++){const n=B()[t];if(!n)continue;const o=no(t)?.findings??[];o.length&&e.push({index:t,item:n,unusualCount:o.filter(i=>i.severity==="unusual").length,notableCount:o.filter(i=>i.severity==="notable").length,totalCount:o.length})}return e}function ji(e){const t=x[e]??B()[e];t&&ut(e,t)}function zi(e){const t=no(e)?.findings??[];if(t.length)return{total:t.length,unusual:t.filter(n=>n.severity==="unusual").length,notable:t.filter(n=>n.severity==="notable").length}}function Ni(){import("../stats/renderSummaryReport.js").then(({renderLotReportHtml:e})=>{ga(e(Ua(B(),yt())),{anchor:r})})}function _i(){if(!S)return;S.innerHTML="";const e=Hi();if(B().length>0){const n=r.ownerDocument.createElement("div"),o=e.length,i=B().filter(Boolean).length;n.textContent=o===0?`No findings on any of the ${i} wafers`:`${o} of ${i} wafer${i===1?"":"s"} with findings`,Object.assign(n.style,{fontSize:N.body,color:w.label,marginBottom:M.md}),S.appendChild(n)}if(e.length>0){const n=r.ownerDocument.createElement("button");n.type="button",n.textContent="Summary report",Object.assign(n.style,{...Ks("outlined"),marginBottom:M.lg,display:"block",width:"100%",textAlign:"left"}),Pn(n),n.addEventListener("click",Ni),S.appendChild(n)}if(e.length===0){const n=r.ownerDocument.createElement("div");Object.assign(n.style,{color:w.icon,fontSize:N.body,padding:"4px 0"}),n.textContent="No findings on any wafer.",S.appendChild(n)}else for(const{index:n,item:o,unusualCount:i,notableCount:s,totalCount:l}of e){const u=i?"unusual":s?"notable":"info",d=i+s||l,m=r.ownerDocument.createElement("button");m.type="button",Object.assign(m.style,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"5px 8px",marginBottom:M.xs,border:"none",borderLeft:`3px solid ${si(u)}`,borderRadius:Y.control,background:w.bgHover,cursor:"pointer",fontSize:N.body,textAlign:"left",boxSizing:"border-box"}),m.addEventListener("mouseover",()=>{m.style.background=w.bgActive}),m.addEventListener("mouseout",()=>{m.style.background=w.bgHover});const v=r.ownerDocument.createElement("span");v.textContent=ht(o,n),Object.assign(v.style,{color:w.iconHover,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});const p=r.ownerDocument.createElement("span");p.textContent=String(d),m.setAttribute("aria-label",`${ht(o,n)} \u2014 ${d} finding${d===1?"":"s"}${i?`, ${i} unusual`:""} \u2014 view wafer`),Object.assign(p.style,{marginLeft:M.sm,flexShrink:"0",background:si(u),color:"#fff",borderRadius:Y.container,padding:"1px 5px",fontSize:N.body,fontWeight:"600"}),m.appendChild(v),m.appendChild(p),m.addEventListener("click",()=>ut(n,o)),S.appendChild(m)}const t=r.ownerDocument.createElement("div");t.style.height="12px",S.appendChild(t)}let ze=null,at=null;function R(){if(!S||ae&&_&&!Ae&&et)return;ze?.cancel(),ze=null;const e=se();if(e){const t=Vt(B().map(o=>o?.hbinDefs)),n=Vt(B().map(o=>o?.sbinDefs));ze=il(Ya(S,{lotSummary:e,items:B(),hbinDefs:t.length?t:void 0,sbinDefs:n.length?n:void 0,testDefs:tt(),ringCount:yt(),binColors:a.binColors,plotMode:a.plotMode??"hardBin",fallbackFormat:a.fallbackFormat,activeFindingId:J,warnings:f.warnings?.display??!0?he:[],findingsFilter:Bi,findingsNotice:en(),onFindingsFilterChange:R,onSaveText:V.onSaveText,attributes:f.attributes,onFindingClick:(o,i)=>{J===o.id?(Oe(),eo()):(xt(),So(o,i)),R()},activeTest:me,onTestClick:o=>{const i=me===o;i||xt(),Oe(),i?eo():vo(o),R()},onShowChart:I?o=>{Ge(!0),Io().then(i=>i?.showWorthCard(o))}:void 0,onWaferClick:ji,findingsFor:zi,dieListOptions:f.dieList,onLocateDie:(o,i)=>ge(i,o),onClose:()=>cn(!1)}),{onDone:()=>{const o=at;at=null,o?.()}})}else _i()}function ho(e){const t=e.highlight;return t?.kind==="wafer"&&t.waferIndices?.length?t.waferIndices:null}let Bt=[];function yo(){if(Bt.length!==0){for(const e of Bt)C[e]?.setOptions({plotMode:a.plotMode,activeTest:a.activeTest});Bt=[]}}function Oe(){J=null,me=null,nn(),on(),yo(),P({highlightBin:void 0},{fireCallback:!1})}function bo(){J===null&&me===null||(Ve=null,Oe(),R())}function wo(e,t){const n=tt();if(n===void 0||n.some(i=>i.testNumber===e))P({plotMode:"value",activeTest:e,highlightBin:void 0},{fireCallback:!1});else{P({highlightBin:void 0},{fireCallback:!1});const s=ie.has(a.plotMode??"hardBin")?null:t;if(s){for(const l of s)C[l]?.setOptions({plotMode:"value",activeTest:e});Bt=[...s]}}}function vo(e){me=e;const t=o=>x[o]?.statsSummary?.stats.testFailures?.[e]?.dieKeys,n=x.map((o,i)=>i).filter(o=>t(o)?.length);if(wo(e,n.length?n:null),nn(),on(),!ie.has(a.plotMode??"hardBin"))for(const o of n)Dt(t(o),[o])}function So(e,t){if(J===e.id){Oe();return}J=e.id,me=null,t&&(t.style.background=w.bgActive,t.style.fontWeight="600"),yo();const{kind:n,index:o}=e.variable;if(n==="test")wo(o??0,ho(e));else{const s=x.some(u=>u?.dies?.some(d=>d.hbin!=null)),l=oi(x.map(u=>u?Ue(u):void 0));P({plotMode:La(e,a.plotMode,s),highlightBin:Ta(e,l,s)},{fireCallback:!1})}nn(),on();const i=e.highlight;if(i.kind==="wafer"){ro(i.waferIndices);const s=hi(e);for(const l of i.waferIndices){const u=i.dieKeysByWafer?void 0:x[l]?.statsSummary?.findings.find(m=>hi(m)===s),d=i.dieKeysByWafer?.[l]??u?.highlight?.dieKeys;d?.length&&Dt(d,[l])}}else i.kind==="bin"?i.dieKeys?.length&&Dt(i.dieKeys):(i.kind==="region"||i.kind==="dies")&&i.dieKeys?.length&&Dt(i.dieKeys)}function rn(){return!!S&&S.style.display!=="none"}function cn(e){!S||e===rn()||(e&&R(),S.style.display=e?"flex":"none",re())}function re(){Ct&&(Zt(H),Qt(H,"inline-flex"),Ct.sync({visible:!!(_||se()||oo())&&!!S&&!Ke,open:rn(),notable:!!(se()?.hasNotableFindings||B().some(e=>e?.statsSummary?.hasNotableFindings))}))}const H=r.ownerDocument.createElement("div");H.dataset.wmapToolbar="gallery",Object.assign(H.style,{flexShrink:"0",marginLeft:"auto",display:"inline-flex",flexDirection:"row",alignItems:"center",gap:"0",background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,padding:"0",boxShadow:Ln.panel,flexWrap:"wrap",minWidth:"0",overflowX:"auto"});const Co=()=>{const e=ot();e&&(e.remove(),it(null)),gt(ce,!1)},ce=je("mode","Plot mode",()=>{if(ot()){Co();return}const e=B().flatMap(y=>y?.dies??[]),t=tt(),{testEntries:n,binEntries:o,stackedEntries:i}=pa(e,t,{includeStacked:!0}),s=B().filter(Boolean).length,l=y=>{if(y===void 0)return s;let E=0;for(const A of B())A?.dies?.some(j=>yi(j,y)!==void 0||ol(j,y)!==void 0)&&E++;return E},u=s<2?n:n.map(y=>{const E=l(y.activeTest);return E===s?y:{...y,label:`${y.label} \u2014 ${E} of ${s} wafers`}}),d=a.plotMode??"hardBin",m=a.activeTest??0;function v(y){return y.plotMode!==d?!1:y.plotMode==="value"?m===(y.activeTest??0):y.plotMode==="metadata"?a.activeMetadataKey===y.activeMetadataKey:!0}function p(y,E){y.activeTest!==void 0?P({plotMode:"value",activeTest:y.activeTest,activeMetadataKey:void 0,logScale:y.logScale}):y.activeMetadataKey!==void 0?P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:y.activeMetadataKey,passFailDisplay:"off"}):P({plotMode:y.plotMode,activeTest:void 0,activeMetadataKey:void 0,passFailDisplay:"off"}),E.remove(),it(null),gt(ce,!1)}const c=new Set,g=B().flatMap(y=>y?.metadataFields??[]).filter(y=>!c.has(y.key)&&c.add(y.key)).filter(y=>ma(e,y.key)).map(fi);ke===0&&Is(B())&&g.push(fi(As));const h=Zs(ce.getBoundingClientRect(),u,o,i,v,p,{makeMenuRow:Oi,makeMenuSection:Ti},d,ce.ownerDocument.defaultView??window,g);ri(ce).appendChild(h),it(h),gt(ce,!0),ci(h,ce,Co)});gt(ce,!1);const Ki=()=>x.flatMap(e=>e?[...e.hbinDefs??[],...e.sbinDefs??[]]:[]).some(e=>e.color),{btn:Gi,sync:xo}=oa(He,()=>({...a,plotMode:a.plotMode??"hardBin"}),Ki,e=>P(e));xo();const qi=k.some(e=>typeof e!="function"&&(e.reticles?.length??0)>0);function Et(){const e=tt(),{testNumber:t}=Bs(a.activeTest??0,e);return{testNumber:t,td:Es(e,t)}}function Mo(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&(e.limitLow!==void 0||e.limitHigh!==void 0)}function lt(){if((a.plotMode??"hardBin")!=="value")return!1;const{td:e}=Et();return e!==void 0&&!Fn(e)}function Xi(){if((a.plotMode??"hardBin")!=="value")return!1;const{testNumber:e,td:t}=Et();return B().some(n=>n?.dies?.some(o=>yi(o,e,t)!==void 0))}function Yi(e,t){if(!t||!Fn(t))return;const n=t.limitLow!==void 0||t.limitHigh!==void 0;if((di(a)==="spec"&&n?"spec":a.colorbarRangeMode??"spec")==="spec"&&n)return;let s=1/0,l=-1/0;for(const u of B())if(u)for(const d of u.dies){const m=$a(d,e);m!==void 0&&(m<s&&(s=m),m>l&&(l=m))}if(isFinite(s))return s===l?[s,s+1]:[s,l]}function Ot(e,t,n){const o=a[e];if(o===t||o!=null&&t!=null&&n(o,t))return!1;a={...a,[e]:t};for(const i of C)i&&i.setOptions({[e]:t});return!0}function ko(){if((a.plotMode??"hardBin")!=="metadata")return;const e=a.activeMetadataKey;if(!e)return;if(mt(a))return{key:e,values:[...$s]};const t=new Set;for(const n of B())if(n)for(const o of Os(n.dies,e))t.add(o);return{key:e,values:[...t].sort(jn)}}function dn(){Ot("metadataValueOrder",ko(),(e,t)=>e.key===t.key&&jt(e.values,t.values))}function un(){if((a.plotMode??"hardBin")!=="value")return;const{testNumber:e,td:t}=Et(),n=Yi(e,t);Ot("valueRange",n?{test:e,range:n}:void 0,(i,s)=>{const l=m=>Array.isArray(m)?{test:void 0,range:m}:{test:m.test,range:m.range},u=l(i),d=l(s);return u.test===d.test&&jt(u.range,d.range)})}let fn=!1;function Ui(){if(fn)return;fn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{fn=!1,un(),dn(),Oo(),Eo()})}let pn=!1;function Zi(){if(pn)return;pn=!0,(r.ownerDocument.defaultView?.requestAnimationFrame??(t=>setTimeout(()=>t(0),0)))(()=>{pn=!1,Ft()})}let Do=[];function K(){const{colors:e,mixedHardBins:t}=Ls(B().filter(n=>n!=null),{binColorScheme:a.binColorScheme,useDefinedBinColors:a.useDefinedBinColors});return Do=t,e}function mn(){return x.filter(e=>e!=null).flatMap(e=>e.dies)}function Bo(){return a.compact?Ka(mn()):void 0}const Qi=(e,t)=>jt(e.columns,t.columns)&&jt(e.rows,t.rows);function Eo(){Ot("compactMap",Bo(),Qi)&&zo()}function Ji(){return Ga(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig))}function Oo(){Ot("binColors",K(),Rs),Te()}const es=aa(He,()=>ca(a,qi,{functionalActive:lt(),hasLimits:Mo()&&!lt(),hasRecorded:Xi()&&!lt(),binMode:(a.plotMode??"hardBin")==="hardBin"||(a.plotMode??"hardBin")==="softBin"},e=>P(e),{on:!!a.compact,offered:Ji(),onChange:e=>P({compact:e}),onDiagnostics:()=>ua(mn(),x.filter(e=>e!=null).map(e=>e.reticleConfig),{anchor:r,onSaveText:V.onSaveText})}),()=>da(a)),{btn:ts,sync:To}=sa(He,()=>({plotMode:a.plotMode,legendPosition:Ze}),e=>{Ze=e;for(const t of C)t&&t.setOptions({legendPosition:Ze})},{get:()=>bt,set:e=>{bt=e,Kn()},blockedReason:Qe});To();const ns=[{value:"mean",label:"Mean"},{value:"median",label:"Median"},{value:"stddev",label:"Std Dev"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"count",label:"Count"}],Lo=so("aggr","Aggregation method",()=>ns,()=>a.aggregationMethod??"mean",e=>P({aggregationMethod:e}));function Po(){const e=a.plotMode==="stackedValues";Lo.style.display=e?"":"none"}Po();const{btn:os,sync:Wo}=ia(He,()=>({...a,functionalActive:lt()}),e=>P(e));Wo();const Tt=je("specRange","Colour bar range: test limits",()=>{const e=a.colorbarRangeMode==="data"?"spec":"data";P({colorbarRangeMode:e})});function Ro(){const e=(a.plotMode??"hardBin")==="value"&&Mo()&&di(a)==="off"&&!lt();Tt.style.display=e?"":"none";const t=(a.colorbarRangeMode??"spec")==="spec";io(Tt,t),Tt.ariaLabel=t?"Colour bar range: test limits (click for data range)":"Colour bar range: data range (click for test limits)"}Ro();const is=la(He,()=>a,e=>P(e)),ss=je("downloadAll","Download gallery PNG",Ss),Ne=je("boxSelect","Select the same dies on every wafer",()=>{le&&Ee.size>0?uo():$i(!le)});Ne.style.position="relative";const rt=r.ownerDocument.createElement("span");rt.dataset.wmapSelectAcrossCount="1",Object.assign(rt.style,{position:"absolute",top:"0",right:"0",minWidth:"14px",height:"14px",boxSizing:"border-box",padding:"0 3px",borderRadius:Y.pill,background:w.iconActive,color:w.menuBg,fontSize:"11px",lineHeight:"14px",fontWeight:"700",textAlign:"center",pointerEvents:"none",display:"none"}),Ne.appendChild(rt);function Lt(){io(Ne,le);const e=le?Ee.size:0;rt.style.display=e>0?"block":"none",rt.textContent=e>99?"99+":String(e),Ne.ariaLabel=le?e>0?`Select the same dies on every wafer: on, ${e.toLocaleString()} die position${e===1?"":"s"} selected (click to clear the selection)`:"Select the same dies on every wafer: on (click to turn off)":"Select the same dies on every wafer: off (click to turn on)",Ne.setAttribute("aria-pressed",String(le))}const ee=r.ownerDocument.createElement("button");ee.type="button",ee.dataset.wmapPickedWafers="1",Object.assign(ee.style,{display:"none",border:"none",background:w.bgActive,color:w.iconActive,borderRadius:Y.control,padding:`${M.xs} ${M.md}`,fontSize:N.body,cursor:"pointer",whiteSpace:"nowrap",flexShrink:"0"}),Pn(ee,"bare"),ee.addEventListener("click",Vi);const Ao=()=>{const e=x.filter(o=>o!=null&&!fe.has(o)).length,t=Math.min(5,Math.max(1,e)),n=Array.from({length:t},(o,i)=>i+1);return O!=null&&!n.includes(O)&&n.push(O),n},as=so("columns","Columns",()=>[{value:"auto",label:"Auto (0)"},...Ao().map(e=>({value:String(e),label:`${e} column${e===1?"":"s"} (${e})`}))],()=>O!=null?String(O):"auto",e=>Sn(e==="auto"?void 0:Number(e))),L=r.ownerDocument.createElement("div");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:"0"}),H.appendChild(L),L.appendChild(ce),L.appendChild(Gi),L.appendChild(Lo),L.appendChild(os),L.appendChild(Tt),L.appendChild(De()),L.appendChild(es),L.appendChild(De()),L.appendChild(ts),L.appendChild(De()),L.appendChild(is),L.appendChild(De()),L.appendChild(as),L.appendChild(De()),L.appendChild(Ne),L.appendChild(ee),L.appendChild(ss),Lt();let te=null,Pt=null,he=[],Fo=!1;function Te(){const e=za({lotStatsSummary:se(),result:{warnings:[...B().flatMap(n=>n?.warnings??[]),...Ie().warnings]},extra:[a.binColors&&Ps(a.binColors,a.plotMode),Ws(Do),Mi(_n())].filter(n=>!!n)}),t=e.length!==he.length||e.some((n,o)=>n.code!==he[o]?.code||n.message!==he[o]?.message);he=e,(t||!Fo)&&(Fo=!0,f.warnings?.onWarning?.(e)),ls()}function ls(){if(!te||!Pt)return;const e=he.length,t=e>0;if(te.style.display=t?"flex":"none",Pt.style.display=t?"":"none",Zt(H),Qt(H,"inline-flex"),!t)return;const n=_a(he[0]),o=`${e} data ${e===1?"warning":"warnings"}`;te.style.color=n==="error"?w.errText:w.warnText,te.ariaLabel=n==="error"?`${o} \u2014 some wafers may be positionally wrong`:o}(f.warnings?.display??!0)&&(Pt=De(),te=je("warning","Data warnings",()=>{const e=ot();if(Mt(new MouseEvent("click")),e)return;const t=Na(te.getBoundingClientRect(),he,te.ownerDocument.defaultView??window);ri(r).appendChild(t),it(t),ci(t,te,()=>Mt(new MouseEvent("click")))}),gt(te,!1),H.appendChild(Pt),H.appendChild(te)),Te();function gn(e){import("./userGuideHtml.js").then(t=>ha({buildWaferMap:Wa,renderWaferMap:ka,renderWaferGallery,analyzeWaferMap:$n},t.USER_GUIDE_HTML,T,r,e))}const rs=ya(e=>gn(e));D&&(H.appendChild(De()),H.appendChild(je("help","User guide",()=>gn())));const _e=r.ownerDocument.createElement("div");_e.dataset.wmapGalleryMeta="1",Object.assign(_e.style,{flex:"1",minWidth:"0",overflow:"hidden",display:"flex",alignItems:"center",padding:`${M.sm} ${M.lg}`,fontSize:N.sub,lineHeight:ii.none,boxSizing:"border-box"});const Le=r.ownerDocument.createElement("div");Object.assign(Le.style,{background:w.canvasBg,display:"flex",alignItems:"stretch",gap:M.lg,paddingBottom:M.lg,minWidth:"0"});const ye=r.ownerDocument.createElement("div");ye.dataset.wmapGalleryLegend="1",Object.assign(ye.style,{display:"flex",flexDirection:"column",gap:M.sm,background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,padding:`${M.sm} ${M.lg}`,marginBottom:M.lg,boxShadow:Ln.panel,fontSize:N.body,lineHeight:ii.none,boxSizing:"border-box",width:"100%",minWidth:"0"});const Z=r.ownerDocument.createElement("div");Object.assign(Z.style,{display:"flex",flexDirection:"row",alignItems:"flex-start"});let be=null,ct=null,$o=null;function Io(){return I?be?Promise.resolve(be):($o??=Promise.all([import("./insightsTab.js"),qt()]).then(([{createInsightsTab:e},t])=>(be=e({pageFilter:t,showFilterButton:!1,initialAxisPrefs:In(a),onAxisPrefsChange:n=>{a={...a,...ja(n)};const o=[...Vn];f.onViewOptionsChange?.(Ht(a),o,An(o))},attributes:f.attributes,getItems:()=>W,getLotStats:()=>_,getBinColors:()=>a.binColors??K(),getRingCount:()=>ne({ringCount:yt()},"the Insights tab"),defaultView:f.insights?.defaultView,plotStore:$,onPickPlotsFile:f.insights?.onPickPlotsFile,showPatMap:()=>{Ge(!1),P({plotMode:"metadata",activeTest:void 0,activeMetadataKey:Fs,passFailDisplay:"off"})},showOnMap:n=>{if(Ge(!1),n.kind==="test")xt(),Oe(),vo(n.testNumber);else if(n.kind==="finding"){const o=se(),i=o?Pa(o).findings.find(s=>s.id===n.id):void 0;i&&J!==i.id&&(xt(),So(i))}cn(!0),R()},onOpenGuide:void 0,showMetadataStrip:!1,onSaveImage:V.onSaveImage,onSaveText:V.onSaveText,ownerDocument:r.ownerDocument,locateDie:(n,o)=>{Ge(!1),ge(o,n)},openWafer:(n,o,i)=>{const s=B()[n];if(!s)return;let l=null;const u=ea({title:o,onClose:()=>l?.destroy(),anchor:r});Xo(u,o,s.wafer.metadata??void 0),l=kn(u.contentWrap,s,i,void 0,ui(u))}}),ct=be.el,ct.style.display="none",r.appendChild(ct),be)),$o):Promise.resolve(null)}let Ke=!1,hn=null;function Ge(e){I&&(Ke=e,hn?.setInsightsOpen(e),ct&&(ct.style.display=e?"flex":"none"),Z.style.display=e?"none":"flex",pe&&(pe.el.style.display=q?.get()&&!e?"":"none"),L.style.display=e?"none":"inline-flex",Zt(H),Qt(H,"inline-flex"),H.style.display="inline-flex",re(),Ft(),e&&Io().then(t=>{!t||!Ke||(t.el.style.display="flex",t.render())}))}I&&f.insights?.defaultOpen&&queueMicrotask(()=>Ge(!0));const cs=6,ds=4,Wt=240,yn=480,us=720,fs=1.25;let Pe=yn;function Vo(e){const t=z*2+110+2,n=Ho();if(n)return Math.ceil(n.across*ds+t);let o=null;for(const i of e){if(i==null||!i.dies?.length)continue;const s=i.dies[0].width;if(!(s>0))continue;const l=i.wafer.radius*2*(cs/s),u=Math.ceil(l+t);(o==null||u>o)&&(o=u)}return o}function ps(e){const t=Vo(e);return t==null?Wt:Math.min(Pe,Math.max(Wt,t))}function ms(e){const t=Vo(e);if(t==null)return!1;const n=Math.min(us,Math.max(yn,t));return n<=Pe?!1:(Pe=n,!0)}function Ho(){const e=a.compact?a.compactMap:void 0,t=x.find(i=>i?.dies?.length)?.dies[0];if(!e||!t||e.columns.length===0||e.rows.length===0||!(t.width>0)||!(t.height>0))return;const n=(a.rotation??0)%180!==0,o=a.showXYIndicator?2.5:0;return{across:(n?e.rows.length:e.columns.length)+o,down:(n?e.columns.length:e.rows.length)+o,cellAspect:n?t.height/t.width:t.width/t.height}}function jo(e,t){const n=Ho();if(!n){e.style.aspectRatio="1",t.style.flex="1",t.style.width="",t.style.aspectRatio="";return}e.style.aspectRatio="auto",t.style.flex="none",t.style.width="100%",t.style.aspectRatio=String(n.across*n.cellAspect/n.down)}function gs(){for(const e of ue)e?.parentElement&&jo(e.parentElement,e)}function zo(){Pe=yn,dt=Wt,vn(x.map(e=>e??null)),Rt(),gs()}function bn(){return No()?`${Pe}px`:"none"}function No(){return O==null&&!wn}let wn=!1;function Rt(){const e=bn();for(const t of Array.from(F.children))t.classList.contains("wmap-gallery-card")&&(t.style.maxWidth=e,t.style.maxHeight=e)}let dt=Wt,_o=0;function vn(e){if(ms(e)&&Rt(),O==null){const n=ps(e);n>dt&&(dt=n)}xn()}function Sn(e){O=vi(e),Rt(),xn()}let At=!1;r.addEventListener("pointerenter",()=>{At=!0}),r.addEventListener("pointermove",()=>{At=!0}),r.addEventListener("pointerleave",()=>{At=!1});const hs=()=>{if(At)return!0;try{return r.matches(":hover")}catch{return!1}},Ko=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||Ke||!hs()&&!r.contains(e.target)||!/^[0-5]$/.test(e.key)||r.ownerDocument.querySelector('[role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||e.key!=="0"&&!Ao().includes(Number(e.key))||(e.preventDefault(),Sn(e.key==="0"?void 0:Number(e.key)))};r.ownerDocument.addEventListener("keydown",Ko);function Cn(e){return`repeat(${e}, minmax(0, ${No()?`${Pe}px`:"1fr"}))`}function Go(e){F.style.gridTemplateColumns!==e&&(F.style.gridTemplateColumns=e)}function xn(){if(O!=null){Go(Cn(O));return}const e=Math.max(1,_o),t=12,n=F.clientWidth||0,o=l=>(n-t*(l-1))/l;let i=Math.max(1,Math.ceil(Math.sqrt(e)));if(n>0){const l=Math.min(Pe,dt*fs),u=d=>{let m=0;for(;m<e&&o(m+1)>=d;)m++;return m};i=u(l)||u(dt)||1}const s=n>0&&i<e;s!==wn&&(wn=s,Rt()),Go(Cn(i))}const F=r.ownerDocument.createElement("div");if(Object.assign(F.style,{flex:"1 1 0",minWidth:"0",display:"grid",gridTemplateColumns:Cn(1),gap:M.xl,paddingLeft:oe,paddingRight:oe,justifyContent:"start",alignContent:"start",isolation:"isolate"}),Re?.placement){const e=Re.placement;S=zn(e,oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.display="flex",S.style.flexDirection="column"}else if(_||se()||oo()){const e=!!Re?.defaultOpen;S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display=e?"flex":"none",R()}re(),(Re?.placement??"right")==="left"?(S&&Z.appendChild(S),Z.appendChild(F)):(Z.appendChild(F),S&&Z.appendChild(S));const We=r.ownerDocument.createElement("div");Object.assign(We.style,{position:"sticky",top:"0",display:"flex",flexDirection:"column",paddingLeft:oe,paddingRight:oe,paddingTop:oe,zIndex:"1",background:w.menuBg}),Le.appendChild(_e),Le.appendChild(H),Ct=ks(r.ownerDocument,()=>cn(!rn())),Le.appendChild(Ct.el),re(),I&&(hn=Ms(r.ownerDocument,"Maps","lot",e=>Ge(e)),Le.appendChild(hn.el)),I&&(St=ba(r.ownerDocument,"Filter\u2026","wmapGalleryFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>{qt().then(e=>e.openEditor(St??r,Yt()))}),St.style.order="1",Le.appendChild(St)),We.appendChild(Le),We.appendChild(ye),r.appendChild(We),r.appendChild(Z);function Ft(){ye.innerHTML="";const e=a.plotMode??"hardBin",t=!Ke&&ai.has(e),n=x.filter(b=>b!=null&&!fe.has(b)),o=n.find(b=>b.isLotStack),i=qa(n.map(b=>({metadata:b.wafer.metadata??void 0})),o?{lotSize:o.lotSize??n.length,aggrMethod:o.aggrMethod}:void 0,{curation:f.attributes}),s=e==="metadata",l=a.activeMetadataKey,u=t&&!s?Si(n,b=>(e==="softBin"?b.sbin:b.hbin)??void 0,Ce):{counts:new Map,total:0,pass:0},d=t&&!s?a.binColors??K():void 0,m=d?e==="softBin"?d.pass.soft:d.pass.hard:new Set,v=Sa(u.counts.entries(),m).map(([b])=>b),p=t&&s&&l?Si(n,b=>Ts(b.metadata?.[l])):{counts:new Map,total:0,pass:0},c=s?ko()?.values:void 0,g=t&&s?(c??[...p.counts.keys()].sort(jn)).filter(b=>p.counts.has(b)):[];if(_e.innerHTML="",i&&_e.appendChild(i),_e.style.display=i?"flex":"none",!v.length&&!g.length){ye.style.display="none";return}ye.style.display="flex";const h=r.ownerDocument.createElement("div");Object.assign(h.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${M.sm} ${M.xl}`,maxHeight:"86px",overflowY:"auto",overflowX:"hidden"}),ye.appendChild(h);const y=Hn(a.highlightBin),E=x.flatMap(b=>b?.metadataFields??[]).find(b=>b.key===l),A=s?E?.label??(l?Za(l):"Metadata"):qs[e],j=r.ownerDocument.createElement("span");if(j.textContent=A,Object.assign(j.style,{fontSize:N.body,fontWeight:"700",letterSpacing:_s,textTransform:"uppercase",color:w.label,flexShrink:"0"}),h.appendChild(j),!s&&u.total>0){const b=u.pass,G=b/u.total*100,we=r.ownerDocument.createElement("span");we.textContent=`Yield ${Nt(G)}`,Object.assign(we.style,{fontSize:N.body,fontWeight:"700",color:w.value,whiteSpace:"nowrap",flexShrink:"0"});const ve=r.ownerDocument.createElement("span");ve.textContent=`${b.toLocaleString()} / ${u.total.toLocaleString()} dies`,Object.assign(ve.style,{fontSize:N.body,color:w.label,whiteSpace:"nowrap",flexShrink:"0"}),h.appendChild(we),h.appendChild(ve)}if(s){const b=Hn(a.highlightMetadataValue);g.forEach((G,we)=>{const ve=b.includes(G),Ye=E?.values?.find(On=>On.value===G),pt=Ye?.color??zs(we),ni=p.counts.get(G)??0;Ci(h,{color:pt,isActive:ve,label:Ye?.label??G,count:ni,percent:p.total>0?ni/p.total*100:void 0,onClick:On=>{const xs=bi(a.highlightMetadataValue,G,On);bo(),P({highlightMetadataValue:xs})}})});return}const ft=e==="softBin"?x.flatMap(b=>b?.sbinDefs??[]):x.flatMap(b=>b?.hbinDefs??[]),Jo=new Set,Bn=[];for(const b of ft)Jo.has(b.bin)||(Jo.add(b.bin),Bn.push(b));const En=Bn.length>0?new Map(Bn.map(b=>[b.bin,b])):null,ei=d??a.binColors??K(),Cs=e==="softBin"?ei.soft:ei.hard,ti=b=>Cs.get(b)??js;for(const b of v){const G=y.includes(b),we=En?.get(b),ve=u.counts.get(b)??0;Ci(h,{color:ti(b),isActive:G,label:we?.name?`${b} \xB7 ${we.name}`:`Bin ${b}`,count:ve,percent:u.total>0?ve/u.total*100:void 0,onMenu:(Ye,pt)=>Ai(e==="softBin"?"soft":"hard",b,Ye,pt),onClick:Ye=>{const pt=bi(a.highlightBin,b,Ye);bo(),P({highlightBin:pt})}})}u.total>0&&v.length>1&&ye.appendChild(sl(r.ownerDocument,[...u.counts.entries()].sort(([,b],[,G])=>G-b).map(([b,G])=>({color:ti(b),count:G,label:En?.get(b)?.name?`${b} \xB7 ${En.get(b).name}`:`Bin ${b}`})),u.total))}function qe(e){const t=B().filter(p=>p!==null&&!fe.has(p));if(!t.length)return[];const n=t.map(p=>p.dies.filter(nl).filter(c=>!c.filteredOut)),o=t[0].wafer,i=t.length,s=oi(t.map(p=>Ue(p)));if(!s)return[];const l=new Set(t.map(p=>ne(p,"renderWaferGallery")));if(l.size!==1)return[];const u=[...l][0],d=o.metadata?{...o,metadata:(({wafer:p,waferId:c,...g})=>g)(o.metadata)}:o;function m(p,c){return{...p,stats:{...p.stats,isLotStack:!0,aggregationMethod:c,lotSize:i}}}function v(p,c){const g=p.map(h=>({...h,hbin:void 0,sbin:void 0}));return $n({wafer:d,dies:g,passBins:[...s],ringCount:u,testDefs:[{testNumber:0,name:c}]},{testNumbers:[0]})}if(e==="stackedValues"){const p=tt();let c=p?.filter(Fn);if(p!==void 0&&c?.length===0)return[];if(p?.length||(c=Ds(t.flatMap(y=>y.dies)).map(y=>({testNumber:y,name:Qa(void 0,y)}))),!c?.length)return[];const g=a.aggregationMethod??"mean";return c.map(h=>{const y=Ma(n,g,h.testNumber),E={testNumber:0,name:h.name,unit:h.unit,...el(h)};return{wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E],label:`${Ja(h,h.testNumber)} \xB7 ${g}`,isLotStack:!0,aggrMethod:g,lotSize:i,statsSummary:m($n({wafer:d,dies:y,passBins:[...s],ringCount:u,testDefs:[E]},{testNumbers:[0]}),g)}})}if(e==="stackedBins"){let p=Vt(t.map(c=>c?.hbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.hbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=pi(n,c.bin,"hard"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,hbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in hard bin ${c.bin}`),"countBin")}})}if(e==="stackedSoftBins"){let p=Vt(t.map(c=>c?.sbinDefs));return(!p||p.length===0)&&(p=[...new Set(t.flatMap(g=>g.dies.map(h=>h.sbin).filter(h=>h!=null)))].sort((g,h)=>g-h).map(g=>({bin:g,name:`Bin ${g}`}))),p.map(c=>{const g=pi(n,c.bin,"soft"),h=[{bin:c.bin,name:c.name}];return{wafer:d,dies:g,passBins:[...s],ringCount:u,sbinDefs:h,label:`${c.bin} \xB7 ${c.name}`,isLotStack:!0,aggrMethod:"countBin",lotSize:i,statsSummary:m(v(g,`Wafers in soft bin ${c.bin}`),"countBin")}})}return t}function $t(e){const t=B().length;return e==="stackedBins"||e==="stackedSoftBins"?{valueRange:[0,t],lotSize:t}:e==="stackedValues"?{aggregationMethod:a.aggregationMethod??"mean",valueRange:void 0,lotSize:void 0}:{}}function P(e,{fireCallback:t=!0}={}){const n=Object.keys(e);if(n.length>0&&n.every(c=>Vn.includes(c))){a={...a,...e},be?.setAxisPrefs(In(a)),t&&f.onViewOptionsChange?.(Ht(a),n,An(n));return}Vn.some(c=>c in e)&&be?.setAxisPrefs(In({...a,...e}));const o=a.plotMode,i=mt(a),s=Qe()!==null;a={...a,...e};const l=a.plotMode,u=ie.has(l),d=mt(a),m=o!==void 0&&ie.has(o),v=ke>0;if("binColorScheme"in e||"useDefinedBinColors"in e){const c=K();a={...a,binColors:c},e={...e,binColors:c}}if("compact"in e){const c=Bo();a={...a,compactMap:c},e={...e,compactMap:c}}if(("compact"in e||a.compact&&("rotation"in e||"showXYIndicator"in e))&&zo(),e.plotMode!==void 0)if(u){const c=$t(l);if(a={...a,...c},v)for(const g of C)g&&g.setOptions(e);else X(qe(l))}else if(m){const{valueRange:c,lotSize:g,aggregationMethod:h,...y}=a;if(a=y,v)for(const E of C)E&&E.setOptions(e);else X(d?$e(W.filter(E=>E!==null)):B().filter(E=>E!==null))}else if(i!==d&&!v)X($e(W.filter(c=>c!==null)));else for(const c of C)c&&c.setOptions(e);else if(e.aggregationMethod!==void 0&&l==="stackedValues")if(v)for(const c of C)c&&c.setOptions(e);else X(qe("stackedValues"));else for(const c of C)c&&c.setOptions(e);Qe()!==null!==s&&Kn(),Ft(),Po(),To(),xo();const p=e.plotMode!==void 0&&e.plotMode!==o;(Oa.some(c=>c in e)||p)&&R(),Te(),Wo(),Ro(),un(),dn(),t&&f.onViewOptionsChange?.(Ht(a),n,An(n))}function qo(e,t,n){const o=e.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"});const i=e.createElement("span");i.textContent=t,Object.assign(i.style,{fontWeight:"700",fontSize:N.sub,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(i);const s=wi(e,o,t,n,f.attributes);return{wrap:o,metaPanel:s}}function Xo(e,t,n){const o=e.box.querySelector("[data-wmap-window-title]");if(!o||Xa(n??{}).length===0)return;const i=o.parentElement,s=r.ownerDocument.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",gap:M.xs,flex:"1",minWidth:"0"}),i?.insertBefore(s,o),s.appendChild(o);const l=wi(r.ownerDocument,s,t,n,f.attributes);l&&(e.contentWrap.style.position="relative",e.contentWrap.appendChild(l))}function Mn(e,t,n){const o=r.ownerDocument.createElement("div");o.className="wmap-gallery-card",Object.assign(o.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,boxShadow:Ln.panel,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",aspectRatio:"1",maxWidth:bn(),maxHeight:bn()});const i=r.ownerDocument.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm});const{wrap:s,metaPanel:l}=qo(document,ht(e,t),e.wafer.metadata??void 0);i.appendChild(s);const u=r.ownerDocument.createElement("button");u.dataset.wmapExpandBtn="1",u.setAttribute("aria-label","Open full view"),Wn(u),u.innerHTML=Tn.expand,Object.assign(u.style,{display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${w.menuBorder}`,borderRadius:Y.control,background:w.panelBg,color:w.label,padding:M.xxs,cursor:"pointer",flexShrink:"0",width:"22px",height:"22px"}),Pn(u),i.appendChild(u),i.addEventListener("click",c=>{(c.ctrlKey||c.metaKey)&&(c.preventDefault(),c.stopPropagation(),Ii(x.indexOf(e)))},!0),o.appendChild(i);const d=r.ownerDocument.createElement("div");Object.assign(d.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),o.appendChild(d),jo(o,d),l&&d.appendChild(l),F.appendChild(o),o.addEventListener("contextmenu",c=>{if(c.defaultPrevented)return;c.preventDefault();const g=e.viewOptions?{...a,...e.viewOptions}:a,h=sn()??go(t),y=h?.source??Da(e.dies,{waferLabel:Se(e),testDefs:e.testDefs,isLotStack:e.isLotStack,activeTest:g.plotMode==="value"?g.activeTest:void 0,waferIndex:t,wafer:e.wafer,passBins:Ce(e),ringCount:ne(e,"renderWaferGallery")}),E={x:c.clientX,y:c.clientY};import("./drilldown.js").then(({openDrilldownMenu:A})=>{o.isConnected&&A(E,o,y,h?{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,...h.ctx}:{plots:$,getBinColors:()=>a.binColors??K(),attributes:f.attributes,onSaveImage:p.getSaveImageHook(),onSaveText:p.getSaveTextHook(),onLocateDie:j=>ge(t,j)})})});const m=bt||Qe()!==null,v=e.viewOptions?{...a,...e.viewOptions}:a,p=mi(d,e,{viewOptions:{...v,showLegend:m,legendPosition:Ze},showTooltip:!0,padding:z,statsSummary:e.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:e.onClick,onSelect:co(e),drilldownSourceOverride:()=>Ri(t),insights:de,onExpand:()=>ut(t,e),showIdentity:!1,chromeInset:Gs,drawWhenVisible:!0});return p.setViewControlsVisible(!1),p.setSummaryVisible(!1),u.onclick=()=>ut(t,e),fe.has(e)&&(o.style.display="none"),{card:o,ctrl:p,canvasWrapper:d,expandBtn:u}}function ys(e){const t=Fe[e];if(!t)return;const n=[...Q.values()].find(o=>o.cardIndex===e);n?(t.innerHTML=Tn.minimize,t.setAttribute("aria-label","Reattach to gallery"),t.onclick=()=>ws(n.id)):(t.innerHTML=Tn.expand,t.setAttribute("aria-label","Open full view"),t.onclick=()=>ut(e,x[e]))}function X(e){vs(),ot()?.remove(),it(null),Oe(),x=[],U.clear(),ln.clear(),ee.style.display="none";for(const d of C)d&&d.destroy();C=[],ue=[],Fe=[],ke=0,F.innerHTML="",_o=e.length,vn(e.map(d=>typeof d=="function"?null:d));const t=[];for(let d=0;d<e.length;d++){const m=e[d];if(typeof m=="function"){const v=r.ownerDocument.createElement("div");v.className="wmap-gallery-card",Object.assign(v.style,{background:w.menuBg,border:`1px solid ${w.menuBorder}`,borderRadius:Y.container,aspectRatio:"1",display:"flex",alignItems:"center",justifyContent:"center"});const p=r.ownerDocument.createElement("span");p.textContent="\u2026",Object.assign(p.style,{color:w.label,fontSize:"18px"}),v.appendChild(p),F.appendChild(v),x.push(null),C.push(null),ue.push(null),Fe.push(null),t.push({index:d,factory:m,placeholder:v}),ke++}else{const{ctrl:v,canvasWrapper:p,expandBtn:c}=Mn(m,d,e.length);x.push(m),C.push(v),ue.push(p),Fe.push(c)}}Oo(),Ft(),un(),dn(),Eo();const n=++nt,o=()=>{setTimeout(()=>{n===nt&&f.onItemsResolved?.()},0)},i=d=>{setTimeout(()=>{n===nt&&f.onItemResolved?.(d,e.length)},0)};let s=e.length-t.length;s>0&&i(s);let l=0;function u(){if(n!==nt)return;if(l>=t.length){if(ie.has(a.plotMode)){const A=a.plotMode;X(qe(A));return}if(wt){Ut();return}at=o,R(),ze||(at=null,o());return}const{index:d,factory:m,placeholder:v}=t[l++],p=m();W[d]=p;const c=Gt(p,d);Je(p,d)!==p&&(ae=!0),x[d]=c,vn([c]);const{card:g,ctrl:h,canvasWrapper:y,expandBtn:E}=Mn(c,d,e.length);C[d]=h,ue[d]=y,Fe[d]=E,ke--,v.replaceWith(g),i(++s),Zi(),Ui(),!S&&!Re?.placement&&c.statsSummary?.findings.length&&(S=zn("right",oe,r.ownerDocument,an),S.style.maxHeight="calc(100vh - 80px)",S.style.position="sticky",S.style.top="8px",S.style.flexDirection="column",S.style.display="none",(Re?.placement??"right")==="left"?Z.insertBefore(S,F):Z.appendChild(S),R(),re()),re(),setTimeout(u,0)}t.length>0?setTimeout(u,0):o()}if(ie.has(a.plotMode)&&B().length>0){const e=$t(a.plotMode);a={...a,...e},X(qe(a.plotMode))}else X($e(k));f.insights?.filter!==void 0&&qt(),Te();let Xe=0;const Yo=new(r.ownerDocument.defaultView??window).ResizeObserver(()=>{if(Xe)return;Xe=(r.ownerDocument.defaultView??window).requestAnimationFrame(()=>{Xe=0,O==null&&xn()})});Yo.observe(F);const Uo=()=>{r.style.setProperty("--wmap-sticky-top",`${We.offsetHeight}px`)};Uo();const Zo=new(r.ownerDocument.defaultView??window).ResizeObserver(Uo);Zo.observe(We),S&&R();function bs(e,t){const n=ue[e];if(!n)return;n.innerHTML="",Object.assign(n.style,{alignItems:"center",justifyContent:"center"});const o=r.ownerDocument.createElement("span");o.textContent=t?"Opened in its own window":"Opened in the wafer viewer",Object.assign(o.style,{color:w.label,fontSize:N.body,textAlign:"center",padding:"0 12px"}),n.appendChild(o)}function ut(e,t){for(const l of Q.values())if(l.cardIndex===e)return;const n=ht(t,e),o=Di++,i=C[e]?.getOptions(),s=Qs(n);if(s){const l=s.document;l.title=n,Object.assign(l.documentElement.style,{height:"100%"}),Object.assign(l.body.style,{margin:"0",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",fontFamily:N.family}),ta(r,l.documentElement);const u=na(r,l.documentElement,()=>y.setOptions({})),d=l.createElement("div");d.dataset.wmapWindowBanner="1",d.textContent=n,Object.assign(d.style,{display:"none",padding:`${M.sm} ${M.xl}`,fontSize:N.body,fontWeight:"700",background:w.warnBg,color:w.warnText,borderBottom:`1px solid ${w.warnBorder}`,flexShrink:"0"}),l.body.appendChild(d);const m=l.createElement("div");Object.assign(m.style,{flex:"1",minHeight:"0",display:"flex",flexDirection:"column"}),l.body.appendChild(m);const{wrap:v,metaPanel:p}=qo(l,n,t.wafer.metadata??void 0),c=l.createElement("div");Object.assign(c.style,{display:"flex",alignItems:"center",padding:`${M.md} ${M.lg} ${M.sm}`,borderBottom:`1px solid ${w.menuBorder}`,flexShrink:"0",gap:M.sm}),c.appendChild(v),m.appendChild(c);const g=l.createElement("div");Object.assign(g.style,{position:"relative",flex:"1",minHeight:"0",overflow:"hidden",display:"flex",flexDirection:"column"}),p&&g.appendChild(p),m.appendChild(g);let h=0;const y=kn(g,t,void 0,i,(A,j)=>{const ft=A?j:-h;try{s.resizeBy(ft,0),h=A?j:0}catch{}}),E=setInterval(()=>{s.closed&&It(o)},400);s.addEventListener("pagehide",()=>It(o)),Q.set(o,{id:o,ctrl:y,cardIndex:e,label:n,closePollId:E,stopThemeSync:u,close:()=>{s.closed||s.close()},setTitle:A=>{l.title=A,d.textContent=A,d.style.display="block"}})}else{const l=Js({title:n,onClose:()=>It(o),anchor:r});l.contentWrap.style.flexDirection="column",Xo(l,n,t.wafer.metadata??void 0);const u=kn(l.contentWrap,t,void 0,i,ui(l));Q.set(o,{id:o,ctrl:u,cardIndex:e,label:n,closePollId:null,close:()=>l.close(),setTitle:d=>{const m=l.box.querySelector("[data-wmap-window-title]");m&&(m.textContent=d,m.title=d)}})}C[e]?.destroy(),C[e]=null,bs(e,s!==null),ys(e)}function kn(e,t,n,o,i){const s=t.viewOptions?{...a,...t.viewOptions}:a,l=o?{...s,...o}:s,d={...n!==void 0?{...l,plotMode:"value",activeTest:n}:l,showLegend:!0,legendPosition:Ze},m=mi(e,t,{viewOptions:d,showTooltip:!0,padding:z,statsSummary:t.statsSummary,testValueOffer:en,onSaveImage:f.onSaveImage,onSaveText:f.onSaveText,downloadFilename:f.downloadFilename,onClick:t.onClick,onSelect:co(t),insights:de,showExpandButton:!1,onSummaryPanelChange:i,showIdentity:!1});return m.setViewControlsVisible(!0),m.setSummaryVisible(!0),m.setExpandVisible(!1),m}function It(e){const t=Q.get(e);if(!t||(Q.delete(e),t.closePollId!=null&&clearInterval(t.closePollId),t.stopThemeSync?.(),t.ctrl.destroy(),t.cardIndex===null))return;const n=t.cardIndex,o=x[n];if(!o)return;const{card:i,ctrl:s,canvasWrapper:l,expandBtn:u}=Mn(o,n,x.length);ue[n]?.parentElement?.replaceWith(i),C[n]=s,ue[n]=l,Fe[n]=u}function ws(e){const t=Q.get(e);t&&(t.close(),It(e))}function vs(){for(const e of Q.values())e.cardIndex!==null&&(e.cardIndex=null,e.setTitle(`${e.label} \u2014 unlinked from gallery`))}function Dn(){for(const e of C)e?.drawPendingNow()}const Qo=r.ownerDocument.defaultView??window;Qo.addEventListener("beforeprint",Dn);function Ss(){Dn();const e=[...F.querySelectorAll("canvas")];if(!e.length)return;const t=e.length,n=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/n),i=e[0].width,s=e[0].height,l=8,u=(r.ownerDocument.defaultView??window).devicePixelRatio||1,d=Math.round(26*u),m=Math.round(12*u),v=r.ownerDocument.createElement("canvas");v.width=n*i+(n-1)*l,v.height=o*(s+d)+(o-1)*l;const p=v.getContext("2d"),c=Ns(F);p.fillStyle=c.background,p.fillRect(0,0,v.width,v.height),e.forEach((g,h)=>{const y=h%n,E=Math.floor(h/n),A=y*(i+l),j=E*(s+d+l),ft=g.closest(".wmap-gallery-card")?.querySelector("span")?.textContent??"";p.fillStyle=c.surface,p.fillRect(A,j,i,d),p.fillStyle=c.text,p.font=`700 ${m}px system-ui, sans-serif`,p.textAlign="left",p.textBaseline="middle",p.fillText(ft,A+Math.round(10*u),j+d/2,i-Math.round(20*u)),p.drawImage(g,A,j+d)}),v.toBlob(g=>{if(!g)return;const h=C.find(y=>y!=null)?.getExportTitle();ra(g,["gallery",h].filter(Boolean).join(" "),V.onSaveImage)})}return{setItems(e){tn(),W=e.map(n=>typeof n=="function"?null:n);const t=a.plotMode;if(ie.has(t))if(e.some(o=>typeof o=="function"))X($e(e));else{const o=$t(t);a={...a,...o},X(qe(t))}else X($e(e));Jn()},setOptions(e){P(e,{fireCallback:!1})},getOptions(){return Ht(a)},setFindingsNotice(e){lo=e,R()},setColumns(e){Sn(e)},getBinColors(){return a.binColors??K()},setLotStatsSummary(e){tn(),_=e,Jn(),Te(),S&&R(),re()},openUserGuide:()=>gn(),destroy(){rs(),$.flush(),tn(),nt++,Qo.removeEventListener("beforeprint",Dn),r.ownerDocument.removeEventListener("keydown",Ko),ze?.cancel(),ze=null,at=null;for(const e of[...Q.values()])e.closePollId!=null&&clearInterval(e.closePollId),e.close(),e.ctrl.destroy();Q.clear();for(const e of C)e&&e.destroy();C=[],ot()?.remove(),Yo.disconnect(),Zo.disconnect(),Xe&&((r.ownerDocument.defaultView??window).cancelAnimationFrame(Xe),Xe=0),r.ownerDocument.removeEventListener("click",Mt,!0),window.removeEventListener("blur",ao),xi(),li(),We.remove(),Z.remove(),S?.remove(),_t=!0,vt++,clearTimeout(Xt),pe?.el.remove(),be?.destroy()}}}