All files / src/renderers MeasurementRenderer.js

83.29% Statements 329/395
63.51% Branches 148/233
62.22% Functions 28/45
84.75% Lines 317/374

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692                    1x                         1x                         1x                   1x 1x 1x     1x 1x 1x 1x   1x 1x       1x   1x   1x 1x 1x 1x 2x 1x           1x 1x 1x     1x 1x 1x   1x               1x     1x 1x     1x 1x       1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x     1x 1x                                                                                           1x 1x   1x 1x 1x 1x 2x 1x         1x 1x 1x   1x       1x   1x 1x 1x       1x 1x 1x 1x 2x 1x 1x 1x         1x 1x 1x 1x 4x 1x   3x 3x 3x 3x 3x 1x 1x 1x 1x 1x     3x         1x 3x 3x 3x 3x   3x             3x 3x     3x 3x 3x   3x 3x 3x   3x 3x   3x 3x   3x 3x 3x   3x 3x   3x             1x 1x 1x     1x 1x 1x 1x     1x   1x   1x 1x 1x 1x       1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x   1x 1x   1x         1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x   1x 1x 1x 1x   1x   1x   1x 1x 1x 1x 3x 3x 3x 3x 3x   1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x     1x 1x 1x   1x 1x               1x     1x   1x 31x 31x 31x 93x 93x 62x   93x 93x 31x       31x 31x 31x 31x 1x 1x 1x       31x 1x   30x   31x   1x   1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 93x 3x   90x   3x                     1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x   3x 3x                                             3x 3x                                                             3x   3x 3x 1x 1x   3x 3x 3x                                           3x     3x 3x             3x 3x 3x 3x 3x   3x           3x     3x                     1x 1x 1x 1x 32x 32x 192x 192x 6x 6x 4x       186x 31x   155x   186x         31x 31x 31x       192x 192x 192x   32x 32x 32x   1x       1x 1x 1x 3x 3x 3x 1x 1x     1x                             1x 1x 1x 1x   1x 1x 1x          
// src/renderers/MeasurementRenderer.js
import Plotly from 'plotly.js-dist';
import { DCCRealListQuantity, DCCConformity } from '../dccQuantity.js';
import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';
import { UsedMethodsRenderer } from './UsedMethodsRenderer.js';
import { InfluenceConditionsRenderer } from './InfluenceConditionsRenderer.js';
import { MeasuringEquipmentsRenderer } from './MeasuringEquipmentRenderer.js';
 
// Palette definitions
const palette = [
  '#1f77b4',
  '#ff7f0e',
  '#2ca02c',
  '#d62728',
  '#9467bd',
  '#8c564b',
  '#e377c2',
  '#7f7f7f',
  '#bcbd22',
  '#17becf'
];
 
const lightPalette = [
  '#c6e2ff',
  '#ffddbf',
  '#c9e6c8',
  '#f4c2c2',
  '#dcd0ff',
  '#e0cda9',
  '#ffccff',
  '#d3d3d3',
  '#e6e6a9',
  '#b3ffff'
];
 
const conformityColors = {
  pass: '#2ca02c',
  fail: '#d62728',
  conditionalpass: '#8bc34a',
  conditionalfail: '#ff9800',
  nopass: '#9e9e9e',
  nofail: '#9e9e9e'
};
 
