@wafertools/wafermap 0.38.0 → 0.39.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 (61) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +2 -1
  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 +1 -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 +3 -0
  16. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  17. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  18. package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +1 -0
  19. package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
  20. package/dist/packages/canvas-adapter/filterJson.d.ts +25 -0
  21. package/dist/packages/canvas-adapter/filterJson.js +5 -0
  22. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  23. package/dist/packages/canvas-adapter/pageFilter.js +2 -2
  24. package/dist/packages/canvas-adapter/plotEditor.js +10 -1
  25. package/dist/packages/canvas-adapter/plotJsonComplete.d.ts +46 -0
  26. package/dist/packages/canvas-adapter/plotJsonComplete.js +4 -0
  27. package/dist/packages/canvas-adapter/plotJsonHistory.d.ts +12 -0
  28. package/dist/packages/canvas-adapter/plotJsonHistory.js +1 -0
  29. package/dist/packages/canvas-adapter/plotJsonSuggest.d.ts +16 -0
  30. package/dist/packages/canvas-adapter/plotJsonSuggest.js +1 -0
  31. package/dist/packages/canvas-adapter/plotModal.js +1 -1
  32. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  33. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  34. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  35. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  36. package/dist/packages/canvas-adapter/userGuideHtml.js +40 -18
  37. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  38. package/dist/packages/canvas-adapter/version.js +1 -1
  39. package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -0
  40. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  41. package/dist/packages/core/utils.d.ts +6 -0
  42. package/dist/packages/core/utils.js +1 -1
  43. package/dist/packages/renderer/fmt.js +1 -1
  44. package/dist/packages/stats/chartCatalogue.js +1 -1
  45. package/dist/packages/stats/coFailure.d.ts +11 -0
  46. package/dist/packages/stats/coFailure.js +1 -0
  47. package/dist/packages/stats/correlation.d.ts +7 -0
  48. package/dist/packages/stats/correlation.js +1 -1
  49. package/dist/packages/stats/differenceMap.d.ts +2 -0
  50. package/dist/packages/stats/differenceMap.js +1 -1
  51. package/dist/packages/stats/plotData.d.ts +11 -2
  52. package/dist/packages/stats/plotData.js +1 -1
  53. package/dist/packages/stats/plotSpec.d.ts +31 -2
  54. package/dist/packages/stats/plotSpec.js +4 -4
  55. package/dist/packages/stats/plotTable.d.ts +18 -0
  56. package/dist/packages/stats/plotTable.js +1 -0
  57. package/dist/packages/stats/synthesis.d.ts +6 -0
  58. package/dist/packages/stats/synthesis.js +1 -1
  59. package/dist/packages/stats/testsByWafer.d.ts +11 -0
  60. package/dist/packages/stats/testsByWafer.js +1 -0
  61. package/package.json +1 -1
