@wafertools/wafermap 0.37.1 → 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 (86) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +21 -13
  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/chartPopulation.d.ts +8 -3
  6. package/dist/packages/canvas-adapter/chartPopulation.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +45 -19
  8. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  9. package/dist/packages/canvas-adapter/charts/commonality.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/correlation.d.ts +11 -0
  11. package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
  12. package/dist/packages/canvas-adapter/charts/divergingScale.d.ts +23 -0
  13. package/dist/packages/canvas-adapter/charts/divergingScale.js +1 -0
  14. package/dist/packages/canvas-adapter/charts/groupComparison.js +1 -1
  15. package/dist/packages/canvas-adapter/charts/palette.d.ts +10 -3
  16. package/dist/packages/canvas-adapter/charts/palette.js +1 -1
  17. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +3 -7
  18. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  19. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  20. package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +1 -0
  21. package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
  22. package/dist/packages/canvas-adapter/drilldown.d.ts +5 -0
  23. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  24. package/dist/packages/canvas-adapter/filterJson.d.ts +25 -0
  25. package/dist/packages/canvas-adapter/filterJson.js +5 -0
  26. package/dist/packages/canvas-adapter/index.d.ts +1 -0
  27. package/dist/packages/canvas-adapter/index.js +1 -1
  28. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  29. package/dist/packages/canvas-adapter/pageFilter.js +2 -2
  30. package/dist/packages/canvas-adapter/pinnedTests.d.ts +10 -0
  31. package/dist/packages/canvas-adapter/pinnedTests.js +1 -0
  32. package/dist/packages/canvas-adapter/plotCard.d.ts +1 -1
  33. package/dist/packages/canvas-adapter/plotCard.js +1 -1
  34. package/dist/packages/canvas-adapter/plotEditor.js +10 -1
  35. package/dist/packages/canvas-adapter/plotJsonComplete.d.ts +46 -0
  36. package/dist/packages/canvas-adapter/plotJsonComplete.js +4 -0
  37. package/dist/packages/canvas-adapter/plotJsonHistory.d.ts +12 -0
  38. package/dist/packages/canvas-adapter/plotJsonHistory.js +1 -0
  39. package/dist/packages/canvas-adapter/plotJsonSuggest.d.ts +16 -0
  40. package/dist/packages/canvas-adapter/plotJsonSuggest.js +1 -0
  41. package/dist/packages/canvas-adapter/plotModal.js +1 -1
  42. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  43. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  44. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  45. package/dist/packages/canvas-adapter/summaryPanel.d.ts +3 -3
  46. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  47. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  48. package/dist/packages/canvas-adapter/userGuideHtml.js +68 -33
  49. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  50. package/dist/packages/canvas-adapter/version.js +1 -1
  51. package/dist/packages/canvas-adapter/viewSwitch.js +1 -1
  52. package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -0
  53. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  54. package/dist/packages/core/utils.d.ts +6 -0
  55. package/dist/packages/core/utils.js +1 -1
  56. package/dist/packages/renderer/buildWaferMap.js +1 -1
  57. package/dist/packages/renderer/derivedTests/apply.d.ts +10 -0
  58. package/dist/packages/renderer/derivedTests/apply.js +1 -1
  59. package/dist/packages/renderer/derivedTests/check.d.ts +35 -0
  60. package/dist/packages/renderer/derivedTests/check.js +1 -0
  61. package/dist/packages/renderer/fmt.d.ts +5 -0
  62. package/dist/packages/renderer/fmt.js +1 -1
  63. package/dist/packages/renderer/index.d.ts +2 -0
  64. package/dist/packages/renderer/index.js +1 -1
  65. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  66. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  67. package/dist/packages/stats/chartCatalogue.js +1 -1
  68. package/dist/packages/stats/clusterDetection.js +1 -1
  69. package/dist/packages/stats/coFailure.d.ts +11 -0
  70. package/dist/packages/stats/coFailure.js +1 -0
  71. package/dist/packages/stats/correlation.d.ts +7 -0
  72. package/dist/packages/stats/correlation.js +1 -1
  73. package/dist/packages/stats/differenceMap.d.ts +2 -0
  74. package/dist/packages/stats/differenceMap.js +1 -1
  75. package/dist/packages/stats/plotData.d.ts +18 -2
  76. package/dist/packages/stats/plotData.js +1 -1
  77. package/dist/packages/stats/plotSpec.d.ts +31 -2
  78. package/dist/packages/stats/plotSpec.js +4 -4
  79. package/dist/packages/stats/plotTable.d.ts +18 -0
  80. package/dist/packages/stats/plotTable.js +1 -0
  81. package/dist/packages/stats/reportHtml.js +33 -29
  82. package/dist/packages/stats/synthesis.d.ts +7 -1
  83. package/dist/packages/stats/synthesis.js +1 -1
  84. package/dist/packages/stats/testsByWafer.d.ts +11 -0
  85. package/dist/packages/stats/testsByWafer.js +1 -0
  86. package/package.json +8 -4