export function renderMeasurementResults(measurementResults, language) {
  console.debug('renderMeasurementResults called with:', measurementResults);
  const container = document.getElementById('measurementResults');
  container.innerHTML = '';
 
  // Create tab headers and content container
  const tabHeader = document.createElement('ul');
  tabHeader.className = 'tab-header';
  const tabContent = document.createElement('div');
  tabContent.className = 'tab-content';
 
  let results = measurementResults['dcc:measurementResult'];
  Iif (!results) {
    console.error("Missing 'dcc:measurementResult' in measurementResults");
    return;
  }
  Eif (!Array.isArray(results)) { results = [results]; }
 
  results.forEach((result, index) => {
    // Determine tab title from dcc:name
    let resultName = 'Measurement Result ' + (index + 1);
    Eif (result['dcc:name'] && result['dcc:name']['dcc:content']) {
      let content = result['dcc:name']['dcc:content'];
      if (Array.isArray(content)) {
        const match = content.find(item => item.$ && item.$.lang === language) || content[0];
        resultName = match._ || match;
      } else E{
        resultName = content._ || content;
      }
    }
    // Create tab header item
    const tabItem = document.createElement('li');
    tabItem.textContent = resultName;
    Eif (index === 0) tabItem.classList.add('active');
 
    // Create tab panel for this measurement result
    const tabPanel = document.createElement('div');
    tabPanel.className = 'tab-panel';
    tabPanel.style.display = (index === 0) ? 'block' : 'none';
 
    tabItem.addEventListener('click', () => {
      document.querySelectorAll('.tab-header li').forEach(li => li.classList.remove('active'));
      document.querySelectorAll('.tab-content > div').forEach(div => div.style.display = 'none');
      tabItem.classList.add('active');
      tabPanel.style.display = 'block';
      // Force a resize event for Plotly to recalc dimensions
      window.dispatchEvent(new Event('resize'));
    });
    tabHeader.appendChild(tabItem);
 
    // Extract the single dcc:result from this measurement result and render it
    let resultObj = result['dcc:results'] && result['dcc:results']['dcc:result'];
    Iif (!resultObj) {
      console.error("Missing 'dcc:results' or 'dcc:result' in measurementResult:", result);
    } else {
      let singleResult = Array.isArray(resultObj) ? resultObj[0] : resultObj;
      renderSingleMeasurementResult(singleResult, language, tabPanel);
    }
 
    // Render Used Methods directly (always visible but collapsed)
    const usedMethodsContainer = document.createElement('div');
    const usedMethodsRenderer = new UsedMethodsRenderer(result['dcc:usedMethods'], language);
    usedMethodsContainer.appendChild(usedMethodsRenderer.render());
    tabPanel.appendChild(usedMethodsContainer);
 
    // Render Influence Conditions using the new renderer (collapsible by default)
    const influenceRenderer = new InfluenceConditionsRenderer(result['dcc:influenceConditions'], language);
    const influenceDetails = document.createElement('div');
    influenceDetails.open = false;
    const influenceSummary = document.createElement('summary');
    influenceDetails.appendChild(influenceSummary);
    influenceDetails.appendChild(influenceRenderer.render());
    tabPanel.appendChild(influenceDetails);
 
    // *** NEW: Render Measuring Equipments using the new renderer (collapsible by default) ***
    const equipmentsRenderer = new MeasuringEquipmentsRenderer(result['dcc:measuringEquipments'], language);
    const equipmentsDetails = document.createElement('div');
    equipmentsDetails.open = false;
    const equipmentsSummary = document.createElement('summary');
    equipmentsDetails.appendChild(equipmentsSummary);
    equipmentsDetails.appendChild(equipmentsRenderer.render());
    tabPanel.appendChild(equipmentsDetails);
    tabContent.appendChild(tabPanel);
  });
 
  container.appendChild(tabHeader);
  container.appendChild(tabContent);
}
 
// Helper to render used methods as JSON tree via JSONEditor
function renderUsedMethods(measurementResult, language) {
  const container = document.createElement('div');
  container.style.maxHeight = '200px';
  container.style.overflowY = 'auto';
  const options = {
    mode: 'view',
    mainMenuBar: false,
    navigationBar: false,
    statusBar: false
  };
  const editor = new JSONEditor(container, options);
  if (measurementResult['dcc:usedMethods']) {
    editor.set(measurementResult['dcc:usedMethods']);
  } else {
    container.textContent = 'No used methods data available.';
  }
  return container;
}
 
// Helper to render influence conditions as JSON tree via JSONEditor
function renderInfluenceConditions(measurementResult, language) {
  const container = document.createElement('div');
  container.style.maxHeight = '200px';
  container.style.overflowY = 'auto';
  const options = {
    mode: 'view',
    mainMenuBar: false,
    navigationBar: false,
    statusBar: false
  };
  const editor = new JSONEditor(container, options);
  if (measurementResult['dcc:influenceConditions']) {
    editor.set(measurementResult['dcc:influenceConditions']);
  } else {
    container.textContent = 'No influence conditions data available.';
  }
  return container;
}
 