@@ -1 +1 @@
1
- import{MEAN_WAFER_YIELD_LABEL as Pt}from"../stats/presentation.js";import{buildFacetTable as Wt,facetValueOf as Ie,FACET_NONE_VALUE as Rt,DEFAULT_FACET_CURATION as Nt}from"../stats/facets.js";import{mergeTestDefs as Le}from"../stats/mergeTestDefs.js";import{isParametricTest as Oe}from"../renderer/buildWaferMap.js";import{dieFailsTest as Ft,hasJudgeableTests as Mt,testsForPassKind as jt,buildTestPassRateData as Ue}from"../stats/testPassRate.js";import{fmt as Xe}from"../renderer/fmt.js";import{testLabel as Qe}from"../renderer/testLabel.js";import{waferDisplayLabel as zt,waferIdentityLabel as Ht}from"../core/waferLabel.js";import{waferPopulation as _t}from"./chartPopulation.js";import{openDrilldownMenu as Ae}from"./drilldown.js";import{plotStoreFor as Gt}from"./plotStore.js";import{createPageFilter as Vt}from"./pageFilter.js";import{bandButton as Yt}from"./filterButton.js";import{itemPassBins as Kt,passBinsLabel as Je}from"../core/passBins.js";import{describeWaferPopulation as qt,populationStat as Ut}from"../stats/population.js";import{LEADING as De,ALPHA as Xt,SPACE as D,EDGE_GUTTER as Pe,FONT as _,CLR as R,RADIUS as Qt,SHADOW as Jt,controlStyle as Ze,wireControlHover as pe,wireTooltip as he}from"./toolbar.js";import{ICONS as Zt}from"./icons.js";import{renderCapabilityPanel as en}from"./charts/capability.js";import{renderGroupComparisonPanel as tn}from"./charts/groupComparison.js";import{renderCommonalityPanel as nn}from"./charts/commonality.js";import{renderPatCard as sn}from"./charts/patCard.js";import{renderDifferenceMapPanel as an}from"./differenceMapPanel.js";import{renderCorrelationPanel as on}from"./charts/correlation.js";import{cardFrameStyle as rn,makeChartGridWrap as me,makeLabeledSelect as et,makeLinkedGroupSelect as ln,makeLinkedTestSelect as dn,makeWaferSelect as tt,makeTestSelect as nt,makeLimitsSelect as cn,makeLinkedAxisPrefs as un,makeToggle as fn,limitLines as st,limitExtent as pn,shouldIncludeLimitsByDefault as hn,hasBothLimitKinds as it}from"./charts/chartShell.js";import{maxOf as mn,minOf as bn}from"../core/utils.js";import{buildYieldData as at,buildYieldDataCombined as gn}from"../stats/yield.js";import{buildLotTestSectionSteps as yn,buildLotFunctionalSection as wn,buildMetadataStripBox as xn}from"./summaryPanel.js";import{runChunked as Sn}from"./chunked.js";import{buildRegionYieldData as We,buildRingRegions as ot,buildQuadrantRegions as rt,buildReticlePositionRegions as Cn,diesInRegion as vn}from"../stats/regions.js";import{renderDataSection as Bn}from"./dataTab.js";import{sourceFromDies as kn,toPlotItems as le}from"./plotItems.js";import{isYieldEligibleDie as $n}from"../core/dies.js";import{renderPlotCard as se}from"./plotCard.js";import{orderFieldValues as En,axisValues as Tn}from"../stats/plotData.js";import{buildSynthesis as In,synthesisKey as Ln}from"../stats/synthesis.js";import{commonPassBins as On}from"../core/passBins.js";import{renderRegionYieldDiagram as Re}from"./charts/regionYieldDiagram.js";const An=[{key:"overview",label:"Overview"},{key:"distributions",label:"Distributions"},{key:"correlation",label:"Correlation"}],Dn={key:"data",label:"Data"},Pn={key:"plot",label:"My plots"},Wn={overview:"Yield, bins and what stands out",distributions:"How each test\u2019s values spread",correlation:"How tests move together",data:"The same scope as tables, with CSV exports",plot:"Plots you have built and saved"};export function createInsightsTab(I){const{getItems:lt,getLotStats:Ne,getBinColors:J,getRingCount:K,onSaveImage:N,onSaveText:U,openWafer:Z,focusTest:be,locateDie:de}=I,ce={...Nt,...I.attributes},dt=I.showMetadataStrip??!0,ee=I.contentInset??Pe,a=I.ownerDocument??document,H=a.createElement("div");Object.assign(H.style,{display:"none",flexDirection:"column",width:"100%",paddingTop:"0"});const ct=Pe,ie=a.createElement("div");Object.assign(ie.style,{paddingLeft:ct});const X=a.createElement("div");Object.assign(X.style,{display:"flex",gap:D.xs,alignItems:"center",background:R.menuBg,border:`1px solid ${R.menuBorder}`,borderRadius:Qt.container,boxShadow:Jt.panel,padding:`0 ${D.lg}`,margin:"0"}),X.setAttribute("role","tablist");const ge=a.createElement("div");Object.assign(ge.style,{position:"sticky",top:"var(--wmap-sticky-top, 0px)",zIndex:"1",background:R.menuBg,paddingLeft:ee,paddingRight:ee,paddingBottom:D.lg}),ge.appendChild(X),X.addEventListener("keydown",e=>{if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=Array.from(X.querySelectorAll('[role="tab"]')),n=t.indexOf(a.activeElement);if(n===-1)return;e.preventDefault();const o=t[(n+(e.key==="ArrowRight"?1:-1)+t.length)%t.length];o.focus(),o.click()});const te=a.createElement("div");Object.assign(te.style,{display:"flex",flexDirection:"column",gap:D.lg,marginTop:"0",isolation:"isolate",paddingLeft:ee,paddingRight:ee});const ue=I.pageFilter??Vt({doc:a,initial:I.filter,onChange:I.onFilterChange,attributes:I.attributes,getRingCount:I.getRingCount}),Fe=ue.createBand(()=>$e(),{marginLeft:ee,marginRight:ee,marginBottom:D.lg}),ut=Fe.el;let ye,we=null;const Me=e=>{ye=e,e===void 0?(H.style.removeProperty("--wmap-insights-cols"),H.style.removeProperty("--wmap-insights-min")):(H.style.setProperty("--wmap-insights-cols",String(e)),H.style.setProperty("--wmap-insights-min","0px")),we&&(we.value=e===void 0?"auto":String(e))},je=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||!/^[0-5]$/.test(e.key)||!H.isConnected||H.style.display==="none"||a.querySelector('[data-wmap-panels-hover], [role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||(e.preventDefault(),Me(e.key==="0"?void 0:Number(e.key)))};a.addEventListener("keydown",je),H.appendChild(ie),H.appendChild(ge),H.appendChild(ut),H.appendChild(te);const ft=[...An,Dn,Pn],ae=I.plotStore??Gt(I),ne=(e,t)=>{import("./plotModal.js").then(({openPlotEditor:n})=>n({doc:a,anchor:H,store:ae,plot:e,draft:!0,items:[...t.items],ctx:t.ctx,title:e.title?`New plot from \u201C${e.title}\u201D`:"New plot",chart:{onSaveImage:N,binColors:J()}}))};let V=I.defaultView==="sweeps"?"plot":I.defaultView??"overview",F,xe=!1;ue.subscribe(()=>Q());let ze="statistics",He="wide",Y=null,_e=null,Se=[],M=null,Ce=I.initialAxisPrefs??{includeLimits:void 0,clipOutliers:!1,limits:"both"};const ve=new Map,Be=(e,t,n=!1)=>{Ce=e;for(const o of ve.values())for(const u of o)u!==t&&u.setAxisPrefs(e);n||I.onAxisPrefsChange?.(e)},ke=e=>{M!==e&&(M=e,Q())};let oe=new Map;function Ge(){for(const e of oe.values())e.destroy();oe=new Map}function Ve(e,t,n){Z?.(e,t,n)}function fe(e){return(t,n,o)=>{const u=e.find(p=>p.waferIndex===t);if(!u)return;o.preventDefault();const y=_t(u.dies,{waferLabel:u.identity,testDefs:u.testDefs,activeTest:n??Y??void 0,waferIndex:t,wafer:u.wafer,passBins:u.passBins,ringCount:K()});Ae({x:o.clientX,y:o.clientY},o.target,y,{plots:ae,getBinColors:J,onSaveImage:N,onSaveText:U,onLocateDie:de})}}function pt(e,t,n,o,u){re({x:e.clientX,y:e.clientY},e.target,t,n,o,u)}function re(e,t,n,o,u,y){const p=kn(n.map(l=>({label:l.identity??l.label,dies:l.dies,waferIndex:l.waferIndex,wafer:l.wafer,passBins:l.passBins,ringCount:K()})),o,u,Le(n).defs,y);p&&Ae(e,t,p,{plots:ae,getBinColors:J,onSaveImage:N,onSaveText:U,onLocateDie:de})}function Ye(e){return Z?{open:(t,n)=>Ve(t,`Wafer ${e.find(o=>o.waferIndex===t)?.label??t}`,n)}:be&&e.length===1?{open:(t,n)=>be(n),label:"show this test on the map"}:null}function $e(){return lt().map((e,t)=>e==null?null:{metadata:e.wafer.metadata??void 0,dies:e.dies,wafer:e.wafer,label:zt(e,t),identity:Ht(e),waferIndex:t,passBins:Kt(e),statsSummary:e.statsSummary,testDefs:e.testDefs,source:e}).filter(e=>e!=null)}function ht(e,t){Object.assign(e.style,{background:"none",border:"none",borderBottom:t?`2px solid ${R.iconActive}`:"2px solid transparent",color:t?R.iconActive:R.label,fontWeight:t?"700":"500",fontSize:_.body,padding:`${D.sm} ${Pe} ${D.md}`,cursor:"pointer"})}function mt(e,t){const n=a.createElement("button");n.type="button",n.textContent=t;const o=e===V;ht(n,o),n.dataset.on=o?"true":"false",pe(n,"bare"),n.dataset.wmapInsightsTab=e;const u=Wn[e];return u&&he(n,u),n.setAttribute("role","tab"),n.setAttribute("aria-selected",o?"true":"false"),n.tabIndex=o?0:-1,n.addEventListener("click",()=>{V!==e&&(V=e,Q({keepSections:!0}))}),n}function bt(e,t,n,o=!0){const u=me(a),y=J(),p=n??"group",l=Je(e.map(f=>f.passBins)),w=le(e.map(f=>({label:f.identity??f.label.replace(/\s*·\s*\d+(\.\d+)?%$/,""),dies:f.dies,waferIndex:f.waferIndex,wafer:f.wafer,passBins:f.passBins,ringCount:K()}))),h=Le(e).defs,d=t?F:void 0,c={testDefs:h,groupBy:d,curation:I.attributes},b=(f,i,S=!1)=>({id:"card-yield",title:t?`Yield by ${p} (pass: ${l})`:`Yield by wafer (pass: ${l})`,chart:"bar",fields:{x:S?[{slot:"groupBy"},{builtin:"wafer"}]:{slot:"groupBy"},y:{builtin:"yield"},color:{none:!0}},...S?{}:{valueLabels:!0},...f&&!S?{sort:"value"}:{},...i>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}}),O=t?t.length:e.length;let v=null,T=!1;o&&(v=se({doc:a,editAsPlot:ne,items:w,ctx:c,spec:{choices:[{current:"natural",options:f=>[["value","Sort: yield"],["natural",t&&!f?`Sort: ${p}`:"Sort: wafer"],...t&&!f?[["nested",`${p}, then wafer`,`Each ${p} with its wafers inside it`]]:[]]}],build:([f])=>(T=f==="nested",b(f==="value",O,T))},drill:t&&d?f=>{if(T)return null;const i=Ie(w[f[0]?.item]?.metadata,d,I.attributes);if(i===void 0)return null;const S=t.find(L=>L.key===i)?.items.length??0;return L=>({...L,title:`Yield by wafer \u2014 ${p}: ${i} (pass: ${l})`,fields:{...L.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:d},values:[i]}]},axes:S>=3?{y:{references:[{stat:"median"}]}}:void 0})}:void 0,drillLabel:()=>T?void 0:"see its wafers",chart:{onSaveImage:N,onOpenWafer:Z?f=>Ve(w[f].waferIndex??f,`Wafer ${w[f].label}`):void 0,onWaferMenu:fe(e)}}),v.card.style.minHeight="360px",u.appendChild(v.card));const j={current:"hbin",options:[["hbin","Hard bins","The physical sort result: where the part goes on the handler"],["sbin","Soft bins","The test program\u2019s failure category: many soft bins can map to one hard bin"]]},z={current:"share",options:[["count","Counts"],["share",`Share of ${p}`,`Each ${p}\u2019s dies in a bin as a share of all its dies, so ${p} values of different sizes compare`],["mix","Bin mix",`Each ${p} as one bar split into its bins, as shares of its own dies`]]},g=15,s=(f,i)=>t&&i==="mix"?{id:"card-bin-pareto",title:`${f==="sbin"?"Soft":"Hard"} bin mix by ${p}`,chart:"bar",stack:"percent",fields:{x:{slot:"groupBy"},color:{builtin:f==="sbin"?"sbin":"hbin"}}}:{id:"card-bin-pareto",title:`${f==="sbin"?"Soft":"Hard"} bin pareto`,chart:"bar",sort:"value",fields:{x:{builtin:f==="sbin"?"sbin":"hbin"},color:t?{follow:"groupBy"}:{builtin:f==="sbin"?"sbin":"hbin"}},...f==="sbin"?{top:g}:{},...t?i==="share"?{barNorm:"percent"}:{}:{cumulative:!0}},$=se({doc:a,editAsPlot:ne,items:w,ctx:c,spec:t?{choices:[j,z],build:([f,i])=>s(f,i)}:{choices:[j],build:([f])=>s(f,void 0)},chart:{onSaveImage:N,binColors:y,onSelectPoints:(f,i,S,L)=>{const r=$.current().fields,C=r.x,A=r.color,m=k=>!!k&&!Array.isArray(k)&&typeof k=="object"&&"builtin"in k&&k.builtin==="sbin",x=m(C)||m(A)?"sbin":"hbin",B=new Set(f.map(k=>x==="hbin"?k.die?.hbin:k.die?.sbin));if(B.size!==1)return;const E=[...B][0];if(C&&!Array.isArray(C)&&"slot"in C){const k=new Set(f.map(G=>G.die).filter(G=>!!G)),P=new Set(f.map(G=>w[G.item]?.waferIndex));re(i,S,e.filter(G=>P.has(G.waferIndex)),`in ${x==="hbin"?"hard":"soft"} bin ${E}`,G=>k.has(G));return}const W=t?L?.group:void 0,q=W!==void 0?t?.find(k=>k.key===W)?.items??[]:e;re(i,S,q,`in ${x==="hbin"?"hard":"soft"} bin ${E}${W!==void 0?` of ${W}`:""}`,k=>$n(k)&&(x==="hbin"?k.hbin:k.sbin)===E)}}});return $.card.style.minHeight="360px",u.appendChild($.card),{card:u,destroy:()=>{v?.destroy(),$.destroy()}}}function Ee(){const e=a.createElement("div");return e.dataset.wmapChartCard="1",Object.assign(e.style,{...rn(),display:"flex",flexDirection:"column",gap:D.lg,minWidth:"0"}),e}function gt(e){if(ie.innerHTML="",ie.style.marginBottom="0",!dt)return;const t=xn(e.map(n=>({metadata:n.metadata})),void 0,{facetableOnly:!1});t&&(t.style.marginBottom="0",ie.appendChild(t),ie.style.marginBottom=D.xs)}function yt(e,t,n,o,u){if(!e.length)return{elements:[],destroy:()=>{}};const y=e.map(g=>g.wafer),p=e.map(g=>g.dies),l=K(),w=[],h=[],d=o??[{key:"",items:e}],c=e.flatMap(g=>g.dies),b=["spec","testFlag","functional"].filter(g=>Mt(n,g,c));if(b.length){const g={spec:{label:"Test limits",hint:"Judged from each die\u2019s measured value against the test\u2019s limits",title:"Parametric pass rate \xB7 test limits"},testFlag:{label:"Tester flag",hint:"The pass or fail the tester recorded for each die",title:"Parametric pass rate \xB7 tester flag"},functional:{label:"Functional",hint:"Tests that only pass or fail and have no measured value",title:"Functional test pass rate"}},s=!!o,$=le(e.map(m=>({label:m.identity??m.label,dies:m.dies,waferIndex:m.waferIndex,wafer:m.wafer,passBins:m.passBins,ringCount:l}))),f=25,i=m=>jt(n,m).map(x=>x.testNumber),S=m=>Ue(d.map(x=>({key:x.key,items:x.items.map(B=>({dies:B.dies}))})),n,m).rows.map(x=>x.testNumber),L=m=>m==="testFlag"?{judge:"flag"}:{},r=(m,x="bars",B="worst")=>s&&x==="grid"?{id:`card-pass-rate-${m}`,title:g[m].title,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},y:{tests:S(m).slice(0,f),passRate:!0,...L(m)}}}:{id:`card-pass-rate-${m}`,title:g[m].title,chart:"bar",orientation:"horizontal",sort:"ascending",...i(m).length>f&&B==="worst"?{top:f}:{},fields:{x:{builtin:"test"},y:{tests:i(m),passRate:!0,...L(m)},color:s?{follow:"groupBy"}:{none:!0}},...s?{}:{valueLabels:!0},axes:{y:{min:0,max:100}}},C=m=>m.id.slice(15),A=se({doc:a,editAsPlot:ne,items:$,ctx:{testDefs:n,groupBy:s?F:void 0,curation:I.attributes},spec:(()=>{const m=b.some(B=>i(B).length>f),x=[];return b.length>1&&x.push({current:b[0],options:b.map(B=>[B,g[B].label,g[B].hint])}),s&&x.push({current:"bars",options:[["bars","Bars"],["grid","Grid",`The worst ${f} tests as a grid of test by group`]]}),m&&x.push({current:"worst",options:[["worst",`Worst ${f}`],["all","All tests"]]}),x.length?{choices:x,build:B=>{let E=0;const W=b.length>1?B[E++]:b[0],q=s?B[E++]:"bars",k=m?B[E++]:"worst";return r(W,q,k)}}:r(b[0])})(),notes:m=>{const x=C(m);if(x==="functional")return[];const B=Ue(d.map(E=>({key:E.key,items:E.items.map(W=>({dies:W.dies}))})),n,x).disagreementDies;return B?[`${B.toLocaleString("en-GB")} die${B===1?"":"s"} judged differently by test limits and the tester flag`]:[]},chart:{onSaveImage:N,selectActionLabel:"chart or tabulate the dies that fail its test",onSelectPoints:(m,x,B,E)=>{const W=n.find(P=>P.testNumber===E?.test);if(!W)return;const q=C(A.current()),k=E?.group!==void 0?d.find(P=>P.key===E.group)?.items??e:e;re(x,B,k,`failing ${Qe(W,W.testNumber)}${E?.group!==void 0?` in ${E.group}`:""}`,P=>Ft(P,W,q)===!0,Oe(W)?W.testNumber:void 0)}}});A.card.style.minHeight="300px",w.push(A.card),h.push(A.destroy)}const O=g=>(s,$)=>{const f=new Set;for(const i of e)for(const S of vn(i.dies,i.wafer,l,s.key,g))f.add(S);pt($,e,`in ${s.label}`,i=>f.has(i))},v=We(p,y,l,g=>e[g].passBins,ot);if(v.length){const g=Re({title:"Ring yield",mode:"ring",rows:v,onSelectRegion:O(ot),onSaveImage:N,ownerDocument:a});w.push(g.card),h.push(g.destroy)}const T=(g,s,$)=>{const f=!!o,i=le(e.map(L=>({label:L.identity??L.label,dies:L.dies,waferIndex:L.waferIndex,wafer:L.wafer,passBins:L.passBins,ringCount:l}))),S=se({doc:a,editAsPlot:ne,items:i,ctx:{testDefs:n,groupBy:f?F:void 0,curation:I.attributes},spec:{id:g,title:`${$} yield by ${f?u??"group":"wafer"}`,chart:"heatmap",fields:{x:{slot:"groupBy"},rows:{builtin:s},y:{builtin:"yield"}}},chart:{onSaveImage:N}});S.card.style.minHeight="300px",w.push(S.card),h.push(S.destroy)};v.length&&e.length>=2&&T("card-ring-wafer","ring","Ring");const j=We(p,y,l,g=>e[g].passBins,rt);if(j.length){const g=Re({title:"Quadrant yield",mode:"quadrant",rows:j,onSelectRegion:O(rt),onSaveImage:N,ownerDocument:a});w.push(g.card),h.push(g.destroy),e.length>=2&&T("card-quadrant-wafer","quadrant","Quadrant")}const z=y.find(g=>g.reticle!==void 0)?.reticle;if(z){const g=($,f)=>Cn($,f.reticle),s=We(p,y,l,$=>e[$].passBins,g);if(s.length){const $=Re({title:"Reticle cell yield",mode:"reticleCell",rows:s,grid:{width:Math.max(1,Math.floor(z.width)),height:Math.max(1,Math.floor(z.height))},onSelectRegion:O(g),onSaveImage:N,ownerDocument:a});w.push($.card),h.push($.destroy)}}return{elements:w,destroy:()=>{for(const g of h)g()}}}function wt(e,t,n){if(!e.length)return{cards:[],destroy:()=>{}};const o=e.map(c=>c.dies),u=e.flatMap(c=>c.dies),y=e.map(c=>c.statsSummary),p=y.every(c=>c!==void 0)?y:void 0,l=[],w=[];let h=null;if(t.length){const c=Ee();let b=null;const O=Sn(yn(u,t,void 0,p,U,o.map(v=>({dies:v})),void 0,"full"),{onDone:v=>{b=v,c.removeAttribute("aria-busy"),v?c.replaceChildren(v):c.remove()}});if(O.done)b&&(h=c);else{const v=a.createElement("div");v.textContent="Computing test statistics\u2026",Object.assign(v.style,{color:R.label,fontSize:_.body}),c.setAttribute("aria-busy","true"),c.appendChild(v),h=c,l.push(()=>O.cancel())}}let d=null;if(n.length){const c=wn(u,n,p,U);if(c){const b=Ee();b.appendChild(c),d=b}}return h&&w.push(h),d&&w.push(d),{cards:w,destroy:()=>{for(const c of l)c()}}}function xt(e){const t=Je(e.map(h=>h.passBins)),n=e.length===1,o=e[0],u=Ee();Object.assign(u.style,{flexDirection:"row",flexWrap:"wrap",gap:D.md});const y=h=>{const d=h.lastElementChild;return d&&Object.assign(d.style,{borderRight:"none",paddingRight:"0",marginRight:"0"}),h};function p(h,d,c){const b=a.createElement("div");Object.assign(b.style,{display:"flex",alignItems:"baseline",gap:D.sm,paddingRight:D.xxl,marginRight:D.md,borderRight:`1px solid ${R.menuBorder}`});const O=a.createElement("div");O.textContent=h,Object.assign(O.style,{fontSize:_.heading,fontWeight:"700",color:R.value,lineHeight:De.tight});const v=a.createElement("div");if(v.textContent=d,Object.assign(v.style,{fontSize:_.body,color:R.label}),b.append(O,v),c){const T=a.createElement("div");T.textContent=c,Object.assign(T.style,{fontSize:_.meta,color:R.label,opacity:Xt.muted}),b.appendChild(T)}return b}if(n){const h=at([{...o,key:o.waferIndex}])[0]?.percent;return h!==void 0&&u.appendChild(p(`${h.toFixed(1)}%`,`Yield \xB7 pass: ${t}`)),u.appendChild(p(String(o.dies.length),"Total dies")),y(u)}u.appendChild(p(String(e.length),"Wafers"));const l=at(e.map(h=>({...h,key:h.waferIndex}))).map(h=>h.percent).filter(h=>Number.isFinite(h));if(l.length){const h=l.reduce((b,O)=>b+O,0)/l.length,d=gn([{key:"all",items:e.map(b=>({...b,key:b.waferIndex}))}])[0]?.percent,c=d!==void 0&&d.toFixed(1)!==h.toFixed(1);u.appendChild(p(`${h.toFixed(1)}%`,`${Pt} \xB7 pass: ${t}`,c?`${d.toFixed(1)}% by dies`:void 0))}const w=e.map(h=>h.statsSummary);if(w.every(h=>h!==void 0)){const h=w.reduce((c,b)=>c+b.stats.analyzedDies,0),d=w.reduce((c,b)=>c+b.stats.excludedDies,0);u.appendChild(p(h.toLocaleString(),"Dies analysed",d?`${d.toLocaleString()} excluded`:void 0))}else u.appendChild(p(e.reduce((h,d)=>h+d.dies.length,0).toLocaleString(),"Total dies"));return y(u)}function St(e,t,n,o,u){const y=a.createElement("div");Object.assign(y.style,{display:"flex",flexDirection:"column",gap:D.lg});const p=e.length===1&&!o;e.length&&!o&&y.appendChild(xt(e));const l=bt(e,o,u,!p);y.appendChild(l.card);const w=yt(e,t,n,o,u);for(const c of w.elements)l.card.appendChild(c);const h=Ct(e,n);if(h&&y.appendChild(h.el),e.length>=4&&Se.length){const c=nn({wafers:e,fields:Se,curation:ce,groupedBy:F,onGroupBy:b=>{F=b,M=null,Q()},ownerDocument:a});y.appendChild(c.card)}const d=sn({items:e.map(c=>({...c,ringCount:K()})),testDefs:n,ownerDocument:a,showMap:I.showPatMap});return d&&y.appendChild(d.card),y.appendChild(vt()),{card:y,destroy:()=>{l.destroy(),w.destroy(),h?.destroy()}}}function Ct(e,t){const n=Ne?.()??(e.length===1?e[0].statsSummary:void 0);if(!n)return null;const o=a.createElement("section");o.dataset.wmapWorthALook="1",Object.assign(o.style,{display:"flex",flexDirection:"column",gap:D.md});const u=a.createElement("h3");u.textContent="Worth a look",Object.assign(u.style,{margin:"0",fontSize:_.heading,fontWeight:"600",color:R.value}),o.appendChild(u);const y=(d,c)=>{const b=a.createElement("p");b.textContent=d,c&&(b.dataset[c]="1"),Object.assign(b.style,{margin:"0",fontSize:_.body,color:R.label,lineHeight:De.base}),o.appendChild(b)};if(xe||M!==null)return y("Worth a look describes the whole lot, as What stands out beside the map does. Switch the filter off, or Show all groups, to see it here.","wmapWorthNarrowed"),{el:o,destroy:()=>{}};const p=In(n,{passBins:On(e.map(d=>d.passBins)),attributes:I.attributes});if(p.items.length===0)return y(p.nothing??"Nothing stands out.","wmapWorthNothing"),{el:o,destroy:()=>{}};const l=me(a);o.appendChild(l);const w=le(e.map(d=>({label:d.identity??d.label,dies:d.dies,waferIndex:d.waferIndex,wafer:d.wafer,passBins:d.passBins,ringCount:K()}))),h=[];if(p.items.forEach((d,c)=>{const b=a.createElement("div");b.dataset.wmapWorthWhy="1",b.textContent=`Shown because: ${d.reason}`,d.text!==d.reason&&he(b,d.text),Object.assign(b.style,{flexBasis:"100%",fontSize:_.body,color:R.text,lineHeight:De.base});const O=[b];if(I.showOnMap){const T=a.createElement("button");T.type="button",T.textContent="Show on map",T.dataset.wmapWorthShowOnMap="1",Object.assign(T.style,{...Ze("outlined"),fontSize:_.body,padding:`0 ${D.md}`}),pe(T),he(T,"Leave Insights and show this on the map, as its row in What stands out does"),T.addEventListener("click",()=>I.showOnMap(d.target)),O.push(T)}const v=se({doc:a,items:w,ctx:{testDefs:t,curation:ce},spec:{id:`worth-${c}`,...d.chart},extras:O,editAsPlot:ne,chart:{onSaveImage:N}});v.card.dataset.wmapWorthKey=Ln(d),l.appendChild(v.card),h.push(v.destroy)}),p.also){const d=p.also.items.map(c=>c.brief).join("; ");y(`Also: ${d}${p.also.more?`; and ${p.also.more} more`:""}. Their rows in What stands out show them on the map.`,"wmapWorthAlso")}return{el:o,destroy:()=>h.forEach(d=>d())}}function vt(){const e=a.createElement("div");Object.assign(e.style,{fontSize:_.body,color:R.label});const t=a.createElement("button");return t.type="button",t.textContent="Data tab",t.dataset.wmapOpenDataTab="1",Object.assign(t.style,{border:"none",background:"none",padding:"0",cursor:"pointer",font:"inherit",color:R.iconActive,textDecoration:"underline"}),pe(t,"bare"),t.addEventListener("click",()=>{V="data",Q({keepSections:!0})}),e.append("Test statistics, every die and every wafer as tables, with CSV export: see the ",t,"."),e}function Bt(e,t,n,o){const u=a.createElement("div");u.style.width="100%";let y,p=!1;return import("./plotTab.js").then(({createPlotSection:l})=>{if(p)return;const w=l({doc:a,store:ae,items:e,testDefs:t,ringCount:K(),attributes:I.attributes,groupBy:n,groupLabel:o,onSaveImage:N,onSaveText:U,getBinColors:J,waferMenu:fe(e),openWafer:Z?(h,d,c)=>Z(h,d,c):void 0,focusTest:be,locateDie:de,pickPlotsFile:I.onPickPlotsFile});u.appendChild(w.card),y=w}),{card:u,destroy:()=>{p=!0,y?.destroy()}}}function kt(e,t,n,o,u){const y=xe?void 0:Ne?.(),p=()=>{oe.get("data")?.destroy(),oe.delete("data"),Q({keepSections:!0})};return Bn({doc:a,items:e,testDefs:t,allTestDefs:n,groups:o,groupLabelText:u,ringCount:K(),attributes:I.attributes,yieldByWaferIndex:new Map(y?.lotYieldSeries.map(l=>[l.waferIndex,l.yieldPercent])),onSaveText:U,onLocateDie:de,onOpenWafer:Z?(l,w)=>Z(l,w):void 0,buildStatistics:l=>wt(l,t,n),view:ze,onViewChange:l=>{ze=l,p()},diesLayout:He,onDiesLayoutChange:l=>{He=l}})}function Ke(e,t){const n=a.createElement("h3");return n.textContent=e,n.dataset.wmapRowHeading=t,Object.assign(n.style,{gridColumn:"1 / -1",margin:`${D.md} 0 0`,color:R.value,fontSize:_.heading,fontWeight:"600"}),n}function $t(e,t,n,o){const u=me(a),y=Ye(e),p=le(e.map(r=>({label:r.identity??r.label,dies:r.dies,waferIndex:r.waferIndex,wafer:r.wafer,passBins:r.passBins,ringCount:K()}))),l=t.filter(r=>r.testNumber!==void 0),w=!!n&&!!F,h=w&&M!==null,d={testDefs:t,groupBy:w?F:void 0,curation:I.attributes},c=(r,C,A)=>({limits:C.limits??"both",axes:{[r]:{...C.includeLimits!==void 0?{includeLimits:C.includeLimits}:{},...C.clipOutliers?{clip:!0}:{},...A?{scale:"log"}:{}}}});function b(r){let C=Ce,A=!1,m;const x=dn(l,Y??l[0]?.testNumber??null,P=>{m?.refresh(),$(P)},{ownerDocument:a}),B=a.createElement("span");Object.assign(B.style,{display:"inline-flex",flexWrap:"wrap",gap:D.sm,alignItems:"center"});const E={setAxisPrefs:P=>{W.set(P)&&(C=P,m?.refresh())}},W=un(B,C,P=>{C=P,m?.refresh(),Be(P,E)},a),q=[x.el,B];r.logToggle&&q.push(fn("Log scale",A,P=>{A=P,m?.refresh()},a,"Draw the value axis on a logarithmic scale")),q.push(...r.extras??[]),m=se({doc:a,editAsPlot:ne,items:p,ctx:d,...r.card,spec:{choices:r.choices??[],build:P=>r.build(C,A,P)},slots:()=>({test:x.get()??void 0}),extras:q,onResolved:P=>{const G=t.find(Dt=>Dt.testNumber===x.get()),qe=st(G,C.limits),Te=Tn(P,r.valueRole),{lo:Lt,hi:Ot}=pn(qe),At=Te.length>0&&qe.length>0&&hn(bn(Te),mn(Te),Lt,Ot);W.sync(C.includeLimits??At,st(G).length>0,it(G))},chart:r.chart});const k=m;return{card:k.card,setTest:P=>{x.set(P)&&k.refresh()},refresh:()=>k.refresh(),setAxisPrefs:E.setAxisPrefs,destroy:()=>k.destroy()}}const O=y?(r,C)=>y.open(p[r]?.waferIndex??r,C??Y??l[0]?.testNumber??0):void 0;let v=!1;const T=b({valueRole:"y",logToggle:!0,choices:w&&!h?[{current:"groups",options:[["groups",`By ${o??"group"}`],["nested",`${o??"Group"}, then wafer`,"Each group with its wafers inside it"]]}]:[],build:(r,C,[A])=>(v=w&&!h&&A==="nested",{id:"card-box",title:"Test value distribution",chart:"box",orientation:"horizontal",fields:{x:v?[{slot:"groupBy"},{builtin:"wafer"}]:w&&!h?{slot:"groupBy"}:{builtin:"wafer"},y:{slot:"test"},color:v?{follow:"groupBy"}:{none:!0}},...h?{where:{conditions:[{field:{meta:F},values:[M]}]}}:{},...c("y",r,C)}),card:{...w&&!h?{drill:r=>{if(v)return null;const C=Ie(p[r[0]?.item]?.metadata,F,I.attributes);return C===void 0?null:A=>({...A,fields:{...A.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:F},values:[C]}]}})},drillLabel:()=>v?void 0:"see its wafers"}:{},...M!==null?{externalBack:{shown:()=>M!==null,onBack:()=>ke(null)}}:{}},chart:{onSaveImage:N,onOpenWafer:O,openActionLabel:y?.label,onWaferMenu:fe(e)}});let j=null;const z=w?[]:[tt(p.map(r=>({label:r.label})),null,r=>{j=r,g.refresh()},{ownerDocument:a})],g=b({valueRole:"x",extras:z,choices:w?[{current:"percent",options:[["percent",`Share of ${o??"group"}`,"Each group\u2019s bars as a share of its own dies, so groups of different sizes compare"],["count","Counts"]]}]:[],card:M!==null?{externalBack:{shown:()=>M!==null,onBack:()=>ke(null)}}:{},build:(r,C,[A])=>({id:"card-histogram",title:"Value histogram",chart:"histogram",fields:{y:{slot:"test"},color:w?{follow:"groupBy"}:{none:!0}},...w&&A!=="count"?{histNorm:"percent"}:{},...j!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[p[j].label]}]}}:{},...c("x",r,!1)}),chart:{onSaveImage:N,onSelectPoints:(r,C,A,m)=>{const x=t.find(k=>k.testNumber===(Y??l[0]?.testNumber)),B=new Set(r.map(k=>k.die).filter(k=>!!k)),E=new Set(r.map(k=>p[k.item]?.waferIndex)),W=m?.range,q=x&&W?`with ${Qe(x,x.testNumber)} from ${Xe(W.lo,x.unit,"engineering")} to ${Xe(W.hi,x.unit,"engineering")}${m?.group?` in ${m.group}`:""}`:"selected in the histogram";re(C,A,e.filter(k=>E.has(k.waferIndex)),q,k=>B.has(k),x?.testNumber)}}}),s=b({valueRole:"y",choices:e.length>=3?[{current:"trend",options:[["trend","Trend","Each wafer\u2019s mean with a band of one standard deviation"],["control","Control chart","One value per wafer against control limits, with the points that break a Western Electric rule marked"]]}]:[],build:(r,C,[A])=>A==="control"?{id:"card-trend",title:"Wafer-to-wafer control chart",chart:"control",aggregate:"mean",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:{none:!0}},...c("y",r,!1)}:{id:"card-trend",title:"Wafer-to-wafer trend",chart:"line",aggregate:"mean",spread:"sd",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:{none:!0}},...c("y",r,!1),axes:{...c("y",r,!1).axes,y:{...c("y",r,!1).axes.y,references:[{stat:"mean",label:Ut(qt(e.map(m=>m.wafer.metadata)),"mean")}]}}},card:{ctx:{...d,groupBy:void 0},...e.length<2?{unavailable:"A trend needs at least two wafers"}:{}},chart:{onSaveImage:N,onWaferMenu:fe(e),selectActionLabel:O?"open that wafer":"chart or tabulate its dies",selectRangeLabel:"wafers",onSelectPoints:(r,C,A)=>{const m=new Set(r.map(E=>E.item));if(m.size===1&&O){O([...m][0]);return}const x=new Set(r.map(E=>E.die).filter(E=>!!E)),B=new Set(r.map(E=>p[E.item]?.waferIndex));re(C,A,e.filter(E=>B.has(E.waferIndex)),"selected in the trend",E=>x.has(E),Y??void 0)}}}),$=r=>{Y=r,T.setTest(r),g.setTest(r),s.setTest(r),L.setTest(r),i?.setTest(r),S?.setTest(r)},f=()=>tn({groups:n,testDefs:t,groupLabelText:o,control:_e,onControlChange:r=>{_e=r;const C=f();i.card.replaceWith(C.card),i=C},selectedTestNumber:Y??void 0,onSelectTest:r=>$(r),onSaveText:U,ownerDocument:a});let i=n&&n.length>=2?f():void 0;const S=n&&n.length>=2?an({groups:n,testDefs:t,groupLabelText:o,selectedTestNumber:Y??void 0,onSaveImage:N,ownerDocument:a}):void 0;ve.set("distribution",[T,g,s]);const L=en({title:"Process capability",items:e,testDefs:t,onSaveImage:N,selectedTestNumber:Y??void 0,onSelectTest:r=>$(r),ownerDocument:a});return(i||S)&&(u.append(Ke(`Comparing ${o??"groups"}`,"comparing")),i&&u.append(i.card),S&&u.append(S.card),u.append(Ke("Test by test","tests"))),u.append(L.card,T.card,g.card,s.card),{card:u,destroy:()=>{L.destroy(),T.destroy(),g.destroy(),s.destroy(),i?.destroy(),S?.destroy()}}}function Et(e,t,n){const o=me(a),u=Ye(e),y=le(e.map(i=>({label:i.identity??i.label,dies:i.dies,waferIndex:i.waferIndex,wafer:i.wafer,passBins:i.passBins,ringCount:K()}))),p=t.filter(i=>i.testNumber!==void 0&&Oe(i));let l=p[0]?.testNumber,w=p[1]?.testNumber??l,h=null,d=Ce;const c=!!n&&!!F,b=(i,S)=>{const L=a.createElement("label");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:D.xs,fontSize:_.body,color:R.label});const r=a.createElement("span");return r.textContent=i,L.append(r,S),L},O=nt(p,l??null,i=>{l=i,z(),$.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:a}),v=nt(p,w??null,i=>{w=i,z(),$.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:a}),T=a.createElement("span"),j={setXY:(i,S)=>{l=i,w=S,O.value=String(i),v.value=String(S),z(),$.refresh()},setAxisPrefs:i=>{d=i,z(),$.refresh()},destroy:()=>$.destroy()};function z(){const i=[l,w].map(S=>t.find(L=>L.testNumber===S));T.replaceChildren(...i.some(it)?[cn(d.limits??"both",S=>{d={...d,limits:S},$.refresh(),Be(d,j)},a)]:[])}const g=i=>{const S=t.find(L=>L.testNumber===i);return S?.name?{test:i??0,name:S.name}:{test:i??0}},s=[b("X:",O),b("Y:",v),T];!c&&e.length>1&&s.push(tt(y.map(i=>({label:i.label})),null,i=>{h=i,$.refresh()},{ownerDocument:a}));const $=se({doc:a,editAsPlot:ne,items:y,ctx:{testDefs:t,groupBy:c?F:void 0,curation:I.attributes},extras:s,spec:{choices:[],build:()=>({id:"card-scatter",title:"Test scatter",chart:"scatter",limits:d.limits??"both",fields:{x:g(l),y:g(w),color:c?{follow:"groupBy"}:{builtin:"hbin"}},...c?{fit:"linear"}:{},...h!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[y[h].label]}]}}:{}})},...l===void 0?{unavailable:"No parametric test has values to plot"}:{},chart:{onSaveImage:N,binColors:J(),onOpenWafer:u?(i,S)=>u.open(y[i]?.waferIndex??i,S??l??0):void 0,openActionLabel:u?.label,onSelectPoints:(i,S,L)=>{const r=new Map;for(const m of i){const x=y[m.item]?.waferIndex;if(x===void 0||!m.die)continue;const B=r.get(x);B?B.push(m.die):r.set(x,[m.die])}const C=[...r].flatMap(([m,x])=>{const B=e.find(E=>E.waferIndex===m);return B?[{label:B.identity??B.label,dies:x,waferIndex:m,wafer:B.wafer,passBins:B.passBins,ringCount:K()}]:[]});if(C.length===0)return;const A=C.length===1?`selected on ${C[0].label} in the scatter`:`selected in the scatter, across ${C.length} wafers`;Ae(S,L,{items:C,population:A,testDefs:t,activeTest:l},{plots:ae,getBinColors:J,onSaveImage:N,onSaveText:U,onLocateDie:de})}}});z(),ve.set("correlation",[j]);const f=on({title:"Test correlation matrix",items:e,testDefs:t,onSaveImage:N,onSaveText:U,onSelectPair:(i,S)=>j.setXY(i,S),ownerDocument:a});return o.append(f.card,$.card),{card:o,destroy:()=>{f.destroy(),j.destroy()}}}const Tt=(e,t,n,o)=>Yt(a,e,t,n,o),It=()=>ue.openEditor(H,$e());function Q(e){e?.keepSections||Ge(),te.innerHTML="",X.innerHTML="";for(const s of ft)X.appendChild(mt(s.key,s.label));const t=$e(),n=ue.keep(t),o=n.items;xe=n.narrowing,Fe.refresh(n.result,t),gt(o);const u=Wt(o,{facetableOnly:!0,curation:ce}).filter(s=>s.splittable);Se=u.map(s=>({key:s.key,label:s.label}));const y=a.createElement("div");Object.assign(y.style,{display:"flex",gap:D.md,alignItems:"center",marginLeft:D.xxl,paddingBottom:D.xs}),I.showFilterButton!==!1&&y.appendChild(Tt("Filter\u2026","wmapInsightsFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>It()));let p;u.length>0?(y.appendChild(et("Group by:",[{value:"",label:"None"},...u.map(s=>({value:s.key,label:`${s.label} (${s.values.length})`}))],F??"",s=>{F=s||void 0,M=null,Q()},{hook:"group-by",ownerDocument:a,hint:"Split every chart by a wafer attribute, such as lot or tester"})),p=u.find(s=>s.key===F)?.label):F=void 0;let l;if(F){const s=new Map,$=[];for(const f of o){const i=Ie(f.metadata,F,ce)??Rt;s.has(i)||(s.set(i,[]),$.push(i)),s.get(i).push(f)}l=En($).map(f=>({key:f,items:s.get(f)}))}M!==null&&!l?.some(s=>s.key===M)&&(M=null),l&&l.length>0&&y.appendChild(ln(l.map(s=>s.key),"Show:",M,s=>ke(s),{ownerDocument:a,hint:"Show every group, or analyse just one"}).el);const w=et("Columns:",[{value:"auto",label:"Auto (0)"},...[1,2,3,4,5].map(s=>({value:String(s),label:`${s} (${s})`}))],ye===void 0?"auto":String(ye),s=>Me(s==="auto"?void 0:Number(s)),{hook:"insights-columns",maxWidth:"90px",ownerDocument:a,hint:"How many cards sit side by side; the keys 1 to 5 set it and 0 returns to Auto"});we=w.querySelector("button"),y.appendChild(w);let h=null;if(I.onOpenGuide){const s=a.createElement("button");s.type="button",s.innerHTML=Zt.help,s.setAttribute("aria-label","User guide"),Object.assign(s.style,{...Ze("bare"),display:"inline-flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",flexShrink:"0"}),pe(s,"bare"),he(s,"User guide"),s.addEventListener("click",()=>I.onOpenGuide()),Object.assign(s.style,{marginLeft:"auto"}),h=s}X.appendChild(y),h&&X.appendChild(h);const d=M!==null?l?.find(s=>s.key===M):void 0,c=d?.items??o,b=d?void 0:l,O=Le(c),v=O.defs,T=v.filter(Oe);if(Y!==null&&!T.some(s=>s.testNumber===Y)&&(Y=null),o.length===0){const s=a.createElement("div");s.dataset.wmapInsightsFilterEmpty="1",s.textContent="The filter keeps no wafer and no die. Edit the filter or switch it off to see the data.",Object.assign(s.style,{color:R.label,fontSize:_.body,padding:D.xl}),te.appendChild(s);return}const j=e?.keepSections?oe.get(V):void 0,z=j??(V==="overview"?St(c,T,v,b,p):V==="distributions"?$t(c,T,b,p):V==="data"?kt(c,T,v,b,p):V==="plot"?Bt(c,v,d?void 0:F,d?void 0:p):Et(c,T,b));j||oe.set(V,z);const g=O.conflicts.filter(s=>s.excluded);if(g.length>0){const s=a.createElement("div");Object.assign(s.style,{color:R.label,fontSize:_.body,padding:`0 ${ee} ${D.sm}`});const $=g.slice(0,6).map(S=>S.testNumber).join(", "),f=g.length>6?`, and ${g.length-6} more`:"",i=g.length===1?"it":"them";s.textContent=`${g.length} test ${g.length===1?"number is":"numbers are"} hidden (${$}${f}) \u2014 the wafers in view describe ${i} differently, so their values cannot be pooled. `+(l&&l.length>0?`Pick one ${p??"group"} under "Show:" to analyse ${i}.`:"Load one test program at a time to analyse them."),s.dataset.wmapWithheldTests=String(g.length),te.appendChild(s)}te.appendChild(z.card)}return{el:H,render:Q,destroy:()=>{a.removeEventListener("keydown",je),Ge(),ae.flush(),H.remove()},setAxisPrefs:e=>Be(e,null,!0),showWorthCard:e=>{V!=="overview"&&(V="overview",Q({keepSections:!0}));const t=[...te.querySelectorAll("[data-wmap-worth-key]")].find(u=>u.dataset.wmapWorthKey===e);if(!t)return!1;const n=a.defaultView,o=()=>t.scrollIntoView({block:"center"});return n?.requestAnimationFrame?n.requestAnimationFrame(()=>n.requestAnimationFrame(o)):o(),t.style.outline=`2px solid ${R.iconActive}`,t.style.outlineOffset="2px",setTimeout(()=>{t.style.outline="",t.style.outlineOffset=""},1600),!0}}}
1
+ import{MEAN_WAFER_YIELD_LABEL as Zt}from"../stats/presentation.js";import{buildFacetTable as en,facetValueOf as ze,FACET_NONE_VALUE as tn,DEFAULT_FACET_CURATION as nn}from"../stats/facets.js";import{mergeTestDefs as He}from"../stats/mergeTestDefs.js";import{isParametricTest as Ce}from"../renderer/buildWaferMap.js";import{dieFailsTest as sn,hasJudgeableTests as an,testsForPassKind as rn,buildTestPassRateData as ot}from"../stats/testPassRate.js";import{fmt as lt}from"../renderer/fmt.js";import{testLabel as dt}from"../renderer/testLabel.js";import{waferDisplayLabel as on,waferIdentityLabel as ln}from"../core/waferLabel.js";import{waferPopulation as dn}from"./chartPopulation.js";import{openDrilldownMenu as Ye}from"./drilldown.js";import{plotStoreFor as cn}from"./plotStore.js";import{createPageFilter as un}from"./pageFilter.js";import{bandButton as fn}from"./filterButton.js";import{itemPassBins as pn,passBinsLabel as ct}from"../core/passBins.js";import{describeWaferPopulation as hn,populationStat as mn}from"../stats/population.js";import{LEADING as Ve,ALPHA as bn,SPACE as O,EDGE_GUTTER as _e,FONT as G,CLR as M,RADIUS as gn,SHADOW as yn,controlStyle as ut,wireControlHover as Be,wireTooltip as ke}from"./toolbar.js";import{ICONS as wn}from"./icons.js";import{renderCapabilityPanel as xn}from"./charts/capability.js";import{renderGroupComparisonPanel as vn}from"./charts/groupComparison.js";import{renderCommonalityPanel as Sn}from"./charts/commonality.js";import{renderPatCard as Cn}from"./charts/patCard.js";import{renderDifferenceMapPanel as Bn}from"./differenceMapPanel.js";import{renderCorrelationPanel as kn}from"./charts/correlation.js";import{cardFrameStyle as $n,pairCards as En,makeChartGridWrap as $e,makeLabeledSelect as ft,makeLinkedGroupSelect as Tn,makeLinkedTestSelect as pt,makeWaferSelect as ht,makeTestSelect as mt,isExpandedCard as In,makeLinkedAxisPrefs as bt,makeToggle as Ge,limitLines as Ee,limitExtent as gt,shouldIncludeLimitsByDefault as yt,hasBothLimitKinds as wt}from"./charts/chartShell.js";import{maxOf as xt,minOf as vt}from"../core/utils.js";import{buildYieldData as St,buildYieldDataCombined as On}from"../stats/yield.js";import{buildLotTestSectionSteps as An,buildLotFunctionalSection as Ln,buildMetadataStripBox as Dn}from"./summaryPanel.js";import{runChunked as Pn}from"./chunked.js";import{buildRegionYieldData as qe,buildRingRegions as Ct,buildQuadrantRegions as Bt,buildReticlePositionRegions as Wn,diesInRegion as Rn}from"../stats/regions.js";import{renderDataSection as Nn}from"./dataTab.js";import{sourceFromDies as Mn,toPlotItems as re}from"./plotItems.js";import{rankTestsByWaferSpread as Fn}from"../stats/testsByWafer.js";import{isYieldEligibleDie as jn}from"../core/dies.js";import{renderPlotCard as zn}from"./plotCard.js";import{orderFieldValues as Hn,axisValues as kt}from"../stats/plotData.js";import{buildSynthesis as Yn,groupColouredChart as Vn,synthesisKey as _n}from"../stats/synthesis.js";import{commonPassBins as Gn}from"../core/passBins.js";import{renderRegionYieldDiagram as Ke}from"./charts/regionYieldDiagram.js";const qn=12,Kn=[{key:"overview",label:"Overview"},{key:"distributions",label:"Distributions"},{key:"correlation",label:"Correlation"}],Xn={key:"data",label:"Data"},Un={key:"plot",label:"My plots"},Qn={overview:"Yield, bins and what stands out",distributions:"How each test\u2019s values spread",correlation:"How tests move together",data:"The same scope as tables, with CSV exports",plot:"Plots you have built and saved"};export function createInsightsTab(T){const{getItems:$t,getLotStats:Xe,getBinColors:ie,getRingCount:Q,onSaveImage:W,onSaveText:J,openWafer:oe,focusTest:Te,locateDie:me}=T,ye={...nn,...T.attributes},Et=T.showMetadataStrip??!0,le=T.contentInset??_e,a=T.ownerDocument??document,Y=a.createElement("div");Object.assign(Y.style,{display:"none",flexDirection:"column",width:"100%",paddingTop:"0"});const Tt=_e,ce=a.createElement("div");Object.assign(ce.style,{paddingLeft:Tt});const te=a.createElement("div");Object.assign(te.style,{display:"flex",gap:O.xs,alignItems:"center",background:M.menuBg,border:`1px solid ${M.menuBorder}`,borderRadius:gn.container,boxShadow:yn.panel,padding:`0 ${O.lg}`,margin:"0"}),te.setAttribute("role","tablist");const Ie=a.createElement("div");Object.assign(Ie.style,{position:"sticky",top:"var(--wmap-sticky-top, 0px)",zIndex:"1",background:M.menuBg,paddingLeft:le,paddingRight:le,paddingBottom:O.lg}),Ie.appendChild(te),te.addEventListener("keydown",e=>{if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=Array.from(te.querySelectorAll('[role="tab"]')),s=t.indexOf(a.activeElement);if(s===-1)return;e.preventDefault();const o=t[(s+(e.key==="ArrowRight"?1:-1)+t.length)%t.length];o.focus(),o.click()});const se=a.createElement("div");Object.assign(se.style,{display:"flex",flexDirection:"column",gap:O.lg,marginTop:"0",isolation:"isolate",paddingLeft:le,paddingRight:le});const we=T.pageFilter??un({doc:a,initial:T.filter,onChange:T.onFilterChange,attributes:T.attributes,getRingCount:T.getRingCount}),Ue=we.createBand(()=>Me(),{marginLeft:le,marginRight:le,marginBottom:O.lg}),It=Ue.el;let de,Oe=null;const Ot=()=>{let e=0;for(const t of Array.from(Y.querySelectorAll("[data-wmap-chart-grid]")))t.offsetParent!==null&&(e=Math.max(e,Array.from(t.children).filter(s=>s.offsetParent!==null).length));return e},xe=()=>{if(de===void 0){Y.style.removeProperty("--wmap-insights-cols"),Y.style.removeProperty("--wmap-insights-min");return}const e=Ot(),t=e>0?Math.min(de,e):de;Y.style.getPropertyValue("--wmap-insights-cols")!==String(t)&&Y.style.setProperty("--wmap-insights-cols",String(t)),Y.style.setProperty("--wmap-insights-min","0px")},Qe=e=>{de=e,xe(),Oe&&(Oe.value=e===void 0?"auto":String(e))},Je=a.defaultView?.MutationObserver;let Ae=0;const Ze=Je?new Je(()=>{if(Ae||de===void 0)return;const e=a.defaultView;if(!e){xe();return}Ae=e.requestAnimationFrame(()=>{Ae=0,xe()})}):void 0;Ze?.observe(se,{childList:!0,subtree:!0});const et=e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||!/^[0-5]$/.test(e.key)||!Y.isConnected||Y.style.display==="none"||a.querySelector('[data-wmap-panels-hover], [role="dialog"]'))return;const t=e.target;typeof t?.closest=="function"&&t.closest('input, textarea, select, [contenteditable="true"], [role="menu"], [role="dialog"]')||(e.preventDefault(),Qe(e.key==="0"?void 0:Number(e.key)))};a.addEventListener("keydown",et),Y.appendChild(ce),Y.appendChild(Ie),Y.appendChild(It),Y.appendChild(se);const At=[...Kn,Xn,Un],ue=T.plotStore??cn(T),Z=(e,t)=>{import("./plotModal.js").then(({openPlotEditor:s})=>s({doc:a,anchor:Y,store:ue,plot:e,draft:!0,items:[...t.items],ctx:t.ctx,title:e.title?`New plot from \u201C${e.title}\u201D`:"New plot",chart:{onSaveImage:W,binColors:ie()}}))};let X=T.defaultView==="sweeps"?"plot":T.defaultView??"overview",N,Le=!1;we.subscribe(()=>ne());let tt="statistics",nt="wide",q=null,st=null,De=[],V=null,Pe=T.initialAxisPrefs??{includeLimits:void 0,clipOutliers:!1,limits:"both"};const ee=e=>zn({...e,chart:{onSaveText:J,...e.chart}}),ae=(e,t,s)=>({limits:t.limits??"both",axes:{[e]:{...t.includeLimits!==void 0?{includeLimits:t.includeLimits}:{},...t.clipOutliers?{clip:!0}:{},...s?{scale:"log"}:{}}}}),We=new Map,Re=(e,t,s=!1)=>{Pe=e;for(const o of We.values())for(const l of o)l!==t&&l.setAxisPrefs(e);s||T.onAxisPrefsChange?.(e)},Ne=e=>{V!==e&&(V=e,ne())};let fe=new Map;function at(){for(const e of fe.values())e.destroy();fe=new Map}function rt(e,t,s){oe?.(e,t,s)}function ve(e){return(t,s,o)=>{const l=e.find(f=>f.waferIndex===t);if(!l)return;o.preventDefault();const v=dn(l.dies,{waferLabel:l.identity,testDefs:l.testDefs,activeTest:s??q??void 0,waferIndex:t,wafer:l.wafer,passBins:l.passBins,ringCount:Q()});Ye({x:o.clientX,y:o.clientY},o.target,v,{plots:ue,getBinColors:ie,onSaveImage:W,onSaveText:J,onLocateDie:me})}}function Lt(e,t,s,o,l){pe({x:e.clientX,y:e.clientY},e.target,t,s,o,l)}function pe(e,t,s,o,l,v){const f=Mn(s.map(d=>({label:d.identity??d.label,dies:d.dies,waferIndex:d.waferIndex,wafer:d.wafer,passBins:d.passBins,ringCount:Q()})),o,l,He(s).defs,v);f&&Ye(e,t,f,{plots:ue,getBinColors:ie,onSaveImage:W,onSaveText:J,onLocateDie:me})}function it(e){return oe?{open:(t,s)=>rt(t,`Wafer ${e.find(o=>o.waferIndex===t)?.label??t}`,s)}:Te&&e.length===1?{open:(t,s)=>Te(s),label:"show this test on the map"}:null}function Me(){return $t().map((e,t)=>e==null?null:{metadata:e.wafer.metadata??void 0,dies:e.dies,wafer:e.wafer,label:on(e,t),identity:ln(e),waferIndex:t,passBins:pn(e),statsSummary:e.statsSummary,testDefs:e.testDefs,source:e}).filter(e=>e!=null)}function Dt(e,t){Object.assign(e.style,{background:"none",border:"none",borderBottom:t?`2px solid ${M.iconActive}`:"2px solid transparent",color:t?M.iconActive:M.label,fontWeight:t?"700":"500",fontSize:G.body,padding:`${O.sm} ${_e} ${O.md}`,cursor:"pointer"})}function Pt(e,t){const s=a.createElement("button");s.type="button",s.textContent=t;const o=e===X;Dt(s,o),s.dataset.on=o?"true":"false",Be(s,"bare"),s.dataset.wmapInsightsTab=e;const l=Qn[e];return l&&ke(s,l),s.setAttribute("role","tab"),s.setAttribute("aria-selected",o?"true":"false"),s.tabIndex=o?0:-1,s.addEventListener("click",()=>{X!==e&&(X=e,ne({keepSections:!0}))}),s}function Wt(e,t,s,o=!0){const l=$e(a),v=ie(),f=s??"group",d=ct(e.map(r=>r.passBins)),b=re(e.map(r=>({label:r.identity??r.label.replace(/\s*·\s*\d+(\.\d+)?%$/,""),dies:r.dies,waferIndex:r.waferIndex,wafer:r.wafer,passBins:r.passBins,ringCount:Q()}))),c=He(e).defs,p=t?N:void 0,u={testDefs:c,groupBy:p,curation:T.attributes},g=(r,x,S=!1)=>({id:"card-yield",title:t?`Yield by ${f} (pass: ${d})`:`Yield by wafer (pass: ${d})`,chart:"bar",fields:{x:S?[{slot:"groupBy"},{builtin:"wafer"}]:{slot:"groupBy"},y:{builtin:"yield"},color:t?{follow:"groupBy"}:{none:!0}},...S?{}:{valueLabels:!0},...r&&!S?{sort:"value"}:{},...x>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}}),A=t?t.length:e.length;let k=null,$=!1;o&&(k=ee({doc:a,editAsPlot:Z,items:b,ctx:u,spec:{choices:[{current:"natural",options:r=>[["value","Sort: yield"],["natural",t&&!r?`Sort: ${f}`:"Sort: wafer"],...t&&!r?[["nested",`${f}, then wafer`,`Each ${f} with its wafers inside it`]]:[]]}],build:([r])=>($=r==="nested",g(r==="value",A,$))},drill:t&&p?r=>{if($)return null;const x=ze(b[r[0]?.item]?.metadata,p,T.attributes);if(x===void 0)return null;const S=t.find(P=>P.key===x)?.items.length??0;return P=>({...P,title:`Yield by wafer \u2014 ${f}: ${x} (pass: ${d})`,fields:{...P.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:p},values:[x]}]},axes:S>=3?{y:{references:[{stat:"median"}]}}:void 0})}:void 0,drillLabel:()=>$?void 0:"see its wafers",chart:{onSaveImage:W,onOpenWafer:oe?r=>rt(b[r].waferIndex??r,`Wafer ${b[r].label}`):void 0,onWaferMenu:ve(e)}}),k.card.style.minHeight="360px",l.appendChild(k.card));const j={current:"hbin",options:[["hbin","Hard bins","The physical sort result: where the part goes on the handler"],["sbin","Soft bins","The test program\u2019s failure category: many soft bins can map to one hard bin"]]},_={current:"share",options:[["count","Counts"],["share",`Share of ${f}`,`Each ${f}\u2019s dies in a bin as a share of all its dies, so ${f} values of different sizes compare`],["mix","Bin mix",`Each ${f} as one bar split into its bins, as shares of its own dies`]]},R=15,i=(r,x)=>t&&x==="mix"?{id:"card-bin-pareto",title:`${r==="sbin"?"Soft":"Hard"} bin mix by ${f}`,chart:"bar",stack:"percent",fields:{x:{slot:"groupBy"},color:{builtin:r==="sbin"?"sbin":"hbin"}}}:{id:"card-bin-pareto",title:`${r==="sbin"?"Soft":"Hard"} bin pareto`,chart:"bar",sort:"value",fields:{x:{builtin:r==="sbin"?"sbin":"hbin"},color:t?{follow:"groupBy"}:{builtin:r==="sbin"?"sbin":"hbin"}},...r==="sbin"?{top:R}:{},...t?x==="share"?{barNorm:"percent"}:{}:{cumulative:!0}},w=ee({doc:a,editAsPlot:Z,items:b,ctx:u,spec:t?{choices:[j,_],build:([r,x])=>i(r,x)}:{choices:[j],build:([r])=>i(r,void 0)},chart:{onSaveImage:W,binColors:v,onSelectPoints:(r,x,S,P)=>{const m=w.current().fields,E=m.x,L=m.color,F=B=>!!B&&!Array.isArray(B)&&typeof B=="object"&&"builtin"in B&&B.builtin==="sbin",D=F(E)||F(L)?"sbin":"hbin",n=new Set(r.map(B=>D==="hbin"?B.die?.hbin:B.die?.sbin));if(n.size!==1)return;const h=[...n][0];if(E&&!Array.isArray(E)&&"slot"in E){const B=new Set(r.map(I=>I.die).filter(I=>!!I)),K=new Set(r.map(I=>b[I.item]?.waferIndex));pe(x,S,e.filter(I=>K.has(I.waferIndex)),`in ${D==="hbin"?"hard":"soft"} bin ${h}`,I=>B.has(I));return}const y=t?P?.group:void 0,C=y!==void 0?t?.find(B=>B.key===y)?.items??[]:e;pe(x,S,C,`in ${D==="hbin"?"hard":"soft"} bin ${h}${y!==void 0?` of ${y}`:""}`,B=>jn(B)&&(D==="hbin"?B.hbin:B.sbin)===h)}}});return w.card.style.minHeight="360px",l.appendChild(w.card),{card:l,destroy:()=>{k?.destroy(),w.destroy()}}}function Fe(){const e=a.createElement("div");return e.dataset.wmapChartCard="1",Object.assign(e.style,{...$n(),display:"flex",flexDirection:"column",gap:O.lg,minWidth:"0"}),e}function Rt(e){if(ce.innerHTML="",ce.style.marginBottom="0",!Et)return;const t=Dn(e.map(s=>({metadata:s.metadata})),void 0,{facetableOnly:!1});t&&(t.style.marginBottom="0",ce.appendChild(t),ce.style.marginBottom=O.xs)}function Nt(e,t,s,o,l){if(!e.length)return{elements:[],destroy:()=>{}};const v=e.map(w=>w.wafer),f=e.map(w=>w.dies),d=Q(),b=[],c=[],p=o??[{key:"",items:e}],u=e.flatMap(w=>w.dies),g=["spec","testFlag","functional"].filter(w=>an(s,w,u));if(g.length){const w={spec:{label:"Test limits",hint:"Judged from each die\u2019s measured value against the test\u2019s limits",title:"Parametric pass rate \xB7 test limits"},testFlag:{label:"Tester flag",hint:"The pass or fail the tester recorded for each die",title:"Parametric pass rate \xB7 tester flag"},functional:{label:"Functional",hint:"Tests that only pass or fail and have no measured value",title:"Functional test pass rate"}},r=!!o,x=re(e.map(n=>({label:n.identity??n.label,dies:n.dies,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:d}))),S=25,P=n=>rn(s,n).map(h=>h.testNumber),m=n=>ot(p.map(h=>({key:h.key,items:h.items.map(y=>({dies:y.dies}))})),s,n).rows.map(h=>h.testNumber),E=n=>n==="testFlag"?{judge:"flag"}:{},L=(n,h="bars",y="worst")=>r&&h==="grid"?{id:`card-pass-rate-${n}`,title:w[n].title,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},y:{tests:m(n).slice(0,S),passRate:!0,...E(n)}}}:{id:`card-pass-rate-${n}`,title:w[n].title,chart:"bar",orientation:"horizontal",sort:"ascending",...P(n).length>S&&y==="worst"?{top:S}:{},fields:{x:{builtin:"test"},y:{tests:P(n),passRate:!0,...E(n)},color:r?{follow:"groupBy"}:{none:!0}},...r?{}:{valueLabels:!0},axes:{y:{min:0,max:100}}},F=n=>n.id.slice(15),D=ee({doc:a,editAsPlot:Z,items:x,ctx:{testDefs:s,groupBy:r?N:void 0,curation:T.attributes},spec:(()=>{const n=g.some(y=>P(y).length>S),h=[];return g.length>1&&h.push({current:g[0],options:g.map(y=>[y,w[y].label,w[y].hint])}),r&&h.push({current:"bars",options:[["bars","Bars"],["grid","Grid",`The worst ${S} tests as a grid of test by group`]]}),n&&h.push({current:"worst",options:[["worst",`Worst ${S}`],["all","All tests"]]}),h.length?{choices:h,build:y=>{let C=0;const B=g.length>1?y[C++]:g[0],K=r?y[C++]:"bars",I=n?y[C++]:"worst";return L(B,K,I)}}:L(g[0])})(),notes:n=>{const h=F(n);if(h==="functional")return[];const y=ot(p.map(C=>({key:C.key,items:C.items.map(B=>({dies:B.dies}))})),s,h).disagreementDies;return y?[`${y.toLocaleString("en-GB")} die${y===1?"":"s"} judged differently by test limits and the tester flag`]:[]},chart:{onSaveImage:W,selectActionLabel:"chart or tabulate the dies that fail its test",onSelectPoints:(n,h,y,C)=>{const B=s.find(U=>U.testNumber===C?.test);if(!B)return;const K=F(D.current()),I=C?.group!==void 0?p.find(U=>U.key===C.group)?.items??e:e;pe(h,y,I,`failing ${dt(B,B.testNumber)}${C?.group!==void 0?` in ${C.group}`:""}`,U=>sn(U,B,K)===!0,Ce(B)?B.testNumber:void 0)}}});D.card.style.minHeight="300px",b.push(D.card),c.push(D.destroy)}const A=w=>(r,x)=>{const S=new Set;for(const P of e)for(const m of Rn(P.dies,P.wafer,d,r.key,w))S.add(m);Lt(x,e,`in ${r.label}`,P=>S.has(P))},k=qe(f,v,d,w=>e[w].passBins,Ct),$=k.length?Ke({title:"Ring yield",mode:"ring",rows:k,onSelectRegion:A(Ct),onSaveImage:W,ownerDocument:a}):void 0;$&&c.push($.destroy);const j=(w,r,x,S)=>{const P=!!o,m=re(e.map(L=>({label:L.identity??L.label,dies:L.dies,waferIndex:L.waferIndex,wafer:L.wafer,passBins:L.passBins,ringCount:d}))),E=ee({doc:a,editAsPlot:Z,items:m,ctx:{testDefs:s,groupBy:P?N:void 0,curation:T.attributes},spec:{id:w,title:`${x} yield by ${P?l??"group":"wafer"}`,chart:"heatmap",fields:{x:{slot:"groupBy"},rows:{builtin:r},y:{builtin:"yield"}}},chart:{onSaveImage:W}});E.card.style.minHeight="300px",b.push(S?En([{label:"Heatmap",card:E.card},{label:"Diagram",card:S.card}],a):E.card),c.push(E.destroy)};k.length&&e.length>=2?j("card-ring-wafer","ring","Ring",$):$&&b.push($.card);const _=qe(f,v,d,w=>e[w].passBins,Bt);if(_.length){const w=Ke({title:"Quadrant yield",mode:"quadrant",rows:_,onSelectRegion:A(Bt),onSaveImage:W,ownerDocument:a});c.push(w.destroy),e.length>=2?j("card-quadrant-wafer","quadrant","Quadrant",w):b.push(w.card)}const R=v.find(w=>w.reticle!==void 0)?.reticle;if(R){const w=(x,S)=>Wn(x,S.reticle),r=qe(f,v,d,x=>e[x].passBins,w);if(r.length){const x=Ke({title:"Reticle cell yield",mode:"reticleCell",rows:r,grid:{width:Math.max(1,Math.floor(R.width)),height:Math.max(1,Math.floor(R.height))},onSelectRegion:A(w),onSaveImage:W,ownerDocument:a});b.push(x.card),c.push(x.destroy)}}const i=new Set;for(const w of e)for(const r of w.dies)r.siteNum!==void 0&&i.add(r.siteNum);if(i.size>=2){const w=re(e.map(x=>({label:x.identity??x.label,dies:x.dies,waferIndex:x.waferIndex,wafer:x.wafer,passBins:x.passBins,ringCount:d}))),r=ee({doc:a,editAsPlot:Z,items:w,ctx:{testDefs:s,curation:T.attributes},spec:{id:"card-site",title:"Yield by site",chart:"bar",fields:{x:{builtin:"site"},y:{builtin:"yield"},color:{none:!0}},valueLabels:!0,...i.size>=3?{axes:{y:{references:[{stat:"median"}]}}}:{}},chart:{onSaveImage:W}});b.push(r.card),c.push(r.destroy)}if(e.some(w=>w.dies.some(r=>r.retestCount!==void 0))){const w=re(e.map(S=>({label:S.identity??S.label,dies:S.dies,waferIndex:S.waferIndex,wafer:S.wafer,passBins:S.passBins,ringCount:d}))),r=!!o,x=ee({doc:a,editAsPlot:Z,items:w,ctx:{testDefs:s,groupBy:r?N:void 0,curation:T.attributes},spec:{id:"card-reprobed",title:`Re-probed dies by ring and ${r?l??"group":"wafer"}`,chart:"heatmap",aggregate:"mean",fields:{x:{slot:"groupBy"},rows:{builtin:"ring"},y:{builtin:"reprobed"}}},chart:{onSaveImage:W}});x.card.style.minHeight="300px",b.push(x.card),c.push(x.destroy)}return{elements:b,destroy:()=>{for(const w of c)w()}}}function Mt(e,t,s){if(!e.length)return{cards:[],destroy:()=>{}};const o=e.map(u=>u.dies),l=e.flatMap(u=>u.dies),v=e.map(u=>u.statsSummary),f=v.every(u=>u!==void 0)?v:void 0,d=[],b=[];let c=null;if(t.length){const u=Fe();let g=null;const A=Pn(An(l,t,void 0,f,J,o.map(k=>({dies:k})),void 0,"full"),{onDone:k=>{g=k,u.removeAttribute("aria-busy"),k?u.replaceChildren(k):u.remove()}});if(A.done)g&&(c=u);else{const k=a.createElement("div");k.textContent="Computing test statistics\u2026",Object.assign(k.style,{color:M.label,fontSize:G.body}),u.setAttribute("aria-busy","true"),u.appendChild(k),c=u,d.push(()=>A.cancel())}}let p=null;if(s.length){const u=Ln(l,s,f,J);if(u){const g=Fe();g.appendChild(u),p=g}}return c&&b.push(c),p&&b.push(p),{cards:b,destroy:()=>{for(const u of d)u()}}}function Ft(e){const t=ct(e.map(c=>c.passBins)),s=e.length===1,o=e[0],l=Fe();Object.assign(l.style,{flexDirection:"row",flexWrap:"wrap",gap:O.md});const v=c=>{const p=c.lastElementChild;return p&&Object.assign(p.style,{borderRight:"none",paddingRight:"0",marginRight:"0"}),c};function f(c,p,u){const g=a.createElement("div");Object.assign(g.style,{display:"flex",alignItems:"baseline",gap:O.sm,paddingRight:O.xxl,marginRight:O.md,borderRight:`1px solid ${M.menuBorder}`});const A=a.createElement("div");A.textContent=c,Object.assign(A.style,{fontSize:G.heading,fontWeight:"700",color:M.value,lineHeight:Ve.tight});const k=a.createElement("div");if(k.textContent=p,Object.assign(k.style,{fontSize:G.body,color:M.label}),g.append(A,k),u){const $=a.createElement("div");$.textContent=u,Object.assign($.style,{fontSize:G.meta,color:M.label,opacity:bn.muted}),g.appendChild($)}return g}if(s){const c=St([{...o,key:o.waferIndex}])[0]?.percent;return c!==void 0&&l.appendChild(f(`${c.toFixed(1)}%`,`Yield \xB7 pass: ${t}`)),l.appendChild(f(String(o.dies.length),"Total dies")),v(l)}l.appendChild(f(String(e.length),"Wafers"));const d=St(e.map(c=>({...c,key:c.waferIndex}))).map(c=>c.percent).filter(c=>Number.isFinite(c));if(d.length){const c=d.reduce((g,A)=>g+A,0)/d.length,p=On([{key:"all",items:e.map(g=>({...g,key:g.waferIndex}))}])[0]?.percent,u=p!==void 0&&p.toFixed(1)!==c.toFixed(1);l.appendChild(f(`${c.toFixed(1)}%`,`${Zt} \xB7 pass: ${t}`,u?`${p.toFixed(1)}% by dies`:void 0))}const b=e.map(c=>c.statsSummary);if(b.every(c=>c!==void 0)){const c=b.reduce((u,g)=>u+g.stats.analyzedDies,0),p=b.reduce((u,g)=>u+g.stats.excludedDies,0);l.appendChild(f(c.toLocaleString(),"Dies analysed",p?`${p.toLocaleString()} excluded`:void 0))}else l.appendChild(f(e.reduce((c,p)=>c+p.dies.length,0).toLocaleString(),"Total dies"));return v(l)}function jt(e,t,s,o,l){const v=a.createElement("div");Object.assign(v.style,{display:"flex",flexDirection:"column",gap:O.lg});const f=e.length===1&&!o;e.length&&!o&&v.appendChild(Ft(e));const d=Wt(e,o,l,!f),b=Nt(e,t,s,o,l);for(const u of b.elements)d.card.appendChild(u);const c=zt(e,s);if(c&&v.appendChild(c.el),e.length>=4&&De.length){const u=Sn({wafers:e,fields:De,curation:ye,groupedBy:N,onGroupBy:g=>{N=g,V=null,ne()},ownerDocument:a});v.appendChild(u.card)}v.appendChild(d.card);const p=Cn({items:e.map(u=>({...u,ringCount:Q()})),testDefs:s,ownerDocument:a,showMap:T.showPatMap});return p&&v.appendChild(p.card),v.appendChild(Ht()),{card:v,destroy:()=>{d.destroy(),b.destroy(),c?.destroy()}}}function zt(e,t){const s=Xe?.()??(e.length===1?e[0].statsSummary:void 0);if(!s)return null;const o=a.createElement("section");o.dataset.wmapWorthALook="1",Object.assign(o.style,{display:"flex",flexDirection:"column",gap:O.md});const l=a.createElement("h3");l.textContent="Worth a look",Object.assign(l.style,{margin:"0",fontSize:G.heading,fontWeight:"600",color:M.value}),o.appendChild(l);const v=(p,u)=>{const g=a.createElement("p");g.textContent=p,u&&(g.dataset[u]="1"),Object.assign(g.style,{margin:"0",fontSize:G.body,color:M.label,lineHeight:Ve.base}),o.appendChild(g)};if(Le||V!==null)return v("Worth a look describes the whole lot, as What stands out beside the map does. Switch the filter off, or Show all groups, to see it here.","wmapWorthNarrowed"),{el:o,destroy:()=>{}};const f=Yn(s,{passBins:Gn(e.map(p=>p.passBins)),attributes:T.attributes});if(f.items.length===0)return v(f.nothing??"Nothing stands out.","wmapWorthNothing"),{el:o,destroy:()=>{}};const d=$e(a);o.appendChild(d);const b=re(e.map(p=>({label:p.identity??p.label,dies:p.dies,waferIndex:p.waferIndex,wafer:p.wafer,passBins:p.passBins,ringCount:Q()}))),c=[];if(f.items.forEach((p,u)=>{const g=a.createElement("div");g.dataset.wmapWorthWhy="1",g.textContent=`Shown because: ${p.reason}`,p.text!==p.reason&&ke(g,p.text),Object.assign(g.style,{flexBasis:"100%",fontSize:G.body,color:M.text,lineHeight:Ve.base});const A=[g];if(T.showOnMap){const $=a.createElement("button");$.type="button",$.textContent="Show on map",$.dataset.wmapWorthShowOnMap="1",Object.assign($.style,{...ut("outlined"),fontSize:G.body,padding:`0 ${O.md}`}),Be($),ke($,"Leave Insights and show this on the map, as its row in What stands out does"),$.addEventListener("click",()=>T.showOnMap(p.target)),A.push($)}const k=ee({doc:a,items:b,ctx:{testDefs:t,curation:ye,groupBy:N},spec:{id:`worth-${u}`,...Vn(p.chart,!!N)},extras:A,editAsPlot:Z,chart:{onSaveImage:W}});k.card.dataset.wmapWorthKey=_n(p),d.appendChild(k.card),c.push(k.destroy)}),f.also){const p=f.also.items.map(u=>u.brief).join("; ");v(`Also: ${p}${f.also.more?`; and ${f.also.more} more`:""}. Their rows in What stands out show them on the map.`,"wmapWorthAlso")}return{el:o,destroy:()=>c.forEach(p=>p())}}function Ht(){const e=a.createElement("div");Object.assign(e.style,{fontSize:G.body,color:M.label});const t=a.createElement("button");return t.type="button",t.textContent="Data tab",t.dataset.wmapOpenDataTab="1",Object.assign(t.style,{border:"none",background:"none",padding:"0",cursor:"pointer",font:"inherit",color:M.iconActive,textDecoration:"underline"}),Be(t,"bare"),t.addEventListener("click",()=>{X="data",ne({keepSections:!0})}),e.append("Test statistics, every die and every wafer as tables, with CSV export: see the ",t,"."),e}function Yt(e,t,s,o){const l=a.createElement("div");l.style.width="100%";let v,f=!1;return import("./plotTab.js").then(({createPlotSection:d})=>{if(f)return;const b=d({doc:a,store:ue,items:e,testDefs:t,ringCount:Q(),attributes:T.attributes,groupBy:s,groupLabel:o,onSaveImage:W,onSaveText:J,getBinColors:ie,waferMenu:ve(e),openWafer:oe?(c,p,u)=>oe(c,p,u):void 0,focusTest:Te,locateDie:me,pickPlotsFile:T.onPickPlotsFile});l.appendChild(b.card),v=b}),{card:l,destroy:()=>{f=!0,v?.destroy()}}}function Vt(e,t,s,o,l){const v=Le?void 0:Xe?.(),f=()=>{fe.get("data")?.destroy(),fe.delete("data"),ne({keepSections:!0})};return Nn({doc:a,items:e,testDefs:t,allTestDefs:s,groups:o,groupLabelText:l,ringCount:Q(),attributes:T.attributes,yieldByWaferIndex:new Map(v?.lotYieldSeries.map(d=>[d.waferIndex,d.yieldPercent])),onSaveText:J,onLocateDie:me,onOpenWafer:oe?(d,b)=>oe(d,b):void 0,buildStatistics:d=>Mt(d,t,s),view:tt,onViewChange:d=>{tt=d,f()},diesLayout:nt,onDiesLayoutChange:d=>{nt=d}})}function Se(e,t){const s=a.createElement("h3");return s.textContent=e,s.dataset.wmapRowHeading=t,Object.assign(s.style,{gridColumn:"1 / -1",margin:`${O.md} 0 0`,color:M.value,fontSize:G.heading,fontWeight:"600"}),s}function _t(e,t,s,o){const l=$e(a),v=it(e),f=re(e.map(n=>({label:n.identity??n.label,dies:n.dies,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:Q()}))),d=t.filter(n=>n.testNumber!==void 0),b=!!s&&!!N,c=b&&V!==null,p={testDefs:t,groupBy:b?N:void 0,curation:T.attributes},u=d.length>1;let g;const A=[];function k(n){let h=Pe,y=!1,C;const B=pt(d,q??d[0]?.testNumber??null,H=>{C?.refresh(),S(H)},{ownerDocument:a}),K=a.createElement("span");Object.assign(K.style,{display:"inline-flex",flexWrap:"wrap",gap:O.sm,alignItems:"center"});const I={setAxisPrefs:H=>{U.set(H)&&(h=H,C?.refresh())}},U=bt(K,h,H=>{h=H,C?.refresh(),Re(H,I)},a),be=[B.el,K];n.logToggle&&be.push(Ge("Log scale",y,H=>{y=H,C?.refresh()},a,"Draw the value axis on a logarithmic scale")),be.push(...n.extras??[]),C=ee({doc:a,editAsPlot:Z,items:f,ctx:p,...n.card,spec:{choices:n.choices??[],build:H=>n.build(h,y,H)},slots:()=>({test:B.get()??void 0}),extras:be,onResolved:H=>{const he=t.find(Jt=>Jt.testNumber===B.get()),ge=Ee(he,h.limits),je=kt(H,n.valueRole),{lo:Xt,hi:Ut}=gt(ge),Qt=je.length>0&&ge.length>0&&yt(vt(je),xt(je),Xt,Ut);U.sync(h.includeLimits??Qt,Ee(he).length>0,wt(he))},chart:n.chart});const z=C;if(u){const H=()=>{B.el.style.display=In(z.card)?"":"none"};H();const he=a.defaultView?.MutationObserver;if(he){const ge=new he(H);ge.observe(z.card,{attributes:!0,attributeFilter:["data-wmap-expanded"]}),A.push(ge)}}return{card:z.card,setTest:H=>{B.set(H)&&z.refresh()},refresh:()=>z.refresh(),setAxisPrefs:I.setAxisPrefs,destroy:()=>z.destroy()}}const $=v?(n,h)=>v.open(f[n]?.waferIndex??n,h??q??d[0]?.testNumber??0):void 0;let j=!1,_=!1;const R=k({valueRole:"y",logToggle:!0,choices:[{current:b&&!c?"groups":"wafers",options:[...b&&!c?[["groups",`By ${o??"group"}`],["nested",`${o??"Group"}, then wafer`,"Each group with its wafers inside it"]]:[["wafers","By wafer"]],["radius","By radius","A box for each ring, from the centre to the edge: whether the test changes across the wafer"]]}],build:(n,h,[y])=>(j=b&&!c&&y==="nested",_=y==="radius",{id:"card-box",title:_?"Test value by radius":"Test value distribution",chart:"box",orientation:"horizontal",fields:{x:_?{builtin:"ring"}:j?[{slot:"groupBy"},{builtin:"wafer"}]:b&&!c?{slot:"groupBy"}:{builtin:"wafer"},y:{slot:"test"},color:j?{follow:"groupBy"}:{none:!0}},...c?{where:{conditions:[{field:{meta:N},values:[V]}]}}:{},...ae("y",n,h)}),card:{...b&&!c?{drill:n=>{if(j||_)return null;const h=ze(f[n[0]?.item]?.metadata,N,T.attributes);return h===void 0?null:y=>({...y,fields:{...y.fields,x:{builtin:"wafer"}},where:{conditions:[{field:{meta:N},values:[h]}]}})},drillLabel:()=>j||_?void 0:"see its wafers"}:{},...V!==null?{externalBack:{shown:()=>V!==null,onBack:()=>Ne(null)}}:{}},chart:{onSaveImage:W,onOpenWafer:$,openActionLabel:v?.label,onWaferMenu:ve(e)}});let i=null;const w=b?[]:[ht(f.map(n=>({label:n.label})),null,n=>{i=n,r.refresh()},{ownerDocument:a})],r=k({valueRole:"x",logToggle:!0,extras:w,choices:[{current:"bars",options:[["bars","Histogram"],["cumulative","Cumulative","The share of dies at or below each value, as one curve per colour"]]},...b?[{current:"percent",options:[["percent",`Share of ${o??"group"}`,"Each group\u2019s bars as a share of its own dies, so groups of different sizes compare"],["count","Counts"]]}]:[]],card:V!==null?{externalBack:{shown:()=>V!==null,onBack:()=>Ne(null)}}:{},build:(n,h,[y,C])=>({id:"card-histogram",title:y==="cumulative"?"Cumulative distribution":"Value histogram",chart:y==="cumulative"?"probability":"histogram",fields:{y:{slot:"test"},color:b?{follow:"groupBy"}:{none:!0}},...b&&C!=="count"&&y!=="cumulative"?{histNorm:"percent"}:{},...i!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[f[i].label]}]}}:{},...ae("x",n,h)}),chart:{onSaveImage:W,onSelectPoints:(n,h,y,C)=>{const B=t.find(z=>z.testNumber===(q??d[0]?.testNumber)),K=new Set(n.map(z=>z.die).filter(z=>!!z)),I=new Set(n.map(z=>f[z.item]?.waferIndex)),U=C?.range,be=B&&U?`with ${dt(B,B.testNumber)} from ${lt(U.lo,B.unit,"engineering")} to ${lt(U.hi,B.unit,"engineering")}${C?.group?` in ${C.group}`:""}`:"selected in the histogram";pe(h,y,e.filter(z=>I.has(z.waferIndex)),be,z=>K.has(z),B?.testNumber)}}}),x=k({valueRole:"y",logToggle:!0,choices:e.length>=3?[{current:"trend",options:[["trend","Trend","Each wafer\u2019s mean with a band of one standard deviation"],["control","Control chart","One value per wafer against control limits, with the points that break a Western Electric rule marked"]]}]:[],build:(n,h,[y])=>y==="control"?{id:"card-trend",title:"Wafer-to-wafer control chart",chart:"control",aggregate:"mean",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:b?{follow:"groupBy"}:{none:!0}},...ae("y",n,h)}:{id:"card-trend",title:"Wafer-to-wafer trend",chart:"line",aggregate:"mean",spread:"sd",fields:{x:{builtin:"waferOrder"},y:{slot:"test"},color:{none:!0}},...ae("y",n,h),axes:{...ae("y",n,h).axes,y:{...ae("y",n,h).axes.y,references:[{stat:"mean",label:mn(hn(e.map(C=>C.wafer.metadata)),"mean")}]}}},card:{ctx:p,...e.length<2?{unavailable:"A trend needs at least two wafers"}:{}},chart:{onSaveImage:W,onWaferMenu:ve(e),selectActionLabel:$?"open that wafer":"chart or tabulate its dies",selectRangeLabel:"wafers",onSelectPoints:(n,h,y)=>{const C=new Set(n.map(I=>I.item));if(C.size===1&&$){$([...C][0]);return}const B=new Set(n.map(I=>I.die).filter(I=>!!I)),K=new Set(n.map(I=>f[I.item]?.waferIndex));pe(h,y,e.filter(I=>K.has(I.waferIndex)),"selected in the trend",I=>B.has(I),q??void 0)}}}),S=n=>{q=n,g?.set(n),R.setTest(n),r.setTest(n),x.setTest(n),L.setTest(n),m?.setTest(n),E?.setTest(n)},P=()=>vn({groups:s,testDefs:t,groupLabelText:o,control:st,onControlChange:n=>{st=n;const h=P();m.card.replaceWith(h.card),m=h},selectedTestNumber:q??void 0,onSelectTest:n=>S(n),onSaveText:J,ownerDocument:a});let m=s&&s.length>=2?P():void 0;const E=s&&s.length>=2?Bn({groups:s,testDefs:t,groupLabelText:o,selectedTestNumber:q??void 0,onSaveImage:W,ownerDocument:a}):void 0;We.set("distribution",[R,r,x]);const L=xn({title:"Process capability",items:e,testDefs:t,onSaveImage:W,selectedTestNumber:q??void 0,onSelectTest:n=>S(n),ownerDocument:a}),F=e.length>=2?Fn(e.map(n=>({dies:n.dies})),t.filter(n=>n.testNumber!==void 0&&Ce(n)).map(n=>n.testNumber),qn):[],D=F.length>=2?ee({doc:a,editAsPlot:Z,items:f,ctx:p,spec:{id:"card-tests-wafer",title:`Tests by ${s?o??"group":"wafer"} (z-scores)`,chart:"heatmap",level:"wafer",aggregate:"mean",normalize:"zscore",fields:{x:{slot:"groupBy"},y:{tests:F}}},chart:{onSaveImage:W}}):void 0;if(D&&(D.card.style.minHeight="300px"),D&&(l.append(Se(`Tests across ${s?o??"groups":"wafers"}`,"tests-grid")),l.append(D.card)),(m||E)&&(l.append(Se(`Comparing ${o??"groups"}`,"comparing")),m&&l.append(m.card),E&&l.append(E.card)),u){g=pt(d,q??d[0]?.testNumber??null,B=>S(B),{ownerDocument:a});const n=a.createElement("div");n.dataset.wmapSectionTest="1",Object.assign(n.style,{gridColumn:"1 / -1",display:"flex",alignItems:"center",gap:O.lg,flexWrap:"wrap",marginTop:O.md});const h=Se("Test by test","tests");h.style.margin="0";const y=a.createElement("label");Object.assign(y.style,{display:"inline-flex",alignItems:"center",gap:O.xs,fontSize:G.body,color:M.label});const C=a.createElement("span");C.textContent="Test",y.append(C,g.el),n.append(h,y),l.append(n)}else(m||E)&&l.append(Se("Test by test","tests"));return l.append(L.card,R.card,r.card,x.card),{card:l,destroy:()=>{for(const n of A)n.disconnect();L.destroy(),R.destroy(),r.destroy(),x.destroy(),m?.destroy(),E?.destroy(),D?.destroy()}}}function Gt(e,t,s,o){const l=$e(a),v=it(e),f=re(e.map(m=>({label:m.identity??m.label,dies:m.dies,waferIndex:m.waferIndex,wafer:m.wafer,passBins:m.passBins,ringCount:Q()}))),d=t.filter(m=>m.testNumber!==void 0&&Ce(m));let b=d[0]?.testNumber,c=d[1]?.testNumber??b,p=null,u=Pe;const g=!!s&&!!N,A=(m,E)=>{const L=a.createElement("label");Object.assign(L.style,{display:"inline-flex",alignItems:"center",gap:O.xs,fontSize:G.body,color:M.label});const F=a.createElement("span");return F.textContent=m,L.append(F,E),L},k=mt(d,b??null,m=>{b=m,S.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:a}),$=mt(d,c??null,m=>{c=m,S.refresh()},{maxWidth:"180px",emptyText:"No tests",ownerDocument:a}),j=a.createElement("span");Object.assign(j.style,{display:"inline-flex",flexWrap:"wrap",gap:O.sm,alignItems:"center"});let _=!1,R=!1;const i={setXY:(m,E)=>{b=m,c=E,k.value=String(m),$.value=String(E),S.refresh()},setAxisPrefs:m=>{w.set(m)&&(u=m,S.refresh())},destroy:()=>S.destroy()},w=bt(j,u,m=>{u=m,S.refresh(),Re(m,i)},a),r=m=>{const E=t.find(L=>L.testNumber===m);return E?.name?{test:m??0,name:E.name}:{test:m??0}},x=[A("X:",k),A("Y:",$),j,Ge("Log X",_,m=>{_=m,S.refresh()},a,"Draw the X axis on a logarithmic scale"),Ge("Log Y",R,m=>{R=m,S.refresh()},a,"Draw the Y axis on a logarithmic scale")];!g&&e.length>1&&x.push(ht(f.map(m=>({label:m.label})),null,m=>{p=m,S.refresh()},{ownerDocument:a}));const S=ee({doc:a,editAsPlot:Z,items:f,ctx:{testDefs:t,groupBy:g?N:void 0,curation:T.attributes},extras:x,onResolved:m=>{const E=[b,c].map(F=>t.find(D=>D.testNumber===F)),L=["x","y"].some((F,D)=>{const n=Ee(E[D],u.limits),h=kt(m,F),{lo:y,hi:C}=gt(n);return h.length>0&&n.length>0&&yt(vt(h),xt(h),y,C)});w.sync(u.includeLimits??L,E.some(F=>Ee(F).length>0),E.some(wt))},spec:{choices:[],build:()=>({id:"card-scatter",title:"Test scatter",chart:"scatter",limits:u.limits??"both",axes:{...ae("x",u,_).axes,...ae("y",u,R).axes},fields:{x:r(b),y:r(c),color:g?{follow:"groupBy"}:{builtin:"hbin"}},...g?{fit:"linear"}:{},...p!==null?{where:{conditions:[{field:{builtin:"wafer"},values:[f[p].label]}]}}:{}})},...b===void 0?{unavailable:"No parametric test has values to plot"}:{},chart:{onSaveImage:W,binColors:ie(),onOpenWafer:v?(m,E)=>v.open(f[m]?.waferIndex??m,E??b??0):void 0,openActionLabel:v?.label,onSelectPoints:(m,E,L)=>{const F=new Map;for(const h of m){const y=f[h.item]?.waferIndex;if(y===void 0||!h.die)continue;const C=F.get(y);C?C.push(h.die):F.set(y,[h.die])}const D=[...F].flatMap(([h,y])=>{const C=e.find(B=>B.waferIndex===h);return C?[{label:C.identity??C.label,dies:y,waferIndex:h,wafer:C.wafer,passBins:C.passBins,ringCount:Q()}]:[]});if(D.length===0)return;const n=D.length===1?`selected on ${D[0].label} in the scatter`:`selected in the scatter, across ${D.length} wafers`;Ye(E,L,{items:D,population:n,testDefs:t,activeTest:b},{plots:ue,getBinColors:ie,onSaveImage:W,onSaveText:J,onLocateDie:me})}}});We.set("correlation",[i]);const P=kn({title:"Test correlation matrix",items:e,testDefs:t,onSaveImage:W,onSaveText:J,...g&&s&&s.length>=2?{groups:s,groupLabelText:o}:{},onSelectPair:(m,E)=>i.setXY(m,E),ownerDocument:a});return l.append(P.card,S.card),{card:l,destroy:()=>{P.destroy(),i.destroy()}}}const qt=(e,t,s,o)=>fn(a,e,t,s,o),Kt=()=>we.openEditor(Y,Me());function ne(e){e?.keepSections||at(),se.innerHTML="",te.innerHTML="";for(const i of At)te.appendChild(Pt(i.key,i.label));const t=Me(),s=we.keep(t),o=s.items;Le=s.narrowing,Ue.refresh(s.result,t),Rt(o);const l=en(o,{facetableOnly:!0,curation:ye}).filter(i=>i.splittable);De=l.map(i=>({key:i.key,label:i.label}));const v=a.createElement("div");Object.assign(v.style,{display:"flex",gap:O.md,alignItems:"center",marginLeft:O.xxl,paddingBottom:O.xs}),T.showFilterButton!==!1&&v.appendChild(qt("Filter\u2026","wmapInsightsFilterOpen","Show only the wafers and dies that meet conditions you set, on the maps, the gallery and every Insights tab",()=>Kt()));let f;l.length>0?(v.appendChild(ft("Group by:",[{value:"",label:"None"},...l.map(i=>({value:i.key,label:`${i.label} (${i.values.length})`}))],N??"",i=>{N=i||void 0,V=null,ne()},{hook:"group-by",ownerDocument:a,hint:"Split every chart by a wafer attribute, such as lot or tester"})),f=l.find(i=>i.key===N)?.label):N=void 0;let d;if(N){const i=new Map,w=[];for(const r of o){const x=ze(r.metadata,N,ye)??tn;i.has(x)||(i.set(x,[]),w.push(x)),i.get(x).push(r)}d=Hn(w).map(r=>({key:r,items:i.get(r)}))}V!==null&&!d?.some(i=>i.key===V)&&(V=null),d&&d.length>0&&v.appendChild(Tn(d.map(i=>i.key),"Show:",V,i=>Ne(i),{ownerDocument:a,hint:"Show every group, or analyse just one"}).el);const b=ft("Columns:",[{value:"auto",label:"Auto (0)"},...[1,2,3,4,5].map(i=>({value:String(i),label:`${i} (${i})`}))],de===void 0?"auto":String(de),i=>Qe(i==="auto"?void 0:Number(i)),{hook:"insights-columns",maxWidth:"90px",ownerDocument:a,hint:"The most cards that sit side by side (a tab with fewer cards uses fewer); the keys 1 to 5 set it and 0 returns to Auto"});Oe=b.querySelector("button"),v.appendChild(b);let c=null;if(T.onOpenGuide){const i=a.createElement("button");i.type="button",i.innerHTML=wn.help,i.setAttribute("aria-label","User guide"),Object.assign(i.style,{...ut("bare"),display:"inline-flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",flexShrink:"0"}),Be(i,"bare"),ke(i,"User guide"),i.addEventListener("click",()=>T.onOpenGuide()),Object.assign(i.style,{marginLeft:"auto"}),c=i}te.appendChild(v),c&&te.appendChild(c);const p=V!==null?d?.find(i=>i.key===V):void 0,u=p?.items??o,g=p?void 0:d,A=He(u),k=A.defs,$=k.filter(Ce);if(q!==null&&!$.some(i=>i.testNumber===q)&&(q=null),o.length===0){const i=a.createElement("div");i.dataset.wmapInsightsFilterEmpty="1",i.textContent="The filter keeps no wafer and no die. Edit the filter or switch it off to see the data.",Object.assign(i.style,{color:M.label,fontSize:G.body,padding:O.xl}),se.appendChild(i);return}const j=e?.keepSections?fe.get(X):void 0,_=j??(X==="overview"?jt(u,$,k,g,f):X==="distributions"?_t(u,$,g,f):X==="data"?Vt(u,$,k,g,f):X==="plot"?Yt(u,k,p?void 0:N,p?void 0:f):Gt(u,$,g,f));j||fe.set(X,_);const R=A.conflicts.filter(i=>i.excluded);if(R.length>0){const i=a.createElement("div");Object.assign(i.style,{color:M.label,fontSize:G.body,padding:`0 ${le} ${O.sm}`});const w=R.slice(0,6).map(S=>S.testNumber).join(", "),r=R.length>6?`, and ${R.length-6} more`:"",x=R.length===1?"it":"them";i.textContent=`${R.length} test ${R.length===1?"number is":"numbers are"} hidden (${w}${r}) \u2014 the wafers in view describe ${x} differently, so their values cannot be pooled. `+(d&&d.length>0?`Pick one ${f??"group"} under "Show:" to analyse ${x}.`:"Load one test program at a time to analyse them."),i.dataset.wmapWithheldTests=String(R.length),se.appendChild(i)}se.appendChild(_.card),xe()}return{el:Y,render:ne,destroy:()=>{a.removeEventListener("keydown",et),Ze?.disconnect(),at(),ue.flush(),Y.remove()},setAxisPrefs:e=>Re(e,null,!0),showWorthCard:e=>{X!=="overview"&&(X="overview",ne({keepSections:!0}));const t=[...se.querySelectorAll("[data-wmap-worth-key]")].find(l=>l.dataset.wmapWorthKey===e);if(!t)return!1;const s=a.defaultView,o=()=>t.scrollIntoView({block:"center"});return s?.requestAnimationFrame?s.requestAnimationFrame(()=>s.requestAnimationFrame(o)):o(),t.style.outline=`2px solid ${M.iconActive}`,t.style.outlineOffset="2px",setTimeout(()=>{t.style.outline="",t.style.outlineOffset=""},1600),!0}}}
@@ -1,2 +1,2 @@
1
- import{mergeTestDefs as I}from"../stats/mergeTestDefs.js";import{DEFAULT_FACET_CURATION as T}from"../stats/facets.js";import{conditionText as k}from"../stats/plotData.js";import{readFilter as A}from"../stats/plotSpec.js";import{addSavedFilters as B,readSavedFilters as L,readFiltersFile as J,writeFiltersFile as W}from"../stats/filterFile.js";import{newFilterId as R}from"../stats/plotId.js";import{applyConditions as $,fieldCatalogue as P,fieldExtent as G,fieldValues as z}from"../stats/plotData.js";import{toPlotItems as U}from"./plotItems.js";import{buildFilterEditor as K,buildFilterStrip as M}from"./filterEditor.js";import{CLR as b,FONT as j,RADIUS as _,SPACE as g,openModal as q,saveTextFile as H,wireTooltip as V}from"./toolbar.js";import{inputStyle as Y}from"./charts/chartShell.js";import{bandButton as O}from"./filterButton.js";export function readFilterOption(n){if(n==null)return;const t=[],l=typeof n=="object"&&!Array.isArray(n)?A(JSON.parse(JSON.stringify(n)),"insights.filter",t):void 0;return l||t.push("insights.filter: needs at least one condition, so no filter is applied"),t.length&&console.warn(`[wafermap] ${t.join("; ")}`),l}const D=n=>JSON.parse(JSON.stringify(n));export function createPageFilter(n){const{doc:t}=n,h={...T,...n.attributes};let l=readFilterOption(n.initial);const y=new Set;let x=(()=>{if(!n.savedFilters)return[];const i=L(n.savedFilters,"insights.savedFilters");return i.warnings.length&&console.warn(`[wafermap] ${i.warnings.join("; ")}`),i.filters})();const E=i=>({items:U(i.map(s=>({label:s.identity??s.label,dies:s.dies,waferIndex:s.waferIndex,wafer:s.wafer,passBins:s.passBins,ringCount:n.getRingCount()}))),ctx:{testDefs:I([...i]).defs,curation:h}}),v=i=>{if(!l||l.off)return;const s=E(i);return $(l.conditions,s.items,s.ctx)},S={get:()=>l,set(i){l=i,n.onChange?.(i?D(i):void 0);for(const s of[...y])s()},subscribe(i){return y.add(i),()=>{y.delete(i)}},saved:()=>x,setSaved(i){x=i.map(s=>JSON.parse(JSON.stringify(s))),n.onSavedFiltersChange?.(x.map(s=>JSON.parse(JSON.stringify(s))))},keep(i){const s=v(i);if(!s||s.issue)return{items:i,result:s,narrowing:!1};const r=s.index.map((p,u)=>{const a=i[p],e=s.items[u].dies;return e.length===a.dies.length?a:{...a,dies:e,statsSummary:void 0}});return{items:r,result:s,narrowing:r.length!==i.length||r.some((p,u)=>p!==i[s.index[u]])}},mark(i){const s=new Set,r=v(i);if(!r||r.issue)return{items:i,hidden:s,result:r,narrowing:!1};const p=new Map(r.index.map((e,c)=>[e,r.items[c].dies]));let u=!1;return{items:i.map((e,c)=>{const o=p.get(c);if(o===void 0&&(s.add(c),u=!0),o&&o.length===e.dies.length)return e;u=!0;const w=o?new Set(o):void 0,d=e.dies.map(m=>w?.has(m)?m:{...m,filteredOut:!0});return{...e,dies:d,statsSummary:void 0}}),hidden:s,result:r,narrowing:u}},createBand(i,s){const r=t.createElement("div");r.dataset.wmapInsightsFilter="1",Object.assign(r.style,{display:"none",...s});const p=(a,e,c,o)=>O(t,a,e,c,o);return{el:r,refresh:(a,e)=>{if(r.replaceChildren(),r.style.display=l?"":"none",!l)return;const c=[p("Edit\u2026","wmapInsightsFilterEdit","Change the conditions",()=>S.openEditor(r,e)),p("Remove","wmapInsightsFilterRemove","Delete the filter: every wafer and die is shown again",()=>S.set(void 0))];if(a?.issue){const d=t.createElement("div");d.dataset.wmapInsightsFilterIssue="1",d.setAttribute("role","status"),Object.assign(d.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:g.md,padding:`${g.xs} ${g.md}`,background:b.warnBg,border:`1px solid ${b.warnBorder}`,borderRadius:_.control,color:b.warnText,fontSize:j.body});const m=t.createElement("span");m.textContent=`The filter cannot be applied to these wafers (${a.issue}), so nothing is filtered.`;const F=t.createElement("span");Object.assign(F.style,{display:"inline-flex",gap:g.sm,marginLeft:"auto"}),F.append(...c),d.append(m,F),r.appendChild(d);return}const o=d=>d.toLocaleString("en-GB"),w=a?`${o(a.wafers.kept)} of ${o(a.wafers.total)} wafer${a.wafers.total===1?"":"s"} \xB7 ${o(a.dies.kept)} of ${o(a.dies.total)} dies`:void 0;r.appendChild(M({doc:t,filter:l,testDefs:I([...e]).defs,attributes:h,label:"Filter",kept:w,actions:c,onToggle:d=>{if(!l)return;const m={...l};d?delete m.off:m.off=!0,S.set(m)}}))}}},openEditor(i,s){const r=E(s);let p=l?D(l):void 0,u;const a=q({title:"Filter",anchor:i,ownerDocument:t,boxSize:{width:"min(92vw, 640px)",height:"min(85vh, 640px)"},maximizable:!1,initialFocus:()=>p?u:d.el.querySelector("[data-wmap-filter-add]")??u,onClose:()=>{}});a.box.dataset.wmapInsightsFilterModal="1";const e=t.createElement("div");Object.assign(e.style,{display:"flex",flexDirection:"column",gap:g.lg,padding:g.xl,color:b.text,fontSize:j.body,overflowY:"auto",flex:"1 1 auto",minHeight:"0"});const c=t.createElement("p");c.style.margin="0",c.textContent="The maps, the gallery and every Insights tab show only the wafers and dies that meet every condition. A condition on a wafer field (split, yield) keeps whole wafers; one on a die field (bin, ring, a test) keeps those dies inside them, and a map draws the others dimmed. The filter is shown above each view for as long as it exists, and can be switched off there without losing it.";const o=t.createElement("div");o.dataset.wmapInsightsFilterPreview="1",o.setAttribute("aria-live","polite"),Object.assign(o.style,{fontWeight:"600",color:b.value});const w=()=>{if(!p||p.off){o.textContent=p?"Off: every wafer and die is shown.":"No conditions: every wafer and die is shown.";return}const f=$(p.conditions,r.items,r.ctx);o.textContent=f.issue?`Cannot be applied: ${f.issue}`:`Keeps ${f.wafers.kept.toLocaleString("en-GB")} of ${f.wafers.total.toLocaleString("en-GB")} wafers \xB7 ${f.dies.kept.toLocaleString("en-GB")} of ${f.dies.total.toLocaleString("en-GB")} dies`},d=K({doc:t,catalogue:P(r.items,r.ctx),filter:p,testDefs:r.ctx.testDefs,attributes:h,switchLabel:"Filter",valuesOf:f=>z(f,r.items,r.ctx),extentOf:f=>G(f,r.items,r.ctx),onChange:f=>{p=f,w()}});w();const m=t.createElement("div");Object.assign(m.style,{display:"flex",justifyContent:"flex-end",gap:g.md,flexWrap:"wrap",flexShrink:"0",padding:`${g.md} ${g.xl}`,borderTop:`1px solid ${b.menuBorder}`});const F=O(t,"Cancel","wmapInsightsFilterCancel","Close without changing the filter",()=>a.close());u=O(t,"Apply","wmapInsightsFilterApply","Filter the maps, the gallery and Insights by these conditions",()=>{a.close(),S.set(p)});for(const f of[F,u])f.style.padding=`${g.sm} ${g.lg}`;m.append(F,u),e.append(c,d.el,o,Q({doc:t,popItems:r,getDraft:()=>p,load:f=>{p={conditions:JSON.parse(JSON.stringify(f.conditions))},d.set(p),w()},saved:()=>S.saved(),setSaved:f=>S.setSaved(f),onSaveText:n.onSaveText,pickFile:n.pickFiltersFile,attributes:h})),a.contentWrap.style.flexDirection="column",a.contentWrap.append(e,m)}};return S}function Q(n){const{doc:t}=n,h=t.createElement("div");h.dataset.wmapSavedFilters="1",Object.assign(h.style,{display:"flex",flexDirection:"column",gap:g.md,borderTop:`1px solid ${b.menuBorder}`,paddingTop:g.lg});const l=t.createElement("div");l.textContent="Saved filters",Object.assign(l.style,{fontWeight:"600",color:b.value});const y=t.createElement("div");y.dataset.wmapSavedFiltersStatus="1",y.setAttribute("role","status"),Object.assign(y.style,{color:b.label,whiteSpace:"pre-line"});const x=(a,e=[])=>{y.textContent=[a,...e].filter(Boolean).join(`
2
- `)},E=t.createElement("div");Object.assign(E.style,{display:"flex",gap:g.sm,flexWrap:"wrap",alignItems:"center"});const v=t.createElement("input");v.type="text",v.placeholder="Name for the conditions above",v.setAttribute("aria-label","Name for the saved filter"),v.dataset.wmapSavedFilterName="1",Object.assign(v.style,{...Y(),flex:"1 1 12em"});const S=O(t,"Save","wmapSavedFilterSave","Keep the conditions above under this name",()=>{const a=n.getDraft(),e=v.value.trim();if(!a||a.conditions.length===0){x("Add a condition first: there is nothing to save.");return}if(!e){x("Give the filter a name."),v.focus();return}const c=JSON.parse(JSON.stringify(a.conditions)),o=n.saved(),w=o.findIndex(d=>d.name===e);n.setSaved(w<0?[...o,{id:R(),name:e,conditions:c}]:o.map((d,m)=>m===w?{...d,conditions:c}:d)),v.value="",x(w<0?`Saved \u201C${e}\u201D.`:`Updated \u201C${e}\u201D.`),s()});E.append(v,S);const i=t.createElement("div");i.dataset.wmapSavedFilterList="1",Object.assign(i.style,{display:"flex",flexDirection:"column",gap:g.xs});function s(){i.replaceChildren();const a=n.saved();if(a.length===0){const e=t.createElement("div");e.textContent="None yet. Set conditions above and save them under a name to use them again.",e.style.color=b.label,i.appendChild(e);return}for(const e of a){const c=t.createElement("div");c.dataset.wmapSavedFilter=e.id,Object.assign(c.style,{display:"flex",gap:g.sm,alignItems:"center",flexWrap:"wrap"});const o=t.createElement("span");Object.assign(o.style,{flex:"1 1 14em",minWidth:"0"});const w=t.createElement("strong");w.textContent=e.name;const d=t.createElement("span");d.style.color=b.label,d.textContent=` \u2014 ${e.conditions.map(C=>k(C,n.popItems.ctx.testDefs,n.attributes)).join(" \xB7 ")}`,o.append(w,d);const m=$(e.conditions,n.popItems.items,n.popItems.ctx).issue;if(m){const C=t.createElement("div");C.dataset.wmapSavedFilterIssue="1",C.textContent=`Cannot be applied to these wafers: ${m}`,Object.assign(C.style,{color:b.warnText,fontSize:j.body}),o.appendChild(C)}const F=O(t,"Load","wmapSavedFilterLoad","Put these conditions in the editor, replacing the ones there",()=>{n.load(e),x(`Loaded \u201C${e.name}\u201D. Press Apply to filter by it.`)}),f=O(t,"Delete","wmapSavedFilterDelete","Remove this saved filter",()=>{const C=n.saved();n.setSaved(C.filter(N=>N.id!==e.id)),x(`Deleted \u201C${e.name}\u201D.`),s()});c.append(o,F,f),i.appendChild(c)}}const r=t.createElement("div");Object.assign(r.style,{display:"flex",gap:g.sm,flexWrap:"wrap"});const p=O(t,"Export\u2026","wmapSavedFilterExport","Save all your saved filters to a file, to share or to keep a copy",()=>{if(n.saved().length===0){x("There are no saved filters to export yet.");return}H(W(n.saved()),"wafermap-filters.json","application/json",n.onSaveText)}),u=O(t,"Import\u2026","wmapSavedFilterImport","Add the filters from a file written by Export\u2026",()=>{(async()=>{const a=await X(t,n.pickFile);if(a===null)return;const e=J(a);if(e.error){x(`Could not import: ${e.error}`);return}const{filters:c,copies:o}=B(n.saved(),e.filters);n.setSaved(c),s(),x(`Imported ${e.filters.length} filter${e.filters.length===1?"":"s"}.`,[...e.warnings,...o.length?[`Kept as copies, since a filter with the same id already existed: ${o.join(", ")}`]:[]])})()});for(const a of[S,p,u])a.style.padding=`${g.sm} ${g.lg}`;return r.append(u,p),V(v,"The name the filter is listed under; saving under a name already used updates that filter"),s(),h.append(l,E,i,r,y),h}async function X(n,t){return t?t():new Promise(h=>{const l=n.createElement("input");l.type="file",l.accept=".json,application/json",l.addEventListener("change",()=>{const y=l.files?.[0];if(!y){h(null);return}y.text().then(h,()=>h(null))}),l.addEventListener("cancel",()=>h(null)),l.click()})}
1
+ import{mergeTestDefs as T}from"../stats/mergeTestDefs.js";import{DEFAULT_FACET_CURATION as P}from"../stats/facets.js";import{conditionText as W}from"../stats/plotData.js";import{readFilter as R}from"../stats/plotSpec.js";import{addSavedFilters as M,readSavedFilters as G,readFiltersFile as z,writeFiltersFile as K}from"../stats/filterFile.js";import{newFilterId as U}from"../stats/plotId.js";import{applyConditions as N,fieldCatalogue as A,fieldExtent as V,fieldValues as B}from"../stats/plotData.js";import{toPlotItems as _}from"./plotItems.js";import{buildFilterEditor as q,buildFilterStrip as H}from"./filterEditor.js";import{CLR as x,FONT as k,RADIUS as Y,SPACE as g,openModal as Q,saveTextFile as X,wireTooltip as Z}from"./toolbar.js";import{inputStyle as ee,makeSegmented as te}from"./charts/chartShell.js";import{buildFilterJsonPanel as ne}from"./filterJson.js";import{bandButton as O}from"./filterButton.js";export function readFilterOption(i){if(i==null)return;const t=[],c=typeof i=="object"&&!Array.isArray(i)?R(JSON.parse(JSON.stringify(i)),"insights.filter",t):void 0;return c||t.push("insights.filter: needs at least one condition, so no filter is applied"),t.length&&console.warn(`[wafermap] ${t.join("; ")}`),c}const L=i=>JSON.parse(JSON.stringify(i));export function createPageFilter(i){const{doc:t}=i,h={...P,...i.attributes};let c=readFilterOption(i.initial);const y=new Set;let b=(()=>{if(!i.savedFilters)return[];const a=G(i.savedFilters,"insights.savedFilters");return a.warnings.length&&console.warn(`[wafermap] ${a.warnings.join("; ")}`),a.filters})();const E=a=>({items:_(a.map(o=>({label:o.identity??o.label,dies:o.dies,waferIndex:o.waferIndex,wafer:o.wafer,passBins:o.passBins,ringCount:i.getRingCount()}))),ctx:{testDefs:T([...a]).defs,curation:h}}),v=a=>{if(!c||c.off)return;const o=E(a);return N(c.conditions,o.items,o.ctx)},F={get:()=>c,set(a){c=a,i.onChange?.(a?L(a):void 0);for(const o of[...y])o()},subscribe(a){return y.add(a),()=>{y.delete(a)}},saved:()=>b,setSaved(a){b=a.map(o=>JSON.parse(JSON.stringify(o))),i.onSavedFiltersChange?.(b.map(o=>JSON.parse(JSON.stringify(o))))},keep(a){const o=v(a);if(!o||o.issue)return{items:a,result:o,narrowing:!1};const s=o.index.map((d,m)=>{const r=a[d],e=o.items[m].dies;return e.length===r.dies.length?r:{...r,dies:e,statsSummary:void 0}});return{items:s,result:o,narrowing:s.length!==a.length||s.some((d,m)=>d!==a[o.index[m]])}},mark(a){const o=new Set,s=v(a);if(!s||s.issue)return{items:a,hidden:o,result:s,narrowing:!1};const d=new Map(s.index.map((e,f)=>[e,s.items[f].dies]));let m=!1;return{items:a.map((e,f)=>{const l=d.get(f);if(l===void 0&&(o.add(f),m=!0),l&&l.length===e.dies.length)return e;m=!0;const w=l?new Set(l):void 0,p=e.dies.map(u=>w?.has(u)?u:{...u,filteredOut:!0});return{...e,dies:p,statsSummary:void 0}}),hidden:o,result:s,narrowing:m}},createBand(a,o){const s=t.createElement("div");s.dataset.wmapInsightsFilter="1",Object.assign(s.style,{display:"none",...o});const d=(r,e,f,l)=>O(t,r,e,f,l);return{el:s,refresh:(r,e)=>{if(s.replaceChildren(),s.style.display=c?"":"none",!c)return;const f=[d("Edit\u2026","wmapInsightsFilterEdit","Change the conditions",()=>F.openEditor(s,e)),d("Remove","wmapInsightsFilterRemove","Delete the filter: every wafer and die is shown again",()=>F.set(void 0))];if(r?.issue){const p=t.createElement("div");p.dataset.wmapInsightsFilterIssue="1",p.setAttribute("role","status"),Object.assign(p.style,{display:"flex",flexWrap:"wrap",alignItems:"center",gap:g.md,padding:`${g.xs} ${g.md}`,background:x.warnBg,border:`1px solid ${x.warnBorder}`,borderRadius:Y.control,color:x.warnText,fontSize:k.body});const u=t.createElement("span");u.textContent=`The filter cannot be applied to these wafers (${r.issue}), so nothing is filtered.`;const C=t.createElement("span");Object.assign(C.style,{display:"inline-flex",gap:g.sm,marginLeft:"auto"}),C.append(...f),p.append(u,C),s.appendChild(p);return}const l=p=>p.toLocaleString("en-GB"),w=r?`${l(r.wafers.kept)} of ${l(r.wafers.total)} wafer${r.wafers.total===1?"":"s"} \xB7 ${l(r.dies.kept)} of ${l(r.dies.total)} dies`:void 0;s.appendChild(H({doc:t,filter:c,testDefs:T([...e]).defs,attributes:h,label:"Filter",kept:w,actions:f,onToggle:p=>{if(!c)return;const u={...c};p?delete u.off:u.off=!0,F.set(u)}}))}}},openEditor(a,o){const s=E(o);let d=c?L(c):void 0,m;const r=Q({title:"Filter",anchor:a,ownerDocument:t,boxSize:{width:"min(92vw, 640px)",height:"min(85vh, 640px)"},maximizable:!1,initialFocus:()=>d?m:p.el.querySelector("[data-wmap-filter-add]")??m,onClose:()=>{}});r.box.dataset.wmapInsightsFilterModal="1";const e=t.createElement("div");Object.assign(e.style,{display:"flex",flexDirection:"column",gap:g.lg,padding:g.xl,color:x.text,fontSize:k.body,overflowY:"auto",flex:"1 1 auto",minHeight:"0"});const f=t.createElement("p");f.style.margin="0",f.textContent="The maps, the gallery and every Insights tab show only the wafers and dies that meet every condition. A condition on a wafer field (split, yield) keeps whole wafers; one on a die field (bin, ring, a test) keeps those dies inside them, and a map draws the others dimmed. The filter is shown above each view for as long as it exists, and can be switched off there without losing it.";const l=t.createElement("div");l.dataset.wmapInsightsFilterPreview="1",l.setAttribute("aria-live","polite"),Object.assign(l.style,{fontWeight:"600",color:x.value});const w=()=>{if(!d||d.off){l.textContent=d?"Off: every wafer and die is shown.":"No conditions: every wafer and die is shown.";return}const n=N(d.conditions,s.items,s.ctx);l.textContent=n.issue?`Cannot be applied: ${n.issue}`:`Keeps ${n.wafers.kept.toLocaleString("en-GB")} of ${n.wafers.total.toLocaleString("en-GB")} wafers \xB7 ${n.dies.kept.toLocaleString("en-GB")} of ${n.dies.total.toLocaleString("en-GB")} dies`},p=q({doc:t,catalogue:A(s.items,s.ctx),filter:d,testDefs:s.ctx.testDefs,attributes:h,switchLabel:"Filter",valuesOf:n=>B(n,s.items,s.ctx),extentOf:n=>V(n,s.items,s.ctx),onChange:n=>{d=n,w()}});w();const u=t.createElement("div");Object.assign(u.style,{display:"flex",justifyContent:"flex-end",gap:g.md,flexWrap:"wrap",flexShrink:"0",padding:`${g.md} ${g.xl}`,borderTop:`1px solid ${x.menuBorder}`});const C=O(t,"Cancel","wmapInsightsFilterCancel","Close without changing the filter",()=>r.close());m=O(t,"Apply","wmapInsightsFilterApply","Filter the maps, the gallery and Insights by these conditions",()=>{r.close(),F.set(d)});for(const n of[C,m])n.style.padding=`${g.sm} ${g.lg}`;u.append(C,m);let $="conditions",S;const I=A(s.items,s.ctx),j=ne({doc:t,filter:d,source:()=>({tests:s.ctx.testDefs?.flatMap(n=>n.testNumber!==void 0?[{number:n.testNumber,name:n.name}]:[]),metaKeys:I.flatMap(n=>"meta"in n.field?[{key:n.field.meta,label:n.name}]:[]),conditionValues:n=>B(n,s.items,s.ctx)}),onChange:n=>{d=n,w()},onProblem:n=>{S=n,m&&(m.disabled=!!n,m.style.opacity=n?"0.5":"")}});j.el.style.display="none";const J=n=>{n!==$&&(n==="conditions"?(S&&j.discard(d),p.set(d)):j.set(d),$=n,p.el.style.display=n==="conditions"?"":"none",j.el.style.display=n==="json"?"":"none",n==="json"&&j.focus())},D=te([["conditions","Conditions","Add and change the conditions one at a time"],["json","JSON","The filter as text: paste one in, edit it, with suggestions from this lot"]],"conditions",n=>J(n==="json"?"json":"conditions"),t);D.dataset.wmapFilterMode="1",e.append(f,D,p.el,j.el,l,ie({doc:t,popItems:s,getDraft:()=>d,load:n=>{d={conditions:JSON.parse(JSON.stringify(n.conditions))},p.set(d),$==="json"&&j.set(d),w()},saved:()=>F.saved(),setSaved:n=>F.setSaved(n),onSaveText:i.onSaveText,pickFile:i.pickFiltersFile,attributes:h})),r.contentWrap.style.flexDirection="column",r.contentWrap.append(e,u)}};return F}function ie(i){const{doc:t}=i,h=t.createElement("div");h.dataset.wmapSavedFilters="1",Object.assign(h.style,{display:"flex",flexDirection:"column",gap:g.md,borderTop:`1px solid ${x.menuBorder}`,paddingTop:g.lg});const c=t.createElement("div");c.textContent="Saved filters",Object.assign(c.style,{fontWeight:"600",color:x.value});const y=t.createElement("div");y.dataset.wmapSavedFiltersStatus="1",y.setAttribute("role","status"),Object.assign(y.style,{color:x.label,whiteSpace:"pre-line"});const b=(r,e=[])=>{y.textContent=[r,...e].filter(Boolean).join(`
2
+ `)},E=t.createElement("div");Object.assign(E.style,{display:"flex",gap:g.sm,flexWrap:"wrap",alignItems:"center"});const v=t.createElement("input");v.type="text",v.placeholder="Name for the conditions above",v.setAttribute("aria-label","Name for the saved filter"),v.dataset.wmapSavedFilterName="1",Object.assign(v.style,{...ee(),flex:"1 1 12em"});const F=O(t,"Save","wmapSavedFilterSave","Keep the conditions above under this name",()=>{const r=i.getDraft(),e=v.value.trim();if(!r||r.conditions.length===0){b("Add a condition first: there is nothing to save.");return}if(!e){b("Give the filter a name."),v.focus();return}const f=JSON.parse(JSON.stringify(r.conditions)),l=i.saved(),w=l.findIndex(p=>p.name===e);i.setSaved(w<0?[...l,{id:U(),name:e,conditions:f}]:l.map((p,u)=>u===w?{...p,conditions:f}:p)),v.value="",b(w<0?`Saved \u201C${e}\u201D.`:`Updated \u201C${e}\u201D.`),o()});E.append(v,F);const a=t.createElement("div");a.dataset.wmapSavedFilterList="1",Object.assign(a.style,{display:"flex",flexDirection:"column",gap:g.xs});function o(){a.replaceChildren();const r=i.saved();if(r.length===0){const e=t.createElement("div");e.textContent="None yet. Set conditions above and save them under a name to use them again.",e.style.color=x.label,a.appendChild(e);return}for(const e of r){const f=t.createElement("div");f.dataset.wmapSavedFilter=e.id,Object.assign(f.style,{display:"flex",gap:g.sm,alignItems:"center",flexWrap:"wrap"});const l=t.createElement("span");Object.assign(l.style,{flex:"1 1 14em",minWidth:"0"});const w=t.createElement("strong");w.textContent=e.name;const p=t.createElement("span");p.style.color=x.label,p.textContent=` \u2014 ${e.conditions.map(S=>W(S,i.popItems.ctx.testDefs,i.attributes)).join(" \xB7 ")}`,l.append(w,p);const u=N(e.conditions,i.popItems.items,i.popItems.ctx).issue;if(u){const S=t.createElement("div");S.dataset.wmapSavedFilterIssue="1",S.textContent=`Cannot be applied to these wafers: ${u}`,Object.assign(S.style,{color:x.warnText,fontSize:k.body}),l.appendChild(S)}const C=O(t,"Load","wmapSavedFilterLoad","Put these conditions in the editor, replacing the ones there",()=>{i.load(e),b(`Loaded \u201C${e.name}\u201D. Press Apply to filter by it.`)}),$=O(t,"Delete","wmapSavedFilterDelete","Remove this saved filter",()=>{const S=i.saved();i.setSaved(S.filter(I=>I.id!==e.id)),b(`Deleted \u201C${e.name}\u201D.`),o()});f.append(l,C,$),a.appendChild(f)}}const s=t.createElement("div");Object.assign(s.style,{display:"flex",gap:g.sm,flexWrap:"wrap"});const d=O(t,"Export\u2026","wmapSavedFilterExport","Save all your saved filters to a file, to share or to keep a copy",()=>{if(i.saved().length===0){b("There are no saved filters to export yet.");return}X(K(i.saved()),"wafermap-filters.json","application/json",i.onSaveText)}),m=O(t,"Import\u2026","wmapSavedFilterImport","Add the filters from a file written by Export\u2026",()=>{(async()=>{const r=await se(t,i.pickFile);if(r===null)return;const e=z(r);if(e.error){b(`Could not import: ${e.error}`);return}const{filters:f,copies:l}=M(i.saved(),e.filters);i.setSaved(f),o(),b(`Imported ${e.filters.length} filter${e.filters.length===1?"":"s"}.`,[...e.warnings,...l.length?[`Kept as copies, since a filter with the same id already existed: ${l.join(", ")}`]:[]])})()});for(const r of[F,d,m])r.style.padding=`${g.sm} ${g.lg}`;return s.append(m,d),Z(v,"The name the filter is listed under; saving under a name already used updates that filter"),o(),h.append(c,E,a,s,y),h}async function se(i,t){return t?t():new Promise(h=>{const c=i.createElement("input");c.type="file",c.accept=".json,application/json",c.addEventListener("change",()=>{const y=c.files?.[0];if(!y){h(null);return}y.text().then(h,()=>h(null))}),c.addEventListener("cancel",()=>h(null)),c.click()})}
@@ -1 +1,10 @@
1
- import{combinationIssue as $e,describeTitleDrift as je,fieldKey as N,fieldsForRole as ge,titleDrift as Pe,withTestSetNames as ye}from"../stats/plotData.js";import{isBinned as $,isField as U,isPassRateSet as We,isTestSet as P,sameField as j,xFieldsOf as Re,PLOT_BINS_DEFAULT as re,PLOT_BINS_MAX as Be,PLOT_BINS_MIN as De,PLOT_X_LEVELS as ce}from"../stats/plotSpec.js";import{formatTestList as Fe,parseTestList as Ie}from"../stats/sweepText.js";import{formatReferences as ze,parseReferences as Me}from"../stats/plotReferences.js";import{CLR as S,FONT as D,RADIUS as we,SPACE as C,controlStyle as K,wireControlHover as Q,wireTooltip as de}from"./toolbar.js";import{inputStyle as Z,makeListSelect as _,makeSegmented as T,makeToggle as Y}from"./charts/chartShell.js";export{Z as inputStyle};import{buildFilterEditor as Ve}from"./filterEditor.js";const ue="\0follow",z="\0none",Xe=[["scatter","Scatter","One point per die or wafer, one value against another"],["histogram","Histogram","How often each value occurs"],["box","Box","Quartiles, with whiskers to the minimum and maximum, for each category"],["bar","Bar","One combined value for each category, or a count"],["line","Line","One combined value at each X, joined"],["probability","Probability","The share of values at or below each value, one curve per colour: on the normal-probability axis a normal distribution is a straight line, and its tails are spread out to read"],["control","Control","One value per wafer in order, against limits from its own wafer-to-wafer variation, with the points that break a Western Electric rule marked"],["heatmap","Heatmap","One cell per row and column, coloured by the value combined there: tests by wafer, bins by wafer, rings by split"],["goal","Goal","Every test with both limits as a point: how far its mean is off centre, and how wide it is, against lines of equal Ppk"]],y="\0auto",fe="\0count",he="\0set",qe=8,_e=[[y,"None","The values as measured, in their own unit"],["limits","To limits","0 at the low limit and 1 at the high one, each test by its own limits (spec limits where it has both)"],["zscore","z-score","Standard deviations from the mean of the values in view, each test on its own"],["robust","Robust z","Like a z-score, from the median and the median absolute deviation, so a few outliers do not set the scale"]],xe={mean:"Mean",median:"Median",min:"Minimum",max:"Maximum",sum:"Sum",count:"Count",yield:"Pooled yield (passing over judged dies)"};export function fieldRow(x,f,G,l){const A=x.createElement("div");Object.assign(A.style,{display:"flex",flexDirection:"column",gap:C.xxs,minWidth:"0"});const k=x.createElement("div");if(k.textContent=f,Object.assign(k.style,{fontSize:D.sub,color:S.label,fontWeight:"600"}),A.append(k,G),l){const M=x.createElement("div");M.textContent=l,Object.assign(M.style,{fontSize:D.sub,color:S.label}),A.appendChild(M)}return A}export function createPlotEditor(x){const{doc:f}=x,G=e=>e.fields?e:{...e,fields:{}};let l=G(x.plot),A="setup";const k=f.createElement("div");k.dataset.wmapPlotEditor="1",Object.assign(k.style,{display:"flex",flexDirection:"column",gap:C.lg,minWidth:"0"});const M=e=>{l=e,x.onChange(e)},b=e=>{const t=JSON.parse(JSON.stringify(l));e(t),M(t)},h=(e,t,i)=>fieldRow(f,e,t,i),H=e=>{if(P(e))return{label:"Tests",level:"die",kind:"numeric",yield:!1};const t=e&&x.catalogue.find(i=>j(i.field,$(e)?e.binned:e));return t?{label:t.name,level:t.level,kind:e&&$(e)?"categorical":t.kind,yield:!(e&&$(e))&&"builtin"in t.field&&t.field.builtin==="yield"}:void 0},E=(e=l)=>[...Re(e.fields?.x)],I=(e,t)=>{t.length===0?delete e.fields.x:e.fields.x=t.length===1?t[0]:t},ve=e=>{const t=e.map(H).filter(i=>!!i);return t.find(i=>i.level==="die")??t[0]};function pe(e,t,i=0){const s=l.fields??{},a=s.color&&!("follow"in s.color)&&!("none"in s.color)?s.color:void 0,o=E();e==="x"&&(o[i]=t.field);const c={x:ve(o),y:H(s.y),color:H(a)};e!=="x"&&(c[e]=H(t.field));const n=l.chart==="scatter"&&c.color?.kind==="numeric"&&!!a&&!("meta"in a);return $e(l.chart,c,{aggregate:l.aggregate,level:l.level,continuousColor:n})?.short}const ee=()=>x.catalogue.flatMap(e=>e.group==="Tests"&&"test"in e.field?[{testNumber:e.field.test,name:e.field.name??""}]:[]),F=()=>P(l.fields?.y)?l.fields.y:void 0,V=e=>!!e&&"builtin"in e&&e.builtin==="test",te=(e,t=0)=>{const i=e==="x"?E()[t]:l.fields?.[e],s=i&&!("follow"in i)&&!("none"in i)?i:void 0,a=e==="x"?E().filter((c,n)=>n!==t):[],o=ge(x.catalogue,l.chart,e).filter(c=>(F()||!V(c.field))&&!a.some(n=>j(n,c.field))).map(c=>{const n=s&&j(c.field,s)?void 0:pe(e,c,t);return{value:N(c.field),label:c.label,group:c.group,...n?{disabled:n}:{}}});return e==="y"?o:[...o,...ie(e,t)]},ie=(e,t=0)=>{if(e==="x"&&!(l.chart==="box"||l.chart==="bar"||l.chart==="heatmap"))return[];if(e==="color"&&l.chart==="scatter")return[];const i=[...e==="x"?E().filter((s,a)=>a!==t):E(),...l.fields?.color&&U(l.fields.color)?[l.fields.color]:[]];return x.catalogue.filter(s=>s.kind==="numeric"&&!s.categorical&&s.group!=="Pass rates"&&!P(s.field)&&!i.some(a=>j(a,s.field))).map(s=>{const a={binned:s.field},o=e==="facet"&&s.level==="die"&&l.level==="wafer"?`${s.name} is per die: this plot has one mark per wafer`:e==="x"||e==="color"?pe(e,{...s,field:a,kind:"categorical",categorical:!0},t):void 0;return{value:N(a),label:`${s.label} in ranges`,group:s.group,...o?{disabled:o}:{}}})},X=e=>{const t=x.catalogue.find(s=>N(s.field)===e)?.field;if(t||!e.startsWith("binned:"))return t;const i=x.catalogue.find(s=>N({binned:s.field})===e)?.field;return i?{binned:i}:void 0};function J(e,t,i,s){if(!t||!$(t))return e;const a=f.createElement("div");Object.assign(a.style,{display:"flex",flexDirection:"column",gap:C.xs,minWidth:"0"});const o=f.createElement("div");Object.assign(o.style,{display:"flex",gap:C.sm,alignItems:"center",minWidth:"0"});const c=R(t.bins??re,"Number of ranges",u=>{const d=u===void 0?re:Math.round(u);b(p=>s(p,g=>{d===re?delete g.bins:g.bins=Math.min(Be,Math.max(De,d))})),O()});c.dataset.wmapPlotBins=i,c.style.width="64px";const n=f.createElement("span");n.textContent="ranges",Object.assign(n.style,{fontSize:D.sub,color:S.label});const r=T([["count","Equal counts","Each range holds about the same number of values (quartiles, deciles)"],["width","Equal widths","Each range spans the same width of values"]],t.by??"count",u=>b(d=>s(d,p=>{u==="count"?delete p.by:p.by="width"})),f);return o.append(c,n,r),a.append(e,o),a}function L(e,t,i={}){const s=i.at??0,a=e==="x"?E()[s]:l.fields.y,o=te(e,s);if(i.optional&&o.unshift({value:fe,label:i.optional,group:"Count"}),e==="y"&&l.chart!=="scatter"&&ee().length>=2&&o.unshift({value:he,label:"Several tests\u2026",group:"Several tests"}),a&&!P(a)&&!o.some(u=>u.value===N(a))){const u=x.catalogue.some(p=>j(p.field,a)),d="test"in a?a.name??`Test ${a.test}`:"meta"in a?a.meta:"builtin"in a?a.builtin:"";o.unshift({value:N(a),label:`${d} (${u?"not usable here":"not in this lot"})`,group:"Saved"})}const n=a?P(a)?he:N(a):i.optional?fe:"",r=_(o,n,u=>{if(u===fe){b(g=>{delete g.fields[e]});return}if(u===he){F()||(Ce(),O());return}const d=X(u)??a;if(!d)return;const p=e==="y"&&!!F();b(g=>{if(e==="x"){const v=E(g);v[s]=d,I(g,v)}else g.fields.y=d;if(!p)return;const w=E(g),m=w.filter(v=>!V(v));m.length!==w.length&&I(g,m.length||!(g.chart==="box"||g.chart==="bar")?m:[{builtin:"wafer"}]),V(g.fields.color)&&delete g.fields.color}),(p||$(d)||a&&$(a))&&O()},{maxWidth:"100%",ownerDocument:f,ariaLabel:t,emptyText:"Choose a field\u2026",searchPlaceholder:"Filter fields\u2026",hook:e==="x"&&s>0?`plot-x-${s+1}`:`plot-${e}`});return r.style.width="100%",r}function Ce(){const e=ee(),t=ye({tests:e.slice(0,qe).map(i=>i.testNumber)},e);b(i=>{i.fields.y=t;const s=E(i);(i.chart==="box"||i.chart==="bar")&&(s.length===0||s.length===1&&j(s[0],{builtin:"wafer"}))&&(i.fields.x={builtin:"test"})})}function Ee(e){const t=f.createElement("div");Object.assign(t.style,{display:"flex",flexDirection:"column",gap:C.xxs});const i=f.createElement("input");i.type="text",i.value=Fe(e.tests),i.placeholder="1010, 1011, 1020..1030",i.setAttribute("aria-label","Tests"),i.dataset.wmapPlotTests="1",Object.assign(i.style,Z(),{width:"100%",fontVariantNumeric:"tabular-nums"});const s=f.createElement("div");return s.setAttribute("role","alert"),Object.assign(s.style,{fontSize:D.sub,color:S.errText}),i.addEventListener("input",()=>{const a=Ie(i.value),o=a.ok?a.value.length===0?"Name at least one test":void 0:a.error;if(s.textContent=o??"",i.setAttribute("aria-invalid",String(!!o)),i.style.borderColor=o?S.errText:S.menuBorder,o||!a.ok)return;const c=a.value;b(n=>{n.fields.y=ye({tests:c},ee())})}),i.addEventListener("keydown",a=>{a.key==="Escape"&&(a.stopPropagation(),i.blur())}),t.append(i,s),t}function me(){const e=E(),t=f.createElement("div");t.dataset.wmapPlotLevels="1",Object.assign(t.style,{display:"flex",flexDirection:"column",gap:C.xs,minWidth:"0"});const i=d=>{const p=e[d];return(p&&x.catalogue.find(g=>j(g.field,p))?.name)??`level ${d+1}`},s=(d,p,g,w,m)=>{const v=f.createElement("button");return v.type="button",v.textContent=d,v.setAttribute("aria-label",p),v.dataset.wmapPlotLevel=g,v.disabled=w,de(v,p),Object.assign(v.style,K("outlined"),{minWidth:"28px",opacity:w?"0.4":"1"}),Q(v),v.addEventListener("click",m),v},a=(...d)=>{O();for(const p of d){const g=k.querySelector(`[data-wmap-plot-level="${p}"]`);if(g&&!g.disabled){g.focus();return}}},o=(d,p)=>{b(w=>{const m=E(w);[m[d],m[d+p]]=[m[d+p],m[d]],I(w,m)});const g=d+p;a(`${p<0?"out":"in"}:${g}`,`${p<0?"in":"out"}:${g}`)},c=Math.max(1,e.length);for(let d=0;d<c;d++){const p=f.createElement("div");Object.assign(p.style,{display:"flex",gap:C.xs,alignItems:"center",minWidth:"0"});const g=J(L("x",c>1?`Categories, level ${d+1} of ${c}`:"Categories",{at:d}),e[d],`x-${d+1}`,(w,m)=>{const v=E(w),W=v[d];W&&$(W)&&(m(W),I(w,v))});Object.assign(g.style,{flex:"1",minWidth:"0"}),p.appendChild(g),e.length>1&&p.append(s("\u2191",`Move ${i(d)} out a level`,`out:${d}`,d===0,()=>o(d,-1)),s("\u2193",`Move ${i(d)} in a level`,`in:${d}`,d===e.length-1,()=>o(d,1)),s("\xD7",`Remove ${i(d)} from the categories`,`remove:${d}`,!1,()=>{b(w=>{const m=E(w);m.splice(d,1),I(w,m)}),a(`remove:${Math.min(d,e.length-2)}`),e.length-1<2&&k.querySelector('[data-wmap-select="plot-x"]')?.focus()})),t.appendChild(p)}const n=e.length<ce&&e.length>0?te("x",e.length).find(d=>!d.disabled):void 0,r=f.createElement("button");r.type="button",r.textContent="+ Add a level",r.dataset.wmapPlotLevelAdd="1",r.disabled=!n;const u=e.length>=ce?`At most ${ce} levels`:n?"Divide each category by another field, nested inside it":"No other field can divide these categories";return de(r,u),Object.assign(r.style,K("outlined"),{alignSelf:"flex-start",opacity:r.disabled?"0.4":"1"}),Q(r),r.addEventListener("click",()=>{const d=n&&X(n.value);d&&(b(p=>{I(p,[...E(p),d])}),O(),k.querySelector(`[data-wmap-select="plot-x-${e.length+1}"]`)?.focus())}),t.appendChild(r),t}const ae={},se={};function Oe(e){b(t=>{t.chart=e;for(const i of["x","y"]){const s=ge(x.catalogue,e,i),a=u=>!!u&&(P(u)?i==="y"&&e!=="scatter":$(u)?i==="x"&&(e==="box"||e==="bar"||e==="heatmap"):s.some(d=>j(d.field,u))),o=u=>Array.isArray(u)?(e==="box"||e==="bar")&&u.every(a):a(u),c=t.fields[i];if(c&&!o(c)&&((Array.isArray(c)||!j(c,se[i]))&&(ae[i]=c),delete t.fields[i]),t.fields[i]||i==="y"&&(e==="bar"||e==="goal"||e==="heatmap"))continue;const n=ae[i];if(o(n)){i==="x"?t.fields.x=n:t.fields.y=n,delete ae[i],delete se[i];continue}const r=i==="x"&&(e==="box"||e==="bar"||e==="heatmap")?{builtin:"wafer"}:i==="x"&&(e==="line"||e==="control")?s.find(u=>u.group==="Wafer")?.field??s[0]?.field:s[0]?.field;r&&!(i==="x"&&(e==="histogram"||e==="probability"||e==="goal"))&&(t.fields[i]=r,se[i]=r)}}),O()}function Se(){const e=!!l.fields.y&&"builtin"in l.fields.y&&l.fields.y.builtin==="yield",t=[{value:y,label:"Automatic"},...["mean","median","min","max","sum","count"].map(s=>({value:s,label:xe[s]}))];e&&t.push({value:"yield",label:xe.yield});const i=_(t,l.aggregate??y,s=>b(a=>{s===y?delete a.aggregate:a.aggregate=s}),{maxWidth:"100%",ownerDocument:f,ariaLabel:"Combine values by",hook:"plot-aggregate"});return i.style.width="100%",i}function Te(){const e=l.fields.color,t=x.followLabel(),i=[{value:ue,label:t?`Follow Group by (${t})`:"Follow Group by (single colour)",group:"Colour"},{value:z,label:"None",group:"Colour"},...te("color")],s=e===void 0||"follow"in e?ue:"none"in e?z:N(e),a=_(i,s,o=>{b(c=>{if(o===ue)delete c.fields.color;else if(o===z)c.fields.color={none:!0};else{const n=X(o);n&&(c.fields.color=n)}}),(o.startsWith("binned:")||s.startsWith("binned:"))&&O()},{maxWidth:"100%",ownerDocument:f,ariaLabel:"Colour",searchPlaceholder:"Filter fields\u2026",hook:"plot-color"});return a.style.width="100%",J(a,e&&U(e)?e:void 0,"color",(o,c)=>{const n=o.fields.color;n&&U(n)&&$(n)&&c(n)})}function Ae(){const e=l.fields.rows,t=x.catalogue.filter(a=>a.categorical&&!E().some(o=>j(o,a.field))&&(!V(a.field)||F())).map(a=>({value:N(a.field),label:a.label,group:a.group}));t.push(...ie("rows"));const i=e?N(e):F()?N({builtin:"test"}):"",s=_(t,i,a=>{const o=X(a);o&&(b(c=>{c.fields.rows=o}),(a.startsWith("binned:")||i.startsWith("binned:"))&&O())},{maxWidth:"100%",ownerDocument:f,ariaLabel:"Rows",emptyText:"Choose a field\u2026",searchPlaceholder:"Filter fields\u2026",hook:"plot-rows"});return s.style.width="100%",J(s,e,"rows",(a,o)=>{const c=a.fields.rows;c&&$(c)&&o(c)})}function ke(){const e=l.fields.facet,t=[...E(),...l.fields.color&&U(l.fields.color)?[l.fields.color]:[]],i=[{value:z,label:"None: one plot",group:"Panels"}];for(const o of x.catalogue){if(!o.categorical||t.some(n=>j(n,o.field))||V(o.field)&&!F())continue;const c=o.level==="die"&&l.level==="wafer"?`${o.name} is per die: this plot has one mark per wafer`:void 0;i.push({value:N(o.field),label:o.label,group:o.group,...c?{disabled:c}:{}})}i.push(...ie("facet"));const s=e?N(e):z,a=_(i,s,o=>{b(c=>{if(o===z)delete c.fields.facet;else{const n=X(o);n&&(c.fields.facet=n)}}),(o.startsWith("binned:")||s.startsWith("binned:"))&&O()},{maxWidth:"100%",ownerDocument:f,ariaLabel:"Panels",searchPlaceholder:"Filter fields\u2026",hook:"plot-facet"});return a.style.width="100%",J(a,e,"facet",(o,c)=>{const n=o.fields.facet;n&&$(n)&&c(n)})}function Le(){const e=Ve({doc:f,catalogue:x.catalogue,filter:l.where,testDefs:x.testDefs,attributes:x.attributes,switchLabel:"Filter this plot",valuesOf:t=>x.valuesOf?.(t)??[],extentOf:t=>x.extentOf?.(t),onChange:t=>b(i=>{t?i.where=t:delete i.where})});return e.el.dataset.wmapPlotWhere="1",e.el}function ne(e,t,i,s){const a=f.createElement("input");return a.type="text",a.value=e,a.placeholder=t,a.setAttribute("aria-label",i),Object.assign(a.style,Z(),{width:"100%"}),a.addEventListener("input",()=>s(a.value)),a.addEventListener("keydown",o=>{o.key==="Escape"&&(o.stopPropagation(),a.blur())}),a}function R(e,t,i){const s=f.createElement("input");s.type="text",s.inputMode="decimal",s.value=e===void 0?"":String(e),s.placeholder="auto",s.setAttribute("aria-label",t),Object.assign(s.style,Z(),{width:"100%",fontVariantNumeric:"tabular-nums"});const a=()=>{const o=s.value.trim();if(o===""){i(void 0);return}const c=Number(o);Number.isFinite(c)?i(c):s.value=e===void 0?"":String(e)};return s.addEventListener("change",a),s.addEventListener("keydown",o=>{o.key==="Enter"&&a(),o.key==="Escape"&&(o.stopPropagation(),s.value=e===void 0?"":String(e),s.blur())}),s}function be(e,t,i,s){const a=l.axes?.[e]??{},o=w=>b(m=>{m.axes=m.axes??{};const v=m.axes[e]=m.axes[e]??{};w(v);for(const W of Object.keys(v))(v[W]===void 0||v[W]===""||W==="reverse"&&v[W]===!1)&&delete v[W];Object.keys(v).length===0&&delete m.axes[e],Object.keys(m.axes).length===0&&delete m.axes}),c=f.createElement("div");Object.assign(c.style,{display:"flex",flexDirection:"column",gap:C.md,padding:C.lg,border:`1px solid ${S.menuBorder}`,borderRadius:we.control});const n=f.createElement("div");n.textContent=t,Object.assign(n.style,{fontSize:D.body,fontWeight:"600",color:S.value}),c.appendChild(n);const r=ne(a.label??"",i??"",`${t} title`,w=>o(m=>{m.label=w.trim()===""?void 0:w}));if(r.dataset.wmapPlotAxisTitle=e,c.appendChild(h("Title",r)),s.limits===!1)return c;const u=f.createElement("div");if(Object.assign(u.style,{display:"grid",gridTemplateColumns:"1fr 1fr",gap:C.md}),u.append(h("Minimum",R(a.min,`${t} minimum`,w=>o(m=>{m.min=w}))),h("Maximum",R(a.max,`${t} maximum`,w=>o(m=>{m.max=w})))),c.appendChild(u),s.scale&&c.appendChild(h("Scale",T([["linear","Linear"],["log","Log"]],a.scale??"linear",w=>o(m=>{m.scale=w==="log"?"log":void 0}),f))),c.appendChild(Y("Reverse direction",!!a.reverse,w=>o(m=>{m.reverse=w}),f)),s.references===!1)return c;const d=ne(ze(a.references),"0.45 Target, 0.3..0.5 Window, median",`${t} reference lines`,w=>{const m=Me(w);if(!m.ok){p.textContent=m.error,d.setAttribute("aria-invalid","true");return}p.textContent="",d.removeAttribute("aria-invalid"),o(v=>{v.references=m.value.length?m.value:void 0})});d.dataset.wmapPlotRefs=e;const p=f.createElement("div");p.setAttribute("role","alert"),Object.assign(p.style,{fontSize:D.sub,color:S.errText});const g=h("Reference lines",d,"A value for a line, or lo..hi for a shaded band, each with an optional name, in the axis\u2019s own unit.");return g.appendChild(p),c.appendChild(g),c}const Ne=e=>k.querySelector(`[role="tab"][data-tab="${e}"]`);let q,B;const le=new Map;function oe(){if(!B)return;const e=je(Pe(l,x.catalogue));if(B.replaceChildren(),B.style.display=e?"flex":"none",!e)return;const t=f.createElement("span");t.textContent=e;const i=f.createElement("button");i.type="button",i.textContent="Use the automatic title",i.dataset.wmapPlotAutoTitle="1",Object.assign(i.style,K("outlined")),Q(i),i.addEventListener("click",()=>{b(s=>{delete s.title}),O()}),B.append(t,i)}function O(){k.replaceChildren(),le.clear();const e=f.createElement("div");e.setAttribute("role","tablist"),Object.assign(e.style,{display:"flex",gap:C.sm,borderBottom:`1px solid ${S.menuBorder}`});for(const[i,s,a]of[["setup","Setup","Which fields to plot and how they are combined"],["customise","Customise","Titles, axis limits, scale and direction"]]){const o=f.createElement("button");o.type="button",o.textContent=s,de(o,a),o.setAttribute("role","tab"),o.dataset.tab=i,o.setAttribute("aria-selected",String(A===i)),Object.assign(o.style,{...K("bare"),padding:`${C.sm} ${C.lg}`,fontSize:D.body,borderBottom:`2px solid ${A===i?S.iconActive:"transparent"}`,borderRadius:"0",color:A===i?S.iconActive:S.text,fontWeight:A===i?"600":"400"}),Q(o,"bare"),o.tabIndex=A===i?0:-1,o.addEventListener("click",()=>{A=i,O()}),o.addEventListener("keydown",c=>{c.key!=="ArrowLeft"&&c.key!=="ArrowRight"||(c.preventDefault(),A=i==="setup"?"customise":"setup",O(),Ne(A)?.focus())}),e.appendChild(o)}k.appendChild(e);const t=f.createElement("div");if(t.setAttribute("role","tabpanel"),Object.assign(t.style,{display:"flex",flexDirection:"column",gap:C.lg}),A==="setup"){t.appendChild(h("Chart type",T(Xe,l.chart,n=>Oe(n),f,!0)));const i=l.level==="wafer"?"wafers":"dies";switch(l.chart){case"scatter":t.appendChild(h("X axis",L("x","X axis"))),t.appendChild(h("Y axis",L("y","Y axis")));break;case"histogram":t.appendChild(h("Values",L("y","Values")));break;case"control":t.appendChild(h("Along (X axis)",L("x","Along"),"A wafer field with a number per wafer: wafer order, slot, a date.")),t.appendChild(h("Values (Y axis)",L("y","Values"),"One value per wafer: a test\u2019s wafer mean (or as Combine values by says), a yield or a pass rate.")),t.appendChild(h("Limits from the first",R(l.baseline,"Wafers the limits are set from",n=>b(r=>{n===void 0||!Number.isInteger(n)||n<3?delete r.baseline:r.baseline=n})),"Wafers, at least 3. Empty sets the limits from every wafer."));break;case"heatmap":t.appendChild(h("Columns (X axis)",L("x","Columns"),"One column per value: wafer, split, site\u2026")),t.appendChild(h("Rows",Ae(),"One row per value. With several tests as the values, Test gives a row per test.")),t.appendChild(h("Values (colour)",L("y","Values",{optional:`Count of ${i}`}),"What each cell\u2019s colour shows, combined over its dies or wafers."));break;case"goal":t.appendChild(h("Tests",L("y","Tests",{optional:"Every test with both limits"}),"Each test with both a low and a high limit is a point. Colour by a split to see it move."));break;case"probability":t.appendChild(h("Values (X axis)",L("y","Values"),"One curve per colour, each value at its share of its group: a shift is a curve moved sideways, a wider spread a flatter one, a second population a bend."));break;case"box":t.appendChild(h("Categories (X axis)",me(),"Compare by this field: one box per value, whether it is a wafer attribute (lot, split) or a die region (ring, reticle cell). Add a level to nest another inside it: the first level is the outer groups.")),t.appendChild(h("Values (Y axis)",L("y","Values")));break;case"bar":t.appendChild(h("Categories (X axis)",me(),"Compare by this field: one bar per value, whether it is a wafer attribute (lot, split) or a die region (ring, reticle cell). Add a level to nest another inside it: the first level is the outer groups.")),t.appendChild(h("Values (Y axis)",L("y","Values",{optional:`Count of ${i}`})));break;case"line":t.appendChild(h("X axis",L("x","X axis"),"A line joins the value at each X.")),t.appendChild(h("Y axis",L("y","Y axis")));break}const s=F();s&&l.chart!=="scatter"&&(t.appendChild(h("Tests",Ee(s),"Test numbers, or a range such as 1010..1030 for the tests declared between them. Put Test on the X axis or the colour to tell them apart.")),(l.chart==="bar"||l.chart==="line")&&t.appendChild(h("Read as",T([[y,"Values","Each test\u2019s measured values"],["passRate","Pass rates","Each test\u2019s share of judged dies that pass it"]],s.passRate?"passRate":y,n=>{b(r=>{const u=r.fields.y;if(!P(u))return;const d={...u};n===y?(delete d.passRate,delete d.judge):(d.passRate=!0,delete r.normalize),r.fields.y=d}),O()},f))));const a=l.fields.y;a&&(We(a)||!P(a)&&"passRate"in a)&&t.appendChild(h("Judged by",T([[y,"Test limits","A parametric test\u2019s measured value against its test limits"],["flag","Tester flag","The pass or fail the tester recorded for each die"]],a.judge??y,n=>b(r=>{const u={...r.fields.y};n===y?delete u.judge:u.judge="flag",r.fields.y=u}),f),"A functional test is judged by its recorded verdict either way.")),t.appendChild(h("Colour",Te(),"Compare by this field: each value gets its own colour. Follow Group by takes it from the Group by control.")),t.appendChild(h("Filter",Le(),"Keep only the dies that meet every condition: bin 1, the edge ring, a range of a test. A condition on a wafer field (split, yield) keeps whole wafers.")),l.chart==="line"&&t.appendChild(h("Band",T([[y,"None"],["sd","\xB11 SD","Mean \xB1 one standard deviation of the values at each X"],["ci95","95% CI","The mean\u2019s 95% confidence interval (Student\u2019s t)"],["iqr","Quartiles"],["minmax","Range"]],l.spread??y,n=>b(r=>{n===y?delete r.spread:r.spread=n}),f),"Round a line of means or medians.")),t.appendChild(h("Panels",ke(),"One panel per value of this field, on shared axes and colours: split or lot takes whole wafers, ring or site the dies in it.")),l.chart==="scatter"&&(t.appendChild(h("Fit line",T([[y,"None"],["linear","Least squares","Y on X: the usual regression line"],["orthogonal","Orthogonal","Closest to the points at right angles: for two measurements of one quantity (two testers, two insertions)"]],l.fit??y,n=>b(r=>{n===y?delete r.fit:r.fit=n}),f),"One line per colour, with its equation, R\xB2 and n above the chart.")),t.appendChild(Y("y = x line",!!l.identity,n=>b(r=>{n?r.identity=!0:delete r.identity}),f))),l.chart==="histogram"&&(t.appendChild(h("Bars as",T([[y,"Counts"],["percent","Shares","Each colour\u2019s bars as a share of its own values, so groups of different size compare"]],l.histNorm==="percent"?"percent":y,n=>b(r=>{n===y?delete r.histNorm:r.histNorm="percent"}),f))),t.appendChild(Y("Normal curve",!!l.normalCurve,n=>b(r=>{n?r.normalCurve=!0:delete r.normalCurve}),f)));const o=l.fields.y;if((l.chart==="histogram"||l.chart==="probability")&&o&&"test"in o&&!l.normalize){const n=f.createElement("div");Object.assign(n.style,{display:"grid",gridTemplateColumns:"1fr 1fr",gap:C.md});const r=u=>d=>b(p=>{const g={...p.whatIf??{}};d===void 0?delete g[u]:g[u]=d,g.lo===void 0&&g.hi===void 0?delete p.whatIf:p.whatIf=g});n.append(h("Low",R(l.whatIf?.lo,"What-if low limit",r("lo"))),h("High",R(l.whatIf?.hi,"What-if high limit",r("hi")))),t.appendChild(h("What-if limits",n,"In the test\u2019s own unit (V, A\u2026). The line under the plot gives the test\u2019s pass rate now and with these, and the dies that change."))}if(l.chart==="box"||l.chart==="bar"){t.appendChild(h("Orientation",T([[y,"Vertical","Categories along the bottom"],["horizontal","Horizontal","Categories down the left: for many categories or long names"]],l.orientation==="horizontal"?"horizontal":y,r=>b(u=>{r===y?delete u.orientation:u.orientation="horizontal"}),f)));const n=E().length<=1;n&&(t.appendChild(h("Order",T([[y,"Field order","The field\u2019s own order: wafers as loaded, numbers by value, names naturally"],["value","Largest first",l.chart==="box"?"By median, largest first":"By value, largest first (a pareto)"],["ascending","Smallest first",l.chart==="box"?"By median, smallest first":"By value, smallest first (the worst pass rate at the top)"]],l.sort??y,r=>{b(u=>{r===y?(delete u.sort,delete u.cumulative):(u.sort=r,r==="ascending"&&delete u.cumulative)}),O()},f))),t.appendChild(h("Show the first",R(l.top,"Categories shown",r=>b(u=>{r===void 0||!Number.isInteger(r)||r<1?delete u.top:u.top=r})),"Leave empty for every category; the rest are counted in a note."))),l.chart==="bar"&&(t.appendChild(h("Colours",T([[y,"Side by side"],["share","Share of colour","Side by side, each colour as its share of its own total, so groups of different sizes compare"],["stack","Stacked","One bar per category, its colours one on another"],["percent","100%","Each colour as its share of the category"]],l.stack??(l.barNorm==="percent"?"share":y),r=>b(u=>{delete u.stack,delete u.barNorm,r==="share"?u.barNorm="percent":r!==y&&(u.stack=r)}),f),"Shares and stacking add values, so they need a count or a sum.")),n&&l.sort==="value"&&t.appendChild(Y("Cumulative line (pareto)",!!l.cumulative,r=>b(u=>{r?u.cumulative=!0:delete u.cumulative}),f)),t.appendChild(Y("Values on the bars",!!l.valueLabels,r=>b(u=>{r?u.valueLabels=!0:delete u.valueLabels}),f,"Each bar\u2019s value at its end. Shown only when every value fits its bar, so none is left unlabelled.")))}const c=l.fields.y;l.chart!=="scatter"&&c&&(P(c)||"test"in c)&&t.appendChild(h("Rescale values",T(_e,l.normalize??y,n=>{b(r=>{n===y?delete r.normalize:r.normalize=n})},f),s?"Tests in different units share one axis only once they are rescaled.":void 0)),(l.chart==="bar"||l.chart==="line"||l.chart==="control"||l.chart==="heatmap"||l.level==="wafer")&&t.appendChild(h("Combine values by",Se())),t.appendChild(h("One mark per",T([[y,"Automatic"],["die","Die"],["wafer","Wafer"]],l.level??y,n=>{b(r=>{n===y?delete r.level:r.level=n}),O()},f,!0),l.level==="wafer"?"Die-level values are combined per wafer.":"Automatic uses the finest level the chosen fields allow."))}else{q=ne(l.title??"",x.autoText().title,"Plot title",n=>{b(r=>{n.trim()===""?delete r.title:Object.assign(r,{title:n})}),oe()}),q.dataset.wmapPlotTitle="1",B=f.createElement("div"),B.dataset.wmapPlotTitleDrift="1",Object.assign(B.style,{display:"none",flexDirection:"column",gap:C.sm,alignItems:"flex-start",padding:`${C.sm} ${C.md}`,background:S.warnBg,border:`1px solid ${S.warnBorder}`,borderRadius:we.control,color:S.warnText,fontSize:D.body}),t.appendChild(h("Title",q)),t.appendChild(B),oe();const i=x.autoText(),s=l.chart==="box"||l.chart==="bar",a=l.chart==="probability",o=n=>{switch(l.chart){case"scatter":case"line":return!0;case"histogram":case"probability":return n==="x";case"box":case"bar":case"control":return n==="y";default:return!1}};t.appendChild(be("x",l.chart==="histogram"||a?"Values axis":s?"Categories axis":"X axis",i.x,{scale:!s,limits:!s,references:o("x")})),t.appendChild(be("y",l.chart==="histogram"?"Count axis":a?"Cumulative share axis":s||l.chart==="line"?"Values axis":"Y axis",i.y,{scale:l.chart!=="histogram"&&!a,limits:!a,references:o("y")})),a&&t.appendChild(h("Share axis",T([["normal","Normal probability","Shares spaced by the normal quantile: a normal distribution is a straight line"],["linear","Linear","Shares spaced evenly, 0 to 100%"]],l.probabilityAxis??"normal",n=>b(r=>{n==="normal"?delete r.probabilityAxis:r.probabilityAxis="linear"}),f),"Normal probability spreads out the tails, where outliers and a second population show.")),l.chart==="histogram"&&t.appendChild(h("Bins",R(l.bins,"Number of bins",n=>b(r=>{n===void 0||!Number.isInteger(n)||n<1?delete r.bins:r.bins=Math.min(n,200)})),"Automatic is 16 equal bins."));const c=l.fields??{};(c.x&&"test"in c.x||c.y&&("test"in c.y||P(c.y)))&&t.appendChild(h("Limits",T([["both","Test + spec"],["test","Test"],["spec","Spec"],["none","None"]],l.limits??"both",n=>b(r=>{n==="both"?delete r.limits:r.limits=n}),f),"Drawn as dashed lines on the axis of a test that has them: short dashes for test limits, long for spec limits."));for(const n of t.querySelectorAll("[data-wmap-plot-axis-title]"))le.set(n.dataset.wmapPlotAxisTitle,n)}k.appendChild(t)}return O(),{el:k,setPlot(e){const t=G(e);JSON.stringify(t)!==JSON.stringify(l)&&(l=t,O())},refreshAuto(){const e=x.autoText();q&&(q.placeholder=e.title),oe();for(const[t,i]of le)i.placeholder=(t==="x"?e.x:e.y)??""}}}
1
+ import{combinationIssue as dt,defaultSweep as ut,describeTitleDrift as pt,fieldKey as R,fieldsForRole as Je,titleDrift as ft,withTestSetNames as Ve}from"../stats/plotData.js";import{isBinned as B,isField as le,isPassRateSet as ht,isTestSet as F,PLOTS_FORMAT as mt,PLOTS_VERSION as bt,plotIssue as gt,readPlot as yt,readPlotsFile as wt,syntaxErrorAt as vt,sameField as z,xFieldsOf as xt,PLOT_BINS_DEFAULT as Le,PLOT_BINS_MAX as Ct,PLOT_BINS_MIN as St,PLOT_X_LEVELS as je}from"../stats/plotSpec.js";import{formatTestList as Ot,parseTestList as Et}from"../stats/sweepText.js";import{formatReferences as At,parseReferences as Tt}from"../stats/plotReferences.js";import{CLR as A,FONT as I,RADIUS as _e,SPACE as T,controlStyle as re,wireControlHover as ce,wireTooltip as be}from"./toolbar.js";import{inputStyle as de,makeListSelect as H,makeSegmented as N,makeToggle as K}from"./charts/chartShell.js";export{de as inputStyle};import{buildFilterEditor as kt}from"./filterEditor.js";import{attachJsonSuggestions as Lt}from"./plotJsonSuggest.js";import{copyText as jt,createTextHistory as Nt}from"./plotJsonHistory.js";import{createSweepEditor as $t}from"./sweepEditor.js";import{listValueColorSchemes as Xe}from"../renderer/colorSchemes.js";import{PLOT_GRADIENTS as ge}from"./charts/divergingScale.js";const Ne="\0follow",Q="\0none",qe=[["scatter","Scatter","One point per die or wafer, one value against another"],["histogram","Histogram","How often each value occurs"],["box","Box","Quartiles, with whiskers to the minimum and maximum, for each category"],["bar","Bar","One combined value for each category, or a count"],["line","Line","One combined value at each X, joined"],["probability","Probability","The share of values at or below each value, one curve per colour: on the normal-probability axis a normal distribution is a straight line, and its tails are spread out to read"],["control","Control","One value per wafer in order, against limits from its own wafer-to-wafer variation, with the points that break a Western Electric rule marked"],["heatmap","Heatmap","One cell per row and column, coloured by the value combined there: tests by wafer, bins by wafer, rings by split"],["goal","Goal","Every test with both limits as a point: how far its mean is off centre, and how wide it is, against lines of equal Ppk"],["sweep","Sweep","Ordered runs of tests read as response curves, with where two curves cross and how far apart they are"]],v="\0auto",$e="\0count",Pe="\0set",Pt=8,Ge=[[v,"None","The values as measured, in their own unit"],["limits","To limits","0 at the low limit and 1 at the high one, each test by its own limits (spec limits where it has both)"],["zscore","z-score","Standard deviations from the mean of the values in view, each test on its own"],["robust","Robust z","Like a z-score, from the median and the median absolute deviation, so a few outliers do not set the scale"]],Re={mean:"Mean",median:"Median",min:"Minimum",max:"Maximum",sum:"Sum",count:"Count",yield:"Pooled yield (passing over judged dies)"};export function fieldRow(C,u,Z,i){const _=C.createElement("div");Object.assign(_.style,{display:"flex",flexDirection:"column",gap:T.xxs,minWidth:"0"});const ee=C.createElement("div");if(ee.textContent=u,Object.assign(ee.style,{fontSize:I.sub,color:A.label,fontWeight:"600"}),_.append(ee,Z),i){const L=C.createElement("div");L.textContent=i,Object.assign(L.style,{fontSize:I.sub,color:A.label}),_.appendChild(L)}return _}export function createPlotEditor(C){const{doc:u}=C,Z=e=>e.fields||e.chart==="sweep"?e:{...e,fields:{}};let i=Z(C.plot);const _=[["setup","Setup","Which fields to plot and how they are combined"],["customise","Customise","Titles, axis limits, scale and direction"],["json","JSON","The plot as text: copy it, paste one in, or edit it directly"]],ee=()=>i.chart==="sweep"?_.filter(e=>e[0]!=="customise"):_;let L="setup",ye,De,ue="",pe=[],fe=[];const W=u.createElement("div");W.dataset.wmapPlotEditor="1",Object.assign(W.style,{display:"flex",flexDirection:"column",gap:T.lg,minWidth:"0"});const te=e=>{i=e,C.onChange(e)},g=e=>{const a=JSON.parse(JSON.stringify(i));e(a),te(a)},m=(e,a,t)=>fieldRow(u,e,a,t),se=e=>{if(F(e))return{label:"Tests",level:"die",kind:"numeric",yield:!1};const a=e&&C.catalogue.find(t=>z(t.field,B(e)?e.binned:e));return a?{label:a.name,level:a.level,kind:e&&B(e)?"categorical":a.kind,yield:!(e&&B(e))&&"builtin"in a.field&&a.field.builtin==="yield"}:void 0},j=(e=i)=>[...xt(e.fields?.x)],G=(e,a)=>{a.length===0?delete e.fields.x:e.fields.x=a.length===1?a[0]:a},Ue=e=>{const a=e.map(se).filter(t=>!!t);return a.find(t=>t.level==="die")??a[0]};function We(e,a,t=0){const s=i.fields??{},n=s.color&&!("follow"in s.color)&&!("none"in s.color)?s.color:void 0,r=j();e==="x"&&(r[t]=a.field);const c={x:Ue(r),y:se(s.y),color:se(n)};e!=="x"&&(c[e]=se(a.field));const f=i.chart==="scatter"&&c.color?.kind==="numeric"&&!!n&&!("meta"in n);return dt(i.chart,c,{aggregate:i.aggregate,level:i.level,continuousColor:f})?.short}const we=()=>C.catalogue.flatMap(e=>e.group==="Tests"&&"test"in e.field?[{testNumber:e.field.test,name:e.field.name??""}]:[]),X=()=>F(i.fields?.y)?i.fields.y:void 0,ie=e=>!!e&&"builtin"in e&&e.builtin==="test",ve=(e,a=0)=>{const t=e==="x"?j()[a]:i.fields?.[e],s=t&&!("follow"in t)&&!("none"in t)?t:void 0,n=e==="x"?j().filter((c,f)=>f!==a):[],r=Je(C.catalogue,i.chart,e).filter(c=>(X()||!ie(c.field))&&!n.some(f=>z(f,c.field))).map(c=>{const f=s&&z(c.field,s)?void 0:We(e,c,a);return{value:R(c.field),label:c.label,group:c.group,...f?{disabled:f}:{}}});return e==="y"?r:[...r,...xe(e,a)]},xe=(e,a=0)=>{if(e==="x"&&!(i.chart==="box"||i.chart==="bar"||i.chart==="heatmap"))return[];if(e==="color"&&i.chart==="scatter")return[];const t=[...e==="x"?j().filter((s,n)=>n!==a):j(),...i.fields?.color&&le(i.fields.color)?[i.fields.color]:[]];return C.catalogue.filter(s=>s.kind==="numeric"&&!s.categorical&&s.group!=="Pass rates"&&!F(s.field)&&!t.some(n=>z(n,s.field))).map(s=>{const n={binned:s.field},r=e==="facet"&&s.level==="die"&&i.level==="wafer"?`${s.name} is per die: this plot has one mark per wafer`:e==="x"||e==="color"?We(e,{...s,field:n,kind:"categorical",categorical:!0},a):void 0;return{value:R(n),label:`${s.label} in ranges`,group:s.group,...r?{disabled:r}:{}}})},ae=e=>{const a=C.catalogue.find(s=>R(s.field)===e)?.field;if(a||!e.startsWith("binned:"))return a;const t=C.catalogue.find(s=>R({binned:s.field})===e)?.field;return t?{binned:t}:void 0};function he(e,a,t,s){if(!a||!B(a))return e;const n=u.createElement("div");Object.assign(n.style,{display:"flex",flexDirection:"column",gap:T.xs,minWidth:"0"});const r=u.createElement("div");Object.assign(r.style,{display:"flex",gap:T.sm,alignItems:"center",minWidth:"0"});const c=M(a.bins??Le,"Number of ranges",o=>{const l=o===void 0?Le:Math.round(o);g(h=>s(h,w=>{l===Le?delete w.bins:w.bins=Math.min(Ct,Math.max(St,l))})),k()});c.dataset.wmapPlotBins=t,c.style.width="64px";const f=u.createElement("span");f.textContent="ranges",Object.assign(f.style,{fontSize:I.sub,color:A.label});const d=N([["count","Equal counts","Each range holds about the same number of values (quartiles, deciles)"],["width","Equal widths","Each range spans the same width of values"]],a.by??"count",o=>g(l=>s(l,h=>{o==="count"?delete h.by:h.by="width"})),u);return r.append(c,f,d),n.append(e,r),n}function $(e,a,t={}){const s=t.at??0,n=e==="x"?j()[s]:i.fields.y,r=ve(e,s);if(t.optional&&r.unshift({value:$e,label:t.optional,group:"Count"}),e==="y"&&i.chart!=="scatter"&&we().length>=2&&r.unshift({value:Pe,label:"Several tests\u2026",group:"Several tests"}),n&&!F(n)&&!r.some(o=>o.value===R(n))){const o=C.catalogue.some(h=>z(h.field,n)),l="test"in n?n.name??`Test ${n.test}`:"meta"in n?n.meta:"builtin"in n?n.builtin:"";r.unshift({value:R(n),label:`${l} (${o?"not usable here":"not in this lot"})`,group:"Saved"})}const f=n?F(n)?Pe:R(n):t.optional?$e:"",d=H(r,f,o=>{if(o===$e){g(w=>{delete w.fields[e]});return}if(o===Pe){X()||(Ye(),k());return}const l=ae(o)??n;if(!l)return;const h=e==="y"&&!!X();g(w=>{if(e==="x"){const O=j(w);O[s]=l,G(w,O)}else w.fields.y=l;if(!h)return;const y=j(w),b=y.filter(O=>!ie(O));b.length!==y.length&&G(w,b.length||!(w.chart==="box"||w.chart==="bar")?b:[{builtin:"wafer"}]),ie(w.fields.color)&&delete w.fields.color}),(h||B(l)||n&&B(n))&&k()},{maxWidth:"100%",ownerDocument:u,ariaLabel:a,emptyText:"Choose a field\u2026",searchPlaceholder:"Filter fields\u2026",hook:e==="x"&&s>0?`plot-x-${s+1}`:`plot-${e}`});return d.style.width="100%",d}function Ye(){const e=we(),a=Ve({tests:e.slice(0,Pt).map(t=>t.testNumber)},e);g(t=>{t.fields.y=a;const s=j(t);(t.chart==="box"||t.chart==="bar")&&(s.length===0||s.length===1&&z(s[0],{builtin:"wafer"}))&&(t.fields.x={builtin:"test"})})}function He(e){const a=u.createElement("div");Object.assign(a.style,{display:"flex",flexDirection:"column",gap:T.xxs});const t=u.createElement("input");t.type="text",t.value=Ot(e.tests),t.placeholder="1010, 1011, 1020..1030",t.setAttribute("aria-label","Tests"),t.dataset.wmapPlotTests="1",Object.assign(t.style,de(),{width:"100%",fontVariantNumeric:"tabular-nums"});const s=u.createElement("div");return s.setAttribute("role","alert"),Object.assign(s.style,{fontSize:I.sub,color:A.errText}),t.addEventListener("input",()=>{const n=Et(t.value),r=n.ok?n.value.length===0?"Name at least one test":void 0:n.error;if(s.textContent=r??"",t.setAttribute("aria-invalid",String(!!r)),t.style.borderColor=r?A.errText:A.menuBorder,r||!n.ok)return;const c=n.value;g(f=>{f.fields.y=Ve({tests:c},we())})}),t.addEventListener("keydown",n=>{n.key==="Escape"&&(n.stopPropagation(),t.blur())}),a.append(t,s),a}function Be(){const e=j(),a=u.createElement("div");a.dataset.wmapPlotLevels="1",Object.assign(a.style,{display:"flex",flexDirection:"column",gap:T.xs,minWidth:"0"});const t=l=>{const h=e[l];return(h&&C.catalogue.find(w=>z(w.field,h))?.name)??`level ${l+1}`},s=(l,h,w,y,b)=>{const O=u.createElement("button");return O.type="button",O.textContent=l,O.setAttribute("aria-label",h),O.dataset.wmapPlotLevel=w,O.disabled=y,be(O,h),Object.assign(O.style,re("outlined"),{minWidth:"28px",opacity:y?"0.4":"1"}),ce(O),O.addEventListener("click",b),O},n=(...l)=>{k();for(const h of l){const w=W.querySelector(`[data-wmap-plot-level="${h}"]`);if(w&&!w.disabled){w.focus();return}}},r=(l,h)=>{g(y=>{const b=j(y);[b[l],b[l+h]]=[b[l+h],b[l]],G(y,b)});const w=l+h;n(`${h<0?"out":"in"}:${w}`,`${h<0?"in":"out"}:${w}`)},c=Math.max(1,e.length);for(let l=0;l<c;l++){const h=u.createElement("div");Object.assign(h.style,{display:"flex",gap:T.xs,alignItems:"center",minWidth:"0"});const w=he($("x",c>1?`Categories, level ${l+1} of ${c}`:"Categories",{at:l}),e[l],`x-${l+1}`,(y,b)=>{const O=j(y),D=O[l];D&&B(D)&&(b(D),G(y,O))});Object.assign(w.style,{flex:"1",minWidth:"0"}),h.appendChild(w),e.length>1&&h.append(s("\u2191",`Move ${t(l)} out a level`,`out:${l}`,l===0,()=>r(l,-1)),s("\u2193",`Move ${t(l)} in a level`,`in:${l}`,l===e.length-1,()=>r(l,1)),s("\xD7",`Remove ${t(l)} from the categories`,`remove:${l}`,!1,()=>{g(y=>{const b=j(y);b.splice(l,1),G(y,b)}),n(`remove:${Math.min(l,e.length-2)}`),e.length-1<2&&W.querySelector('[data-wmap-select="plot-x"]')?.focus()})),a.appendChild(h)}const f=e.length<je&&e.length>0?ve("x",e.length).find(l=>!l.disabled):void 0,d=u.createElement("button");d.type="button",d.textContent="+ Add a level",d.dataset.wmapPlotLevelAdd="1",d.disabled=!f;const o=e.length>=je?`At most ${je} levels`:f?"Divide each category by another field, nested inside it":"No other field can divide these categories";return be(d,o),Object.assign(d.style,re("outlined"),{alignSelf:"flex-start",opacity:d.disabled?"0.4":"1"}),ce(d),d.addEventListener("click",()=>{const l=f&&ae(f.value);l&&(g(h=>{G(h,[...j(h),l])}),k(),W.querySelector(`[data-wmap-select="plot-x-${e.length+1}"]`)?.focus())}),a.appendChild(d),a}const Ce={},Se={},ze=()=>m("Chart type",N(qe,i.chart,e=>Ke(e),u,!0));function Ke(e){const a=i.chart==="sweep";if(e==="sweep"){if(a)return;const{id:t,title:s,chart:n,...r}=i;ye=r,te({id:t,...s?{title:s}:{},chart:"sweep",sweep:De??ut(C.testDefs??[],t).sweep}),k();return}if(a){const{id:t,title:s,sweep:n}=i;De=n,te({id:t,...s?{title:s}:{},...ye??{},chart:e,fields:ye?.fields??{}})}g(t=>{t.chart=e;for(const s of["x","y"]){const n=Je(C.catalogue,e,s),r=l=>!!l&&(F(l)?s==="y"&&e!=="scatter":B(l)?s==="x"&&(e==="box"||e==="bar"||e==="heatmap"):n.some(h=>z(h.field,l))),c=l=>Array.isArray(l)?(e==="box"||e==="bar")&&l.every(r):r(l),f=t.fields[s];if(f&&!c(f)&&((Array.isArray(f)||!z(f,Se[s]))&&(Ce[s]=f),delete t.fields[s]),t.fields[s]||s==="y"&&(e==="bar"||e==="goal"||e==="heatmap"))continue;const d=Ce[s];if(c(d)){s==="x"?t.fields.x=d:t.fields.y=d,delete Ce[s],delete Se[s];continue}const o=s==="x"&&(e==="box"||e==="bar"||e==="heatmap")?{builtin:"wafer"}:s==="x"&&(e==="line"||e==="control")?n.find(l=>l.group==="Wafer")?.field??n[0]?.field:n[0]?.field;o&&!(s==="x"&&(e==="histogram"||e==="probability"||e==="goal"))&&(t.fields[s]=o,Se[s]=o)}}),k()}function Qe(){if(i.chart==="heatmap")return!0;const e=i.fields?.color;return i.chart==="scatter"&&!!e&&le(e)&&se(e)?.kind==="numeric"}function Ze(){const e=u.createElement("div");Object.assign(e.style,{display:"flex",flexDirection:"column",gap:T.md});const a=[{value:v,label:"Automatic"},...ge.map(s=>({value:s.name,label:s.label})),...Xe().filter(s=>!ge.some(n=>n.name===s.name)).map(s=>({value:s.name,label:s.label}))],t=H(a,i.colorGradient??v,s=>g(n=>{s===v?delete n.colorGradient:n.colorGradient=s}),{maxWidth:"100%",ownerDocument:u,ariaLabel:"Colours",hook:"plot-colours"});return t.style.width="100%",e.appendChild(m("Colours",t,"Automatic is blue to orange around zero for values rescaled around zero, orange-red to blue for a yield or pass rate, and the map\u2019s gradient for any other. Cividis is the map gradient that is safe for colour-blind readers.")),e.appendChild(K("Reverse colours",!!i.colorReverse,s=>g(n=>{s?n.colorReverse=!0:delete n.colorReverse}),u)),e}function et(){const e=!!i.fields.y&&"builtin"in i.fields.y&&i.fields.y.builtin==="yield",a=[{value:v,label:"Automatic"},...["mean","median","min","max","sum","count"].map(s=>({value:s,label:Re[s]}))];e&&a.push({value:"yield",label:Re.yield});const t=H(a,i.aggregate??v,s=>g(n=>{s===v?delete n.aggregate:n.aggregate=s}),{maxWidth:"100%",ownerDocument:u,ariaLabel:"Combine values by",hook:"plot-aggregate"});return t.style.width="100%",t}function tt(){const e=i.fields.color,a=C.followLabel(),t=[{value:Ne,label:a?`Follow Group by (${a})`:"Follow Group by (single colour)",group:"Colour"},{value:Q,label:"None",group:"Colour"},...ve("color")],s=e===void 0||"follow"in e?Ne:"none"in e?Q:R(e),n=H(t,s,r=>{g(c=>{if(r===Ne)delete c.fields.color;else if(r===Q)c.fields.color={none:!0};else{const f=ae(r);f&&(c.fields.color=f)}}),(r.startsWith("binned:")||s.startsWith("binned:"))&&k()},{maxWidth:"100%",ownerDocument:u,ariaLabel:"Colour",searchPlaceholder:"Filter fields\u2026",hook:"plot-color"});return n.style.width="100%",he(n,e&&le(e)?e:void 0,"color",(r,c)=>{const f=r.fields.color;f&&le(f)&&B(f)&&c(f)})}function st(){const e=i.fields.rows,a=C.catalogue.filter(n=>n.categorical&&!j().some(r=>z(r,n.field))&&(!ie(n.field)||X())).map(n=>({value:R(n.field),label:n.label,group:n.group}));a.push(...xe("rows"));const t=e?R(e):X()?R({builtin:"test"}):"",s=H(a,t,n=>{const r=ae(n);r&&(g(c=>{c.fields.rows=r}),(n.startsWith("binned:")||t.startsWith("binned:"))&&k())},{maxWidth:"100%",ownerDocument:u,ariaLabel:"Rows",emptyText:"Choose a field\u2026",searchPlaceholder:"Filter fields\u2026",hook:"plot-rows"});return s.style.width="100%",he(s,e,"rows",(n,r)=>{const c=n.fields.rows;c&&B(c)&&r(c)})}function it(){const e=i.fields.facet,a=[...j(),...i.fields.color&&le(i.fields.color)?[i.fields.color]:[]],t=[{value:Q,label:"None: one plot",group:"Panels"}];for(const r of C.catalogue){if(!r.categorical||a.some(f=>z(f,r.field))||ie(r.field)&&!X())continue;const c=r.level==="die"&&i.level==="wafer"?`${r.name} is per die: this plot has one mark per wafer`:void 0;t.push({value:R(r.field),label:r.label,group:r.group,...c?{disabled:c}:{}})}t.push(...xe("facet"));const s=e?R(e):Q,n=H(t,s,r=>{g(c=>{if(r===Q)delete c.fields.facet;else{const f=ae(r);f&&(c.fields.facet=f)}}),(r.startsWith("binned:")||s.startsWith("binned:"))&&k()},{maxWidth:"100%",ownerDocument:u,ariaLabel:"Panels",searchPlaceholder:"Filter fields\u2026",hook:"plot-facet"});return n.style.width="100%",he(n,e,"facet",(r,c)=>{const f=r.fields.facet;f&&B(f)&&c(f)})}function at(){const e=kt({doc:u,catalogue:C.catalogue,filter:i.where,testDefs:C.testDefs,attributes:C.attributes,switchLabel:"Filter this plot",valuesOf:a=>C.valuesOf?.(a)??[],extentOf:a=>C.extentOf?.(a),onChange:a=>g(t=>{a?t.where=a:delete t.where})});return e.el.dataset.wmapPlotWhere="1",e.el}function Oe(e,a,t,s){const n=u.createElement("input");return n.type="text",n.value=e,n.placeholder=a,n.setAttribute("aria-label",t),Object.assign(n.style,de(),{width:"100%"}),n.addEventListener("input",()=>s(n.value)),n.addEventListener("keydown",r=>{r.key==="Escape"&&(r.stopPropagation(),n.blur())}),n}function M(e,a,t){const s=u.createElement("input");s.type="text",s.inputMode="decimal",s.value=e===void 0?"":String(e),s.placeholder="auto",s.setAttribute("aria-label",a),Object.assign(s.style,de(),{width:"100%",fontVariantNumeric:"tabular-nums"});const n=()=>{const r=s.value.trim();if(r===""){t(void 0);return}const c=Number(r);Number.isFinite(c)?t(c):s.value=e===void 0?"":String(e)};return s.addEventListener("change",n),s.addEventListener("keydown",r=>{r.key==="Enter"&&n(),r.key==="Escape"&&(r.stopPropagation(),s.value=e===void 0?"":String(e),s.blur())}),s}function Fe(e,a,t,s){const n=i.axes?.[e]??{},r=y=>g(b=>{b.axes=b.axes??{};const O=b.axes[e]=b.axes[e]??{};y(O);for(const D of Object.keys(O))(O[D]===void 0||O[D]===""||D==="reverse"&&O[D]===!1)&&delete O[D];Object.keys(O).length===0&&delete b.axes[e],Object.keys(b.axes).length===0&&delete b.axes}),c=u.createElement("div");Object.assign(c.style,{display:"flex",flexDirection:"column",gap:T.md,padding:T.lg,border:`1px solid ${A.menuBorder}`,borderRadius:_e.control});const f=u.createElement("div");f.textContent=a,Object.assign(f.style,{fontSize:I.body,fontWeight:"600",color:A.value}),c.appendChild(f);const d=Oe(n.label??"",t??"",`${a} title`,y=>r(b=>{b.label=y.trim()===""?void 0:y}));if(d.dataset.wmapPlotAxisTitle=e,c.appendChild(m("Title",d)),s.limits===!1)return c;const o=u.createElement("div");if(Object.assign(o.style,{display:"grid",gridTemplateColumns:"1fr 1fr",gap:T.md}),o.append(m("Minimum",M(n.min,`${a} minimum`,y=>r(b=>{b.min=y}))),m("Maximum",M(n.max,`${a} maximum`,y=>r(b=>{b.max=y})))),c.appendChild(o),s.scale&&c.appendChild(m("Scale",N([["linear","Linear"],["log","Log"]],n.scale??"linear",y=>r(b=>{b.scale=y==="log"?"log":void 0}),u))),c.appendChild(K("Reverse direction",!!n.reverse,y=>r(b=>{b.reverse=y}),u)),s.references===!1)return c;const l=Oe(At(n.references),"0.45 Target, 0.3..0.5 Window, median",`${a} reference lines`,y=>{const b=Tt(y);if(!b.ok){h.textContent=b.error,l.setAttribute("aria-invalid","true");return}h.textContent="",l.removeAttribute("aria-invalid"),r(O=>{O.references=b.value.length?b.value:void 0})});l.dataset.wmapPlotRefs=e;const h=u.createElement("div");h.setAttribute("role","alert"),Object.assign(h.style,{fontSize:I.sub,color:A.errText});const w=m("Reference lines",l,"A value for a line, or lo..hi for a shaded band, each with an optional name, in the axis\u2019s own unit.");return w.appendChild(h),c.appendChild(w),c}const nt=e=>W.querySelector(`[role="tab"][data-tab="${e}"]`);let ne,J;const Ee=new Map;function Ae(){if(!J)return;const e=pt(ft(i,C.catalogue));if(J.replaceChildren(),J.style.display=e?"flex":"none",!e)return;const a=u.createElement("span");a.textContent=e;const t=u.createElement("button");t.type="button",t.textContent="Use the automatic title",t.dataset.wmapPlotAutoTitle="1",Object.assign(t.style,re("outlined")),ce(t),t.addEventListener("click",()=>{g(s=>{delete s.title}),k()}),J.append(a,t)}function ot(){const e=u.createElement("div");Object.assign(e.style,{display:"flex",flexDirection:"column",gap:T.sm});const a=u.createElement("textarea");a.dataset.wmapPlotJson="1";const t=p=>{const{id:E,...x}=p;return JSON.stringify(x,null,2)};a.value=t(i),a.spellcheck=!1,a.rows=18,a.setAttribute("aria-label","Plot as JSON"),Object.assign(a.style,{...de(),fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:I.sub,width:"100%",boxSizing:"border-box",resize:"vertical",whiteSpace:"pre",overflow:"auto"});const n=Lt({doc:u,area:a,source:()=>({tests:C.testDefs?.map(p=>({number:p.testNumber,name:p.name})),gradients:[...ge,...Xe().filter(p=>!ge.some(E=>E.name===p.name))],metaKeys:C.catalogue.flatMap(p=>"meta"in p.field?[{key:p.field.meta,label:p.name}]:[]),describe:(p,E)=>{if(p==="chart")return qe.find(x=>x[0]===E)?.[2];if(p==="aggregate")return Re[E];if(p==="normalize")return Ge.find(x=>x[0]===E)?.[2];if(p==="builtin")return C.catalogue.find(x=>"builtin"in x.field&&x.field.builtin===E)?.name;if(p==="level")return E==="die"?"One mark per die":"One mark per wafer"}})}),r=Nt(a),c=p=>{a.focus(),a.select(),u.execCommand?.("insertText",!1,p)||(a.value=p,a.dispatchEvent(new Event("input",{bubbles:!0}))),a.setSelectionRange(0,0)},f=u.createElement("div");f.append(a,n.el);const d=u.createElement("div");Object.assign(d.style,{display:"flex",flexDirection:"column",gap:T.xs,alignItems:"flex-start"});const o=u.createElement("div");o.setAttribute("role","status"),o.setAttribute("aria-live","polite"),Object.assign(o.style,{fontSize:I.sub,minHeight:"1.4em",whiteSpace:"pre-wrap"});const l=(p,E)=>{const x=u.createElement("button");return x.type="button",x.textContent=p,be(x,E),Object.assign(x.style,re("outlined")),ce(x),x},h=l("Apply","Use this text as the plot");h.dataset.wmapPlotJsonApply="1";const w=l("Copy","Copy the text to the clipboard"),y=l("Suggest","Show what can be written at the cursor (also Ctrl/Cmd+Space)");y.dataset.wmapPlotJsonSuggest="1",y.addEventListener("click",()=>{n.show()||(o.style.color=A.label,o.textContent="Nothing to suggest at the cursor")});const b=l("Discard edits","Put the text back as the plot stands, dropping what is not applied");b.dataset.wmapPlotJsonDiscard="1";const O=()=>{let p;try{p=JSON.parse(a.value)}catch(S){return{problem:`Not valid JSON: ${vt(a.value,S instanceof Error?S.message:String(S))}`,dropped:[]}}const E=[];let x;if(Array.isArray(p)||typeof p=="object"&&p!==null&&!("chart"in p)&&("plots"in p||"sweeps"in p||"format"in p)){const S=wt(Array.isArray(p)?JSON.stringify({format:mt,version:bt,plots:p}):a.value);if(S.error)return{problem:[S.error,...S.warnings].join(`
2
+ `),dropped:[]};if(S.plots.length>1)return{choices:S.plots,dropped:S.warnings};if(E.push(...S.warnings),x=S.plots[0]??null,!x)return{problem:E.join(`
3
+ `)||"The file holds no plots",dropped:[]}}else if(x=yt(p,"plot",E),!x)return{problem:E.map(S=>S.replace(/, skipped$/,"")).join(`
4
+ `)||"Not a plot",dropped:[]};const V=S=>typeof S=="object"&&S!==null&&!Array.isArray(S),U=(S,P,oe)=>{if(!V(S)||!V(P)||!("name"in P)||P.name!==S.name)return P;for(const Y of["test","passRate"])if(Y in S&&Y in P&&S[Y]!==P[Y]){E.push(`${oe}.name: the test number changed, so its old name "${String(P.name)}" is left out`);const{name:ke,...ct}=P;return ct}return P},me={...x.fields??{}},rt=i.fields??{};for(const S of["x","y","color","rows","facet"]){const P=me[S],oe=rt[S];Array.isArray(P)?me[S]=P.map((Y,ke)=>U(Array.isArray(oe)?oe[ke]:void 0,Y,`fields.${S} ${ke+1}`)):P!==void 0&&(me[S]=U(oe,P,`fields.${S}`))}x.fields=me;const Me=Z({...x,id:i.id});return{plot:Me,dropped:E.filter(S=>!/no id, given a new one/.test(S)),issue:gt(Me)}},D=()=>{const p=O();if(h.disabled=!p.plot,h.style.opacity=p.plot?"":"0.5",d.replaceChildren(),p.choices){o.style.color=A.label,o.textContent=[`This is a plots file with ${p.choices.length} plots, and this editor holds one plot. Choose the one to use:`,...p.dropped].join(`
5
+ `),p.choices.forEach((q,V)=>{const U=l(`${V+1}. ${q.title||`${q.chart[0].toUpperCase()}${q.chart.slice(1)} plot`}`,"Use this plot from the file");U.dataset.wmapPlotJsonChoice=String(V),U.addEventListener("click",()=>c(t(q))),d.appendChild(U)});return}if(!p.plot){o.style.color=A.errText,o.textContent=p.problem??"";return}const E=JSON.stringify(p.plot)===JSON.stringify(i),x=[...p.dropped.length?[`Applying would leave out or ignore:
6
+ ${p.dropped.join(`
7
+ `)}`]:[],...p.issue?[`It could not be drawn: ${p.issue}`]:[]];o.style.color=x.length?A.errText:A.label,o.textContent=x.length?x.join(`
8
+ `):E?ue||"The plot as it stands":"Edited: Apply to use it"};a.addEventListener("input",()=>{ue="",D()});const lt=(p,E)=>{pe.push(JSON.parse(JSON.stringify(i))),fe=[],Ie(p,E)},Ie=(p,E)=>{ue=E,te(p),k(),W.querySelector("[data-wmap-plot-json]")?.focus()};h.addEventListener("click",()=>{const p=O();p.plot&&lt(p.plot,p.dropped.length?`Applied. Left out:
9
+ ${p.dropped.join(`
10
+ `)}`:"Applied")}),a.addEventListener("keydown",p=>{if(!(p.ctrlKey||p.metaKey)||p.altKey)return;const E=p.key.toLowerCase(),x=E==="z"&&!p.shiftKey,q=E==="z"&&p.shiftKey||E==="y";if(!x&&!q)return;if(x?r.canUndo:r.canRedo){p.preventDefault(),x?r.undo():r.redo();return}if(a.value!==t(i))return;const V=x?pe:fe;V.length&&(p.preventDefault(),(x?fe:pe).push(JSON.parse(JSON.stringify(i))),Ie({...V.pop(),id:i.id},x?"Undone":"Redone"))}),b.addEventListener("click",()=>{ue="",c(t(i))}),w.addEventListener("click",()=>{const p=E=>{o.style.color=E?A.label:A.errText,o.textContent=E?"Copied":"The text could not be copied: select it and copy by hand"};jt(u,a.value,p)});const Te=u.createElement("div");return Object.assign(Te.style,{display:"flex",gap:T.sm}),Te.append(h,b,y,w),e.append(m("Plot as JSON",f,"Suggestions open as you type, after a comma or brace, or with the Suggest button or Ctrl/Cmd+Space. The format of a saved plots file, for one plot; a plots file can be pasted too, and offers a choice when it holds several plots. Ctrl/Cmd+Z undoes an Apply. The id is not part of the text."),Te,o,d),D(),e}function k(){W.replaceChildren(),i.chart==="sweep"&&L==="customise"&&(L="setup"),L!=="json"&&(pe=[],fe=[]),Ee.clear();const e=u.createElement("div");e.setAttribute("role","tablist"),Object.assign(e.style,{display:"flex",gap:T.sm,borderBottom:`1px solid ${A.menuBorder}`});const a=ee();for(const[s,n,r]of a){const c=u.createElement("button");c.type="button",c.textContent=n,be(c,r),c.setAttribute("role","tab"),c.dataset.tab=s,c.setAttribute("aria-selected",String(L===s)),Object.assign(c.style,{...re("bare"),padding:`${T.sm} ${T.lg}`,fontSize:I.body,borderBottom:`2px solid ${L===s?A.iconActive:"transparent"}`,borderRadius:"0",color:L===s?A.iconActive:A.text,fontWeight:L===s?"600":"400"}),ce(c,"bare"),c.tabIndex=L===s?0:-1,c.addEventListener("click",()=>{L=s,k()}),c.addEventListener("keydown",f=>{if(f.key!=="ArrowLeft"&&f.key!=="ArrowRight")return;f.preventDefault();const d=a.findIndex(o=>o[0]===s);L=a[(d+(f.key==="ArrowRight"?1:a.length-1))%a.length][0],k(),nt(L)?.focus()}),e.appendChild(c)}W.appendChild(e);const t=u.createElement("div");if(t.setAttribute("role","tabpanel"),Object.assign(t.style,{display:"flex",flexDirection:"column",gap:T.lg}),L==="json")t.appendChild(ot());else if(L==="setup"&&i.chart==="sweep")t.appendChild(ze()),t.appendChild($t({doc:u,plot:i,testDefs:C.testDefs,onChange:s=>te(s)}).el);else if(L==="setup"){t.appendChild(ze());const s=i.level==="wafer"?"wafers":"dies";switch(i.chart){case"scatter":t.appendChild(m("X axis",$("x","X axis"))),t.appendChild(m("Y axis",$("y","Y axis")));break;case"histogram":t.appendChild(m("Values",$("y","Values")));break;case"control":t.appendChild(m("Along (X axis)",$("x","Along"),"A wafer field with a number per wafer: wafer order, slot, a date.")),t.appendChild(m("Values (Y axis)",$("y","Values"),"One value per wafer: a test\u2019s wafer mean (or as Combine values by says), a yield or a pass rate.")),t.appendChild(m("Limits from the first",M(i.baseline,"Wafers the limits are set from",d=>g(o=>{d===void 0||!Number.isInteger(d)||d<3?delete o.baseline:o.baseline=d})),"Wafers, at least 3. Empty sets the limits from every wafer."));break;case"heatmap":t.appendChild(m("Columns (X axis)",$("x","Columns"),"One column per value: wafer, split, site\u2026")),t.appendChild(m("Rows",st(),"One row per value. With several tests as the values, Test gives a row per test.")),t.appendChild(m("Values (colour)",$("y","Values",{optional:`Count of ${s}`}),"What each cell\u2019s colour shows, combined over its dies or wafers."));break;case"goal":t.appendChild(m("Tests",$("y","Tests",{optional:"Every test with both limits"}),"Each test with both a low and a high limit is a point. Colour by a split to see it move."));break;case"probability":t.appendChild(m("Values (X axis)",$("y","Values"),"One curve per colour, each value at its share of its group: a shift is a curve moved sideways, a wider spread a flatter one, a second population a bend."));break;case"box":t.appendChild(m("Categories (X axis)",Be(),"Compare by this field: one box per value, whether it is a wafer attribute (lot, split) or a die region (ring, reticle cell). Add a level to nest another inside it: the first level is the outer groups.")),t.appendChild(m("Values (Y axis)",$("y","Values")));break;case"bar":t.appendChild(m("Categories (X axis)",Be(),"Compare by this field: one bar per value, whether it is a wafer attribute (lot, split) or a die region (ring, reticle cell). Add a level to nest another inside it: the first level is the outer groups.")),t.appendChild(m("Values (Y axis)",$("y","Values",{optional:`Count of ${s}`})));break;case"line":t.appendChild(m("X axis",$("x","X axis"),"A line joins the value at each X.")),t.appendChild(m("Y axis",$("y","Y axis")));break}const n=X();n&&i.chart!=="scatter"&&(t.appendChild(m("Tests",He(n),"Test numbers, or a range such as 1010..1030 for the tests declared between them. Put Test on the X axis or the colour to tell them apart.")),(i.chart==="bar"||i.chart==="line")&&t.appendChild(m("Read as",N([[v,"Values","Each test\u2019s measured values"],["passRate","Pass rates","Each test\u2019s share of judged dies that pass it"]],n.passRate?"passRate":v,d=>{g(o=>{const l=o.fields.y;if(!F(l))return;const h={...l};d===v?(delete h.passRate,delete h.judge):(h.passRate=!0,delete o.normalize),o.fields.y=h}),k()},u))));const r=i.fields.y;r&&(ht(r)||!F(r)&&"passRate"in r)&&t.appendChild(m("Judged by",N([[v,"Test limits","A parametric test\u2019s measured value against its test limits"],["flag","Tester flag","The pass or fail the tester recorded for each die"]],r.judge??v,d=>g(o=>{const l={...o.fields.y};d===v?delete l.judge:l.judge="flag",o.fields.y=l}),u),"A functional test is judged by its recorded verdict either way.")),t.appendChild(m("Colour",tt(),"Compare by this field: each value gets its own colour. Follow Group by takes it from the Group by control.")),t.appendChild(m("Filter",at(),"Keep only the dies that meet every condition: bin 1, the edge ring, a range of a test. A condition on a wafer field (split, yield) keeps whole wafers.")),i.chart==="line"&&t.appendChild(m("Band",N([[v,"None"],["sd","\xB11 SD","Mean \xB1 one standard deviation of the values at each X"],["ci95","95% CI","The mean\u2019s 95% confidence interval (Student\u2019s t)"],["iqr","Quartiles"],["minmax","Range"]],i.spread??v,d=>g(o=>{d===v?delete o.spread:o.spread=d}),u),"Round a line of means or medians.")),t.appendChild(m("Panels",it(),"One panel per value of this field, on shared axes and colours: split or lot takes whole wafers, ring or site the dies in it.")),i.chart==="scatter"&&(t.appendChild(m("Fit line",N([[v,"None"],["linear","Least squares","Y on X: the usual regression line"],["orthogonal","Orthogonal","Closest to the points at right angles: for two measurements of one quantity (two testers, two insertions)"]],i.fit??v,d=>g(o=>{d===v?delete o.fit:o.fit=d}),u),"One line per colour, with its equation, R\xB2 and n above the chart.")),t.appendChild(K("y = x line",!!i.identity,d=>g(o=>{d?o.identity=!0:delete o.identity}),u))),i.chart==="histogram"&&(t.appendChild(m("Bars as",N([[v,"Counts"],["percent","Shares","Each colour\u2019s bars as a share of its own values, so groups of different size compare"]],i.histNorm==="percent"?"percent":v,d=>g(o=>{d===v?delete o.histNorm:o.histNorm="percent"}),u))),t.appendChild(K("Normal curve",!!i.normalCurve,d=>g(o=>{d?o.normalCurve=!0:delete o.normalCurve}),u)));const c=i.fields.y;if((i.chart==="histogram"||i.chart==="probability")&&c&&"test"in c&&!i.normalize){const d=u.createElement("div");Object.assign(d.style,{display:"grid",gridTemplateColumns:"1fr 1fr",gap:T.md});const o=l=>h=>g(w=>{const y={...w.whatIf??{}};h===void 0?delete y[l]:y[l]=h,y.lo===void 0&&y.hi===void 0?delete w.whatIf:w.whatIf=y});d.append(m("Low",M(i.whatIf?.lo,"What-if low limit",o("lo"))),m("High",M(i.whatIf?.hi,"What-if high limit",o("hi")))),t.appendChild(m("What-if limits",d,"In the test\u2019s own unit (V, A\u2026). The line under the plot gives the test\u2019s pass rate now and with these, and the dies that change."))}if(i.chart==="box"||i.chart==="bar"){t.appendChild(m("Orientation",N([[v,"Vertical","Categories along the bottom"],["horizontal","Horizontal","Categories down the left: for many categories or long names"]],i.orientation==="horizontal"?"horizontal":v,o=>g(l=>{o===v?delete l.orientation:l.orientation="horizontal"}),u)));const d=j().length<=1;d&&(t.appendChild(m("Order",N([[v,"Field order","The field\u2019s own order: wafers as loaded, numbers by value, names naturally"],["value","Largest first",i.chart==="box"?"By median, largest first":"By value, largest first (a pareto)"],["ascending","Smallest first",i.chart==="box"?"By median, smallest first":"By value, smallest first (the worst pass rate at the top)"]],i.sort??v,o=>{g(l=>{o===v?(delete l.sort,delete l.cumulative):(l.sort=o,o==="ascending"&&delete l.cumulative)}),k()},u))),t.appendChild(m("Show the first",M(i.top,"Categories shown",o=>g(l=>{o===void 0||!Number.isInteger(o)||o<1?delete l.top:l.top=o})),"Leave empty for every category; the rest are counted in a note."))),i.chart==="bar"&&(t.appendChild(m("Colours",N([[v,"Side by side"],["share","Share of colour","Side by side, each colour as its share of its own total, so groups of different sizes compare"],["stack","Stacked","One bar per category, its colours one on another"],["percent","100%","Each colour as its share of the category"]],i.stack??(i.barNorm==="percent"?"share":v),o=>g(l=>{delete l.stack,delete l.barNorm,o==="share"?l.barNorm="percent":o!==v&&(l.stack=o)}),u),"Shares and stacking add values, so they need a count or a sum.")),d&&i.sort==="value"&&t.appendChild(K("Cumulative line (pareto)",!!i.cumulative,o=>g(l=>{o?l.cumulative=!0:delete l.cumulative}),u)),t.appendChild(K("Values on the bars",!!i.valueLabels,o=>g(l=>{o?l.valueLabels=!0:delete l.valueLabels}),u,"Each bar\u2019s value at its end. Shown only when every value fits its bar, so none is left unlabelled.")))}const f=i.fields.y;i.chart!=="scatter"&&f&&(F(f)||"test"in f)&&t.appendChild(m("Rescale values",N(Ge,i.normalize??v,d=>{g(o=>{d===v?delete o.normalize:o.normalize=d})},u),n?"Tests in different units share one axis only once they are rescaled.":void 0)),(i.chart==="bar"||i.chart==="line"||i.chart==="control"||i.chart==="heatmap"||i.level==="wafer")&&t.appendChild(m("Combine values by",et())),t.appendChild(m("One mark per",N([[v,"Automatic"],["die","Die"],["wafer","Wafer"]],i.level??v,d=>{g(o=>{d===v?delete o.level:o.level=d}),k()},u,!0),i.level==="wafer"?"Die-level values are combined per wafer.":"Automatic uses the finest level the chosen fields allow."))}else{ne=Oe(i.title??"",C.autoText().title,"Plot title",d=>{g(o=>{d.trim()===""?delete o.title:Object.assign(o,{title:d})}),Ae()}),ne.dataset.wmapPlotTitle="1",J=u.createElement("div"),J.dataset.wmapPlotTitleDrift="1",Object.assign(J.style,{display:"none",flexDirection:"column",gap:T.sm,alignItems:"flex-start",padding:`${T.sm} ${T.md}`,background:A.warnBg,border:`1px solid ${A.warnBorder}`,borderRadius:_e.control,color:A.warnText,fontSize:I.body}),t.appendChild(m("Title",ne)),t.appendChild(J),Ae(),Qe()&&t.appendChild(Ze());const s=C.autoText(),n=i.chart==="box"||i.chart==="bar",r=i.chart==="probability",c=d=>{switch(i.chart){case"scatter":case"line":return!0;case"histogram":case"probability":return d==="x";case"box":case"bar":case"control":return d==="y";default:return!1}};t.appendChild(Fe("x",i.chart==="histogram"||r?"Values axis":n?"Categories axis":"X axis",s.x,{scale:!n,limits:!n,references:c("x")})),t.appendChild(Fe("y",i.chart==="histogram"?"Count axis":r?"Cumulative share axis":n||i.chart==="line"?"Values axis":"Y axis",s.y,{scale:i.chart!=="histogram"&&!r,limits:!r,references:c("y")})),r&&t.appendChild(m("Share axis",N([["normal","Normal probability","Shares spaced by the normal quantile: a normal distribution is a straight line"],["linear","Linear","Shares spaced evenly, 0 to 100%"]],i.probabilityAxis??"normal",d=>g(o=>{d==="normal"?delete o.probabilityAxis:o.probabilityAxis="linear"}),u),"Normal probability spreads out the tails, where outliers and a second population show.")),i.chart==="histogram"&&t.appendChild(m("Bins",M(i.bins,"Number of bins",d=>g(o=>{d===void 0||!Number.isInteger(d)||d<1?delete o.bins:o.bins=Math.min(d,200)})),"Automatic is 16 equal bins."));const f=i.fields??{};(f.x&&"test"in f.x||f.y&&("test"in f.y||F(f.y)))&&t.appendChild(m("Limits",N([["both","Test + spec"],["test","Test"],["spec","Spec"],["none","None"]],i.limits??"both",d=>g(o=>{d==="both"?delete o.limits:o.limits=d}),u),"Drawn as dashed lines on the axis of a test that has them: short dashes for test limits, long for spec limits."));for(const d of t.querySelectorAll("[data-wmap-plot-axis-title]"))Ee.set(d.dataset.wmapPlotAxisTitle,d)}W.appendChild(t)}return k(),{el:W,setPlot(e){const a=Z(e);JSON.stringify(a)!==JSON.stringify(i)&&(i=a,k())},refreshAuto(){const e=C.autoText();ne&&(ne.placeholder=e.title),Ae();for(const[a,t]of Ee)t.placeholder=(a==="x"?e.x:e.y)??""}}}
@@ -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