@wafertools/wafermap 0.40.0 → 0.41.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 (220) hide show
  1. package/AGENTS.md +20 -21
  2. package/CHANGELOG.md +154 -0
  3. package/README.md +6 -6
  4. package/dist/packages/canvas-adapter/canvasTheme.d.ts +12 -0
  5. package/dist/packages/canvas-adapter/canvasTheme.js +1 -1
  6. package/dist/packages/canvas-adapter/cellShade.d.ts +2 -2
  7. package/dist/packages/canvas-adapter/cellShade.js +1 -1
  8. package/dist/packages/canvas-adapter/chartPopulation.d.ts +3 -0
  9. package/dist/packages/canvas-adapter/chartPopulation.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/capability.d.ts +3 -0
  11. package/dist/packages/canvas-adapter/charts/capability.js +1 -1
  12. package/dist/packages/canvas-adapter/charts/cardAbout.d.ts +2 -1
  13. package/dist/packages/canvas-adapter/charts/cardAbout.js +1 -1
  14. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +47 -27
  15. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  16. package/dist/packages/canvas-adapter/charts/commonality.js +4 -4
  17. package/dist/packages/canvas-adapter/charts/correlation.d.ts +6 -12
  18. package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
  19. package/dist/packages/canvas-adapter/charts/divergingScale.d.ts +45 -15
  20. package/dist/packages/canvas-adapter/charts/divergingScale.js +1 -1
  21. package/dist/packages/canvas-adapter/charts/groupComparison.js +1 -1
  22. package/dist/packages/canvas-adapter/charts/palette.d.ts +16 -30
  23. package/dist/packages/canvas-adapter/charts/palette.js +1 -1
  24. package/dist/packages/canvas-adapter/charts/patCard.js +1 -1
  25. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +29 -3
  26. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  27. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.d.ts +3 -0
  28. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
  29. package/dist/packages/canvas-adapter/charts/sweep.d.ts +3 -0
  30. package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
  31. package/dist/packages/canvas-adapter/chromeRow.d.ts +68 -0
  32. package/dist/packages/canvas-adapter/chromeRow.js +1 -0
  33. package/dist/packages/canvas-adapter/chunked.d.ts +6 -0
  34. package/dist/packages/canvas-adapter/chunked.js +1 -1
  35. package/dist/packages/canvas-adapter/columnFilterPopup.d.ts +25 -0
  36. package/dist/packages/canvas-adapter/columnFilterPopup.js +1 -0
  37. package/dist/packages/canvas-adapter/composePng.d.ts +37 -0
  38. package/dist/packages/canvas-adapter/composePng.js +1 -0
  39. package/dist/packages/canvas-adapter/dataTab.d.ts +39 -6
  40. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  41. package/dist/packages/canvas-adapter/dieList.js +1 -1
  42. package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +3 -1
  43. package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
  44. package/dist/packages/canvas-adapter/drilldown.d.ts +20 -1
  45. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  46. package/dist/packages/canvas-adapter/filterButton.d.ts +2 -0
  47. package/dist/packages/canvas-adapter/filterButton.js +1 -1
  48. package/dist/packages/canvas-adapter/filterEditor.d.ts +5 -0
  49. package/dist/packages/canvas-adapter/filterEditor.js +1 -1
  50. package/dist/packages/canvas-adapter/guideWindow.js +1 -1
  51. package/dist/packages/canvas-adapter/icons.js +1 -1
  52. package/dist/packages/canvas-adapter/identityHeader.d.ts +5 -0
  53. package/dist/packages/canvas-adapter/identityHeader.js +1 -1
  54. package/dist/packages/canvas-adapter/index.d.ts +7 -0
  55. package/dist/packages/canvas-adapter/index.js +1 -1
  56. package/dist/packages/canvas-adapter/insightsTab.d.ts +32 -9
  57. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  58. package/dist/packages/canvas-adapter/maplessSummary.d.ts +4 -2
  59. package/dist/packages/canvas-adapter/maplessSummary.js +1 -1
  60. package/dist/packages/canvas-adapter/openWaferMode.d.ts +7 -0
  61. package/dist/packages/canvas-adapter/openWaferMode.js +1 -0
  62. package/dist/packages/canvas-adapter/panelChart.d.ts +7 -0
  63. package/dist/packages/canvas-adapter/panelChart.js +1 -0
  64. package/dist/packages/canvas-adapter/panelTable.d.ts +50 -0
  65. package/dist/packages/canvas-adapter/panelTable.js +1 -0
  66. package/dist/packages/canvas-adapter/plotCard.js +1 -1
  67. package/dist/packages/canvas-adapter/plotEditor.d.ts +12 -0
  68. package/dist/packages/canvas-adapter/plotEditor.js +10 -10
  69. package/dist/packages/canvas-adapter/plotItems.d.ts +9 -4
  70. package/dist/packages/canvas-adapter/plotItems.js +1 -1
  71. package/dist/packages/canvas-adapter/plotJsonComplete.js +1 -1
  72. package/dist/packages/canvas-adapter/plotModal.d.ts +7 -0
  73. package/dist/packages/canvas-adapter/plotModal.js +1 -1
  74. package/dist/packages/canvas-adapter/plotStore.js +1 -1
  75. package/dist/packages/canvas-adapter/plotTab.d.ts +60 -2
  76. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  77. package/dist/packages/canvas-adapter/renderWaferGallery.d.ts +7 -0
  78. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  79. package/dist/packages/canvas-adapter/renderWaferMap.d.ts +41 -9
  80. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  81. package/dist/packages/canvas-adapter/reportCharts.d.ts +41 -0
  82. package/dist/packages/canvas-adapter/reportCharts.js +1 -0
  83. package/dist/packages/canvas-adapter/reportExport.d.ts +91 -0
  84. package/dist/packages/canvas-adapter/reportExport.js +1 -0
  85. package/dist/packages/canvas-adapter/reportFigures.d.ts +29 -0
  86. package/dist/packages/canvas-adapter/reportFigures.js +1 -0
  87. package/dist/packages/canvas-adapter/reportRun.d.ts +9 -0
  88. package/dist/packages/canvas-adapter/reportRun.js +1 -0
  89. package/dist/packages/canvas-adapter/selectionOverlay.d.ts +12 -0
  90. package/dist/packages/canvas-adapter/selectionOverlay.js +1 -0
  91. package/dist/packages/canvas-adapter/summaryPanel.d.ts +152 -111
  92. package/dist/packages/canvas-adapter/summaryPanel.js +7 -4
  93. package/dist/packages/canvas-adapter/summaryToggle.js +1 -1
  94. package/dist/packages/canvas-adapter/tableDrilldown.d.ts +48 -0
  95. package/dist/packages/canvas-adapter/tableDrilldown.js +1 -0
  96. package/dist/packages/canvas-adapter/tableFilter.d.ts +42 -0
  97. package/dist/packages/canvas-adapter/tableFilter.js +1 -0
  98. package/dist/packages/canvas-adapter/tablePlots.d.ts +85 -0
  99. package/dist/packages/canvas-adapter/tablePlots.js +1 -0
  100. package/dist/packages/canvas-adapter/themeWatch.d.ts +7 -0
  101. package/dist/packages/canvas-adapter/themeWatch.js +1 -0
  102. package/dist/packages/canvas-adapter/toCanvas.d.ts +3 -0
  103. package/dist/packages/canvas-adapter/toCanvas.js +1 -1
  104. package/dist/packages/canvas-adapter/toolbar.d.ts +125 -36
  105. package/dist/packages/canvas-adapter/toolbar.js +2 -2
  106. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  107. package/dist/packages/canvas-adapter/userGuideHtml.js +530 -414
  108. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  109. package/dist/packages/canvas-adapter/version.js +1 -1
  110. package/dist/packages/canvas-adapter/viewSwitch.js +1 -1
  111. package/dist/packages/canvas-adapter/virtualTable.d.ts +37 -7
  112. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  113. package/dist/packages/core/aggregates.d.ts +14 -0
  114. package/dist/packages/core/aggregates.js +1 -1
  115. package/dist/packages/core/dies.d.ts +7 -0
  116. package/dist/packages/core/dies.js +1 -1
  117. package/dist/packages/core/utils.d.ts +2 -0
  118. package/dist/packages/core/utils.js +1 -1
  119. package/dist/packages/experimental/charts.d.ts +4 -0
  120. package/dist/packages/experimental/charts.js +1 -0
  121. package/dist/packages/renderer/binColors.d.ts +6 -2
  122. package/dist/packages/renderer/binColors.js +1 -1
  123. package/dist/packages/renderer/buildView.d.ts +36 -14
  124. package/dist/packages/renderer/buildView.js +1 -1
  125. package/dist/packages/renderer/buildWaferMap.d.ts +8 -0
  126. package/dist/packages/renderer/buildWaferMap.js +1 -1
  127. package/dist/packages/renderer/categoryColors.d.ts +3 -0
  128. package/dist/packages/renderer/categoryColors.js +1 -0
  129. package/dist/packages/renderer/colorMap.d.ts +15 -16
  130. package/dist/packages/renderer/colorMap.js +1 -1
  131. package/dist/packages/renderer/colorSchemes.d.ts +34 -30
  132. package/dist/packages/renderer/colorSchemes.js +1 -1
  133. package/dist/packages/renderer/dataColors.d.ts +126 -0
  134. package/dist/packages/renderer/dataColors.js +1 -0
  135. package/dist/packages/renderer/deprecate.js +1 -1
  136. package/dist/packages/renderer/fmt.d.ts +16 -0
  137. package/dist/packages/renderer/fmt.js +1 -1
  138. package/dist/packages/renderer/index.d.ts +2 -0
  139. package/dist/packages/renderer/index.js +1 -1
  140. package/dist/packages/renderer/spec.d.ts +5 -0
  141. package/dist/packages/renderer/spec.js +1 -1
  142. package/dist/packages/renderer/stacks.d.ts +21 -0
  143. package/dist/packages/renderer/stacks.js +1 -0
  144. package/dist/packages/renderer/timeAxis.d.ts +19 -0
  145. package/dist/packages/renderer/timeAxis.js +1 -0
  146. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  147. package/dist/packages/stats/analyzeWaferMap.d.ts +2 -4
  148. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  149. package/dist/packages/stats/binRows.js +1 -1
  150. package/dist/packages/stats/binShifts.d.ts +59 -0
  151. package/dist/packages/stats/binShifts.js +1 -0
  152. package/dist/packages/stats/capability.d.ts +6 -1
  153. package/dist/packages/stats/capability.js +1 -1
  154. package/dist/packages/stats/chartCatalogue.d.ts +3 -0
  155. package/dist/packages/stats/chartCatalogue.js +1 -1
  156. package/dist/packages/stats/clusterDetection.js +1 -1
  157. package/dist/packages/stats/columnPlot.d.ts +38 -0
  158. package/dist/packages/stats/columnPlot.js +1 -0
  159. package/dist/packages/stats/commonality.d.ts +8 -1
  160. package/dist/packages/stats/commonality.js +1 -1
  161. package/dist/packages/stats/correlation.d.ts +7 -2
  162. package/dist/packages/stats/correlation.js +1 -1
  163. package/dist/packages/stats/dataTable.d.ts +44 -0
  164. package/dist/packages/stats/dataTable.js +1 -0
  165. package/dist/packages/stats/dieRegions.js +1 -1
  166. package/dist/packages/stats/examplePicks.js +1 -1
  167. package/dist/packages/stats/facets.d.ts +11 -0
  168. package/dist/packages/stats/facets.js +1 -1
  169. package/dist/packages/stats/filterFindings.d.ts +21 -0
  170. package/dist/packages/stats/filterFindings.js +1 -1
  171. package/dist/packages/stats/groupEffects.d.ts +8 -0
  172. package/dist/packages/stats/groupEffects.js +1 -1
  173. package/dist/packages/stats/math.d.ts +2 -0
  174. package/dist/packages/stats/math.js +1 -1
  175. package/dist/packages/stats/overview.d.ts +114 -0
  176. package/dist/packages/stats/overview.js +1 -0
  177. package/dist/packages/stats/pat.d.ts +0 -2
  178. package/dist/packages/stats/pat.js +1 -1
  179. package/dist/packages/stats/patternClassification.d.ts +20 -3
  180. package/dist/packages/stats/patternClassification.js +1 -1
  181. package/dist/packages/stats/permutationNull.d.ts +16 -0
  182. package/dist/packages/stats/permutationNull.js +1 -0
  183. package/dist/packages/stats/plotData.d.ts +138 -12
  184. package/dist/packages/stats/plotData.js +1 -1
  185. package/dist/packages/stats/plotSpec.d.ts +10 -1
  186. package/dist/packages/stats/plotSpec.js +3 -3
  187. package/dist/packages/stats/plotTable.js +1 -1
  188. package/dist/packages/stats/plotWords.d.ts +52 -0
  189. package/dist/packages/stats/plotWords.js +1 -0
  190. package/dist/packages/stats/presentation.d.ts +63 -14
  191. package/dist/packages/stats/presentation.js +1 -1
  192. package/dist/packages/stats/presentationPresets.d.ts +35 -0
  193. package/dist/packages/stats/presentationPresets.js +1 -0
  194. package/dist/packages/stats/presentationSections.d.ts +83 -0
  195. package/dist/packages/stats/presentationSections.js +1 -0
  196. package/dist/packages/stats/renderSummaryReport.d.ts +80 -2
  197. package/dist/packages/stats/renderSummaryReport.js +1 -67
  198. package/dist/packages/stats/reportBlocks.d.ts +249 -0
  199. package/dist/packages/stats/reportBlocks.js +1 -0
  200. package/dist/packages/stats/reportContents.d.ts +22 -0
  201. package/dist/packages/stats/reportContents.js +1 -0
  202. package/dist/packages/stats/reportDeck.d.ts +245 -0
  203. package/dist/packages/stats/reportDeck.js +212 -0
  204. package/dist/packages/stats/reportHtml.d.ts +44 -43
  205. package/dist/packages/stats/reportHtml.js +82 -46
  206. package/dist/packages/stats/reportMaps.d.ts +67 -0
  207. package/dist/packages/stats/reportMaps.js +1 -0
  208. package/dist/packages/stats/reportSections.d.ts +55 -0
  209. package/dist/packages/stats/reportSections.js +1 -0
  210. package/dist/packages/stats/sweep.d.ts +14 -6
  211. package/dist/packages/stats/sweep.js +1 -1
  212. package/dist/packages/stats/synthesis.d.ts +87 -10
  213. package/dist/packages/stats/synthesis.js +1 -1
  214. package/dist/packages/stats/types.d.ts +22 -0
  215. package/dist/packages/stats/worthItems.d.ts +15 -0
  216. package/dist/packages/stats/worthItems.js +1 -0
  217. package/dist/packages/stats/yield.d.ts +13 -0
  218. package/dist/packages/stats/yield.js +1 -1
  219. package/llms.txt +1 -1
  220. package/package.json +6 -1