// In src/renderers/MeasurementRenderer.js, update the renderSingleMeasurementResult function:
 
export function renderSingleMeasurementResult(resultObj, language, tabPanel) {
  console.debug('renderSingleMeasurementResult called with:', resultObj);
  tabPanel.innerHTML = '';
 
  let resultName = 'Measurement Result';
  Eif (resultObj['dcc:name'] && resultObj['dcc:name']['dcc:content']) {
    let content = resultObj['dcc:name']['dcc:content'];
    if (Array.isArray(content)) {
      const match = content.find(item => item.$ && item.$.lang === language) || content[0];
      resultName = match._ || match;
    } else E{
      resultName = content._ || content;
    }
  }
  const header = document.createElement('h2');
  header.textContent = resultName;
  tabPanel.appendChild(header);
 
  Iif (!resultObj['dcc:data'] || !resultObj['dcc:data']['dcc:list']) {
    console.error("Missing 'dcc:data' or 'dcc:list' in result object:", resultObj);
    return;
  }
  const listData = resultObj['dcc:data']['dcc:list'];
 
  let quantityJSONs = [];
  Eif (listData['dcc:quantity']) {
    quantityJSONs = Array.isArray(listData['dcc:quantity'])
        ? listData['dcc:quantity']
        : [listData['dcc:quantity']];
  }
  Eif (listData['dcc:measurementMetaData'] && listData['dcc:measurementMetaData']['dcc:metaData']) {
    let metaData = listData['dcc:measurementMetaData']['dcc:metaData'];
    Iif (!Array.isArray(metaData)) { metaData = [metaData]; }
    metaData.forEach(md => {
      if (md['dcc:data'] && md['dcc:data']['dcc:quantity']) {
        let qs = md['dcc:data']['dcc:quantity'];
        Eif (!Array.isArray(qs)) { qs = [qs]; }
        quantityJSONs = quantityJSONs.concat(qs);
      }
    });
  }
 
  const indexQuantities = [];
  const dataQuantities = [];
  const extraInfo = [];
  quantityJSONs.forEach(q => {
    if (q.$ && q.$.refType && q.$.refType.match(/basic_tableIndex/)) {
      indexQuantities.push(new DCCRealListQuantity(q));
    } else {
      const quantity = new DCCRealListQuantity(q);
      dataQuantities.push(quantity);
      let uncertainty = quantity.getUncertainty();
      let conformity = null;
      if (q['dcc:measurementMetaData'] && q['dcc:measurementMetaData']['dcc:metaData']) {
        let md = q['dcc:measurementMetaData']['dcc:metaData'];
        Eif (!Array.isArray(md)) { md = [md]; }
        const confMeta = md.find(item => item.$ && item.$.refType && item.$.refType.includes('basic_conformity'));
        Eif (confMeta) {
          conformity = new DCCConformity(confMeta, language);
        }
      }
      extraInfo.push({ uncertainty, conformity });
    }
  });
 
  // Build header texts using dsiUnits conversion.
  const dataHeaders = dataQuantities.map((q, idx) => {
    let headerText = q.getName(language);
    let unit = q.getUnit({ oneLine: true, wrapper: 'span' });
    Eif (!headerText.toLowerCase().includes(" in ")) {
      headerText = `${headerText} in ${unit}`;
    }
    return headerText;
  });
 
// Create scaling toggles and X-axis selector controls
 
// === Helper function to create a mobile-friendly toggle switch ===
  function createToggleSwitch(id, labelText) {
    const switchContainer = document.createElement('div');
    switchContainer.classList.add('toggle-switch-container');
 
    // The label acts as the clickable area
    const toggleSwitch = document.createElement('label');
    toggleSwitch.classList.add('toggle-switch');
    toggleSwitch.htmlFor = id;
 
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = id;
 
    const slider = document.createElement('span');
    slider.classList.add('slider');
 
    toggleSwitch.appendChild(checkbox);
    toggleSwitch.appendChild(slider);
 
    const switchLabel = document.createElement('span');
    switchLabel.textContent = labelText;
    switchLabel.classList.add('toggle-label');
 
    switchContainer.appendChild(toggleSwitch);
    switchContainer.appendChild(switchLabel);
 
    return switchContainer;
  }
 
// === Build the control elements ===
// --- 1. Scaling toggles (Log-scale X and Y) ---
 
// Container for scaling controls
  const scalingContainer = document.createElement('div');
  scalingContainer.classList.add('mobile-control');
  scalingContainer.innerHTML = '<strong>Log-Axis Scaling:</strong> ';
 
// Flex container for side-by-side toggle switches
  const scalingToggles = document.createElement('div');
  scalingToggles.style.display = 'flex';
  scalingToggles.style.flexWrap = 'wrap';
  scalingToggles.style.gap = '10px';
 
// Create toggle switch for Log-scale X
  const logXSwitch = createToggleSwitch('logXToggle', 'X');
// Create toggle switch for Log-scale Y
  const logYSwitch = createToggleSwitch('logYToggle', 'Y');
 
  scalingToggles.appendChild(logXSwitch);
  scalingToggles.appendChild(logYSwitch);
  scalingContainer.appendChild(scalingToggles);
  tabPanel.appendChild(scalingContainer);
 
// --- 2. X-axis selector controls (Radio buttons) ---
 
  const xAxisContainer = document.createElement('div');
  xAxisContainer.classList.add('mobile-control');
  xAxisContainer.innerHTML = '<strong>Select X-Axis</strong> ';
 
  indexQuantities.forEach((q, idx) => {
    let nameStr = q.getName(language) || ('Index ' + idx);
    const radio = document.createElement('input');
    radio.type = 'radio';
    radio.name = 'xAxisSelect';
    radio.value = idx;
    Eif (idx === 0) { radio.checked = true; }
    // Optionally add a class for further styling:
    radio.classList.add('mobile-radio');
 
    const label = document.createElement('label');
    label.textContent = nameStr;
    label.style.marginRight = '10px';
 
    xAxisContainer.appendChild(radio);
    xAxisContainer.appendChild(label);
  });
  tabPanel.appendChild(xAxisContainer);
 
 
// --- 3. Tolerance toggle switch ("Show conformity limits") ---
 
  const tolContainer = document.createElement('div');
  tolContainer.classList.add('mobile-control');
  const toleranceSwitch = createToggleSwitch('toleranceToggle', 'Conformity limits');
  tolContainer.appendChild(toleranceSwitch);
  tabPanel.appendChild(tolContainer);
 
  // Create containers for plots and table, add extra spacing between them.
  const subplotsContainer = document.createElement('div');
  subplotsContainer.id = 'subplotsContainer';
  tabPanel.appendChild(subplotsContainer);
  const tableContainer = document.createElement('div');
  tableContainer.id = 'tableContainer';
  tableContainer.style.marginTop = '20px';
  tabPanel.appendChild(tableContainer);
 
  function updateVisualization() {
    const selectedRadio = tabPanel.querySelector('input[name="xAxisSelect"]:checked');
    Iif (!selectedRadio) { console.error('No X-Axis selection found.'); return; }
    const selectedIndex = selectedRadio.value;
    const xQuantity = indexQuantities[selectedIndex];
    const xValues = xQuantity.getValues();
    // Get xUnit using dsiUnits conversion with oneLine true.
    const xUnit = xQuantity.getUnit({ oneLine: true, wrapper: 'span' });
    const XQuantityName = xQuantity.getName(language);
    console.debug('Selected X-Axis values:', xValues);
    console.debug('X-Axis unit:', xUnit);
 
    const headers = [];
    // Use the new header format for the X-axis column.
    headers.push(`${XQuantityName} in ${xUnit} (selected X)`);
 
    const dataValues = [];
    const uncertaintiesArray = [];
    const conformityArray = [];
    extraInfo.forEach((info, idx) => {
      headers.push(dataHeaders[idx]);
      if (info.conformity) { headers.push('Conformity'); }
      dataValues.push(dataQuantities[idx].getValues());
      uncertaintiesArray.push(info.uncertainty || []);
      conformityArray.push(info.conformity ? info.conformity.getConformityValues() : []);
    });
    let commentsArray = [];
    Eif (listData['dcc:measurementMetaData'] && listData['dcc:measurementMetaData']['dcc:metaData']) {
      let metaData = listData['dcc:measurementMetaData']['dcc:metaData'];
      Iif (!Array.isArray(metaData)) { metaData = [metaData]; }
      metaData.forEach(md => {
        if (md.$ && md.$.refType && md.$.refType.includes('basic_tableRowComment')) {
          let commentName = '';
          Eif (md['dcc:name'] && md['dcc:name']['dcc:content']) {
            let content = md['dcc:name']['dcc:content'];
            commentName = Array.isArray(content)
                ? (content.find(item => item.$ && item.$.lang === language) || content[0])._ || ''
                : content._ || content;
          }
          let commentDescription = '';
          Eif (md['dcc:description'] && md['dcc:description']['dcc:content']) {
            let desc = md['dcc:description']['dcc:content'];
            commentDescription = Array.isArray(desc)
                ? (desc.find(item => item.$ && item.$.lang === language) || desc[0])._ || ''
                : desc._ || desc;
          }
          let validListStr = '';
          Eif (md['dcc:validXMLList']) {
            validListStr = md['dcc:validXMLList'].trim();
          }
          let validArray = validListStr.split(/\s+/);
          commentsArray.push({
            name: commentName,
            description: commentDescription,
            valid: validArray
          });
        }
      });
    }
    headers.push('Comments');
 
 
    const tableData = [headers];
// Then, when building each data row:
    for (let i = 0; i < xValues.length; i++) {
      const row = [];
      row.push(xValues[i]);
      extraInfo.forEach((info, idx) => {
        let cellValue = (dataValues[idx][i] !== undefined) ? dataValues[idx][i] : '';
        if (uncertaintiesArray[idx] && uncertaintiesArray[idx][i] !== undefined) {
          cellValue = `${cellValue} ± ${uncertaintiesArray[idx][i]}`;
        }
        row.push(cellValue);
        if (info.conformity) {
          row.push(conformityArray[idx][i] || '');
        }
      });
      // NEW: Build comment cell by checking each comment's valid array for this row
            let tooltipText = '';
            let headerText = '';
            commentsArray.forEach(comment => {
                  if (comment.valid[i] && comment.valid[i].toLowerCase() === 'true') {
                        tooltipText += `${comment.description}\n`;
                       Eif (!headerText) {
                              headerText = comment.name;
                          }
                    }
              });
      if (tooltipText) {
        row.push(`<strong>${headerText}</strong> <details style="display:inline;"><summary style="cursor:pointer; display:inline; list-style:none;">&#9660;</summary><div>${tooltipText.trim()}</div></details>`);
      } else {
        row.push('');
      }
      tableData.push(row);
    }
    renderTable(tableData, computeConformityMapping());
 
    const unitGroups = {};
    dataQuantities.forEach((q, idx) => {
      const unit = q.getUnit({ oneLine: false });
      Eif (!unitGroups[unit]) { unitGroups[unit] = []; }
      const headerText = dataHeaders[idx];
      let values = q.getValues();
      const uncertainty = uncertaintiesArray[idx];
      const conformity = conformityArray[idx];
      const defaultColor = palette[idx % palette.length];
      const markerColorArray = values.map((val, i) => {
        if (conformity && conformity[i] && conformity[i].toLowerCase().includes('fail')) {
          return conformityColors.fail;
        }
        return defaultColor;
      });
      unitGroups[unit].push({
        name: headerText,
        y: values,
        uncertainty,
        conformity,
        defaultColor,
        markerColor: markerColorArray,
        index: idx
      });
    });
 
    subplotsContainer.innerHTML = '';
    const unitKeys = Object.keys(unitGroups);
    const plotDivs = [];
    unitKeys.forEach((unit, groupIdx) => {
      const group = unitGroups[unit];
      const graphDiv = document.createElement('div');
      graphDiv.style.width = '100%';
      graphDiv.style.height = '300px';
      subplotsContainer.appendChild(graphDiv);
      plotDivs.push(graphDiv);
      const groupTraces = group.map(trace => {
        let tooltip = `X: %{x} ${xUnit} | ${trace.name}: %{y}`;
        if (trace.conformity && trace.conformity.length > 0) {
          tooltip += ' | Conformity: %{customdata}';
        }
        tooltip += '<extra></extra>';
        return {
          x: xValues,
          y: trace.y,
          error_y: {
            type: 'data',
            array: (trace.uncertainty && trace.uncertainty.length === xValues.length)
                ? trace.uncertainty
                : new Array(xValues.length).fill(0),
            visible: true,
            color: trace.defaultColor
          },
          type: 'scatter',
          mode: 'lines+markers',
          name: trace.name,
          marker: { color: trace.markerColor },
          line: { color: trace.defaultColor },
          hovertemplate: tooltip,
          customdata: (trace.conformity && trace.conformity.length === xValues.length)
              ? trace.conformity
              : new Array(xValues.length).fill('')
        };
      });
 
      const toleranceTraces = [];
      Iif (tabPanel.querySelector('#toleranceToggle').checked) {
        group.forEach(trace => {
          const confObj = extraInfo[trace.index].conformity;
          if (confObj) {
            const lower = confObj.getLowerLimit(language);
            const upper = confObj.getUpperLimit(language);
            if (lower && typeof lower.value === 'number') {
              toleranceTraces.push({
                x: [Math.min(...xValues), Math.max(...xValues)],
                y: [lower.value, lower.value],
                mode: 'lines',
                line: { dash: 'dash', color: '#d62728', width: 2 },
                name: lower.name,
                hoverinfo: 'none',
                showlegend: true
              });
            }
            if (upper && typeof upper.value === 'number') {
              toleranceTraces.push({
                x: [Math.min(...xValues), Math.max(...xValues)],
                y: [upper.value, upper.value],
                mode: 'lines',
                line: { dash: 'dot', color: '#d62728', width: 2 },
                name: upper.name,
                hoverinfo: 'none',
                showlegend: true
              });
            }
          }
        });
      }
      const allTraces = groupTraces.concat(toleranceTraces);
 
      let xaxisTitle = '';
      if (groupIdx === unitKeys.length - 1) {
        let xLabel = 'X: ' + xQuantity.getName(language);
        xaxisTitle = `<b>${xLabel} in ${xUnit}</b>`;
      }
      const logX = tabPanel.querySelector('#logXToggle').checked;
      const logY = tabPanel.querySelector('#logYToggle').checked;
      const layout = {
        xaxis: {
          title: { text: xaxisTitle, font: { size: 36, family: 'Arial', color: 'black' } },
          tickfont: { family: 'Arial', size: 14, color: 'black' },
          type: logX ? 'log' : 'linear'
        },
        yaxis: {
          title: { text: unit, font: { size: 18, family: 'Arial', color: 'black' } },
          tickfont: { family: 'Arial', size: 14, color: 'black' },
          type: logY ? 'log' : 'linear'
        },
        legend: {
          orientation: 'h',
          x: 0.5,
          y: 0.98,
          xanchor: 'center',
          yanchor: 'top'
        },
        hovermode: 'closest',
        margin: { t: 20, b: 40 }
      };
      // Check for touch (coarse pointer) devices:
      Iif (window.matchMedia && window.matchMedia('(pointer: coarse)').matches) {
        layout.dragmode = false;
      }
      Plotly.newPlot(graphDiv, allTraces, layout, { responsive: true }).then(() => {
        setTimeout(() => {
          if (graphDiv.offsetWidth > 0 && graphDiv.offsetHeight > 0) {
            Plotly.Plots.resize(graphDiv);
          } else {
            console.warn('Plot div is not visible; skipping resize.');
          }
        }, 100);
        const caption = document.createElement('div');
        caption.innerHTML = `<b>${group[0].name}</b>`;
        caption.style.textAlign = 'center';
        caption.style.marginBottom = '5px';
        graphDiv.parentNode.insertBefore(caption, graphDiv);
      });
      graphDiv.on('plotly_hover', function(data) {
        if (data.points && data.points.length > 0) {
          const pointIndex = data.points[0].pointIndex + 1;
          highlightTableRow(pointIndex);
        }
      });
      graphDiv.on('plotly_unhover', function() {
        clearTableRowHighlights();
      });
      graphDiv.on('plotly_relayout', function(eventData) {
        plotDivs.forEach(div => {
          if (div !== graphDiv && eventData['xaxis.range[0]'] && eventData['xaxis.range[1]']) {
            Plotly.relayout(div, { 'xaxis.range': [eventData['xaxis.range[0]'], eventData['xaxis.range[1]']] });
          }
        });
      });
    });
  }
 
  function renderTable(tableData, conformityMapping) {
    const tableContainer = tabPanel.querySelector('#tableContainer');
    tableContainer.innerHTML = '';
    const table = document.createElement('table');
    tableData.forEach((rowData, rowIndex) => {
      const tr = document.createElement('tr');
      rowData.forEach((cellData, cellIndex) => {
        const cell = document.createElement(rowIndex === 0 ? 'th' : 'td');
        if (rowIndex === 0) {
          cell.innerHTML = cellData;
          if (cellData !== 'Comments' && cellIndex > 0 && conformityMapping[cellIndex] !== undefined) {
            cell.style.backgroundColor = conformityMapping[cellIndex];
          }
        } else {
          // For non-header rows, if this is the last column (Comments), use innerHTML.
          if (cellIndex === rowData.length - 1) {
            cell.innerHTML = cellData;
          } else {
            cell.textContent = cellData;
          }
          if (
              tableData[0][cellIndex] &&
              tableData[0][cellIndex].toLowerCase().includes('conformity') &&
              conformityMapping[cellIndex] !== undefined
          ) {
            const confKey = cellData.trim().toLowerCase();
            Eif (conformityColors[confKey]) {
              cell.style.backgroundColor = conformityColors[confKey];
            }
          }
        }
        cell.style.padding = '4px';
        cell.style.border = '1px solid #ccc';
        tr.appendChild(cell);
      });
      tr.addEventListener('mouseover', () => { tr.style.backgroundColor = '#eef'; });
      tr.addEventListener('mouseout', () => { tr.style.backgroundColor = ''; });
      table.appendChild(tr);
    });
    tableContainer.appendChild(table);
  }
 
  function computeConformityMapping() {
    let mapping = {};
    let col = 1; // Column 0 is X-Axis.
    for (let i = 0; i < dataHeaders.length; i++) {
      mapping[col] = palette[i % palette.length]; // Color the data header column
      col++;
      if (extraInfo[i] && extraInfo[i].conformity) {
        mapping[col] = palette[i % palette.length]; // Color the conformity header column
        col++;
      }
    }
    return mapping;
  }
 
  function highlightTableRow(rowIndex) {
    const rows = tabPanel.querySelector('#tableContainer').querySelectorAll('tr');
    if (rows[rowIndex]) {
      rows[rowIndex].style.backgroundColor = '#fee';
    }
  }
 
  function clearTableRowHighlights() {
    const rows = tabPanel.querySelector('#tableContainer').querySelectorAll('tr');
    rows.forEach(row => row.style.backgroundColor = '');
  }
 
  updateVisualization();
  const radios = tabPanel.querySelectorAll('input[name="xAxisSelect"]');
  radios.forEach(radio => {
    radio.addEventListener('change', updateVisualization);
  });
  tabPanel.querySelector('#logXToggle').addEventListener('change', updateVisualization);
  tabPanel.querySelector('#logYToggle').addEventListener('change', updateVisualization);
  tabPanel.querySelector('#toleranceToggle').addEventListener('change', () => {
    console.log('Tolerance toggle:', tabPanel.querySelector('#toleranceToggle').checked);
    updateVisualization();
  });
}