@@ -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
@@ -0,0 +1 @@
1
+ const g=300,T=900;export function createTextHistory(n,i=()=>Date.now()){const e=[{value:n.value,start:n.selectionStart,end:n.selectionEnd}];let t=0,c=!1,d,a=0;const v=()=>({value:n.value,start:n.selectionStart,end:n.selectionEnd});n.addEventListener("input",o=>{if(c)return;const s=o.inputType??"",l=o.data??"",r=i(),p=s==="insertText"&&l.length===1&&!/[\s,:{}[\]]/.test(l)||s==="deleteContentBackward"||s==="deleteContentForward",h=p&&s===d&&r-a<900&&t===e.length-1&&t>0;d=p?s:void 0,a=r;const u=v();if(u.value===e[t].value){e[t]=u;return}if(h){e[t]=u;return}e.length=t+1,e.push(u),e.length>300&&e.shift(),t=e.length-1});function f(o,s){t=o,d=void 0;const l=e[o];c=!0;try{n.value=l.value,n.setSelectionRange(l.start,l.end);const r=n.ownerDocument.defaultView?.InputEvent;n.dispatchEvent(r?new r("input",{bubbles:!0,inputType:s}):new Event("input",{bubbles:!0}))}finally{c=!1}}return{undo(){return t<=0?!1:(f(t-1,"historyUndo"),!0)},redo(){return t>=e.length-1?!1:(f(t+1,"historyRedo"),!0)},get canUndo(){return t>0},get canRedo(){return t<e.length-1}}}export function copyText(n,i,e){const t=n.defaultView?.navigator;t?.clipboard?.writeText?t.clipboard.writeText(i).then(()=>e(!0),()=>e(!1)):e(!1)}
@@ -0,0 +1,16 @@
1
+ import { type CompletionSource } from './plotJsonComplete.js';
2
+ export interface JsonSuggestHandle {
3
+ /** The list, to place under the textarea. */
4
+ el: HTMLElement;
5
+ close(): void;
6
+ /** Open the list at the caret as if Ctrl/Cmd+Space were pressed; false when there is nothing to suggest there. */
7
+ show(): boolean;
8
+ }
9
+ export declare function attachJsonSuggestions(o: {
10
+ doc: Document;
11
+ area: HTMLTextAreaElement;
12
+ source: () => CompletionSource;
13
+ /** The text is a filter, not a plot: its keys and values are a filter's. */
14
+ as?: 'filter';
15
+ }): JsonSuggestHandle;
16
+ //# sourceMappingURL=plotJsonSuggest.d.ts.map
@@ -0,0 +1 @@
1
+ import{completionsAt as C}from"./plotJsonComplete.js";import{CLR as p,FONT as D,RADIUS as L,SPACE as A}from"./toolbar.js";const k=100;let $=0;export function attachJsonSuggestions(f){const{doc:l,area:t}=f,y=`wmap-json-suggest-${++$}`,s=l.createElement("div");s.id=y,s.setAttribute("role","listbox"),s.setAttribute("aria-label","Suggestions"),Object.assign(s.style,{display:"none",maxHeight:"11.5em",overflowY:"auto",border:`1px solid ${p.controlBorder}`,borderRadius:L.control,background:p.menuBg,boxSizing:"border-box",width:"100%",fontSize:D.sub}),t.setAttribute("aria-autocomplete","list"),t.setAttribute("aria-haspopup","listbox"),t.setAttribute("aria-controls",y),t.setAttribute("aria-expanded","false"),t.setAttribute("aria-keyshortcuts","Control+Space Meta+Space");let u,i=0,b=!1,g=!1;const w=e=>`${y}-${e}`;function a(){u=void 0,s.style.display="none",s.replaceChildren(),t.setAttribute("aria-expanded","false"),t.removeAttribute("aria-activedescendant")}function m(){[...s.children].forEach((e,r)=>{const n=r===i;e.setAttribute("aria-selected",String(n)),e.style.background=n?p.menuActive:"transparent",n&&e.scrollIntoView?.({block:"nearest"})}),t.setAttribute("aria-activedescendant",w(i))}function x(e,r){u=e,i=0,b=r||e.typed.length>0,s.replaceChildren(),e.items.slice(0,k).forEach((n,v)=>{const o=l.createElement("div");o.id=w(v),o.setAttribute("role","option"),o.dataset.wmapPlotJsonSuggestion=n.label,Object.assign(o.style,{display:"flex",gap:A.md,padding:`${A.xs} ${A.md}`,cursor:"pointer",color:p.text});const h=l.createElement("span");if(h.textContent=n.label,h.style.fontFamily="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",o.appendChild(h),n.detail){const d=l.createElement("span");d.textContent=n.detail,Object.assign(d.style,{color:p.label,minWidth:"0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),o.appendChild(d)}o.addEventListener("mouseenter",()=>{i=v,m()}),o.addEventListener("mousedown",d=>{d.preventDefault(),E(v)}),s.appendChild(o)}),s.style.display="block",t.setAttribute("aria-expanded","true"),m()}function c(e,r=!1){if(t.selectionStart!==t.selectionEnd)return a(),!1;const n=C(t.value,t.selectionStart,f.source(),{force:e,...f.as?{as:f.as}:{}});return n?x(n,r):a(),!!n}const S=()=>/[{,:[]$/.test(t.value.slice(0,t.selectionStart).trimEnd());function E(e){const r=u,n=r?.items[e];if(!(!r||!n)){a(),t.focus(),g=!0;try{t.setSelectionRange(r.from,r.to),l.execCommand?.("insertText",!1,n.insert)||(t.setRangeText(n.insert,r.from,r.to,"end"),t.dispatchEvent(new Event("input",{bubbles:!0})))}finally{g=!1}/:\s?$/.test(n.insert)&&c(!0,!0)}}return t.addEventListener("input",e=>{if(g)return;const r=e.inputType??"";if(r.startsWith("delete")||r.startsWith("history")){a();return}S()?c(!0):c(!1)}),t.addEventListener("keydown",e=>{const r=e.ctrlKey||e.metaKey;if(r&&e.key===" "){e.preventDefault(),c(!0,!0);return}if(!u||e.altKey||e.shiftKey||r)return;const n=Math.min(u.items.length,k);e.key==="ArrowDown"?(e.preventDefault(),b=!0,i=(i+1)%n,m()):e.key==="ArrowUp"?(e.preventDefault(),b=!0,i=(i+n-1)%n,m()):e.key==="Tab"||e.key==="Enter"&&b?(e.preventDefault(),e.stopPropagation(),E(i)):e.key==="Enter"?a():e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),a()):(e.key==="ArrowLeft"||e.key==="ArrowRight"||e.key==="Home"||e.key==="End"||e.key==="PageUp"||e.key==="PageDown")&&a()}),t.addEventListener("blur",a),t.addEventListener("mousedown",a),{el:s,close:a,show:()=>(t.focus(),c(!0,!0))}}
@@ -1 +1 @@
1
- import{fieldCatalogue as z,fieldValues as H,fieldExtent as I,resolvePlot as $,plotTitle as F}from"../stats/plotData.js";import{plotToSweep as J}from"../stats/plotSpec.js";import{renderPlotChart as M}from"./charts/plotChart.js";import{renderSweepPanel as Y}from"./charts/sweep.js";import{createPlotEditor as V}from"./plotEditor.js";import{createSweepEditor as q}from"./sweepEditor.js";import{CLR as b,FONT as T,SPACE as i,controlStyle as B,openReparentedModal as G,wireControlHover as L}from"./toolbar.js";export function openPlotEditor(e){const{doc:o,store:c}=e;let n=e.plot,a=!e.draft;const W=z(e.items,e.ctx),h=t=>$(t,e.items,e.ctx),p=o.createElement("div");p.dataset.wmapPlotWindow="1",Object.assign(p.style,{display:"flex",flexWrap:"wrap",gap:i.xxl,alignItems:"flex-start",width:"100%",boxSizing:"border-box",padding:i.xl});const f=o.createElement("div");if(Object.assign(f.style,{flex:"3 1 420px",minWidth:"0",display:"flex",flexDirection:"column",gap:i.md,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto"}),e.population){const t=o.createElement("div");t.textContent=`Population: ${e.population}`,t.dataset.wmapPopulation="1",Object.assign(t.style,{color:b.label,fontSize:T.body}),f.appendChild(t)}const w=n.chart==="sweep";let r;if(w){const t=Y({spec:J(n),dies:e.items.flatMap(l=>l.dies),testDefs:e.ctx.testDefs?[...e.ctx.testDefs]:void 0,population:e.rawPopulation??e.population,onSaveImage:e.chart.onSaveImage,onSelectPoint:e.onSelectLevel,ownerDocument:o});r={card:t.card,setPlot:l=>t.setSpec(J(l)),destroy:()=>t.destroy()}}else{const t=M({...e.chart,ownerDocument:o,waferLabel:l=>e.items[l]?.label??""});r={card:t.card,setPlot:l=>t.setPlot(h(l)),destroy:()=>t.destroy()}}r.card.style.alignSelf="stretch",f.appendChild(r.card);const m=o.createElement("div");Object.assign(m.style,{flex:"1 1 300px",minWidth:"260px",maxWidth:"420px",display:"flex",flexDirection:"column",gap:i.lg,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto",paddingRight:i.sm});const C=t=>{n=t,a&&c.upsert(t),y()},u=w?{...q({doc:o,plot:n,testDefs:e.ctx.testDefs,onChange:C}),refreshAuto:()=>{}}:V({doc:o,plot:n,catalogue:W,followLabel:()=>e.groupLabel??(e.items.length>1?"a colour per wafer":void 0),autoText:()=>{const t=h(n);return{title:t.autoTitle,x:t.x?.label,y:t.y?.label}},onChange:C,valuesOf:t=>H(t,e.items,e.ctx),extentOf:t=>I(t,e.items,e.ctx),testDefs:e.ctx.testDefs,attributes:e.ctx.curation});m.appendChild(u.el);const x=o.createElement("div");Object.assign(x.style,{display:"flex",flexDirection:"column",gap:i.sm,color:b.label,fontSize:T.body,position:"sticky",bottom:"0",background:b.menuBg,borderTop:`1px solid ${b.menuBorder}`,paddingTop:i.sm,paddingBottom:i.md});const P=o.createElement("div");x.appendChild(P);const s=o.createElement("button");s.type="button",s.textContent="Add to my plots",s.dataset.wmapPlotAdd="1",Object.assign(s.style,{...B("outlined"),alignSelf:"flex-start"}),L(s),s.addEventListener("click",()=>{a=!0,c.upsert(n),N()});const O=JSON.parse(JSON.stringify(e.plot)),E=(t,l,R)=>{const d=o.createElement("button");return d.type="button",d.textContent=t,d.dataset[l]="1",Object.assign(d.style,B("outlined")),L(d),d.addEventListener("click",R),d},g=E("Reset","wmapPlotReset",()=>D()),k=E("Cancel","wmapPlotCancel",()=>{D(),v?.close()}),S=o.createElement("div");Object.assign(S.style,{display:"flex",gap:i.md,flexWrap:"wrap"}),S.append(g,k,s),x.appendChild(S),m.appendChild(x);const A=()=>JSON.stringify(n)!==JSON.stringify(O);function D(){n=JSON.parse(JSON.stringify(O)),a&&c.upsert(n),u.setPlot(n),y()}function N(){P.textContent=a?`Changes are saved to \u201C${w?n.title??"Sweep":F(h(n))}\u201D.`:"This is a draft: it is not kept until you add it to your plots.",s.style.display=a?"none":"",g.disabled=!A(),g.style.opacity=g.disabled?"0.5":"1"}function y(){r.setPlot(n),u.refreshAuto(),N()}y(),p.append(f,m);const j=c.subscribe(()=>{if(!a)return;const t=c.get().find(l=>l.id===n.id);if(!t){v?.close();return}JSON.stringify(t)!==JSON.stringify(n)&&(n=t,u.setPlot(t),y())}),v=G([p],{title:e.title??(a?"Edit plot":"New plot"),anchor:e.anchor,ownerDocument:o,boxSize:{width:"min(96vw, 1180px)",height:"min(92vh, 800px)"},onClosed:()=>{j(),r.destroy(),e.onClosed?.()}});v||(j(),r.destroy())}
1
+ import{fieldCatalogue as H,fieldValues as I,fieldExtent as $,resolvePlot as F,plotTitle as M}from"../stats/plotData.js";import{plotToSweep as T}from"../stats/plotSpec.js";import{renderPlotChart as Y}from"./charts/plotChart.js";import{renderSweepPanel as V}from"./charts/sweep.js";import{createPlotEditor as q}from"./plotEditor.js";import{CLR as b,FONT as B,SPACE as r,controlStyle as L,openReparentedModal as G,wireControlHover as W}from"./toolbar.js";export function openPlotEditor(t){const{doc:o,store:p}=t;let n=t.plot,d=!t.draft;const k=H(t.items,t.ctx),w=e=>F(e,t.items,t.ctx),f=o.createElement("div");f.dataset.wmapPlotWindow="1",Object.assign(f.style,{display:"flex",flexWrap:"wrap",gap:r.xxl,alignItems:"flex-start",width:"100%",boxSizing:"border-box",padding:r.xl});const u=o.createElement("div");if(Object.assign(u.style,{flex:"3 1 420px",minWidth:"0",display:"flex",flexDirection:"column",gap:r.md,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto"}),t.population){const e=o.createElement("div");e.textContent=`Population: ${t.population}`,e.dataset.wmapPopulation="1",Object.assign(e.style,{color:b.label,fontSize:B.body}),u.appendChild(e)}const P=e=>{if(e){const a=V({spec:T(n),dies:t.items.flatMap(l=>l.dies),testDefs:t.ctx.testDefs?[...t.ctx.testDefs]:void 0,population:t.rawPopulation??t.population,onSaveImage:t.chart.onSaveImage,onSelectPoint:t.onSelectLevel,ownerDocument:o});return{card:a.card,setPlot:l=>a.setSpec(T(l)),destroy:()=>a.destroy()}}const i=Y({...t.chart,ownerDocument:o,waferLabel:a=>t.items[a]?.label??""});return{card:i.card,setPlot:a=>i.setPlot(w(a)),destroy:()=>i.destroy()}};let S=n.chart==="sweep",s=P(S);s.card.style.alignSelf="stretch",u.appendChild(s.card);function R(){const e=n.chart==="sweep";if(e===S)return;const i=s;s=P(e),S=e,s.card.style.alignSelf="stretch",i.card.replaceWith(s.card),i.destroy()}const m=o.createElement("div");Object.assign(m.style,{flex:"1 1 300px",minWidth:"260px",maxWidth:"420px",display:"flex",flexDirection:"column",gap:r.lg,maxHeight:"calc(min(92vh, 800px) - 110px)",overflowY:"auto",paddingRight:r.sm});const x=q({doc:o,plot:n,catalogue:k,followLabel:()=>t.groupLabel??(t.items.length>1?"a colour per wafer":void 0),autoText:()=>{if(n.chart==="sweep")return{title:"Sweep"};const e=w(n);return{title:e.autoTitle,x:e.x?.label,y:e.y?.label}},onChange:e=>{n=e,d&&p.upsert(e),h()},valuesOf:e=>I(e,t.items,t.ctx),extentOf:e=>$(e,t.items,t.ctx),testDefs:t.ctx.testDefs,attributes:t.ctx.curation});m.appendChild(x.el);const g=o.createElement("div");Object.assign(g.style,{display:"flex",flexDirection:"column",gap:r.sm,color:b.label,fontSize:B.body,position:"sticky",bottom:"0",background:b.menuBg,borderTop:`1px solid ${b.menuBorder}`,paddingTop:r.sm,paddingBottom:r.md});const O=o.createElement("div");g.appendChild(O);const c=o.createElement("button");c.type="button",c.textContent="Add to my plots",c.dataset.wmapPlotAdd="1",Object.assign(c.style,{...L("outlined"),alignSelf:"flex-start"}),W(c),c.addEventListener("click",()=>{d=!0,p.upsert(n),j()});const E=JSON.parse(JSON.stringify(t.plot)),D=(e,i,a)=>{const l=o.createElement("button");return l.type="button",l.textContent=e,l.dataset[i]="1",Object.assign(l.style,L("outlined")),W(l),l.addEventListener("click",a),l},y=D("Reset","wmapPlotReset",()=>N()),z=D("Cancel","wmapPlotCancel",()=>{N(),C?.close()}),v=o.createElement("div");Object.assign(v.style,{display:"flex",gap:r.md,flexWrap:"wrap"}),v.append(y,z,c),g.appendChild(v),m.appendChild(g);const A=()=>JSON.stringify(n)!==JSON.stringify(E);function N(){n=JSON.parse(JSON.stringify(E)),d&&p.upsert(n),x.setPlot(n),h()}function j(){O.textContent=d?`Changes are saved to \u201C${n.chart==="sweep"?n.title??"Sweep":M(w(n))}\u201D.`:"This is a draft: it is not kept until you add it to your plots.",c.style.display=d?"none":"",y.disabled=!A(),y.style.opacity=y.disabled?"0.5":"1"}function h(){R(),s.setPlot(n),x.refreshAuto(),j()}h(),f.append(u,m);const J=p.subscribe(()=>{if(!d)return;const e=p.get().find(i=>i.id===n.id);if(!e){C?.close();return}JSON.stringify(e)!==JSON.stringify(n)&&(n=e,x.setPlot(e),h())}),C=G([f],{title:t.title??(d?"Edit plot":"New plot"),anchor:t.anchor,ownerDocument:o,boxSize:{width:"min(96vw, 1180px)",height:"min(92vh, 800px)"},onClosed:()=>{J(),s.destroy(),t.onClosed?.()}});C||(J(),s.destroy())}
@@ -1 +1 @@
1
- import{defaultPlot as te,defaultSweep as oe,describeTitleDrift as ne,examplePlots as se,fieldCatalogue as re,resolvePlot as le,titleDrift as ae}from"../stats/plotData.js";import{addPlots as ie,newPlotId as T,readPlotsFile as ce,writePlotsFile as pe}from"../stats/plotSpec.js";import{buildFilterStrip as de}from"./filterEditor.js";import{isYieldEligibleDie as fe}from"../core/dies.js";import{testValue as ue}from"../core/dieTable.js";import{sweepAppliesTo as me}from"../stats/sweep.js";import{plotToSweep as F}from"../stats/plotSpec.js";import{renderPlotChart as he}from"./charts/plotChart.js";import{renderSweepPanel as ge}from"./charts/sweep.js";import{makeChartGridWrap as we}from"./charts/chartShell.js";import{confirmDialog as ye}from"./confirmDialog.js";import{openDrilldownMenu as L}from"./drilldown.js";import{openPlotEditor as be}from"./plotModal.js";import{sourceFromDies as xe,sourceFromPoints as ve,toPlotItems as Pe}from"./plotItems.js";import{CLR as g,FONT as C,RADIUS as O,SPACE as u,controlStyle as De,markNoPrint as E,saveTextFile as Se,wireControlHover as Ce,wireTooltip as Ee}from"./toolbar.js";const W=1e4;export function createPlotSection(r){const{doc:i,store:l}=r,p=Pe(r.items.map(e=>({label:e.identity??e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:r.ringCount}))),b={testDefs:r.testDefs,groupBy:r.groupBy,curation:r.attributes},M=e=>le(e,p,b),x=re(p,b),m=i.createElement("div");m.dataset.wmapPlotTab="1",Object.assign(m.style,{display:"flex",flexDirection:"column",gap:u.lg,width:"100%"});const v=i.createElement("div");Object.assign(v.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const f=(e,t,n,o)=>{const s=i.createElement("button");return s.type="button",s.textContent=e,s.dataset[t]="1",Object.assign(s.style,{...De("outlined"),fontSize:C.body}),Ce(s),Ee(s,n),s.addEventListener("click",o),s},P=f("Delete all plots\u2026","wmapPlotDeleteAll","Remove every plot and sweep. You are asked first, and Undo brings them back for ten seconds",()=>{X()});v.append(f("+ New plot","wmapPlotNew","Start a chart of your own: choose its type, what goes on each axis and how it is coloured",()=>z()),f("+ New sweep","wmapPlotNewSweep","Read an ordered run of tests as a response curve, and measure where two curves cross",()=>U()),f("Add examples","wmapPlotExamples","Draw one example of each chart type this lot can show, to edit or delete",()=>Y()),f("Import plots\u2026","wmapPlotImport","Add the plots from a file written by Export plots\u2026",()=>{Z()}),f("Export plots\u2026","wmapPlotExport","Save all your plots to a file, to share or to keep a copy",()=>q()),P),E(v),m.appendChild(v);const d=i.createElement("div");d.setAttribute("role","status"),Object.assign(d.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",padding:`${u.sm} ${u.md}`,background:g.menuBg,border:`1px solid ${g.menuBorder}`,borderRadius:O.container,color:g.text,fontSize:C.body}),E(d),m.appendChild(d);let h;function w(e,t,n=[]){h!==void 0&&clearTimeout(h),d.replaceChildren();const o=i.createElement("span");if(o.textContent=e,d.appendChild(o),t){const s=f(t.label,"wmapPlotNoticeAction",t.label==="Undo"?"Put back what was just removed":t.label,()=>{t.run(),I()});d.appendChild(s)}for(const s of n){const a=i.createElement("div");a.textContent=s,Object.assign(a.style,{flexBasis:"100%",color:g.label}),d.appendChild(a)}d.style.display="flex",h=setTimeout(I,t?W:W*2)}function I(){h!==void 0&&(clearTimeout(h),h=void 0),d.style.display="none",d.replaceChildren()}const D=i.createElement("div");D.textContent="No plots yet. A plot is any measured value against another, or a distribution, that you choose: New plot starts one, and it is kept for the next lot. Add examples draws one of each chart type from this lot to start from.",Object.assign(D.style,{color:g.label,fontSize:C.body,padding:`${u.lg} 0`});const S=we(i);m.append(D,S);const y=new Map,A=()=>({onSaveImage:r.onSaveImage,binColors:r.getBinColors?.(),onWaferMenu:r.waferMenu?(e,t,n)=>r.waferMenu(p[e].waferIndex??e,t,n):void 0,onOpenWafer:r.openWafer?(e,t)=>r.openWafer(p[e].waferIndex??e,p[e].label,t):r.focusTest&&p.length===1?(e,t)=>{t!==void 0&&r.focusTest(t)}:void 0,openActionLabel:!r.openWafer&&r.focusTest&&p.length===1?"show this test on the map":void 0,onSelectPoints:(e,t,n)=>R(e,t,n)}),$=()=>({plots:l,getBinColors:r.getBinColors,onSaveImage:r.onSaveImage,onSaveText:r.onSaveText,onLocateDie:r.locateDie});function R(e,t,n){const o=ve(e,p,r.testDefs);o&&L(t,n,o,$())}function k(e,t=!1){be({doc:i,anchor:m,store:l,plot:e,draft:t,items:p,ctx:b,groupLabel:r.groupLabel,chart:A(),onSelectLevel:j})}function U(){const e=oe(r.testDefs,T());l.upsert(e),k(e)}function j(e,t){const n=s=>e.testNumbers.some(a=>{const c=ue(s,a);return c!==void 0&&Number.isFinite(c)}),o=xe(p,`measured at ${e.label}`,s=>fe(s)&&n(s),r.testDefs,e.testNumbers[0]);o&&L({x:t.clientX,y:t.clientY},t.target,o,$())}function z(){const e=te(x,T());l.upsert(e),k(e)}function Y(){const e=o=>JSON.stringify([o.chart,o.fields,o.aggregate??null,o.sweep??null,o.fit??null,o.normalCurve??null,o.spread??null,o.normalize??null,o.sort??null,o.cumulative??null,o.stack??null]),t=new Set(l.get().map(e)),n=se(x,p.length,T,{items:p,ctx:b}).filter(o=>!t.has(e(o)));if(n.length===0){w(x.some(o=>o.group==="Tests")?"The examples for this lot are already in your plots.":"There are no measured values in this lot to draw examples from.");return}for(const o of n)l.upsert(o);w(`Added ${n.length} example plot${n.length===1?"":"s"}: ${[...new Set(n.map(o=>o.chart))].join(", ")}. Edit one to make it yours, or Delete what you do not need.`)}function B(e,t){const n=(o,s,a,c)=>e.appendChild(f(o,s,a,c));n("Edit","wmapPlotEdit","Change this plot\u2019s type, fields, titles, limits and axes",()=>{const o=l.get().find(s=>s.id===t.id);o&&k(o)}),n("Duplicate","wmapPlotDuplicate","Make a copy of this plot to vary",()=>{l.duplicate(t.id)}),n("Delete","wmapPlotDelete","Remove this plot. Undo brings it back for ten seconds",()=>{const o=l.remove(t.id);o&&w(`Deleted \u201C${o.plot.title??"plot"}\u201D.`,{label:"Undo",run:()=>l.insertAt(o.index,o.plot)})})}function _(e){return e.chart==="sweep"?J(e):H(e)}function H(e){const t=he({ownerDocument:i,waferLabel:a=>p[a]?.label??"",...A()});t.card.dataset.wmapPlotId=e.id,E(t.actions),B(t.actions,e);const n=i.createElement("div");n.dataset.wmapPlotTitleDrift="1",Object.assign(n.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",flexBasis:"100%",padding:`${u.xs} ${u.md}`,background:g.warnBg,border:`1px solid ${g.warnBorder}`,borderRadius:O.control,color:g.warnText,fontSize:C.body});const o=i.createElement("div");o.style.flexBasis="100%",t.actions.append(o,n);const s={card:t.card,actions:t.actions,json:"",driftNote:n,destroy:()=>t.destroy(),update:a=>{const c=M(a);t.setPlot(c),G(o,a),t.card.style.opacity=c.issues.length?"0.7":"1",K(n,a)}};return y.set(e.id,s),s}function J(e){const t=F(e),n=p.flatMap(a=>a.dies),o=ge({spec:t,dies:n,testDefs:r.testDefs,onSaveImage:r.onSaveImage,ownerDocument:i,onSelectPoint:j});o.card.dataset.wmapPlotId=e.id,o.card.dataset.wmapSweepPlot="1",E(o.actions),B(o.actions,e);const s={card:o.card,actions:o.actions,json:"",destroy:()=>o.destroy(),update:a=>{const c=F(a);o.setSpec(c),o.card.style.opacity=me(c,r.testDefs)?"1":"0.7"}};return y.set(e.id,s),s}function G(e,t){const n=t.where;e.replaceChildren(),n&&e.appendChild(de({doc:i,filter:n,testDefs:r.testDefs,attributes:r.attributes,label:"Filter",onToggle:o=>{const s=l.get().find(ee=>ee.id===t.id),a=s?.where;if(!s||!a)return;const c={...a};o?delete c.off:c.off=!0,l.upsert({...s,where:c})}}))}function K(e,t){const n=ne(ae(t,x));if(e.replaceChildren(),e.style.display=n?"flex":"none",!n)return;const o=i.createElement("span");o.textContent=n,e.append(o,f("Use the automatic title","wmapPlotAutoTitle","Replace the title you typed with the one written from the plot\u2019s settings",()=>{const s=l.get().find(c=>c.id===t.id);if(!s)return;const a={...s};delete a.title,l.upsert(a)}))}function N(){const e=l.get();for(const[t,n]of y)e.some(o=>o.id===t)||(n.destroy(),n.card.remove(),y.delete(t));e.forEach((t,n)=>{const o=y.get(t.id)??_(t),s=JSON.stringify(t);o.json!==s&&(o.json=s,o.update(t)),S.children[n]!==o.card&&S.insertBefore(o.card,S.children[n]??null)}),D.style.display=e.length===0?"":"none",P.disabled=e.length===0,P.style.opacity=e.length===0?"0.5":"1",P.style.cursor=e.length===0?"default":"pointer"}const V=l.subscribe(N);N();async function X(){const e=l.get().slice();if(e.length===0)return;const t=e.length;if(!await ye({doc:i,anchor:m,title:"Delete all plots",message:t===1?"Delete your 1 saved plot? It is kept on this computer for the next lot, so it will not be there for the next file either. Export plots\u2026 first to keep a copy.":`Delete all ${t} saved plots, sweeps included? They are kept on this computer for the next lot, so they will not be there for the next file either. Export plots\u2026 first to keep a copy.`,confirmLabel:t===1?"Delete 1 plot":`Delete ${t} plots`}))return;const o=l.get().slice();o.length!==0&&(l.replaceAll([]),w(`Deleted ${o.length===1?"1 plot":`all ${o.length} plots`}.`,{label:"Undo",run:()=>l.replaceAll(o)}))}function q(){const e=l.get();if(e.length===0){w("There are no plots to export yet.");return}Se(pe(e),"wafermap-plots.json","application/json",r.onSaveText)}async function Q(){return r.pickPlotsFile?r.pickPlotsFile():new Promise(e=>{const t=i.createElement("input");t.type="file",t.accept=".json,application/json",t.addEventListener("change",()=>{const n=t.files?.[0];if(!n){e(null);return}n.text().then(e,()=>e(null))}),t.addEventListener("cancel",()=>e(null)),t.click()})}async function Z(){const e=await Q();if(e===null)return;const t=ce(e);if(t.error){w(`Could not import: ${t.error}`);return}const{plots:n,copies:o}=ie(l.get(),t.plots);l.replaceAll(n);const s=[...t.warnings,...o.length?[`Kept as copies, since a plot with the same id already existed: ${o.join(", ")}`]:[]];w(`Imported ${t.plots.length} plot${t.plots.length===1?"":"s"}.`,void 0,s)}return{card:m,destroy:()=>{V(),h!==void 0&&clearTimeout(h);for(const e of y.values())e.destroy();y.clear(),l.flush()}}}
1
+ import{defaultPlot as Pe,describeTitleDrift as Ee,examplePlots as Se,fieldCatalogue as De,resolvePlot as Ce,titleDrift as Ae}from"../stats/plotData.js";import{addPlots as ke,newPlotId as V,readPlotsFile as Te,writePlotsFile as Ie}from"../stats/plotSpec.js";import{buildFilterStrip as $e}from"./filterEditor.js";import{isYieldEligibleDie as je}from"../core/dies.js";import{testValue as Be}from"../core/dieTable.js";import{sweepAppliesTo as Oe}from"../stats/sweep.js";import{plotToSweep as Y}from"../stats/plotSpec.js";import{renderPlotChart as ee}from"./charts/plotChart.js";import{renderSweepPanel as te}from"./charts/sweep.js";import{makeChartGridWrap as oe,makeSegmented as Le}from"./charts/chartShell.js";import{confirmDialog as Me}from"./confirmDialog.js";import{openDrilldownMenu as ne}from"./drilldown.js";import{openPlotEditor as Ne}from"./plotModal.js";import{sourceFromDies as Fe,sourceFromPoints as We,toPlotItems as Re}from"./plotItems.js";import{CLR as h,FONT as D,RADIUS as W,SPACE as u,controlStyle as Ue,markNoPrint as I,saveTextFile as ze,wireControlHover as Ve,wireTooltip as Ye}from"./toolbar.js";const se=1e4;export function createPlotSection(l){const{doc:r,store:a}=l,p=Re(l.items.map(e=>({label:e.identity??e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:l.ringCount}))),$={testDefs:l.testDefs,groupBy:l.groupBy,curation:l.attributes},q=e=>Ce(e,p,$),j=De(p,$),g=r.createElement("div");g.dataset.wmapPlotTab="1",Object.assign(g.style,{display:"flex",flexDirection:"column",gap:u.lg,width:"100%"});const B=r.createElement("div");Object.assign(B.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const w=(e,t,n,o)=>{const s=r.createElement("button");return s.type="button",s.textContent=e,s.dataset[t]="1",Object.assign(s.style,{...Ue("outlined"),fontSize:D.body}),Ve(s),Ye(s,n),s.addEventListener("click",o),s},O=w("Delete all plots\u2026","wmapPlotDeleteAll","Remove every plot and sweep. You are asked first, and Undo brings them back for ten seconds",()=>{ye()});let E="plots";const C=Le([["plots","My plots","Your own plots, kept for the next lot"],["examples","Examples","One example of each chart type this lot can show, drawn from its own tests. They are not your plots until you add them"]],E,e=>ie(e),r);C.dataset.wmapPlotViews="1",C.setAttribute("aria-label","Plots shown");for(const e of Array.from(C.querySelectorAll("label")))e.querySelector("input")?.value==="examples"&&(e.dataset.wmapPlotExamples="1");B.append(C,w("+ New plot","wmapPlotNew","Start a chart of your own: choose its type (a sweep reads runs of tests as response curves), what goes on each axis and how it is coloured",()=>ae()),w("Import plots\u2026","wmapPlotImport","Add the plots from a file written by Export plots\u2026",()=>{be()}),w("Export plots\u2026","wmapPlotExport","Save all your plots to a file, to share or to keep a copy",()=>ge()),O),I(B),g.appendChild(B);const y=r.createElement("div");y.setAttribute("role","status"),Object.assign(y.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",padding:`${u.sm} ${u.md}`,background:h.menuBg,border:`1px solid ${h.menuBorder}`,borderRadius:W.container,color:h.text,fontSize:D.body}),I(y),g.appendChild(y);let b;function S(e,t,n=[]){b!==void 0&&clearTimeout(b),y.replaceChildren();const o=r.createElement("span");if(o.textContent=e,y.appendChild(o),t){const s=w(t.label,"wmapPlotNoticeAction",t.label==="Undo"?"Put back what was just removed":t.label,()=>{t.run(),G()});y.appendChild(s)}for(const s of n){const i=r.createElement("div");i.textContent=s,Object.assign(i.style,{flexBasis:"100%",color:h.label}),y.appendChild(i)}y.style.display="flex",b=setTimeout(G,t?se:se*2)}function G(){b!==void 0&&(clearTimeout(b),b=void 0),y.style.display="none",y.replaceChildren()}const x=r.createElement("div");x.dataset.wmapPlotGallery="1",Object.assign(x.style,{display:"none",flexDirection:"column",gap:u.md,padding:u.md,border:`1px solid ${h.menuBorder}`,borderRadius:W.container}),I(x),g.appendChild(x);let L=[];const _=()=>{for(const e of L)e.destroy();L=[],x.replaceChildren(),x.style.display="none"},A=r.createElement("div");A.textContent="No plots yet. A plot is any measured value against another, or a distribution, that you choose: New plot starts one, and it is kept for the next lot. Examples shows one of each chart type from this lot, to look at and to add the ones you want.",Object.assign(A.style,{color:h.label,fontSize:D.body,padding:`${u.lg} 0`});const k=oe(r);g.append(A,k);const v=new Map,R=()=>({onSaveImage:l.onSaveImage,onSaveText:l.onSaveText,binColors:l.getBinColors?.(),onWaferMenu:l.waferMenu?(e,t,n)=>l.waferMenu(p[e].waferIndex??e,t,n):void 0,onOpenWafer:l.openWafer?(e,t)=>l.openWafer(p[e].waferIndex??e,p[e].label,t):l.focusTest&&p.length===1?(e,t)=>{t!==void 0&&l.focusTest(t)}:void 0,openActionLabel:!l.openWafer&&l.focusTest&&p.length===1?"show this test on the map":void 0,onSelectPoints:(e,t,n)=>le(e,t,n)}),H=()=>({plots:a,getBinColors:l.getBinColors,onSaveImage:l.onSaveImage,onSaveText:l.onSaveText,onLocateDie:l.locateDie});function le(e,t,n){const o=We(e,p,l.testDefs);o&&ne(t,n,o,H())}function J(e,t=!1){Ne({doc:r,anchor:g,store:a,plot:e,draft:t,items:p,ctx:$,groupLabel:l.groupLabel,chart:R(),onSelectLevel:U})}function U(e,t){const n=s=>e.testNumbers.some(i=>{const d=Be(s,i);return d!==void 0&&Number.isFinite(d)}),o=Fe(p,`measured at ${e.label}`,s=>je(s)&&n(s),l.testDefs,e.testNumbers[0]);o&&ne({x:t.clientX,y:t.clientY},t.target,o,H())}function ae(){N("plots");const e=Pe(j,V());a.upsert(e),J(e)}const M=e=>JSON.stringify([e.chart,e.fields,e.aggregate??null,e.sweep??null,e.fit??null,e.normalCurve??null,e.spread??null,e.normalize??null,e.sort??null,e.cumulative??null,e.stack??null]);function N(e){const t=C.querySelector(`input[value="${e}"]`);!t||t.checked||(t.checked=!0,t.dispatchEvent(new(r.defaultView??window).Event("change")))}function re(){k.style.display=E==="plots"?"grid":"none",A.style.display=E==="plots"&&a.get().length===0?"":"none",x.style.display=E==="examples"?"flex":"none"}function ie(e){if(e!==E){if(E=e,e==="examples"){if(!ce()){N("plots");return}}else _();re()}}function ce(){const e=Se(j,p.length,V,{items:p,ctx:$});if(e.length===0)return S(j.some(c=>c.group==="Tests")?"There are no examples this lot can draw.":"There are no measured values in this lot to draw examples from."),!1;const t=r.createElement("div");Object.assign(t.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const n=r.createElement("div");Object.assign(n.style,{color:h.text,fontSize:D.body,flex:"1 1 auto"});const o=[],s=w("Add all","wmapPlotExamplesAddAll","Add every example you do not have yet to My plots",()=>{const c=o.map(f=>f.add()).filter(f=>f!==void 0);c.length!==0&&(N("plots"),S(`Added ${c.length} plot${c.length===1?"":"s"} to My plots.`,{label:"Undo",run:()=>{const f=new Set(c);a.replaceAll(a.get().filter(P=>!f.has(P.id)))}}))});t.append(n,s);const i=oe(r);x.append(t,i);const d=[],F=()=>{const c=o.filter(f=>a.get().some(P=>M(P)===M(f.example))).length;n.textContent=`${e.length} examples from this lot, drawn for you. They are not your plots until you add them${c?` (${c} added)`:""}; edit them under My plots.`,s.disabled=c===e.length,s.style.opacity=c===e.length?"0.6":"1"};for(const c of e){let f;if(c.chart==="sweep")f=te({spec:Y(c),dies:p.flatMap(z=>z.dies),testDefs:l.testDefs,onSaveImage:l.onSaveImage,ownerDocument:r,onSelectPoint:U});else{const m=ee({ownerDocument:r,waferLabel:z=>p[z]?.label??"",...R()});m.setPlot(q(c)),f=m}f.card.dataset.wmapPlotExample=c.chart;const P=r.createElement("span");P.textContent="Example",P.dataset.wmapPlotExampleBadge="1",Object.assign(P.style,{fontSize:D.sub,color:h.label,border:`1px dashed ${h.menuBorder}`,borderRadius:W.control,padding:`0 ${u.sm}`});const T=w("Add to my plots","wmapPlotExampleAdd","Add this example to My plots, where you can edit it",()=>{}),Q=()=>a.get().some(m=>M(m)===M(c)),ve=()=>{const m=Q();T.textContent=m?"In your plots":"Add to my plots",T.disabled=m,T.style.opacity=m?"0.6":"1"},Z=()=>{if(Q())return;const m=V();return a.upsert({...c,id:m}),m};T.addEventListener("click",()=>{Z()}),o.push({example:c,add:Z}),d.push(ve),f.actions.append(P,T),i.appendChild(f.card),L.push(f)}const xe=a.subscribe(()=>{for(const c of d)c();F()});L.push({card:t,destroy:xe});for(const c of d)c();return F(),!0}function K(e,t){const n=(o,s,i,d)=>e.appendChild(w(o,s,i,d));n("Edit","wmapPlotEdit","Change this plot\u2019s type, fields, titles, limits and axes",()=>{const o=a.get().find(s=>s.id===t.id);o&&J(o)}),n("Duplicate","wmapPlotDuplicate","Make a copy of this plot to vary",()=>{a.duplicate(t.id)}),n("Delete","wmapPlotDelete","Remove this plot. Undo brings it back for ten seconds",()=>{const o=a.remove(t.id);o&&S(`Deleted \u201C${o.plot.title??"plot"}\u201D.`,{label:"Undo",run:()=>a.insertAt(o.index,o.plot)})})}function de(e){return e.chart==="sweep"?fe(e):pe(e)}function pe(e){const t=ee({ownerDocument:r,waferLabel:i=>p[i]?.label??"",...R()});t.card.dataset.wmapPlotId=e.id,I(t.actions),K(t.actions,e);const n=r.createElement("div");n.dataset.wmapPlotTitleDrift="1",Object.assign(n.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",flexBasis:"100%",padding:`${u.xs} ${u.md}`,background:h.warnBg,border:`1px solid ${h.warnBorder}`,borderRadius:W.control,color:h.warnText,fontSize:D.body});const o=r.createElement("div");o.style.flexBasis="100%",t.actions.append(o,n);const s={sweep:!1,card:t.card,actions:t.actions,json:"",driftNote:n,destroy:()=>t.destroy(),update:i=>{const d=q(i);t.setPlot(d),ue(o,i),t.card.style.opacity=d.issues.length?"0.7":"1",me(n,i)}};return v.set(e.id,s),s}function fe(e){const t=Y(e),n=p.flatMap(i=>i.dies),o=te({spec:t,dies:n,testDefs:l.testDefs,onSaveImage:l.onSaveImage,ownerDocument:r,onSelectPoint:U});o.card.dataset.wmapPlotId=e.id,o.card.dataset.wmapSweepPlot="1",I(o.actions),K(o.actions,e);const s={sweep:!0,card:o.card,actions:o.actions,json:"",destroy:()=>o.destroy(),update:i=>{const d=Y(i);o.setSpec(d),o.card.style.opacity=Oe(d,l.testDefs)?"1":"0.7"}};return v.set(e.id,s),s}function ue(e,t){const n=t.where;e.replaceChildren(),n&&e.appendChild($e({doc:r,filter:n,testDefs:l.testDefs,attributes:l.attributes,label:"Filter",onToggle:o=>{const s=a.get().find(F=>F.id===t.id),i=s?.where;if(!s||!i)return;const d={...i};o?delete d.off:d.off=!0,a.upsert({...s,where:d})}}))}function me(e,t){const n=Ee(Ae(t,j));if(e.replaceChildren(),e.style.display=n?"flex":"none",!n)return;const o=r.createElement("span");o.textContent=n,e.append(o,w("Use the automatic title","wmapPlotAutoTitle","Replace the title you typed with the one written from the plot\u2019s settings",()=>{const s=a.get().find(d=>d.id===t.id);if(!s)return;const i={...s};delete i.title,a.upsert(i)}))}function X(){const e=a.get();for(const[t,n]of v)e.some(o=>o.id===t)||(n.destroy(),n.card.remove(),v.delete(t));e.forEach((t,n)=>{let o=v.get(t.id);o&&o.sweep!==(t.chart==="sweep")&&(o.destroy(),o.card.remove(),v.delete(t.id),o=void 0),o??=de(t);const s=JSON.stringify(t);o.json!==s&&(o.json=s,o.update(t)),k.children[n]!==o.card&&k.insertBefore(o.card,k.children[n]??null)}),A.style.display=E==="plots"&&e.length===0?"":"none",O.disabled=e.length===0,O.style.opacity=e.length===0?"0.5":"1",O.style.cursor=e.length===0?"default":"pointer"}const he=a.subscribe(X);X();async function ye(){const e=a.get().slice();if(e.length===0)return;const t=e.length;if(!await Me({doc:r,anchor:g,title:"Delete all plots",message:t===1?"Delete your 1 saved plot? It is kept on this computer for the next lot, so it will not be there for the next file either. Export plots\u2026 first to keep a copy.":`Delete all ${t} saved plots, sweeps included? They are kept on this computer for the next lot, so they will not be there for the next file either. Export plots\u2026 first to keep a copy.`,confirmLabel:t===1?"Delete 1 plot":`Delete ${t} plots`}))return;const o=a.get().slice();o.length!==0&&(a.replaceAll([]),S(`Deleted ${o.length===1?"1 plot":`all ${o.length} plots`}.`,{label:"Undo",run:()=>a.replaceAll(o)}))}function ge(){const e=a.get();if(e.length===0){S("There are no plots to export yet.");return}ze(Ie(e),"wafermap-plots.json","application/json",l.onSaveText)}async function we(){return l.pickPlotsFile?l.pickPlotsFile():new Promise(e=>{const t=r.createElement("input");t.type="file",t.accept=".json,application/json",t.addEventListener("change",()=>{const n=t.files?.[0];if(!n){e(null);return}n.text().then(e,()=>e(null))}),t.addEventListener("cancel",()=>e(null)),t.click()})}async function be(){const e=await we();if(e===null)return;const t=Te(e);if(t.error){S(`Could not import: ${t.error}`);return}const{plots:n,copies:o}=ke(a.get(),t.plots);a.replaceAll(n),N("plots");const s=[...t.warnings,...o.length?[`Kept as copies, since a plot with the same id already existed: ${o.join(", ")}`]:[]];S(`Imported ${t.plots.length} plot${t.plots.length===1?"":"s"}.`,void 0,s)}return{card:g,destroy:()=>{he(),b!==void 0&&clearTimeout(b),_();for(const e of v.values())e.destroy();v.clear(),a.flush()}}}