@@ -1,10 +1,10 @@
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)??""}}}
1
+ import{WAFER_WORDS as Oe,isWaferWords as rt}from"../stats/plotWords.js";import{barsAddUp as Pt,combinationIssue as Bt,defaultSweep as Dt,describeTitleDrift as Wt,dieCountOf as zt,fieldKey as q,fieldsForRole as ct,titleDrift as Mt,withTestSetNames as dt}from"../stats/plotData.js";import{isBinned as U,isField as se,isPassRateSet as Ft,isStatReference as ut,isTestSet as Y,PLOT_REFERENCES_MAX as ft,PLOTS_FORMAT as It,PLOTS_VERSION as Jt,plotIssue as Vt,readPlot as _t,readPlotsFile as qt,syntaxErrorAt as Xt,sameField as X,xFieldsOf as Gt,PLOT_BINS_DEFAULT as Xe,PLOT_BINS_MAX as Ut,PLOT_BINS_MIN as Yt,PLOT_X_LEVELS as Ge}from"../stats/plotSpec.js";import{formatTestList as Kt,parseTestList as Ht}from"../stats/sweepText.js";import{ALPHA as je,CLR as A,FONT as F,RADIUS as Ue,SPACE as L,controlStyle as ne,wireControlHover as ie,wireTooltip as $e}from"./toolbar.js";import{inputStyle as Ee,makeListSelect as le,makeSegmented as I,makeToggle as pe}from"./charts/chartShell.js";export{Ee as inputStyle};import{buildFilterEditor as Qt}from"./filterEditor.js";import{attachJsonSuggestions as Zt}from"./plotJsonSuggest.js";import{copyText as ea,createTextHistory as ta}from"./plotJsonHistory.js";import{createSweepEditor as aa}from"./sweepEditor.js";import{listValueColorSchemes as pt}from"../renderer/colorSchemes.js";const Ye="\0follow",he="\0none",oa=h=>[["scatter","Scatter",`One point per ${h.item?`${h.item.one} or ${h.row.one}`:h.row.one}, 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 ${h.row.one} in order, against limits from its own ${h.row.one}-to-${h.row.one} variation, with the points that break a Western Electric rule marked`],["heatmap","Heatmap",rt(h)?"One cell per row and column, coloured by the value combined there: tests by wafer, bins by wafer, rings by split":`One cell per row and column, coloured by the value combined there, such as ${h.item?`${h.outcome.field.toLowerCase()} by ${h.row.one}`:"an amount by two groups"}`],["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"]],O="\0auto",Ke="\0count",He="\0set",sa=8,ht=[[O,"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"]],Ne={mean:"Mean",median:"Median",min:"Minimum",max:"Maximum",sum:"Sum",count:"Count",yield:"Yield (passing dies \xF7 tested dies)"};export function fieldRow(h,d,me,s){const Z=h.createElement("div");Object.assign(Z.style,{display:"flex",flexDirection:"column",gap:L.xxs,minWidth:"0"});const be=h.createElement("div");if(be.textContent=d,Object.assign(be.style,{fontSize:F.sub,color:A.label,fontWeight:"600"}),Z.append(be,me),s){const P=h.createElement("div");P.textContent=s,Object.assign(P.style,{fontSize:F.sub,color:A.label}),Z.appendChild(P)}return Z}export function createPlotEditor(h){const{doc:d}=h,me=e=>e.fields||e.chart==="sweep"?e:{...e,fields:{}};let s=me(h.plot);const Z=[["setup","Setup","Which fields to plot and how they are combined"],["customise","Customise","Titles, axis limits, scale and direction"],["json","JSON","The chart as text: copy it, paste one in, or edit it directly"]],be=()=>s.chart==="sweep"?Z.filter(e=>e[0]!=="customise"):Z;let P="setup",Re,Qe,ge="",Ae=[],ke=[];const _=d.createElement("div");_.dataset.wmapPlotEditor="1",Object.assign(_.style,{display:"flex",flexDirection:"column",gap:L.lg,minWidth:"0"});let ee;const ye=e=>{P!=="json"&&ee!==void 0&&(ee=void 0,ge="Your unapplied edits were dropped because the chart changed.",it(!1)),s=e,h.onChange(e)},E=e=>{const o=JSON.parse(JSON.stringify(s));e(o),ye(o)},b=(e,o,n)=>fieldRow(d,e,o,n),Ze=e=>{z(),_.querySelector(`[data-wmap-select="${e}"]`)?.focus()},te=(e,o)=>{E(o),Ze(e)},et=()=>{const e=s.fields?.color;return e&&"none"in e?!0:(e===void 0||"follow"in e)&&h.followLabel()===void 0&&!h.followsWafers?.()},re=e=>{if(Y(e))return{label:"Tests",level:"die",kind:"numeric",yield:!1};const o=e&&h.catalogue.find(n=>X(n.field,U(e)?e.binned:e));return o?{label:o.name,level:o.level,kind:e&&U(e)?"categorical":o.kind,yield:!(e&&U(e))&&"builtin"in o.field&&o.field.builtin==="yield",dieCount:!(e&&U(e))&&o.level==="wafer"&&!!zt(o.field)}:void 0},B=(e=s)=>[...Gt(e.fields?.x)],ce=(e,o)=>{o.length===0?delete e.fields.x:e.fields.x=o.length===1?o[0]:o},tt=e=>{const o=e.map(re).filter(n=>!!n);return o.find(n=>n.level==="die")??o[0]};function at(e,o,n=0){const a=s.fields??{},t=a.color&&!("follow"in a.color)&&!("none"in a.color)?a.color:void 0,i=B();e==="x"&&(i[n]=o.field);const l={x:tt(i),y:re(a.y),color:re(t)};e!=="x"&&(l[e]=re(o.field));const p=s.chart==="scatter"&&l.color?.kind==="numeric"&&!!t&&!("meta"in t);return Bt(s.chart,l,{aggregate:s.aggregate,level:s.level,continuousColor:p,words:h.words})?.short}const Pe=()=>h.catalogue.flatMap(e=>e.group==="Tests"&&"test"in e.field?[{testNumber:e.field.test,name:e.field.name??""}]:[]),ae=()=>Y(s.fields?.y)?s.fields.y:void 0,we=e=>!!e&&"builtin"in e&&e.builtin==="test",Be=(e,o=0)=>{const n=e==="x"?B()[o]:s.fields?.[e],a=n&&!("follow"in n)&&!("none"in n)?n:void 0,t=e==="x"?B().filter((l,p)=>p!==o):[],i=ct(h.catalogue,s.chart,e).filter(l=>(ae()||!we(l.field))&&!t.some(p=>X(p,l.field))).map(l=>{const p=a&&X(l.field,a)?void 0:at(e,l,o);return{value:q(l.field),label:l.label,group:l.groupLabel??l.group,...p?{disabled:p}:{}}});return e==="y"?i:[...i,...De(e,o)]},De=(e,o=0)=>{if(e==="x"&&!(s.chart==="box"||s.chart==="bar"||s.chart==="heatmap"))return[];if(e==="color"&&s.chart==="scatter")return[];const n=[...e==="x"?B().filter((a,t)=>t!==o):B(),...s.fields?.color&&se(s.fields.color)?[s.fields.color]:[]];return h.catalogue.filter(a=>a.kind==="numeric"&&!a.categorical&&a.group!=="Pass rates"&&!Y(a.field)&&!n.some(t=>X(t,a.field))).map(a=>{const t={binned:a.field},i=e==="facet"&&a.level==="die"&&s.level==="wafer"?`${a.name} is per ${(T.item??Oe.item).one}: this chart has one mark per ${T.row.one}`:e==="x"||e==="color"?at(e,{...a,field:t,kind:"categorical",categorical:!0},o):void 0;return{value:q(t),label:`${a.label} in ranges`,group:a.groupLabel??a.group,...i?{disabled:i}:{}}})},ve=e=>{const o=h.catalogue.find(a=>q(a.field)===e)?.field;if(o||!e.startsWith("binned:"))return o;const n=h.catalogue.find(a=>q({binned:a.field})===e)?.field;return n?{binned:n}:void 0};function Le(e,o,n,a){if(!o||!U(o))return e;const t=d.createElement("div");Object.assign(t.style,{display:"flex",flexDirection:"column",gap:L.xs,minWidth:"0"});const i=d.createElement("div");Object.assign(i.style,{display:"flex",gap:L.sm,alignItems:"center",minWidth:"0"});const l=G(o.bins??Xe,"Number of ranges",m=>{const c=m===void 0?Xe:Math.round(m);E(r=>a(r,u=>{c===Xe?delete u.bins:u.bins=Math.min(Ut,Math.max(Yt,c))})),z()});l.dataset.wmapPlotBins=n,l.style.width="64px";const p=d.createElement("span");p.textContent="ranges",Object.assign(p.style,{fontSize:F.sub,color:A.label});const v=I([["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"]],o.by??"count",m=>E(c=>a(c,r=>{m==="count"?delete r.by:r.by="width"})),d);return i.append(l,p,v),t.append(e,i),t}function J(e,o,n={}){const a=n.at??0,t=e==="x"?B()[a]:s.fields.y,i=Be(e,a);if(n.optional&&i.unshift({value:Ke,label:n.optional,group:"Count"}),e==="y"&&s.chart!=="scatter"&&Pe().length>=2&&i.unshift({value:He,label:"Several tests\u2026",group:"Several tests"}),t&&!Y(t)&&!i.some(c=>c.value===q(t))){const c=h.catalogue.some(u=>X(u.field,t)),r="test"in t?t.name??`Test ${t.test}`:"meta"in t?t.meta:"builtin"in t?t.builtin:"";i.unshift({value:q(t),label:`${r} (${c?"not usable here":"not in this lot"})`,group:"Saved"})}const p=t?Y(t)?He:q(t):n.optional?Ke:"",v=e==="x"&&a>0?`plot-x-${a+1}`:`plot-${e}`,m=le(i,p,c=>{if(c===Ke){te(v,g=>{delete g.fields[e]});return}if(c===He){ae()||(mt(),Ze(v));return}const r=ve(c)??t;if(!r)return;const u=e==="y"&&!!ae();te(v,g=>{if(e==="x"){const x=B(g);x[a]=r,ce(g,x)}else g.fields.y=r;if(!u)return;const y=B(g),w=y.filter(x=>!we(x));w.length!==y.length&&ce(g,w.length||!(g.chart==="box"||g.chart==="bar")?w:[{builtin:"wafer"}]),we(g.fields.color)&&delete g.fields.color})},{maxWidth:"100%",ownerDocument:d,ariaLabel:o,emptyText:"Choose a field\u2026",searchPlaceholder:"Filter fields\u2026",hook:v});return m.style.width="100%",m}function mt(){const e=Pe(),o=dt({tests:e.slice(0,sa).map(n=>n.testNumber)},e);E(n=>{n.fields.y=o;const a=B(n);(n.chart==="box"||n.chart==="bar")&&(a.length===0||a.length===1&&X(a[0],{builtin:"wafer"}))&&(n.fields.x={builtin:"test"})})}function bt(e){const o=d.createElement("div");Object.assign(o.style,{display:"flex",flexDirection:"column",gap:L.xxs});const n=d.createElement("input");n.type="text",n.value=Kt(e.tests),n.placeholder="1010, 1011, 1020..1030",n.setAttribute("aria-label","Tests"),n.dataset.wmapPlotTests="1",Object.assign(n.style,Ee(),{width:"100%",fontVariantNumeric:"tabular-nums"});const a=d.createElement("div");return a.setAttribute("role","alert"),Object.assign(a.style,{fontSize:F.sub,color:A.errText}),n.addEventListener("input",()=>{const t=Ht(n.value),i=t.ok?t.value.length===0?"Name at least one test":void 0:t.error;if(a.textContent=i??"",n.setAttribute("aria-invalid",String(!!i)),n.style.borderColor=i?A.errText:A.menuBorder,i||!t.ok)return;const l=t.value;E(p=>{p.fields.y=dt({tests:l},Pe())})}),n.addEventListener("keydown",t=>{t.key==="Escape"&&(t.stopPropagation(),n.blur())}),o.append(n,a),o}function ot(){const e=B(),o=d.createElement("div");o.dataset.wmapPlotLevels="1",Object.assign(o.style,{display:"flex",flexDirection:"column",gap:L.xs,minWidth:"0"});const n=c=>{const r=e[c];return(r&&h.catalogue.find(u=>X(u.field,r))?.name)??`level ${c+1}`},a=(c,r,u,g,y)=>{const w=d.createElement("button");return w.type="button",w.textContent=c,w.setAttribute("aria-label",r),w.dataset.wmapPlotLevel=u,w.disabled=g,$e(w,r),Object.assign(w.style,ne("outlined"),{minWidth:"28px",opacity:g?je.disabled:"1"}),ie(w),w.addEventListener("click",y),w},t=(...c)=>{z();for(const r of c){const u=_.querySelector(`[data-wmap-plot-level="${r}"]`);if(u&&!u.disabled){u.focus();return}}},i=(c,r)=>{E(g=>{const y=B(g);[y[c],y[c+r]]=[y[c+r],y[c]],ce(g,y)});const u=c+r;t(`${r<0?"out":"in"}:${u}`,`${r<0?"in":"out"}:${u}`)},l=Math.max(1,e.length);for(let c=0;c<l;c++){const r=d.createElement("div");Object.assign(r.style,{display:"flex",gap:L.xs,alignItems:"center",minWidth:"0"});const u=Le(J("x",l>1?`Categories, level ${c+1} of ${l}`:"Categories",{at:c}),e[c],`x-${c+1}`,(g,y)=>{const w=B(g),x=w[c];x&&U(x)&&(y(x),ce(g,w))});Object.assign(u.style,{flex:"1",minWidth:"0"}),r.appendChild(u),e.length>1&&r.append(a("\u2191",`Move ${n(c)} out a level`,`out:${c}`,c===0,()=>i(c,-1)),a("\u2193",`Move ${n(c)} in a level`,`in:${c}`,c===e.length-1,()=>i(c,1)),a("\xD7",`Remove ${n(c)} from the categories`,`remove:${c}`,!1,()=>{E(g=>{const y=B(g);y.splice(c,1),ce(g,y)}),t(`remove:${Math.min(c,e.length-2)}`),e.length-1<2&&_.querySelector('[data-wmap-select="plot-x"]')?.focus()})),o.appendChild(r)}const p=e.length<Ge&&e.length>0?Be("x",e.length).find(c=>!c.disabled):void 0,v=d.createElement("button");v.type="button",v.textContent="+ Add a level",v.dataset.wmapPlotLevelAdd="1",v.disabled=!p;const m=e.length>=Ge?`At most ${Ge} levels`:p?"Divide each category by another field, nested inside it":"No other field can divide these categories";return $e(v,m),Object.assign(v.style,ne("outlined"),{alignSelf:"flex-start",opacity:v.disabled?je.disabled:"1"}),ie(v),v.addEventListener("click",()=>{const c=p&&ve(p.value);c&&(E(r=>{ce(r,[...B(r),c])}),z(),_.querySelector(`[data-wmap-select="plot-x-${e.length+1}"]`)?.focus())}),o.appendChild(v),o}const We={},ze={},oe=(e,o)=>h.plain?o:e,T=h.words??Oe,xe=rt(T),Te=T.item?.many??"items",Me=T.rate.toLowerCase(),Fe=oa(T),gt=h.charts?h.charts.flatMap(e=>Fe.filter(o=>o[0]===e)):Fe,st=()=>b("Chart type",I(gt,s.chart,e=>yt(e),d,!0));function yt(e){const o=s.chart==="sweep";if(e==="sweep"){if(o)return;const{id:n,title:a,chart:t,...i}=s;Re=i,ye({id:n,...a?{title:a}:{},chart:"sweep",sweep:Qe??Dt(h.testDefs??[],n).sweep}),z();return}if(o){const{id:n,title:a,sweep:t}=s;Qe=t,ye({id:n,...a?{title:a}:{},...Re??{},chart:e,fields:Re?.fields??{}})}E(n=>{n.chart=e;for(const a of["x","y"]){const t=ct(h.catalogue,e,a),i=c=>!!c&&(Y(c)?a==="y"&&e!=="scatter":U(c)?a==="x"&&(e==="box"||e==="bar"||e==="heatmap"):t.some(r=>X(r.field,c))),l=c=>Array.isArray(c)?(e==="box"||e==="bar")&&c.every(i):i(c),p=n.fields[a];if(p&&!l(p)&&((Array.isArray(p)||!X(p,ze[a]))&&(We[a]=p),delete n.fields[a]),n.fields[a]||a==="y"&&(e==="bar"||e==="goal"||e==="heatmap"))continue;const v=We[a];if(l(v)){a==="x"?n.fields.x=v:n.fields.y=v,delete We[a],delete ze[a];continue}const m=a==="x"&&(e==="box"||e==="bar"||e==="heatmap")?{builtin:"wafer"}:a==="x"&&(e==="line"||e==="control")?t.find(c=>c.group==="Wafer")?.field??t[0]?.field:t[0]?.field;m&&!(a==="x"&&(e==="histogram"||e==="probability"||e==="goal"))&&(n.fields[a]=m,ze[a]=m)}}),z()}function wt(){if(s.chart==="heatmap"||s.chart==="bar"&&s.colorBars==="value")return!0;const e=s.fields?.color;return s.chart==="scatter"&&!!e&&se(e)&&re(e)?.kind==="numeric"}function vt(){const o=le([{value:O,label:"None"},{value:"value",label:"By their value"},{value:"shortfall",label:"Short of the overall yield"}],s.colorBars??O,n=>te("plot-color-bars",a=>{n===O?delete a.colorBars:a.colorBars=n}),{maxWidth:"100%",ownerDocument:d,ariaLabel:"Colour bars",hook:"plot-color-bars"});return o.style.width="100%",b("Colour bars",o,"By their value: each bar coloured on a key, as a heatmap cell is (a yield or count is quiet when nothing is wrong and warmer the further from it). Short of the overall yield, for a yield or pass rate: bars keep their colour, and a bar 1, 2, or 4 or more points below the yield of all the bars together turns orange, stronger the further below.")}function xt(){const e=d.createElement("div");Object.assign(e.style,{display:"flex",flexDirection:"column",gap:L.md});const o=[{value:O,label:"Automatic"},...pt().map(t=>({value:t.name,label:t.label}))],n=s.colorGradient&&o.some(t=>t.value===s.colorGradient)?s.colorGradient:O,a=le(o,n,t=>E(i=>{t===O?delete i.colorGradient:i.colorGradient=t}),{maxWidth:"100%",ownerDocument:d,ariaLabel:"Colours",hook:"plot-colours"});return a.style.width="100%",e.appendChild(b("Colour scale",a,"Automatic: a yield, pass rate or count is quiet when nothing is wrong and warmer the further from it; values rescaled around zero run blue to orange; any other value takes your value colours from the Colour scheme menu. Cividis is made for colour-blind readers.")),e.appendChild(pe("Reverse colours",!!s.colorReverse,t=>E(i=>{t?i.colorReverse=!0:delete i.colorReverse}),d)),e}function Ct(){const e=!!s.fields.y&&"builtin"in s.fields.y&&s.fields.y.builtin==="yield",o=[{value:O,label:"Automatic"},...["mean","median","min","max","sum","count"].map(a=>({value:a,label:e&&a==="mean"?`Average of ${T.row.one} ${Me}s`:Ne[a]}))];e&&o.push({value:"yield",label:h.plain?`${T.rate} of all the ${Te} together`:Ne.yield});const n=le(o,s.aggregate??O,a=>{_e=!0,te("plot-aggregate",t=>{a===O?delete t.aggregate:t.aggregate=a})},{maxWidth:"100%",ownerDocument:d,ariaLabel:"Combine values by",hook:"plot-aggregate"});return n.style.width="100%",n}function St(){const e=s.fields.color,o=h.followLabel(),n=[{value:Ye,label:o?`Follow Group by (${o})`:h.followsWafers?.()?"Wafer (no Group by is set)":"Single colour (no Group by is set)",group:"Colour"},{value:he,label:"None: one colour, no legend",group:"Colour"},...Be("color")],a=e===void 0||"follow"in e?Ye:"none"in e?he:q(e),t=le(n,a,i=>{te("plot-color",l=>{if(i===Ye)delete l.fields.color;else if(i===he)l.fields.color={none:!0};else{const p=ve(i);p&&(l.fields.color=p)}})},{maxWidth:"100%",ownerDocument:d,ariaLabel:"Colour",searchPlaceholder:"Filter fields\u2026",hook:"plot-color"});return t.style.width="100%",Le(t,e&&se(e)?e:void 0,"color",(i,l)=>{const p=i.fields.color;p&&se(p)&&U(p)&&l(p)})}function Ot(){const e=s.fields.rows,o=h.catalogue.filter(t=>t.categorical&&!B().some(i=>X(i,t.field))&&(!we(t.field)||ae())).map(t=>({value:q(t.field),label:t.label,group:t.groupLabel??t.group}));o.push(...De("rows"));const n=e?q(e):ae()?q({builtin:"test"}):"",a=le(o,n,t=>{const i=ve(t);i&&te("plot-rows",l=>{l.fields.rows=i})},{maxWidth:"100%",ownerDocument:d,ariaLabel:"Rows",emptyText:"Choose a field\u2026",searchPlaceholder:"Filter fields\u2026",hook:"plot-rows"});return a.style.width="100%",Le(a,e,"rows",(t,i)=>{const l=t.fields.rows;l&&U(l)&&i(l)})}function $t(){const e=s.fields.facet,o=[...B(),...s.fields.color&&se(s.fields.color)?[s.fields.color]:[]],n=[{value:he,label:"None",group:"Panels"}];for(const i of h.catalogue){if(!i.categorical||o.some(p=>X(p,i.field))||we(i.field)&&!ae())continue;const l=i.level==="die"&&s.level==="wafer"?`${i.name} is per ${(T.item??Oe.item).one}: this chart has one mark per ${T.row.one}`:void 0;n.push({value:q(i.field),label:i.label,group:i.groupLabel??i.group,...l?{disabled:l}:{}})}n.push(...De("facet"));const a=e?q(e):he,t=le(n,a,i=>{te("plot-facet",l=>{if(i===he)delete l.fields.facet;else{const p=ve(i);p&&(l.fields.facet=p)}})},{maxWidth:"100%",ownerDocument:d,ariaLabel:"Panels",searchPlaceholder:"Filter fields\u2026",hook:"plot-facet"});return t.style.width="100%",Le(t,e,"facet",(i,l)=>{const p=i.fields.facet;p&&U(p)&&l(p)})}function Et(){const e=Qt({words:h.words,doc:d,catalogue:h.catalogue,filter:s.where,testDefs:h.testDefs,attributes:h.attributes,switchLabel:"Filter this chart",valuesOf:o=>h.valuesOf?.(o)??[],extentOf:o=>h.extentOf?.(o),onChange:o=>E(n=>{o?n.where=o:delete n.where})});return e.el.dataset.wmapPlotWhere="1",e.el}function Ie(e,o,n,a){const t=d.createElement("input");return t.type="text",t.value=e,t.placeholder=o,t.setAttribute("aria-label",n),Object.assign(t.style,Ee(),{width:"100%"}),t.addEventListener("input",()=>a(t.value)),t.addEventListener("keydown",i=>{i.key==="Escape"&&(i.stopPropagation(),t.blur())}),t}function G(e,o,n){const a=d.createElement("input");a.type="text",a.inputMode="decimal",a.value=e===void 0?"":String(e),a.placeholder="auto",a.setAttribute("aria-label",o),Object.assign(a.style,Ee(),{width:"100%",fontVariantNumeric:"tabular-nums"});const t=()=>{const i=a.value.trim();if(i===""){n(void 0);return}const l=Number(i);Number.isFinite(l)?n(l):a.value=e===void 0?"":String(e)};return a.addEventListener("change",t),a.addEventListener("keydown",i=>{i.key==="Enter"&&t(),i.key==="Escape"&&(i.stopPropagation(),a.value=e===void 0?"":String(e),a.blur())}),a}function nt(e,o,n,a){const t=s.axes?.[e]??{},i=x=>E(j=>{j.axes=j.axes??{};const N=j.axes[e]=j.axes[e]??{};x(N);for(const S of Object.keys(N))(N[S]===void 0||N[S]===""||S==="reverse"&&N[S]===!1)&&delete N[S];Object.keys(N).length===0&&delete j.axes[e],Object.keys(j.axes).length===0&&delete j.axes}),l=d.createElement("div");Object.assign(l.style,{display:"flex",flexDirection:"column",gap:L.md,padding:L.lg,border:`1px solid ${A.menuBorder}`,borderRadius:Ue.control});const p=d.createElement("div");p.textContent=e==="x"?"Horizontal axis":"Vertical axis",Object.assign(p.style,{fontSize:F.body,fontWeight:"600",color:A.value}),l.appendChild(p);const v=d.createElement("div");v.textContent=o.replace(/ axis$/,""),Object.assign(v.style,{fontSize:F.sub,color:A.label,marginTop:`-${L.sm}`}),l.appendChild(v);const m=Ie(t.label??"",n??"",`${o} title`,x=>i(j=>{j.label=x.trim()===""?void 0:x}));if(m.dataset.wmapPlotAxisTitle=e,l.appendChild(b("Title",m)),a.limits===!1)return l;const c=d.createElement("div");if(Object.assign(c.style,{display:"grid",gridTemplateColumns:"1fr 1fr",gap:L.md}),c.append(b("Minimum",G(t.min,`${o} minimum`,x=>i(j=>{j.min=x}))),b("Maximum",G(t.max,`${o} maximum`,x=>i(j=>{j.max=x})))),l.appendChild(c),a.scale&&l.appendChild(b("Scale",I([["linear","Linear"],["log","Log"]],t.scale??"linear",x=>i(j=>{j.scale=x==="log"?"log":void 0}),d))),l.appendChild(pe("Reverse direction",!!t.reverse,x=>i(j=>{j.reverse=x}),d)),a.references===!1)return l;const r=d.createElement("div");r.dataset.wmapPlotRefs=e,Object.assign(r.style,{display:"flex",flexDirection:"column",gap:L.sm});let u=[...t.references??[]];const g=()=>i(x=>{x.references=u.length?u.map(j=>({...j})):void 0}),y=(x,j,N)=>{const S=d.createElement("button");return S.type="button",S.textContent=x,$e(S,j),Object.assign(S.style,ne("outlined")),ie(S),S.addEventListener("click",N),S},w=()=>{r.replaceChildren(),u.forEach((S,D)=>{const f=d.createElement("div");f.dataset.wmapPlotRef=String(D),Object.assign(f.style,{display:"flex",gap:L.sm,alignItems:"center"});const C=d.createElement("span");C.textContent=ut(S)?S.stat==="median"?"Median":"Mean":S.to!==void 0?"Band":"Line",Object.assign(C.style,{fontSize:F.sub,color:A.label,minWidth:"4.5em"}),f.appendChild(C);const $=D+1;if(!ut(S)){const W=G(S.at,`${o} reference ${$} ${S.to!==void 0?"from":"value"}`,M=>{if(M===void 0)return;const R=u[D];u[D]=R.to!==void 0?{...R,at:Math.min(M,R.to),to:Math.max(M,R.to)}:{...R,at:M},g()});if(W.placeholder="",f.appendChild(W),S.to!==void 0){const M=G(S.to,`${o} reference ${$} to`,R=>{if(R===void 0)return;const ue=u[D];R!==ue.at&&(u[D]={...ue,at:Math.min(ue.at,R),to:Math.max(ue.at,R)},g())});M.placeholder="",f.appendChild(M)}}const Q=Ie(S.label??"","Name (optional)",`${o} reference ${$} name`,W=>{const{label:M,...R}=u[D];u[D]=W.trim()===""?R:{...R,label:W},g()});f.appendChild(Q),f.appendChild(y("\xD7",`Remove ${C.textContent.toLowerCase()} ${$}`,()=>{u=u.filter((W,M)=>M!==D),g(),w()})),f.lastElementChild.setAttribute("aria-label",`Remove reference ${$}`),r.appendChild(f)});const x=d.createElement("div");Object.assign(x.style,{display:"flex",gap:L.sm,flexWrap:"wrap"});const j=u.length>=ft,N=[["Add line","A line at a value",{at:0}],["Add band","A shaded band between two values",{at:0,to:1}],["Add median","A line at the median of what the plot draws",{stat:"median"}],["Add mean","A line at the mean of what the plot draws",{stat:"mean"}]];for(const[S,D,f]of N){const C=y(S,D,()=>{u=[...u,{...f}],g(),w()});j&&(C.disabled=!0,C.style.opacity=je.disabled),x.appendChild(C)}r.appendChild(x),j&&r.appendChild(Object.assign(d.createElement("div"),{textContent:`At most ${ft} lines or bands on an axis.`}))};return w(),l.appendChild(b("Reference lines",r,"Lines and shaded bands at values, in the axis\u2019s own unit, and lines at the median or mean of what the plot draws.")),l}const it=e=>{const o=_.querySelector('[role="tab"][data-tab="json"]');o&&(o.textContent=e?"JSON \u2022":"JSON",e?o.setAttribute("aria-label","JSON, edits not applied"):o.removeAttribute("aria-label"))},At=e=>_.querySelector(`[role="tab"][data-tab="${e}"]`);let Ce,H;const Je=new Map;function Ve(){if(!H)return;const e=Wt(Mt(s,h.catalogue));if(H.replaceChildren(),H.style.display=e?"flex":"none",!e)return;const o=d.createElement("span");o.textContent=e;const n=d.createElement("button");n.type="button",n.textContent="Use the automatic title",n.dataset.wmapPlotAutoTitle="1",Object.assign(n.style,ne("outlined")),ie(n),n.addEventListener("click",()=>{E(a=>{delete a.title}),z()}),H.append(o,n)}function kt(){const e=d.createElement("div");Object.assign(e.style,{display:"flex",flexDirection:"column",gap:L.sm});const o=d.createElement("textarea");o.dataset.wmapPlotJson="1";const n=f=>{const{id:C,...$}=f;return JSON.stringify($,null,2)};o.value=ee??n(s),o.spellcheck=!1,o.rows=18,o.setAttribute("aria-label","Chart as JSON"),Object.assign(o.style,{...Ee(),fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:F.sub,width:"100%",boxSizing:"border-box",resize:"vertical",whiteSpace:"pre",overflow:"auto"});const t=Zt({doc:d,area:o,source:()=>({tests:h.testDefs?.map(f=>({number:f.testNumber,name:f.name})),gradients:pt(),metaKeys:h.catalogue.flatMap(f=>"meta"in f.field?[{key:f.field.meta,label:f.name}]:[]),describe:(f,C)=>{if(f==="chart")return Fe.find($=>$[0]===C)?.[2];if(f==="aggregate")return Ne[C];if(f==="normalize")return ht.find($=>$[0]===C)?.[2];if(f==="builtin")return h.catalogue.find($=>"builtin"in $.field&&$.field.builtin===C)?.name;if(f==="level")return C==="die"?"One mark per die":"One mark per wafer"}})}),i=ta(o),l=f=>{o.focus(),o.select(),d.execCommand?.("insertText",!1,f)||(o.value=f,o.dispatchEvent(new Event("input",{bubbles:!0}))),o.setSelectionRange(0,0)},p=d.createElement("div");p.append(o,t.el);const v=d.createElement("div");Object.assign(v.style,{display:"flex",flexDirection:"column",gap:L.xs,alignItems:"flex-start"});const m=d.createElement("div");m.setAttribute("role","status"),m.setAttribute("aria-live","polite"),Object.assign(m.style,{fontSize:F.sub,minHeight:"1.4em",whiteSpace:"pre-wrap"});const c=(f,C)=>{const $=d.createElement("button");return $.type="button",$.textContent=f,$e($,C),Object.assign($.style,ne("outlined")),ie($),$},r=c("Apply","Use this text as the chart");r.dataset.wmapPlotJsonApply="1";const u=c("Copy","Copy the text to the clipboard"),g=c("Suggest","Show what can be written at the cursor (also Ctrl/Cmd+Space)");g.dataset.wmapPlotJsonSuggest="1",g.addEventListener("click",()=>{t.show()||(m.style.color=A.label,m.textContent="Nothing to suggest at the cursor")});const y=c("Discard edits","Put the text back as the chart stands, dropping what is not applied");y.dataset.wmapPlotJsonDiscard="1";const w=()=>{let f;try{f=JSON.parse(o.value)}catch(k){return{problem:`Not valid JSON: ${Xt(o.value,k instanceof Error?k.message:String(k))}`,dropped:[]}}const C=[];let $;if(Array.isArray(f)||typeof f=="object"&&f!==null&&!("chart"in f)&&("plots"in f||"sweeps"in f||"format"in f)){const k=qt(Array.isArray(f)?JSON.stringify({format:It,version:Jt,plots:f}):o.value);if(k.error)return{problem:[k.error,...k.warnings].join(`
2
+ `),dropped:[]};if(k.plots.length>1)return{choices:k.plots,dropped:k.warnings};if(C.push(...k.warnings),$=k.plots[0]??null,!$)return{problem:C.join(`
3
+ `)||"The file holds no charts",dropped:[]}}else if($=_t(f,"chart",C),!$)return{problem:C.map(k=>k.replace(/, skipped$/,"")).join(`
4
+ `)||"Not a chart",dropped:[]};const W=k=>typeof k=="object"&&k!==null&&!Array.isArray(k),M=(k,V,Se)=>{if(!W(k)||!W(V)||!("name"in V)||V.name!==k.name)return V;for(const fe of["test","passRate"])if(fe in k&&fe in V&&k[fe]!==V[fe]){C.push(`${Se}.name: the test number changed, so its old name "${String(V.name)}" is left out`);const{name:qe,...Rt}=V;return Rt}return V},R={...$.fields??{}},ue=s.fields??{};for(const k of["x","y","color","rows","facet"]){const V=R[k],Se=ue[k];Array.isArray(V)?R[k]=V.map((fe,qe)=>M(Array.isArray(Se)?Se[qe]:void 0,fe,`fields.${k} ${qe+1}`)):V!==void 0&&(R[k]=M(Se,V,`fields.${k}`))}$.fields=R;const lt=me({...$,id:s.id});return{plot:lt,dropped:C.filter(k=>!/no id, given a new one/.test(k)),issue:Vt(lt)}},x=()=>{const f=w(),C=o.value!==n(s);if(ee=C?o.value:void 0,it(C),r.disabled=!f.plot||!C,r.style.opacity=r.disabled?"0.5":"",r.style.fontWeight=r.disabled?"":"700",v.replaceChildren(),f.choices){m.style.color=A.label,m.textContent=[`This is a charts file with ${f.choices.length} charts, and this editor holds one chart. Choose the one to use:`,...f.dropped].join(`
5
+ `),f.choices.forEach((W,M)=>{const R=c(`${M+1}. ${W.title||`${W.chart[0].toUpperCase()}${W.chart.slice(1)} chart`}`,"Use this chart from the file");R.dataset.wmapPlotJsonChoice=String(M),R.addEventListener("click",()=>l(n(W))),v.appendChild(R)});return}if(!f.plot){m.style.color=A.errText,m.textContent=f.problem??"";return}const $=!C,Q=[...f.dropped.length?[`Applying would leave out or ignore:
6
+ ${f.dropped.join(`
7
+ `)}`]:[],...f.issue?[`It could not be drawn: ${f.issue}`]:[]];m.style.color=Q.length?A.errText:A.label,m.textContent=Q.length?Q.join(`
8
+ `):$?ge||"The chart as it stands":"Edited: not applied yet. Press Apply to use it."};o.addEventListener("input",()=>{ge="",x()});const j=(f,C)=>{Ae.push(JSON.parse(JSON.stringify(s))),ke=[],N(f,C)},N=(f,C)=>{ge=C,ee=void 0,ye(f),z(),_.querySelector("[data-wmap-plot-json]")?.focus()};r.addEventListener("click",()=>{const f=w();f.plot&&j(f.plot,f.dropped.length?`Applied. Left out:
9
+ ${f.dropped.join(`
10
+ `)}`:"Applied")}),o.addEventListener("keydown",f=>{if(!(f.ctrlKey||f.metaKey)||f.altKey)return;const C=f.key.toLowerCase(),$=C==="z"&&!f.shiftKey,Q=C==="z"&&f.shiftKey||C==="y";if(!$&&!Q)return;if($?i.canUndo:i.canRedo){f.preventDefault(),$?i.undo():i.redo();return}if(o.value!==n(s))return;const W=$?Ae:ke;W.length&&(f.preventDefault(),($?ke:Ae).push(JSON.parse(JSON.stringify(s))),N({...W.pop(),id:s.id},$?"Undone":"Redone"))}),y.addEventListener("click",()=>{ge="",l(n(s))}),u.addEventListener("click",()=>{const f=C=>{m.style.color=C?A.label:A.errText,m.textContent=C?"Copied":"The text could not be copied: select it and copy by hand"};ea(d,o.value,f)});const S=d.createElement("div");Object.assign(S.style,{display:"flex",gap:L.sm}),S.append(r,y,g,u);const D=d.createElement("div");return D.textContent="The whole chart as text. Settings take effect when you press Apply.",Object.assign(D.style,{fontSize:F.sub,color:A.label}),e.append(D,b("Chart as JSON",p,"Suggestions open as you type, after a comma or brace, or with the Suggest button or Ctrl/Cmd+Space. The format of a saved charts file, for one chart; a charts file can be pasted too, and offers a choice when it holds several charts. Ctrl/Cmd+Z undoes an Apply. The id is not part of the text."),S,m,v),x(),e}function de(e,o,n){const a=[...e.querySelectorAll("input, button")].filter(i=>!n||n.includes(i.value));for(const i of a){i.disabled=!0,i.setAttribute("aria-disabled","true");const l=i.closest("label")??i;l.style.opacity=je.disabled,l.style.cursor="not-allowed"}const t=d.createElement("div");return t.dataset.wmapPlotWhyDisabled="1",t.textContent=o,Object.assign(t.style,{fontSize:F.sub,color:A.label}),e.appendChild(t),e}function Lt(){const e=s.fields?.color;if(e&&"none"in e)return;const o=e===void 0||"follow"in e?h.followLabel()===void 0&&h.followsWafers?.()?{builtin:"wafer"}:void 0:e;if(!o||!se(o))return;const n=B();if(n.length===1&&X(n[0],o))return"The colour repeats the X axis: each value keeps its colour, and its chip above the chart shows or hides it. Choose None for one colour.";const a=h.valuesOf?.(o);if(a&&a.length>25)return"Many colours are hard to tell apart. The legend scrolls."}function Tt(e){const o=d.createElement("div");return o.dataset.wmapPlotColourNote="1",o.textContent=e,Object.assign(o.style,{fontSize:F.sub,color:A.warnText,background:A.warnBg,border:`1px solid ${A.warnBorder}`,borderRadius:Ue.control,padding:`${L.sm} ${L.md}`}),o}let _e;function jt(){const e=[];return s.aggregate&&e.push(`combine by ${(Ne[s.aggregate]??s.aggregate).toLowerCase()}`),s.level&&e.push(`one mark per ${s.level}`),s.whatIf&&e.push("what-if limits"),e.join(", ")}function K(e,o,n){const a=d.createElement("div");a.setAttribute("role","group"),a.dataset.wmapPlotSection=o,Object.assign(a.style,{display:"flex",flexDirection:"column",gap:L.lg});const t=d.createElement("div");return t.id=`wmap-plot-section-${o}-${Math.random().toString(36).slice(2,8)}`,t.textContent=e,Object.assign(t.style,{fontSize:F.body,fontWeight:"700",color:A.value,borderBottom:`1px solid ${A.menuBorder}`,paddingBottom:L.xs}),a.setAttribute("aria-labelledby",t.id),a.append(t,...n),a}function Nt(e,o){if(o.data.length&&e.appendChild(K("Data","data",o.data)),o.split.length&&e.appendChild(K("Split and colour","split",o.split)),o.filter.length&&e.appendChild(K("Filter","filter",o.filter)),o.layout.length&&e.appendChild(K("Layout","layout",o.layout)),o.advanced.length){const n=jt(),a=_e??n!=="",t=d.createElement("div");t.dataset.wmapPlotSection="advanced",Object.assign(t.style,{display:"flex",flexDirection:"column",gap:L.lg});const i=d.createElement("div");i.setAttribute("role","group"),Object.assign(i.style,{display:a?"flex":"none",flexDirection:"column",gap:L.lg}),i.append(...o.advanced);const l=d.createElement("button");l.type="button",l.dataset.wmapPlotAdvanced="1",l.setAttribute("aria-expanded",String(a)),l.textContent=`${a?"\u25BE":"\u25B8"} Advanced${n?`: ${n}`:""}`,Object.assign(l.style,{...ne("bare"),textAlign:"left",fontWeight:"700",color:A.value,borderBottom:`1px solid ${A.menuBorder}`,borderRadius:"0",paddingLeft:"0"}),ie(l,"bare"),l.addEventListener("click",()=>{_e=!a,z()}),t.append(l,i),e.appendChild(t)}}function z(){_.replaceChildren(),s.chart==="sweep"&&P==="customise"&&(P="setup"),P!=="json"&&(Ae=[],ke=[]),Je.clear();const e=d.createElement("div");e.setAttribute("role","tablist"),Object.assign(e.style,{display:"flex",gap:L.sm,borderBottom:`1px solid ${A.menuBorder}`});const o=be();for(const[a,t,i]of o){const l=d.createElement("button");l.type="button",l.textContent=a==="json"&&ee!==void 0?"JSON \u2022":t,a==="json"&&ee!==void 0&&l.setAttribute("aria-label","JSON, edits not applied"),$e(l,i),l.setAttribute("role","tab"),l.dataset.tab=a,l.setAttribute("aria-selected",String(P===a)),Object.assign(l.style,{...ne("bare"),padding:`${L.sm} ${L.lg}`,fontSize:F.body,borderBottom:`2px solid ${P===a?A.iconActive:"transparent"}`,borderRadius:"0",color:P===a?A.iconActive:A.text,fontWeight:P===a?"600":"400"}),ie(l,"bare"),l.tabIndex=P===a?0:-1,l.addEventListener("click",()=>{P=a,z()}),l.addEventListener("keydown",p=>{if(p.key!=="ArrowLeft"&&p.key!=="ArrowRight")return;p.preventDefault();const v=o.findIndex(m=>m[0]===a);P=o[(v+(p.key==="ArrowRight"?1:o.length-1))%o.length][0],z(),At(P)?.focus()}),e.appendChild(l)}_.appendChild(e);const n=d.createElement("div");if(n.setAttribute("role","tabpanel"),Object.assign(n.style,{display:"flex",flexDirection:"column",gap:L.lg}),P==="json")n.appendChild(kt());else if(P==="setup"&&s.chart==="sweep")n.appendChild(st()),n.appendChild(aa({doc:d,plot:s,testDefs:h.testDefs,onChange:a=>ye(a)}).el);else if(P==="setup"){n.appendChild(st());const a={data:[],split:[],filter:[],layout:[],advanced:[]},t=(r,u)=>{a[r].push(u)},i=s.level==="wafer"?T.row.many:(T.item??Oe.item).many;switch(s.chart){case"scatter":t("data",b("X axis",J("x","X axis"))),t("data",b("Y axis",J("y","Y axis")));break;case"histogram":t("data",b("Values",J("y","Values")));break;case"control":t("data",b("Along (X axis)",J("x","Along"),`A ${T.row.one} field with a number per ${T.row.one}: ${T.row.one} order, slot, a date.`)),t("data",b("Values (Y axis)",J("y","Values"),oe("One value per wafer: a test\u2019s wafer mean (or as Combine values by says), a yield or a pass rate.",T.item?`One value per ${T.row.one}, such as its ${Me} or the number of ${Te} counted.`:`One value per ${T.row.one}, from one of the columns (a count or an amount).`))),t("data",b("Limits from the first",G(s.baseline,"Wafers the limits are set from",r=>E(u=>{r===void 0||!Number.isInteger(r)||r<3?delete u.baseline:u.baseline=r})),`${T.row.many[0].toUpperCase()}${T.row.many.slice(1)}, at least 3. Empty sets the limits from every ${T.row.one}.`));break;case"heatmap":t("data",b("Columns (X axis)",J("x","Columns"),`One column per value: ${T.row.one}, split, site\u2026`)),t("data",b("Rows",Ot(),"One row per value. With several tests as the values, Test gives a row per test.")),t("data",b("Values (colour)",J("y","Values",{optional:`Count of ${i}`}),`What each cell\u2019s colour shows, combined over its ${(T.item??Oe.item).many} or ${T.row.many}.`));break;case"goal":t("data",b("Tests",J("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("data",b("Values (X axis)",J("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("data",b("Categories (X axis)",ot(),oe("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.",`Compare by this field: one box per value, such as ${xe?"a product, a lot or a date":"a group or a date"}. Add a level to nest another inside it: the first level is the outer group.`))),t("data",b("Values (Y axis)",J("y","Values")));break;case"bar":t("data",b("Categories (X axis)",ot(),oe("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.",`Compare by this field: one bar per value, such as ${xe?"a product, a lot or a date":"a group or a date"}. Add a level to nest another inside it: the first level is the outer group.`))),t("data",b("Values (Y axis)",J("y","Values",{optional:`Count of ${i}`})));break;case"line":t("data",b("X axis",J("x","X axis"),"A line joins the value at each X.")),t("data",b("Y axis",J("y","Y axis")));break}const l=ae();l&&s.chart!=="scatter"&&(t("data",b("Which tests",bt(l),"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.")),(s.chart==="bar"||s.chart==="line")&&t("data",b("Read as",I([[O,"Values","Each test\u2019s measured values"],["passRate","Pass rates","Each test\u2019s share of judged dies that pass it"]],l.passRate?"passRate":O,r=>{E(u=>{const g=u.fields.y;if(!Y(g))return;const y={...g};r===O?(delete y.passRate,delete y.judge):(y.passRate=!0,delete u.normalize),u.fields.y=y}),z()},d))));const p=s.fields.y;p&&(Ft(p)||!Y(p)&&"passRate"in p)&&t("data",b("Judged by",I([[O,"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"]],p.judge??O,r=>E(u=>{const g={...u.fields.y};r===O?delete g.judge:g.judge="flag",u.fields.y=g}),d),"A functional test is judged by its recorded verdict either way.")),t("split",b("Split and colour by",St(),oe("Each value gets its own colour and a legend chip: click a chip to show or hide that value. Follow Group by takes it from the Group by control.",`Each value gets its own colour and a legend chip: click a chip to show or hide that value, such as ${xe?"a bin, a lot or a product":`a group${T.item?` or ${T.outcome.field.toLowerCase()}`:""}`}.`)));const v=Lt();v&&t("split",Tt(v)),t("filter",b("Filter",Et(),oe("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.",xe?"Keep only what meets every condition: one product, wafers with yield below 90%, or only the dies in some bins. A condition on a wafer column (product, lot, yield) keeps whole wafers.":`Keep only what meets every condition: one group, or ${T.row.many} above or below a value${T.item?`, or only the ${Te} with some ${T.outcome.field.toLowerCase()}`:""}. A condition on a column keeps whole ${T.row.many}.`))),s.chart==="line"&&t("layout",b("Band",I([[O,"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"]],s.spread??O,r=>E(u=>{r===O?delete u.spread:u.spread=r}),d),"Round a line of means or medians.")),t("split",b("Split into charts by",$t(),oe("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.",xe?"One chart for each value of this field, side by side on the same scale: a product or a lot, for example.":"One chart for each value of this field, side by side on the same scale."))),s.chart==="scatter"&&(t("layout",b("Fit line",I([[O,"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)"]],s.fit??O,r=>E(u=>{r===O?delete u.fit:u.fit=r}),d),"One line per colour, with its equation, R\xB2 and n above the chart.")),t("layout",pe("y = x line",!!s.identity,r=>E(u=>{r?u.identity=!0:delete u.identity}),d))),s.chart==="histogram"&&(t("layout",b("Bars as",I([[O,"Counts"],["percent","Shares","Each colour\u2019s bars as a share of its own values, so groups of different size compare"]],s.histNorm==="percent"?"percent":O,r=>E(u=>{r===O?delete u.histNorm:u.histNorm="percent"}),d))),t("layout",pe("Normal curve",!!s.normalCurve,r=>E(u=>{r?u.normalCurve=!0:delete u.normalCurve}),d)));const m=s.fields.y;if((s.chart==="histogram"||s.chart==="probability")&&m&&"test"in m&&!s.normalize){const r=d.createElement("div");Object.assign(r.style,{display:"grid",gridTemplateColumns:"1fr 1fr",gap:L.md});const u=g=>y=>E(w=>{const x={...w.whatIf??{}};y===void 0?delete x[g]:x[g]=y,x.lo===void 0&&x.hi===void 0?delete w.whatIf:w.whatIf=x});r.append(b("Low",G(s.whatIf?.lo,"What-if low limit",u("lo"))),b("High",G(s.whatIf?.hi,"What-if high limit",u("hi")))),t("advanced",b("What-if limits",r,"In the test\u2019s own unit (V, A\u2026). The line under the chart gives the test\u2019s pass rate now and with these, and the dies that change."))}if(s.chart==="box"||s.chart==="bar"){t("layout",b("Orientation",I([[O,"Vertical","Categories along the bottom"],["horizontal","Horizontal","Categories down the left: for many categories or long names"]],s.orientation==="horizontal"?"horizontal":O,y=>E(w=>{y===O?delete w.orientation:w.orientation="horizontal"}),d)));const r=B().length<=1,u=b("Order",I([[O,"Field order",`The field\u2019s own order: ${T.row.many} as loaded, numbers by value, names naturally`],["value","Largest first",s.chart==="box"?"By median, largest first":"By value, largest first (a pareto)"],["ascending","Smallest first",s.chart==="box"?"By median, smallest first":"By value, smallest first (the worst pass rate at the top)"]],s.sort??O,y=>{E(w=>{y===O?(delete w.sort,delete w.cumulative):(w.sort=y,y==="ascending"&&delete w.cumulative)}),z()},d)),g=b("Show the first (number of categories)",G(s.top,"Categories shown",y=>E(w=>{y===void 0||!Number.isInteger(y)||y<1?delete w.top:w.top=y})),"Leave empty for every category; the rest are counted in a note.");if(t("layout",r?u:de(u,"Not available with nested levels.")),t("layout",r?g:de(g,"Not available with nested levels.")),s.chart==="bar"){const y=b("Bars",I([[O,"Side by side"],["share","Share of each colour\u2019s total","Side by side, each colour adding up to 100% across the bars, so groups of different sizes compare. It shows where a colour\u2019s values are, not what each bar is made of"],["stack","Stacked","One bar per category, its colours one on another"],["percent","100%","What each bar is made of: its colours add up to 100%"]],s.stack??(s.barNorm==="percent"?"share":O),N=>E(S=>{delete S.stack,delete S.barNorm,N==="share"?S.barNorm="percent":N!==O&&(S.stack=N)}),d),oe("Shares and stacking add values, so they need a count or a sum.",`Stacked and 100% add the colours up, so they work for a count of ${Te}, not for ${Me}.`)),w=s.fields?.color,x=[tt(B()),w&&se(w)?re(w):void 0].some(N=>N?.level==="die"),j=Pt(s.aggregate,s.fields?.y&&!Array.isArray(s.fields.y)?s.fields.y:void 0,x);if(j||de(y,"Stacked and 100% add values up, so they need a count or a sum. Change Combine values by (Advanced).",["stack","percent"]),et()&&de(y,"Choose a colour to split the bars first.",["share","stack","percent"]),t("layout",y),r){const N=pe("Cumulative line (pareto)",!!s.cumulative,S=>E(D=>{S?D.cumulative=!0:delete D.cumulative}),d);t("layout",!j&&!s.cumulative?de(N,"A cumulative line adds the bars up, so it needs a count or a sum. Change Combine values by (Advanced)."):s.sort==="value"?N:de(N,"Needs Order: Largest first."))}t("layout",pe("Values on the bars",!!s.valueLabels,N=>E(S=>{N?S.valueLabels=!0:delete S.valueLabels}),d,"Each bar\u2019s value at its end. Shown only when every value fits its bar, so none is left unlabelled."))}}const c=s.fields.y;s.chart!=="scatter"&&c&&(Y(c)||"test"in c)&&t("data",b("Rescale values",I(ht,s.normalize??O,r=>{E(u=>{r===O?delete u.normalize:u.normalize=r})},d),l?"Tests in different units share one axis only once they are rescaled.":void 0)),(s.chart==="bar"||s.chart==="line"||s.chart==="control"||s.chart==="heatmap"||s.level==="wafer")&&t("advanced",b("Combine values by",Ct())),h.plain||t("advanced",b("One mark per",I([[O,"Automatic"],["die","Die"],["wafer","Wafer"]],s.level??O,r=>{E(u=>{r===O?delete u.level:u.level=r}),z()},d,!0),s.level==="wafer"?"Die-level values are combined per wafer.":"Automatic uses the finest level the chosen fields allow.")),Nt(n,a)}else{Ce=Ie(s.title??"",h.autoText().title,"Chart title",m=>{E(c=>{m.trim()===""?delete c.title:Object.assign(c,{title:m})}),Ve()}),Ce.dataset.wmapPlotTitle="1",H=d.createElement("div"),H.dataset.wmapPlotTitleDrift="1",Object.assign(H.style,{display:"none",flexDirection:"column",gap:L.sm,alignItems:"flex-start",padding:`${L.sm} ${L.md}`,background:A.warnBg,border:`1px solid ${A.warnBorder}`,borderRadius:Ue.control,color:A.warnText,fontSize:F.body});const a={title:[],axes:[],limits:[],scale:[],details:[]};a.title.push(b("Title",Ce),H),Ve(),s.chart==="bar"&&(!s.stack||et())&&a.scale.push(vt()),wt()&&a.scale.push(xt());const t=h.autoText(),i=s.chart==="box"||s.chart==="bar",l=s.chart==="probability",p=m=>{switch(s.chart){case"scatter":case"line":return!0;case"histogram":case"probability":return m==="x";case"box":case"bar":case"control":return m==="y";default:return!1}};a.axes.push(nt("x",s.chart==="histogram"||l?"Values axis":i?"Categories axis":"X axis",t.x,{scale:!i,limits:!i,references:p("x")})),a.axes.push(nt("y",s.chart==="histogram"?"Count axis":l?"Cumulative share axis":i||s.chart==="line"?"Values axis":"Y axis",t.y,{scale:s.chart!=="histogram"&&!l,limits:!l,references:p("y")})),l&&a.details.push(b("Share axis",I([["normal","Normal probability","Shares spaced by the normal quantile: a normal distribution is a straight line"],["linear","Linear","Shares spaced evenly, 0 to 100%"]],s.probabilityAxis??"normal",m=>E(c=>{m==="normal"?delete c.probabilityAxis:c.probabilityAxis="linear"}),d),"Normal probability spreads out the tails, where outliers and a second population show.")),s.chart==="histogram"&&a.details.push(b("Bins",G(s.bins,"Number of bins",m=>E(c=>{m===void 0||!Number.isInteger(m)||m<1?delete c.bins:c.bins=Math.min(m,200)})),"Automatic is 16 equal bins."));const v=s.fields??{};(v.x&&"test"in v.x||v.y&&("test"in v.y||Y(v.y)))&&a.limits.push(b("Limits",I([["both","Test + spec"],["test","Test"],["spec","Spec"],["none","None"]],s.limits??"both",m=>E(c=>{m==="both"?delete c.limits:c.limits=m}),d),"Drawn as dashed lines on the axis of a test that has them: short dashes for test limits, long for spec limits.")),a.title.length&&n.appendChild(K("Title","title",a.title)),a.axes.length&&n.appendChild(K("Axes","axes",a.axes)),a.limits.length&&n.appendChild(K("Limits","limits",a.limits)),a.scale.length&&n.appendChild(K("Colour scale","scale",a.scale)),a.details.length&&n.appendChild(K("Chart details","details",a.details));for(const m of n.querySelectorAll("[data-wmap-plot-axis-title]"))Je.set(m.dataset.wmapPlotAxisTitle,m)}_.appendChild(n)}return z(),{el:_,setPlot(e){const o=me(e);JSON.stringify(o)!==JSON.stringify(s)&&(s=o,z())},refreshAuto(){const e=h.autoText();Ce&&(Ce.placeholder=e.title),Ve();for(const[o,n]of Je)n.placeholder=(o==="x"?e.x:e.y)??""}}}
@@ -1,4 +1,4 @@
1
- import type { Die } from '../core/dies.js';
1
+ import { type Die } from '../core/dies.js';
2
2
  import type { Wafer } from '../core/wafer.js';
3
3
  import type { TestDef } from '../renderer/buildWaferMap.js';
4
4
  import type { PlotItem, PlotPoint } from '../stats/plotData.js';
@@ -17,7 +17,12 @@ export declare function toPlotItems(items: readonly WaferShare[]): PlotItem[];
17
17
  * The dies a drag on a plot picked out, per wafer, as a drilldown population: charts and tables of just these.
18
18
  * `null` when the drag caught no die (a wafer-level plot has none to pick).
19
19
  */
20
- export declare function sourceFromPoints(points: readonly PlotPoint[], items: readonly PlotItem[], testDefs: readonly TestDef[] | undefined): DrilldownSource | null;
20
+ export declare function sourceFromPoints(points: readonly PlotPoint[], items: readonly PlotItem[], testDefs: readonly TestDef[] | undefined,
21
+ /** The clicked mark: what it is in words, and whether it counts only the passing or the failing dies of its wafers. */
22
+ mark?: {
23
+ what?: string;
24
+ counts?: 'pass' | 'fail';
25
+ }): DrilldownSource | null;
21
26
  /**
22
27
  * The dies of each wafer that satisfy `keep`, as a drilldown population worded "`what` on W03" or "`what`, across N
23
28
  * wafers". `null` when none does. Per wafer, so the tables name each die's wafer and a chart opened on it is of
@@ -25,8 +30,8 @@ export declare function sourceFromPoints(points: readonly PlotPoint[], items: re
25
30
  */
26
31
  export declare function sourceFromDies(shares: readonly WaferShare[], what: string, keep: (d: Die) => boolean, testDefs: readonly TestDef[] | undefined, activeTest?: number): DrilldownSource | null;
27
32
  /**
28
- * The dies in `bins` (hard or soft), per wafer, for a legend entry's right-click: the same population a bin pareto bar
29
- * opens. `null` when no die is in them. A stack of a lot holds aggregates, not dies, so it is named as not measured.
33
+ * The dies in `bins` (hard or soft), per wafer, for a legend entry's right-click: the dies its count states, and the
34
+ * same population a bin pareto bar opens. `null` when no die is in them. A stack of a lot holds aggregates, not dies, so it is named as not measured.
30
35
  */
31
36
  export declare function sourceFromBins(shares: readonly WaferShare[], kind: 'hard' | 'soft', bins: readonly number[], testDefs: readonly TestDef[] | undefined, activeTest?: number, stacked?: boolean): DrilldownSource | null;
32
37
  //# sourceMappingURL=plotItems.d.ts.map
@@ -1 +1 @@
1
- import{LOT_STACK_REASON as d}from"./chartPopulation.js";export function toPlotItems(l){return l.map(e=>({label:e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:e.ringCount,metadata:e.wafer?.metadata}))}export function sourceFromPoints(l,e,o){const s=new Map;for(const r of l){const n=s.get(r.item);if(!r.die){s.set(r.item,"all");continue}n!=="all"&&(n?n.push(r.die):s.set(r.item,[r.die]))}const t=[...s].map(([r,n])=>({label:e[r].label,dies:n==="all"?[...e[r].dies]:n,waferIndex:e[r].waferIndex,wafer:e[r].wafer,passBins:e[r].passBins,ringCount:e[r].ringCount}));if(t.length===0)return null;const a=t.length===1?`selected on ${t[0].label} in the plot`:`selected in the plot, across ${t.length} wafers`;return{items:t,population:a,testDefs:o?[...o]:void 0}}export function sourceFromDies(l,e,o,s,t){const a=l.map(n=>({it:n,dies:n.dies.filter(o)})).filter(n=>n.dies.length>0).map(({it:n,dies:f})=>({label:n.label,dies:f,waferIndex:n.waferIndex,wafer:n.wafer,passBins:n.passBins,ringCount:n.ringCount}));if(a.length===0)return null;const r=a.length===1?`${e} on ${a[0].label}`:`${e}, across ${a.length} wafers`;return{items:a,population:r,testDefs:s?[...s]:void 0,activeTest:t}}export function sourceFromBins(l,e,o,s,t,a=!1){const r=new Set(o),n=`in ${e} bin${o.length===1?"":"s"} ${o.join(", ")}`,f=sourceFromDies(l,n,i=>{const u=e==="hard"?i.hbin:i.sbin;return u!==void 0&&r.has(u)},s,t);return f&&a&&(f.notMeasuredReason=d),f}
1
+ import{isYieldEligibleDie as p}from"../core/dies.js";import{LOT_STACK_REASON as w}from"./chartPopulation.js";export function toPlotItems(i){return i.map(e=>({label:e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:e.ringCount,metadata:e.wafer?.metadata}))}export function sourceFromPoints(i,e,o,a){const r=new Map;for(const n of i){const l=r.get(n.item);if(l==="all")continue;const d=n.die?[n.die]:n.dies;if(!d){r.set(n.item,"all");continue}const u=l??new Set;for(const h of d)u.add(h);r.set(n.item,u)}const s=[...r].map(([n,l])=>({label:e[n].label,dies:l==="all"?[...e[n].dies]:e[n].dies.filter(d=>l.has(d)),waferIndex:e[n].waferIndex,wafer:e[n].wafer,passBins:e[n].passBins,ringCount:e[n].ringCount})).filter(n=>n.dies.length>0);if(s.length===0)return null;const c=a?.counts==="pass"?"that pass ":a?.counts==="fail"?"that fail ":"",t=a?.what?`${c}in ${a.what}`:`${c}selected`,f=s.length===1?a?.what?a.what.includes(s[0].label)?t:`${t} on ${s[0].label}`:`${t} on ${s[0].label} in the chart`:`${t}${a?.what?"":" in the chart"}, across ${s.length} wafers`;return{items:s,population:f,testDefs:o?[...o]:void 0}}export function sourceFromDies(i,e,o,a,r){const s=i.map(t=>({it:t,dies:t.dies.filter(o)})).filter(t=>t.dies.length>0).map(({it:t,dies:f})=>({label:t.label,dies:f,waferIndex:t.waferIndex,wafer:t.wafer,passBins:t.passBins,ringCount:t.ringCount}));if(s.length===0)return null;const c=s.length===1?`${e} on ${s[0].label}`:`${e}, across ${s.length} wafers`;return{items:s,population:c,testDefs:a?[...a]:void 0,activeTest:r}}export function sourceFromBins(i,e,o,a,r,s=!1){const c=new Set(o),t=`in ${e} bin${o.length===1?"":"s"} ${o.join(", ")}`,f=sourceFromDies(i,t,n=>{const l=e==="hard"?n.hbin:n.sbin;return l!==void 0&&c.has(l)&&p(n)},a,r);return f&&s&&(f.notMeasuredReason=w),f}
@@ -1,4 +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===`
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 chart 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
2
  `||i==="\r"||i===" "){t++;continue}if(i==='"'){let s=t+1;for(;s<e.length&&e[s]!=='"'&&e[s]!==`
3
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
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}
@@ -1,4 +1,5 @@
1
1
  import type { PlotContext, PlotItem } from '../stats/plotData.js';
2
+ import type { PlotWords } from '../stats/plotWords.js';
2
3
  import { type PlotSpec } from '../stats/plotSpec.js';
3
4
  import { type PlotChartOptions } from './charts/plotChart.js';
4
5
  import { type SweepPanelOptions } from './charts/sweep.js';
@@ -22,6 +23,12 @@ export interface PlotEditorWindowOptions {
22
23
  rawPopulation?: string;
23
24
  /** Click a level of a sweep's curve: the menu on the dies measured there. Sweeps only. */
24
25
  onSelectLevel?: SweepPanelOptions['onSelectPoint'];
26
+ /** @internal The chart types the editor offers; absent = all. */
27
+ charts?: readonly string[];
28
+ /** @internal Plain wording, for a reader building charts from a table of wafers. */
29
+ plain?: boolean;
30
+ /** @internal The words the table says its data in. */
31
+ words?: PlotWords;
25
32
  /** The window's heading. Default: Edit plot, or New plot for a draft. */
26
33
  title?: string;
27
34
  onClosed?: () => void;
@@ -1 +1 @@
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
+ 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 W,SPACE as r,controlStyle as B,openReparentedModal as G,wireControlHover as L}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 m=o.createElement("div");if(Object.assign(m.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:W.body}),m.appendChild(e)}const P=e=>{if(e){const i=V({spec:T(n),dies:t.items.flatMap(a=>a.dies),testDefs:t.ctx.testDefs?[...t.ctx.testDefs]:void 0,population:t.rawPopulation??t.population,onSaveImage:t.chart.onSaveImage,onSelectPoint:t.onSelectLevel,ownerDocument:o,readerColors:t.chart.readerColors});return{card:i.card,setPlot:a=>i.setSpec(T(a)),destroy:()=>i.destroy()}}const s=Y({...t.chart,ownerDocument:o,waferLabel:i=>t.items[i]?.label??""});return{card:s.card,setPlot:i=>s.setPlot(w(i)),destroy:()=>s.destroy()}};let S=n.chart==="sweep",l=P(S);l.card.style.alignSelf="stretch",m.appendChild(l.card);function R(){const e=n.chart==="sweep";if(e===S)return;const s=l;l=P(e),S=e,l.card.style.alignSelf="stretch",s.card.replaceWith(l.card),s.destroy()}const u=o.createElement("div");Object.assign(u.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,followsWafers:()=>t.items.length>1,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),y()},valuesOf:e=>I(e,t.items,t.ctx),extentOf:e=>$(e,t.items,t.ctx),testDefs:t.ctx.testDefs,attributes:t.ctx.curation,charts:t.charts,plain:t.plain,words:t.words??t.ctx.words});u.appendChild(x.el);const h=o.createElement("div");Object.assign(h.style,{display:"flex",flexDirection:"column",gap:r.sm,color:b.label,fontSize:W.body,position:"sticky",bottom:"0",background:b.menuBg,borderTop:`1px solid ${b.menuBorder}`,paddingTop:r.sm,paddingBottom:r.md});const O=o.createElement("div");h.appendChild(O);const c=o.createElement("button");c.type="button",c.textContent="Add to my charts",c.dataset.wmapPlotAdd="1",Object.assign(c.style,{...B("outlined"),alignSelf:"flex-start"}),L(c),c.addEventListener("click",()=>{d=!0,p.upsert(n),j()});const E=JSON.parse(JSON.stringify(t.plot)),D=(e,s,i)=>{const a=o.createElement("button");return a.type="button",a.textContent=e,a.dataset[s]="1",Object.assign(a.style,B("outlined")),L(a),a.addEventListener("click",i),a},g=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(g,z,c),h.appendChild(v),u.appendChild(h);const A=()=>JSON.stringify(n)!==JSON.stringify(E);function N(){n=JSON.parse(JSON.stringify(E)),d&&p.upsert(n),x.setPlot(n),y()}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 charts.",c.style.display=d?"none":"",g.disabled=!A(),g.style.opacity=g.disabled?"0.5":"1"}function y(){R(),l.setPlot(n),x.refreshAuto(),j()}y(),f.append(m,u);const J=p.subscribe(()=>{if(!d)return;const e=p.get().find(s=>s.id===n.id);if(!e){C?.close();return}JSON.stringify(e)!==JSON.stringify(n)&&(n=e,x.setPlot(e),y())}),C=G([f],{title:t.title??(d?"Edit chart":"New chart"),anchor:t.anchor,ownerDocument:o,boxSize:{width:"min(96vw, 1180px)",height:"min(92vh, 800px)"},onClosed:()=>{J(),l.destroy(),t.onClosed?.()}});C||(J(),l.destroy())}
@@ -1 +1 @@
1
- import{sweepToPlot as O}from"../stats/plotSpec.js";import{newPlotId as g}from"../stats/plotId.js";import{noticeOnce as x}from"../renderer/deprecate.js";export function copyTitle(i,m){const l=i.replace(/(?:\s*\(copy(?: \d+)?\))+$/,"")||i,r=new Set(m);let d=`${l} (copy)`;for(let f=2;r.has(d);f++)d=`${l} (copy ${f})`;return d}export function plotStoreFor(i){return createPlotStore(i?.plots,i?.onPlotsChange,void 0,{sweeps:i?.sweeps,onRemove:i?.onRemoveSweeps})}export function createPlotStore(i,m,l=400,r){const d=new Set((i??[]).map(e=>e.id)),f=(r?.sweeps??[]).filter(e=>!d.has(e.id));(r?.sweeps?.length??0)>0&&x("insights.sweeps","`insights.sweeps` is deprecated: sweeps are plots now. Pass them in `insights.plots` as sweep plots (readPlotsFile reads a sweeps file), which the My plots tab can also save and share.");const h=new Set((r?.sweeps??[]).map(e=>e.id));let t=[...i??[],...f.map(O)].map(e=>JSON.parse(JSON.stringify(e)));const u=new Set;let p,w=!1;const S=()=>{p!==void 0&&(clearTimeout(p),p=void 0),w&&(w=!1,m?.(t.map(e=>JSON.parse(JSON.stringify(e)))))},a=()=>{for(const e of[...u])e();w=!0,p!==void 0&&clearTimeout(p),p=setTimeout(S,l)};return{get:()=>t,upsert(e){const s=t.findIndex(n=>n.id===e.id);t=s<0?[...t,e]:t.map((n,o)=>o===s?e:n),a()},insertAt(e,s){const n=Math.max(0,Math.min(e,t.length));t=[...t.slice(0,n),s,...t.slice(n)],a()},remove(e){const s=t.findIndex(o=>o.id===e);if(s<0)return;const n=t[s];return t=t.filter((o,c)=>c!==s),a(),h.has(e)&&r?.onRemove?.([e]),{plot:n,index:s}},duplicate(e){const s=t.findIndex(c=>c.id===e);if(s<0)return;const n=t[s],o=JSON.parse(JSON.stringify(n));return o.id=g(),n.title&&Object.assign(o,{title:copyTitle(n.title,t.map(c=>c.title))}),t=[...t.slice(0,s+1),o,...t.slice(s+1)],a(),o},replaceAll(e){const s=[...h].filter(n=>t.some(o=>o.id===n)&&!e.some(o=>o.id===n));t=e.map(n=>JSON.parse(JSON.stringify(n))),a(),s.length>0&&r?.onRemove?.(s)},subscribe(e){return u.add(e),()=>{u.delete(e)}},flush:S}}
1
+ import{sweepToPlot as O}from"../stats/plotSpec.js";import{newPlotId as g}from"../stats/plotId.js";import{noticeOnce as x}from"../renderer/deprecate.js";export function copyTitle(i,m){const f=i.replace(/(?:\s*\(copy(?: \d+)?\))+$/,"")||i,r=new Set(m);let p=`${f} (copy)`;for(let l=2;r.has(p);l++)p=`${f} (copy ${l})`;return p}export function plotStoreFor(i){return createPlotStore(i?.plots,i?.onPlotsChange,void 0,{sweeps:i?.sweeps,onRemove:i?.onRemoveSweeps})}export function createPlotStore(i,m,f=400,r){const p=new Set((i??[]).map(e=>e.id)),l=(r?.sweeps??[]).filter(e=>!p.has(e.id));(r?.sweeps?.length??0)>0&&x("insights.sweeps","`insights.sweeps` is deprecated: sweeps are charts now. Pass them in `insights.plots` as sweep charts (readPlotsFile reads a sweeps file), which the My charts tab can also save and share.");const w=new Set((r?.sweeps??[]).map(e=>e.id));let t=[...i??[],...l.map(O)].map(e=>JSON.parse(JSON.stringify(e)));const u=new Set;let a,h=!1;const S=()=>{a!==void 0&&(clearTimeout(a),a=void 0),h&&(h=!1,m?.(t.map(e=>JSON.parse(JSON.stringify(e)))))},d=()=>{for(const e of[...u])e();h=!0,a!==void 0&&clearTimeout(a),a=setTimeout(S,f)};return{get:()=>t,upsert(e){const s=t.findIndex(n=>n.id===e.id);t=s<0?[...t,e]:t.map((n,o)=>o===s?e:n),d()},insertAt(e,s){const n=Math.max(0,Math.min(e,t.length));t=[...t.slice(0,n),s,...t.slice(n)],d()},remove(e){const s=t.findIndex(o=>o.id===e);if(s<0)return;const n=t[s];return t=t.filter((o,c)=>c!==s),d(),w.has(e)&&r?.onRemove?.([e]),{plot:n,index:s}},duplicate(e){const s=t.findIndex(c=>c.id===e);if(s<0)return;const n=t[s],o=JSON.parse(JSON.stringify(n));return o.id=g(),n.title&&Object.assign(o,{title:copyTitle(n.title,t.map(c=>c.title))}),t=[...t.slice(0,s+1),o,...t.slice(s+1)],d(),o},replaceAll(e){const s=[...w].filter(n=>t.some(o=>o.id===n)&&!e.some(o=>o.id===n));t=e.map(n=>JSON.parse(JSON.stringify(n))),d(),s.length>0&&r?.onRemove?.(s)},subscribe(e){return u.add(e),()=>{u.delete(e)}},flush:S}}
@@ -1,7 +1,11 @@
1
1
  import type { Die } from '../core/dies.js';
2
+ import type { ReaderColors } from './charts/divergingScale.js';
3
+ import { type PlotWords } from '../stats/plotWords.js';
2
4
  import type { TestDef } from '../renderer/buildWaferMap.js';
3
5
  import type { BinColors } from '../renderer/binColors.js';
4
6
  import type { WaferContextMenuHandler } from './charts/chartShell.js';
7
+ import { fieldCatalogue, type PlotItem } from '../stats/plotData.js';
8
+ import { type PlotSpec } from '../stats/plotSpec.js';
5
9
  import type { FacetCuration } from '../stats/facets.js';
6
10
  import type { PlotStore } from './plotStore.js';
7
11
  import type { InsightsItem } from './insightsTab.js';
@@ -14,7 +18,8 @@ export interface PlotSectionDeps {
14
18
  items: InsightsItem[];
15
19
  /** The population's reconciled test list. */
16
20
  testDefs: TestDef[];
17
- ringCount: number;
21
+ /** The population's ring count. Not needed with `prepared` items, which carry their own. */
22
+ ringCount?: number;
18
23
  /** The tab's Group by key and its label, which "follow Group by" resolves to. */
19
24
  groupBy?: string;
20
25
  groupLabel?: string;
@@ -22,15 +27,68 @@ export interface PlotSectionDeps {
22
27
  onSaveText?: SaveTextHandler;
23
28
  /** The maps' bin colours: a plot coloured by bin draws each bin in its map colour. */
24
29
  getBinColors?: () => BinColors;
30
+ /** The reader's colour preferences (value gradient and Reverse), read when a plot is drawn. */
31
+ getReaderColors?: () => ReaderColors;
25
32
  /** Right-click a wafer's own mark: that wafer's menu, by its index in the host's list. */
26
33
  waferMenu?: WaferContextMenuHandler;
27
34
  /** Click a point: open its wafer, on a test's values when the plot is about one. */
28
- openWafer?: (waferIndex: number, label: string, testNumber?: number) => void;
35
+ openWafer?: (waferIndex: number, label: string, testNumber?: number, view?: 'bins') => void;
29
36
  /** A single-wafer host's version of the same: show the test on the map that is already there. */
30
37
  focusTest?: (testNumber: number) => void;
31
38
  locateDie?: (die: Die, waferIndex: number | undefined) => void;
32
39
  /** The host's own way to choose a plots file (a native dialog). Without it a file input is used. */
33
40
  pickPlotsFile?: () => Promise<string | null>;
41
+ /**
42
+ * @internal Wafers already as plot items (a table of wafers, `stats/dataTable.ts`): used as they are, and `items` is
43
+ * empty. The tab is then worded for a reader who builds charts from a table, with no examples drawn from tests.
44
+ */
45
+ prepared?: PlotItem[];
46
+ /** @internal The chart types the editor offers; absent = all. */
47
+ charts?: readonly string[];
48
+ /** @internal The words the table says its data in. Default: wafers, dies, bins and yield. */
49
+ words?: PlotWords;
50
+ /** @internal The plot New plot starts from, given the fields the population has; `selection`: from a few rows picked on a chart. Default: the first plot `defaultPlot` suggests. */
51
+ starter?: (catalogue: ReturnType<typeof fieldCatalogue>, id: string, selection?: boolean) => PlotSpec;
52
+ /** @internal A click on a bar, box or point: what it stands for and the wafers behind it. Told before the menu opens. */
53
+ onSelect?: (selection: TableSelection) => void;
54
+ /** @internal The host's own places a selection can go, offered in the menu a click opens. */
55
+ targets?: readonly TableTarget[];
56
+ /** @internal Open the menu on a click (default). `false`: the host's `onSelect` alone. */
57
+ drilldown?: boolean;
58
+ }
59
+ /**
60
+ * What a click on a mark of a plot picked out, for a host whose wafers are rows of a table.
61
+ * @experimental May change or be removed without notice.
62
+ */
63
+ export interface TableSelection {
64
+ /** The category the mark stands for (a lot, a bin, a date), and the colour group when the plot has several. */
65
+ category?: string;
66
+ group?: string;
67
+ /** The wafers behind it, as their positions in the table, each once, in order. */
68
+ wafers: number[];
69
+ /** Their names, as the table's label column gave them. */
70
+ labels: string[];
71
+ /** Their columns as the table gave them (the label column excluded: it is `labels`), one object per wafer. */
72
+ rows: Array<Record<string, string | number>>;
73
+ /** Where the click was, in the page. */
74
+ at: {
75
+ x: number;
76
+ y: number;
77
+ };
78
+ }
79
+ /**
80
+ * Somewhere else a selection can go, which the host supplies: its own page for a lot, another tool, a web address.
81
+ * Each is a row in the menu a click on a mark opens, under the library's own "Charts for these wafers".
82
+ * @experimental May change or be removed without notice.
83
+ */
84
+ export interface TableTarget {
85
+ id: string;
86
+ label: string;
87
+ /** The heading the row sits under. Default "Open elsewhere". */
88
+ section?: string;
89
+ /** Why this selection cannot go here (it needs one lot, say), or `null` when it can. Absent = always. */
90
+ unavailable?: (selection: TableSelection) => string | null;
91
+ run: (selection: TableSelection) => void;
34
92
  }
35
93
  export declare function createPlotSection(d: PlotSectionDeps): {
36
94
  card: HTMLElement;
@@ -1 +1 @@
1
- import{defaultPlot as Pe,describeTitleDrift as Ee,examplePlots as Se,fieldCatalogue as De,resolvePlot as Ce,titleDrift as Ae}from"../stats/plotData.js";import{addPlots as ke,newPlotId as V,readPlotsFile as Te,writePlotsFile as Ie}from"../stats/plotSpec.js";import{buildFilterStrip as $e}from"./filterEditor.js";import{isYieldEligibleDie as je}from"../core/dies.js";import{testValue as Be}from"../core/dieTable.js";import{sweepAppliesTo as Oe}from"../stats/sweep.js";import{plotToSweep as Y}from"../stats/plotSpec.js";import{renderPlotChart as ee}from"./charts/plotChart.js";import{renderSweepPanel as te}from"./charts/sweep.js";import{makeChartGridWrap as oe,makeSegmented as Le}from"./charts/chartShell.js";import{confirmDialog as Me}from"./confirmDialog.js";import{openDrilldownMenu as ne}from"./drilldown.js";import{openPlotEditor as Ne}from"./plotModal.js";import{sourceFromDies as Fe,sourceFromPoints as We,toPlotItems as Re}from"./plotItems.js";import{CLR as h,FONT as D,RADIUS as W,SPACE as u,controlStyle as Ue,markNoPrint as I,saveTextFile as ze,wireControlHover as Ve,wireTooltip as Ye}from"./toolbar.js";const se=1e4;export function createPlotSection(l){const{doc:r,store:a}=l,p=Re(l.items.map(e=>({label:e.identity??e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:l.ringCount}))),$={testDefs:l.testDefs,groupBy:l.groupBy,curation:l.attributes},q=e=>Ce(e,p,$),j=De(p,$),g=r.createElement("div");g.dataset.wmapPlotTab="1",Object.assign(g.style,{display:"flex",flexDirection:"column",gap:u.lg,width:"100%"});const B=r.createElement("div");Object.assign(B.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const w=(e,t,n,o)=>{const s=r.createElement("button");return s.type="button",s.textContent=e,s.dataset[t]="1",Object.assign(s.style,{...Ue("outlined"),fontSize:D.body}),Ve(s),Ye(s,n),s.addEventListener("click",o),s},O=w("Delete all plots\u2026","wmapPlotDeleteAll","Remove every plot and sweep. You are asked first, and Undo brings them back for ten seconds",()=>{ye()});let E="plots";const C=Le([["plots","My plots","Your own plots, kept for the next lot"],["examples","Examples","One example of each chart type this lot can show, drawn from its own tests. They are not your plots until you add them"]],E,e=>ie(e),r);C.dataset.wmapPlotViews="1",C.setAttribute("aria-label","Plots shown");for(const e of Array.from(C.querySelectorAll("label")))e.querySelector("input")?.value==="examples"&&(e.dataset.wmapPlotExamples="1");B.append(C,w("+ New plot","wmapPlotNew","Start a chart of your own: choose its type (a sweep reads runs of tests as response curves), what goes on each axis and how it is coloured",()=>ae()),w("Import plots\u2026","wmapPlotImport","Add the plots from a file written by Export plots\u2026",()=>{be()}),w("Export plots\u2026","wmapPlotExport","Save all your plots to a file, to share or to keep a copy",()=>ge()),O),I(B),g.appendChild(B);const y=r.createElement("div");y.setAttribute("role","status"),Object.assign(y.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",padding:`${u.sm} ${u.md}`,background:h.menuBg,border:`1px solid ${h.menuBorder}`,borderRadius:W.container,color:h.text,fontSize:D.body}),I(y),g.appendChild(y);let b;function S(e,t,n=[]){b!==void 0&&clearTimeout(b),y.replaceChildren();const o=r.createElement("span");if(o.textContent=e,y.appendChild(o),t){const s=w(t.label,"wmapPlotNoticeAction",t.label==="Undo"?"Put back what was just removed":t.label,()=>{t.run(),G()});y.appendChild(s)}for(const s of n){const i=r.createElement("div");i.textContent=s,Object.assign(i.style,{flexBasis:"100%",color:h.label}),y.appendChild(i)}y.style.display="flex",b=setTimeout(G,t?se:se*2)}function G(){b!==void 0&&(clearTimeout(b),b=void 0),y.style.display="none",y.replaceChildren()}const x=r.createElement("div");x.dataset.wmapPlotGallery="1",Object.assign(x.style,{display:"none",flexDirection:"column",gap:u.md,padding:u.md,border:`1px solid ${h.menuBorder}`,borderRadius:W.container}),I(x),g.appendChild(x);let L=[];const _=()=>{for(const e of L)e.destroy();L=[],x.replaceChildren(),x.style.display="none"},A=r.createElement("div");A.textContent="No plots yet. A plot is any measured value against another, or a distribution, that you choose: New plot starts one, and it is kept for the next lot. Examples shows one of each chart type from this lot, to look at and to add the ones you want.",Object.assign(A.style,{color:h.label,fontSize:D.body,padding:`${u.lg} 0`});const k=oe(r);g.append(A,k);const v=new Map,R=()=>({onSaveImage:l.onSaveImage,onSaveText:l.onSaveText,binColors:l.getBinColors?.(),onWaferMenu:l.waferMenu?(e,t,n)=>l.waferMenu(p[e].waferIndex??e,t,n):void 0,onOpenWafer:l.openWafer?(e,t)=>l.openWafer(p[e].waferIndex??e,p[e].label,t):l.focusTest&&p.length===1?(e,t)=>{t!==void 0&&l.focusTest(t)}:void 0,openActionLabel:!l.openWafer&&l.focusTest&&p.length===1?"show this test on the map":void 0,onSelectPoints:(e,t,n)=>le(e,t,n)}),H=()=>({plots:a,getBinColors:l.getBinColors,onSaveImage:l.onSaveImage,onSaveText:l.onSaveText,onLocateDie:l.locateDie});function le(e,t,n){const o=We(e,p,l.testDefs);o&&ne(t,n,o,H())}function J(e,t=!1){Ne({doc:r,anchor:g,store:a,plot:e,draft:t,items:p,ctx:$,groupLabel:l.groupLabel,chart:R(),onSelectLevel:U})}function U(e,t){const n=s=>e.testNumbers.some(i=>{const d=Be(s,i);return d!==void 0&&Number.isFinite(d)}),o=Fe(p,`measured at ${e.label}`,s=>je(s)&&n(s),l.testDefs,e.testNumbers[0]);o&&ne({x:t.clientX,y:t.clientY},t.target,o,H())}function ae(){N("plots");const e=Pe(j,V());a.upsert(e),J(e)}const M=e=>JSON.stringify([e.chart,e.fields,e.aggregate??null,e.sweep??null,e.fit??null,e.normalCurve??null,e.spread??null,e.normalize??null,e.sort??null,e.cumulative??null,e.stack??null]);function N(e){const t=C.querySelector(`input[value="${e}"]`);!t||t.checked||(t.checked=!0,t.dispatchEvent(new(r.defaultView??window).Event("change")))}function re(){k.style.display=E==="plots"?"grid":"none",A.style.display=E==="plots"&&a.get().length===0?"":"none",x.style.display=E==="examples"?"flex":"none"}function ie(e){if(e!==E){if(E=e,e==="examples"){if(!ce()){N("plots");return}}else _();re()}}function ce(){const e=Se(j,p.length,V,{items:p,ctx:$});if(e.length===0)return S(j.some(c=>c.group==="Tests")?"There are no examples this lot can draw.":"There are no measured values in this lot to draw examples from."),!1;const t=r.createElement("div");Object.assign(t.style,{display:"flex",flexWrap:"wrap",gap:u.md,alignItems:"center"});const n=r.createElement("div");Object.assign(n.style,{color:h.text,fontSize:D.body,flex:"1 1 auto"});const o=[],s=w("Add all","wmapPlotExamplesAddAll","Add every example you do not have yet to My plots",()=>{const c=o.map(f=>f.add()).filter(f=>f!==void 0);c.length!==0&&(N("plots"),S(`Added ${c.length} plot${c.length===1?"":"s"} to My plots.`,{label:"Undo",run:()=>{const f=new Set(c);a.replaceAll(a.get().filter(P=>!f.has(P.id)))}}))});t.append(n,s);const i=oe(r);x.append(t,i);const d=[],F=()=>{const c=o.filter(f=>a.get().some(P=>M(P)===M(f.example))).length;n.textContent=`${e.length} examples from this lot, drawn for you. They are not your plots until you add them${c?` (${c} added)`:""}; edit them under My plots.`,s.disabled=c===e.length,s.style.opacity=c===e.length?"0.6":"1"};for(const c of e){let f;if(c.chart==="sweep")f=te({spec:Y(c),dies:p.flatMap(z=>z.dies),testDefs:l.testDefs,onSaveImage:l.onSaveImage,ownerDocument:r,onSelectPoint:U});else{const m=ee({ownerDocument:r,waferLabel:z=>p[z]?.label??"",...R()});m.setPlot(q(c)),f=m}f.card.dataset.wmapPlotExample=c.chart;const P=r.createElement("span");P.textContent="Example",P.dataset.wmapPlotExampleBadge="1",Object.assign(P.style,{fontSize:D.sub,color:h.label,border:`1px dashed ${h.menuBorder}`,borderRadius:W.control,padding:`0 ${u.sm}`});const T=w("Add to my plots","wmapPlotExampleAdd","Add this example to My plots, where you can edit it",()=>{}),Q=()=>a.get().some(m=>M(m)===M(c)),ve=()=>{const m=Q();T.textContent=m?"In your plots":"Add to my plots",T.disabled=m,T.style.opacity=m?"0.6":"1"},Z=()=>{if(Q())return;const m=V();return a.upsert({...c,id:m}),m};T.addEventListener("click",()=>{Z()}),o.push({example:c,add:Z}),d.push(ve),f.actions.append(P,T),i.appendChild(f.card),L.push(f)}const xe=a.subscribe(()=>{for(const c of d)c();F()});L.push({card:t,destroy:xe});for(const c of d)c();return F(),!0}function K(e,t){const n=(o,s,i,d)=>e.appendChild(w(o,s,i,d));n("Edit","wmapPlotEdit","Change this plot\u2019s type, fields, titles, limits and axes",()=>{const o=a.get().find(s=>s.id===t.id);o&&J(o)}),n("Duplicate","wmapPlotDuplicate","Make a copy of this plot to vary",()=>{a.duplicate(t.id)}),n("Delete","wmapPlotDelete","Remove this plot. Undo brings it back for ten seconds",()=>{const o=a.remove(t.id);o&&S(`Deleted \u201C${o.plot.title??"plot"}\u201D.`,{label:"Undo",run:()=>a.insertAt(o.index,o.plot)})})}function de(e){return e.chart==="sweep"?fe(e):pe(e)}function pe(e){const t=ee({ownerDocument:r,waferLabel:i=>p[i]?.label??"",...R()});t.card.dataset.wmapPlotId=e.id,I(t.actions),K(t.actions,e);const n=r.createElement("div");n.dataset.wmapPlotTitleDrift="1",Object.assign(n.style,{display:"none",flexWrap:"wrap",gap:u.md,alignItems:"center",flexBasis:"100%",padding:`${u.xs} ${u.md}`,background:h.warnBg,border:`1px solid ${h.warnBorder}`,borderRadius:W.control,color:h.warnText,fontSize:D.body});const o=r.createElement("div");o.style.flexBasis="100%",t.actions.append(o,n);const s={sweep:!1,card:t.card,actions:t.actions,json:"",driftNote:n,destroy:()=>t.destroy(),update:i=>{const d=q(i);t.setPlot(d),ue(o,i),t.card.style.opacity=d.issues.length?"0.7":"1",me(n,i)}};return v.set(e.id,s),s}function fe(e){const t=Y(e),n=p.flatMap(i=>i.dies),o=te({spec:t,dies:n,testDefs:l.testDefs,onSaveImage:l.onSaveImage,ownerDocument:r,onSelectPoint:U});o.card.dataset.wmapPlotId=e.id,o.card.dataset.wmapSweepPlot="1",I(o.actions),K(o.actions,e);const s={sweep:!0,card:o.card,actions:o.actions,json:"",destroy:()=>o.destroy(),update:i=>{const d=Y(i);o.setSpec(d),o.card.style.opacity=Oe(d,l.testDefs)?"1":"0.7"}};return v.set(e.id,s),s}function ue(e,t){const n=t.where;e.replaceChildren(),n&&e.appendChild($e({doc:r,filter:n,testDefs:l.testDefs,attributes:l.attributes,label:"Filter",onToggle:o=>{const s=a.get().find(F=>F.id===t.id),i=s?.where;if(!s||!i)return;const d={...i};o?delete d.off:d.off=!0,a.upsert({...s,where:d})}}))}function me(e,t){const n=Ee(Ae(t,j));if(e.replaceChildren(),e.style.display=n?"flex":"none",!n)return;const o=r.createElement("span");o.textContent=n,e.append(o,w("Use the automatic title","wmapPlotAutoTitle","Replace the title you typed with the one written from the plot\u2019s settings",()=>{const s=a.get().find(d=>d.id===t.id);if(!s)return;const i={...s};delete i.title,a.upsert(i)}))}function X(){const e=a.get();for(const[t,n]of v)e.some(o=>o.id===t)||(n.destroy(),n.card.remove(),v.delete(t));e.forEach((t,n)=>{let o=v.get(t.id);o&&o.sweep!==(t.chart==="sweep")&&(o.destroy(),o.card.remove(),v.delete(t.id),o=void 0),o??=de(t);const s=JSON.stringify(t);o.json!==s&&(o.json=s,o.update(t)),k.children[n]!==o.card&&k.insertBefore(o.card,k.children[n]??null)}),A.style.display=E==="plots"&&e.length===0?"":"none",O.disabled=e.length===0,O.style.opacity=e.length===0?"0.5":"1",O.style.cursor=e.length===0?"default":"pointer"}const he=a.subscribe(X);X();async function ye(){const e=a.get().slice();if(e.length===0)return;const t=e.length;if(!await Me({doc:r,anchor:g,title:"Delete all plots",message:t===1?"Delete your 1 saved plot? It is kept on this computer for the next lot, so it will not be there for the next file either. Export plots\u2026 first to keep a copy.":`Delete all ${t} saved plots, sweeps included? They are kept on this computer for the next lot, so they will not be there for the next file either. Export plots\u2026 first to keep a copy.`,confirmLabel:t===1?"Delete 1 plot":`Delete ${t} plots`}))return;const o=a.get().slice();o.length!==0&&(a.replaceAll([]),S(`Deleted ${o.length===1?"1 plot":`all ${o.length} plots`}.`,{label:"Undo",run:()=>a.replaceAll(o)}))}function ge(){const e=a.get();if(e.length===0){S("There are no plots to export yet.");return}ze(Ie(e),"wafermap-plots.json","application/json",l.onSaveText)}async function we(){return l.pickPlotsFile?l.pickPlotsFile():new Promise(e=>{const t=r.createElement("input");t.type="file",t.accept=".json,application/json",t.addEventListener("change",()=>{const n=t.files?.[0];if(!n){e(null);return}n.text().then(e,()=>e(null))}),t.addEventListener("cancel",()=>e(null)),t.click()})}async function be(){const e=await we();if(e===null)return;const t=Te(e);if(t.error){S(`Could not import: ${t.error}`);return}const{plots:n,copies:o}=ke(a.get(),t.plots);a.replaceAll(n),N("plots");const s=[...t.warnings,...o.length?[`Kept as copies, since a plot with the same id already existed: ${o.join(", ")}`]:[]];S(`Imported ${t.plots.length} plot${t.plots.length===1?"":"s"}.`,void 0,s)}return{card:g,destroy:()=>{he(),b!==void 0&&clearTimeout(b),_();for(const e of v.values())e.destroy();v.clear(),a.flush()}}}
1
+ import{WAFER_WORDS as H}from"../stats/plotWords.js";import{defaultPlot as K,describeTitleDrift as Le,exampleGroups as Oe,fieldCatalogue as Me,resolvePlot as Ne,testsNotInLot as Re,titleDrift as Fe}from"../stats/plotData.js";import{addPlots as We,newPlotId as P,readPlotsFile as ze,writePlotsFile as Ue}from"../stats/plotSpec.js";import{buildFilterStrip as qe}from"./filterEditor.js";import{isYieldEligibleDie as Ge}from"../core/dies.js";import{requireRingCount as Ve}from"../core/ringCount.js";import{testValue as Ye}from"../core/dieTable.js";import{plotToSweep as X}from"../stats/plotSpec.js";import{renderPlotChart as de}from"./charts/plotChart.js";import{renderSweepPanel as pe}from"./charts/sweep.js";import{makeChartGridWrap as ue,makeSegmented as _e}from"./charts/chartShell.js";import{confirmDialog as He}from"./confirmDialog.js";import{openDrilldownMenu as fe}from"./drilldown.js";import{openTableMenu as Je,tableSelection as Ke}from"./tableDrilldown.js";import{openPlotEditor as he}from"./plotModal.js";import{sourceFromDies as Xe,sourceFromPoints as Qe,toPlotItems as Ze}from"./plotItems.js";import{CLR as m,FONT as D,LEADING as et,RADIUS as J,SPACE as g,controlStyle as tt,markNoPrint as R,saveTextFile as ot,wireControlHover as nt,wireTooltip as st}from"./toolbar.js";const me=1e4;export function createPlotSection(n){const{doc:c,store:i}=n,b=n.prepared!==void 0,u=n.prepared??Ze(n.items.map(e=>({label:e.identity??e.label,dies:e.dies,waferIndex:e.waferIndex,wafer:e.wafer,passBins:e.passBins,ringCount:Ve(n,"the My charts tab")}))),I={testDefs:n.testDefs,groupBy:n.groupBy,curation:n.attributes,...b?{plain:!0}:{},...n.words?{words:n.words}:{}},Q=e=>Ne(e,u,I),x=Me(u,I),w=c.createElement("div");w.dataset.wmapPlotTab="1",Object.assign(w.style,{display:"flex",flexDirection:"column",gap:g.lg,width:"100%"});const F=c.createElement("div");Object.assign(F.style,{display:"flex",flexWrap:"wrap",gap:g.md,alignItems:"center"});const v=(e,t,s,o)=>{const r=c.createElement("button");return r.type="button",r.textContent=e,r.dataset[t]="1",Object.assign(r.style,{...tt("outlined"),fontSize:D.body}),nt(r),st(r,s),r.addEventListener("click",o),r},W=v("Delete all charts\u2026","wmapPlotDeleteAll","Remove every saved chart, sweeps included. You are asked first, and Undo brings them back for ten seconds",()=>{Ae()});let A="plots";const B=_e([["plots","My charts","Your own charts, kept for the next lot"],["examples","Examples","Starter charts drawn from this lot\u2019s own tests, grouped by question. They are not your charts until you add them"]],A,e=>be(e),c);B.dataset.wmapPlotViews="1",B.setAttribute("aria-label","Charts shown");for(const e of Array.from(B.querySelectorAll("label")))e.querySelector("input")?.value==="examples"&&(e.dataset.wmapPlotExamples="1");F.append(...b?[]:[B],v("+ New chart","wmapPlotNew",b?"Start a chart of your own: choose its type, what goes on each axis and how it is coloured":"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",()=>ye()),v("Import charts\u2026","wmapPlotImport","Add the charts from a file written by Export charts\u2026",()=>{Ie()}),v("Export charts\u2026","wmapPlotExport","Save all your charts to a file, to share or to keep a copy",()=>ke()),W),R(F),w.appendChild(F);const y=c.createElement("div");y.setAttribute("role","status"),Object.assign(y.style,{display:"none",flexWrap:"wrap",gap:g.md,alignItems:"center",padding:`${g.sm} ${g.md}`,background:m.menuBg,border:`1px solid ${m.menuBorder}`,borderRadius:J.container,color:m.text,fontSize:D.body}),R(y),w.appendChild(y);let C;function k(e,t,s=[]){C!==void 0&&clearTimeout(C),y.replaceChildren();const o=c.createElement("span");if(o.textContent=e,y.appendChild(o),t){const r=v(t.label,"wmapPlotNoticeAction",t.label==="Undo"?"Put back what was just removed":t.label,()=>{t.run(),Z()});y.appendChild(r)}for(const r of s){const l=c.createElement("div");l.textContent=r,Object.assign(l.style,{flexBasis:"100%",color:m.label}),y.appendChild(l)}y.style.display="flex",C=setTimeout(Z,t?me:me*2)}function Z(){C!==void 0&&(clearTimeout(C),C=void 0),y.style.display="none",y.replaceChildren()}const S=c.createElement("div");S.dataset.wmapPlotGallery="1",Object.assign(S.style,{display:"none",flexDirection:"column",gap:g.md,padding:g.md,border:`1px solid ${m.menuBorder}`,borderRadius:J.container}),R(S),w.appendChild(S);let z=[];const ee=()=>{for(const e of z)e.destroy();z=[],S.replaceChildren(),S.style.display="none"},L=c.createElement("div");L.textContent=b?"No charts yet. New chart starts a chart of your own: choose its type, what goes on each axis and how it is coloured. It is kept for next time.":"No charts yet. A chart is any measured value against another, or a distribution, that you choose: New chart starts one, and it is kept for the next lot. Examples has starter charts from this lot, grouped by question (yield and bins, limits, on the wafer, tester, relationships), to look at and to add the ones you want.",Object.assign(L.style,{color:m.label,fontSize:D.body,padding:`${g.lg} 0`});const O=ue(c);w.append(L,O);const E=new Map,U=(e=u)=>({onSaveImage:n.onSaveImage,onSaveText:n.onSaveText,binColors:n.getBinColors?.(),getBinColors:n.getBinColors,readerColors:n.getReaderColors?.(),onWaferMenu:n.waferMenu?(t,s,o)=>n.waferMenu(e[t].waferIndex??t,s,o):void 0,onOpenWafer:n.openWafer?(t,s,o)=>n.openWafer(e[t].waferIndex??t,e[t].label,s,o):n.focusTest&&u.length===1?(t,s)=>{s!==void 0&&n.focusTest(s)}:void 0,openActionLabel:!n.openWafer&&n.focusTest&&u.length===1?"show this test on the map":void 0,onSelectPoints:(t,s,o,r)=>ge(t,s,o,r,e),...b?{selectActionLabel:`choose what to do with those ${(n.words??H).row.many}`,selectRangeLabel:(n.words??H).row.many,openActionLabel:`choose what to do with this ${(n.words??H).row.one}`}:{}}),te=()=>({plots:i,getBinColors:n.getBinColors,getReaderColors:n.getReaderColors,onSaveImage:n.onSaveImage,onSaveText:n.onSaveText,onLocateDie:n.locateDie});function ge(e,t,s,o,r=u){if(b){const d=Ke(e,o,r,u,t);if(!d)return;n.onSelect?.(d),n.drilldown!==!1&&Je({at:t,anchor:s,selection:d,targets:n.targets??[],items:u,ctx:I,words:n.words??H,charts:{plots:i.get(),newPlot:()=>n.starter?n.starter(x,P()):K(x,P()),newPlotOf:()=>n.starter?n.starter(x,P(),!0):K(x,P()),openChart:($,T,M,Y)=>he({doc:c,anchor:w,store:i,plot:$,draft:Y,items:T,ctx:I,groupLabel:n.groupLabel,chart:U(T),onSelectLevel:q,charts:n.charts,plain:!0,words:n.words,population:M})}});return}const l=Qe(e,u,n.testDefs,o);l&&fe(t,s,l,te())}function oe(e,t=!1){he({doc:c,anchor:w,store:i,plot:e,draft:t,items:u,ctx:I,groupLabel:n.groupLabel,chart:U(),onSelectLevel:q,charts:n.charts,plain:b,words:n.words})}function q(e,t){const s=r=>e.testNumbers.some(l=>{const d=Ye(r,l);return d!==void 0&&Number.isFinite(d)}),o=Xe(u,`measured at ${e.label}`,r=>Ge(r)&&s(r),n.testDefs,e.testNumbers[0]);o&&fe({x:t.clientX,y:t.clientY},t.target,o,te())}function ye(){V("plots");const e=n.starter?n.starter(x,P()):K(x,P());i.upsert(e),oe(e)}const G=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 V(e){const t=B.querySelector(`input[value="${e}"]`);!t||t.checked||(t.checked=!0,t.dispatchEvent(new(c.defaultView??window).Event("change")))}function we(){O.style.display=A==="plots"?"grid":"none",L.style.display=A==="plots"&&i.get().length===0?"":"none",S.style.display=A==="examples"?"flex":"none"}function be(e){if(e!==A){if(A=e,e==="examples"){if(!xe()){V("plots");return}}else ee();we()}}function xe(){const e=Oe(x,u.length,P,{items:u,ctx:I}),t=e.flatMap(a=>a.examples.map(f=>f.spec)),s=new Map(e.flatMap(a=>a.examples.map(f=>[f.spec,f.purpose]))),o=new Map(e.map(a=>[a.examples[0].spec,a.group]));if(t.length===0)return k(x.some(a=>a.group==="Tests")?"There are no examples this lot can draw.":"There are no measured values in this lot to draw examples from."),!1;const r=c.createElement("div");Object.assign(r.style,{display:"flex",flexWrap:"wrap",gap:g.md,alignItems:"center"});const l=c.createElement("div");Object.assign(l.style,{color:m.text,fontSize:D.body,flex:"1 1 auto"});const d=[],$=v("Add all","wmapPlotExamplesAddAll","Add every example you do not have yet to My charts",()=>{const a=d.map(f=>f.add()).filter(f=>f!==void 0);a.length!==0&&(V("plots"),k(`Added ${a.length} chart${a.length===1?"":"s"} to My charts.`,{label:"Undo",run:()=>{const f=new Set(a);i.replaceAll(i.get().filter(h=>!f.has(h.id)))}}))});r.append(l,$);const T=ue(c);S.append(r,T);const M=[],Y=()=>{const a=d.filter(f=>i.get().some(h=>G(h)===G(f.example))).length;l.textContent=`${t.length} starter charts from this lot, by question. They are not your charts until you add them${a?` (${a} added)`:""}; edit them under My charts.`,$.disabled=a===t.length,$.style.opacity=a===t.length?"0.6":"1"};for(const a of t){const f=o.get(a);if(f){const p=c.createElement("h3");p.textContent=f,p.dataset.wmapExampleGroup=f,Object.assign(p.style,{gridColumn:"1 / -1",margin:`${g.md} 0 0`,color:m.value,fontSize:D.heading,fontWeight:"600"}),T.appendChild(p)}let h;if(a.chart==="sweep")h=pe({spec:X(a),dies:u.flatMap(j=>j.dies),testDefs:n.testDefs,onSaveImage:n.onSaveImage,ownerDocument:c,onSelectPoint:q,readerColors:n.getReaderColors?.()});else{const p=de({ownerDocument:c,waferLabel:j=>u[j]?.label??"",...U()});p.setPlot(Q(a)),h=p}h.card.dataset.wmapPlotExample=a.chart;const re=s.get(a);if(re){const p=c.createElement("div");p.textContent=re,p.dataset.wmapExamplePurpose="1",Object.assign(p.style,{fontSize:D.body,color:m.label,lineHeight:et.base});const j=h.card.dataset.wmapChartTitle,ie=[...h.card.children],ce=ie.find(Be=>!!j&&Be.textContent?.trim()===j)??ie[0];ce?.nextSibling?h.card.insertBefore(p,ce.nextSibling):h.card.appendChild(p)}const _=c.createElement("span");_.textContent="Example",_.dataset.wmapPlotExampleBadge="1",Object.assign(_.style,{fontSize:D.sub,color:m.label,border:`1px dashed ${m.menuBorder}`,borderRadius:J.control,padding:`0 ${g.sm}`});const N=v("Add to my charts","wmapPlotExampleAdd","Add this example to My charts, where you can edit it",()=>{}),ae=()=>i.get().some(p=>G(p)===G(a)),je=()=>{const p=ae();N.textContent=p?"In your charts":"Add to my charts",N.disabled=p,N.style.opacity=p?"0.6":"1"},le=()=>{if(ae())return;const p=P();return i.upsert({...a,id:p}),p};N.addEventListener("click",()=>{le()}),d.push({example:a,add:le}),M.push(je),h.actions.append(_,N),T.appendChild(h.card),z.push(h)}const Te=i.subscribe(()=>{for(const a of M)a();Y()});z.push({card:r,destroy:Te});for(const a of M)a();return Y(),!0}function ne(e,t){const s=(o,r,l,d)=>e.appendChild(v(o,r,l,d));s("Edit","wmapPlotEdit","Change this chart\u2019s type, fields, titles, limits and axes",()=>{const o=i.get().find(r=>r.id===t.id);o&&oe(o)}),s("Duplicate","wmapPlotDuplicate","Make a copy of this chart to vary",()=>{i.duplicate(t.id)}),s("Delete","wmapPlotDelete","Remove this chart. Undo brings it back for ten seconds",()=>{const o=i.remove(t.id);o&&k(`Deleted \u201C${o.plot.title??"chart"}\u201D.`,{label:"Undo",run:()=>i.insertAt(o.index,o.plot)})})}function ve(e){return e.chart==="sweep"?Se(e):Ce(e)}function Ce(e){const t=de({ownerDocument:c,waferLabel:l=>u[l]?.label??"",...U()});t.card.dataset.wmapPlotId=e.id,R(t.actions),ne(t.actions,e);const s=c.createElement("div");s.dataset.wmapPlotTitleDrift="1",Object.assign(s.style,{display:"none",flexWrap:"wrap",gap:g.md,alignItems:"center",flexBasis:"100%",padding:`${g.xs} ${g.md}`,background:m.warnBg,border:`1px solid ${m.warnBorder}`,borderRadius:J.control,color:m.warnText,fontSize:D.body});const o=c.createElement("div");o.style.flexBasis="100%",t.actions.append(o,s);const r={sweep:!1,card:t.card,actions:t.actions,json:"",driftNote:s,destroy:()=>t.destroy(),update:l=>{const d=Q(l);t.setPlot(d),Ee(o,l),t.card.style.opacity=d.issues.length?"0.7":"1",Pe(s,l)}};return E.set(e.id,r),r}function Se(e){const t=X(e),s=u.flatMap(l=>l.dies),o=pe({spec:t,dies:s,testDefs:n.testDefs,onSaveImage:n.onSaveImage,ownerDocument:c,onSelectPoint:q,readerColors:n.getReaderColors?.()});o.card.dataset.wmapPlotId=e.id,o.card.dataset.wmapSweepPlot="1",R(o.actions),ne(o.actions,e);const r={sweep:!0,card:o.card,actions:o.actions,json:"",destroy:()=>o.destroy(),update:l=>{const d=X(l);o.setSpec(d),o.card.style.opacity=Re(l,n.testDefs??[])?"0.7":"1"}};return E.set(e.id,r),r}function Ee(e,t){const s=t.where;e.replaceChildren(),s&&e.appendChild(qe({doc:c,filter:s,testDefs:n.testDefs,attributes:n.attributes,label:"Filter",words:n.words,onToggle:o=>{const r=i.get().find($=>$.id===t.id),l=r?.where;if(!r||!l)return;const d={...l};o?delete d.off:d.off=!0,i.upsert({...r,where:d})}}))}function Pe(e,t){const s=b?null:Le(Fe(t,x));if(e.replaceChildren(),e.style.display=s?"flex":"none",!s)return;const o=c.createElement("span");o.textContent=s,e.append(o,v("Use the automatic title","wmapPlotAutoTitle","Replace the title you typed with the one written from the chart\u2019s settings",()=>{const r=i.get().find(d=>d.id===t.id);if(!r)return;const l={...r};delete l.title,i.upsert(l)}))}function se(){const e=i.get();for(const[t,s]of E)e.some(o=>o.id===t)||(s.destroy(),s.card.remove(),E.delete(t));e.forEach((t,s)=>{let o=E.get(t.id);o&&o.sweep!==(t.chart==="sweep")&&(o.destroy(),o.card.remove(),E.delete(t.id),o=void 0),o??=ve(t);const r=JSON.stringify(t);o.json!==r&&(o.json=r,o.update(t)),O.children[s]!==o.card&&O.insertBefore(o.card,O.children[s]??null)}),L.style.display=A==="plots"&&e.length===0?"":"none",W.disabled=e.length===0,W.style.opacity=e.length===0?"0.5":"1",W.style.cursor=e.length===0?"default":"pointer"}const De=i.subscribe(se);se();async function Ae(){const e=i.get().slice();if(e.length===0)return;const t=e.length;if(!await He({doc:c,anchor:w,title:"Delete all charts",message:b?t===1?"Delete your 1 saved chart? Export charts\u2026 first to keep a copy.":`Delete all ${t} saved charts? Export charts\u2026 first to keep a copy.`:t===1?"Delete your 1 saved chart? It is kept on this computer for the next lot, so it will not be there for the next file either. Export charts\u2026 first to keep a copy.":`Delete all ${t} saved charts, sweeps included? They are kept on this computer for the next lot, so they will not be there for the next file either. Export charts\u2026 first to keep a copy.`,confirmLabel:t===1?"Delete 1 chart":`Delete ${t} charts`}))return;const o=i.get().slice();o.length!==0&&(i.replaceAll([]),k(`Deleted ${o.length===1?"1 chart":`all ${o.length} charts`}.`,{label:"Undo",run:()=>i.replaceAll(o)}))}function ke(){const e=i.get();if(e.length===0){k("There are no charts to export yet.");return}ot(Ue(e),"wafermap-plots.json","application/json",n.onSaveText)}async function $e(){return n.pickPlotsFile?n.pickPlotsFile():new Promise(e=>{const t=c.createElement("input");t.type="file",t.accept=".json,application/json",t.addEventListener("change",()=>{const s=t.files?.[0];if(!s){e(null);return}s.text().then(e,()=>e(null))}),t.addEventListener("cancel",()=>e(null)),t.click()})}async function Ie(){const e=await $e();if(e===null)return;const t=ze(e);if(t.error){k(`Could not import: ${t.error}`);return}const{plots:s,copies:o}=We(i.get(),t.plots);i.replaceAll(s),V("plots");const r=[...t.warnings,...o.length?[`Kept as copies, since a chart with the same id already existed: ${o.join(", ")}`]:[]];k(`Imported ${t.plots.length} chart${t.plots.length===1?"":"s"}.`,void 0,r)}return{card:w,destroy:()=>{De(),C!==void 0&&clearTimeout(C),ee();for(const e of E.values())e.destroy();E.clear(),i.flush()}}}