All files / Scripts/ui Table.ts

92.98% Statements 265/285
67.03% Branches 61/91
90.74% Functions 49/54
92.7% Lines 254/274

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  1x 1x       1x 1x 1x               1x 18x 18x   18x 24x 24x 24x 24x 24x 24x         43x 43x 43x 43x 43x 43x           20x 20x         108x 108x 90x 85x   5x   5x 5x 5x 5x 5x 5x       5x 5x 5x 5x   5x 5x 5x         5x 5x 5x 5x   5x 5x 5x     5x 5x 5x 5x 5x 5x   5x       1253x 1253x 11618x 450x   11168x           90x 90x 90x 90x         54x 54x 54x   54x 522x 522x 522x 522x 522x 522x 522x 144x   378x   522x 522x   522x 522x 522x   522x             39x 2283x   39x 39x 39x         581x 581x 581x 1x     1x     1x   580x 580x           181x 181x 181x 181x 181x         41x 41x 41x 41x 2209x 2209x           23x 148x     23x       21x 21x 1658x     1658x 1658x 1658x 1658x 182x 121x       1658x 1537x 1537x   121x 121x                 20x     20x 160x       20x 20x 20x 20x 20x 20x   20x 20x 20x 20x 20x 20x 20x       20x       20x 20x 20x 20x 20x         20x 20x 20x 20x               20x 194x 20x     20x 340x       20x 80x       20x 20x                     20x 184x     20x   20x       216x 216x 216x 216x 216x   216x 216x 216x 216x 216x 216x 216x 216x     216x 1x 1x 1x 1x   1x       216x 216x 216x     216x 216x       216x       36x 36x 36x 36x   36x 36x 36x 36x   36x 216x 216x 216x             1x 1x 1x       1x 1x 1x       2x 1x   1x     2x           90x   10x 10x       90x 36x     36x 18x                     18x 18x       36x 18x         18x         90x 54x 54x       90x       18x 18x 18x 18x 18x 18x 18x   18x 18x 18x 18x   18x 18x     18x 18x 342x               19x 19x         18x     18x     18x     18x 18x 18x 18x 18x   18x 18x                      
import { HeaderModel } from "../HeaderModel";
import { mhaStrings } from "../mhaStrings";
import { DomUtils } from "./domUtils";
import { OtherRow } from "../row/OtherRow";
import { ReceivedRow } from "../row/ReceivedRow";
import { Row } from "../row/Row";
import { Column } from "../table/Column";
import { DataTable } from "../table/DataTable";
import { SummaryTable } from "../table/SummaryTable";
import { TableSection } from "../table/TableSection";
 
type Binding = {
    name: string;
    visible: (table: Table) => boolean;
}
 
export class Table {
    private viewModel: HeaderModel = <HeaderModel>{};
    private showExtra = false;
 
    private visibilityBindings: Binding[] = [
        { name: "#lineBreak", visible: function (table: Table) { return table.viewModel.hasData; } },
        { name: "#response", visible: function (table: Table) { return table.viewModel.hasData; } },
        { name: "#status", visible: function (table: Table) { return !!table.viewModel.status; } },
        { name: ".extraCol", visible: function (table: Table) { return table.showExtra; } },
        { name: "#clearButton", visible: function (table: Table) { return table.viewModel.hasData; } },
        { name: "#copyButton", visible: function (table: Table) { return table.viewModel.hasData; } }
    ];
 
    // Adjusts response under our lineBreak
    private positionResponse(): void {
        const lineBreak = document.getElementById("lineBreak");
        Eif (lineBreak) {
            const responseTop: number = lineBreak.offsetTop + (lineBreak.offsetHeight ?? 0);
            const responseElement = document.getElementById("response");
            Eif (responseElement) {
                responseElement.style.top = (responseTop + 15) + "px";
            }
        }
    }
 
    private toggleCollapse(id: string): void {
        DomUtils.toggleClass("#" + id, "hiddenElement");
        this.positionResponse();
    }
 
    // Wraps an element into a collapsible pane with a title
    public makeResizablePane(id: string, paneClass: string, title: string, visibility: (table: Table) => boolean): void {
        const paneElement = document.getElementById(id);
        if (!paneElement) return;
        if (paneElement.classList.contains("collapsibleElement")) {
            return;
        }
        const hidden = paneElement.classList.contains("hiddenElement");
 
        paneElement.classList.add("collapsibleElement");
        const wrapElement = document.createElement("div");
        wrapElement.classList.add("collapsibleWrapper");
        Eif (visibility) {
            wrapElement.setAttribute("id", id + "Wrapper");
            this.visibilityBindings.push({ name: "#" + id + "Wrapper", visible: visibility });
        }
 
        // Fix for Bug 1691235 - Create a hidden h2 element for a11y
        const hiddenHeadingElement = document.createElement("h2");
        hiddenHeadingElement.setAttribute("id", "button-heading");
        hiddenHeadingElement.classList.add("header-hidden");
        hiddenHeadingElement.textContent = title;
 
        const headerElement = document.createElement("button");
        headerElement.classList.add(paneClass);
        headerElement.addEventListener("click", () => {
            this.toggleCollapse(id);
            const currentExpanded = headerElement.getAttribute("aria-expanded") === "true";
            headerElement.setAttribute("aria-expanded", currentExpanded ? "false" : "true");
        });
        headerElement.textContent = title;
        headerElement.setAttribute("tabindex", "0");
        headerElement.setAttribute("type", "button");
        headerElement.setAttribute("aria-expanded", !hidden ? "true" : "false");
 
        const switchSpanElement = document.createElement("span");
        switchSpanElement.setAttribute("aria-hidden", "true");
        switchSpanElement.classList.add("collapsibleSwitch");
 
        // Now that everything is built, put it together
        const parent = paneElement.parentNode;
        Eif (parent) {
            parent.insertBefore(wrapElement, paneElement);
            wrapElement.appendChild(paneElement);
            wrapElement.insertBefore(hiddenHeadingElement, paneElement);
            wrapElement.insertBefore(headerElement, paneElement);
        }
        headerElement.appendChild(switchSpanElement);
    }
 
    private makeVisible(id: string, visible: boolean): void {
        const elements = document.querySelectorAll(id);
        elements.forEach(element => {
            if (visible) {
                element.classList.remove("hiddenElement");
            } else {
                element.classList.add("hiddenElement");
            }
        });
    }
 
    private addTableAccessibility(section: TableSection): void {
        const table = document.getElementById(section.tableName);
        Eif (table) {
            table.setAttribute("aria-label", section.getAriaLabel());
            table.setAttribute("role", "table");
        }
    }
 
    private makeSummaryTable(summaryName: string, rows: Row[], tag: string): void {
        const summaryListElement = document.querySelector(summaryName);
        Eif (summaryListElement) {
            summaryListElement.classList.add("summaryList");
 
            rows.forEach((summaryRow: Row) => {
                const id = summaryRow.header + tag;
                const row = document.createElement("tr");
                Eif (row !== null) {
                    row.id = id;
                    summaryListElement.appendChild(row); // Must happen before we append cells to appease IE7
                    const headerCell = row.insertCell(-1);
                    if (summaryRow.url) {
                        headerCell.innerHTML = summaryRow.url;
                    } else {
                        headerCell.textContent = summaryRow.label;
                    }
                    headerCell.classList.add("summaryHeader");
                    headerCell.setAttribute("id", summaryRow.header + "_id" + tag);
 
                    const valCell = row.insertCell(-1);
                    valCell.setAttribute("id", id + "Val");
                    valCell.setAttribute("aria-labelledby", summaryRow.header + "_id" + tag);
 
                    this.makeVisible("#" + id, false);
                }
            });
        }
    }
 
    private setArrows(table: string, colName: string, sortOrder: number): void {
        const headers = document.querySelectorAll(`#${table} th[role="columnheader"]`);
        headers.forEach(header => header.setAttribute("aria-sort", "none"));
 
        const targetButton = document.querySelector(`#${table} th #${colName}`);
        Eif (targetButton && targetButton.parentElement) {
            targetButton.parentElement.setAttribute("aria-sort", sortOrder === 1 ? "descending" : "ascending");
        }
    }
 
    private setRowValue(row: Row, type: string): void {
        const headerVal = document.getElementById(row.header + type + "Val");
        Eif (headerVal) {
            if (row.value) {
                Iif (row.valueUrl) {
                    headerVal.innerHTML = row.valueUrl;
                } else {
                    headerVal.textContent = row.value;
                }
 
                this.makeVisible("#" + row.header + type, true);
            } else {
                headerVal.textContent = "";
                this.makeVisible("#" + row.header + type, false);
            }
        }
    }
 
    private appendCell(row: HTMLTableRowElement, text: string | number | null, html: string, cellClass: string, headerId?: string): void {
        const cell = row.insertCell(-1);
        if (text) { cell.textContent = text.toString(); }
        if (html) { cell.innerHTML = html; }
        if (cellClass) { cell.classList.add(cellClass); }
        if (headerId) { cell.setAttribute("headers", headerId); }
    }
 
    // Restores table to empty state so we can repopulate it
    private emptyTableUI(id: string): void {
        const rowsToRemove = document.querySelectorAll(`#${id} tr:not(.tableHeader)`);
        rowsToRemove.forEach(row => row.remove()); // Remove the rows
        const headers = document.querySelectorAll(`#${id} th`);
        headers.forEach(header => {
            header.classList.remove("emptyColumn"); // Restore header visibility
            header.classList.remove("hiddenElement"); // Restore header visibility
        });
    }
 
    // Recompute visibility with the current viewModel. Does not repopulate.
    public recalculateVisibility(): void {
        this.visibilityBindings.forEach((binding: Binding) => {
            this.makeVisible(binding.name, binding.visible(this));
        });
 
        this.positionResponse();
    }
 
    private hideEmptyColumns(id: string): void {
        const headers = document.querySelectorAll(`#${id} th`);
        headers.forEach((header, i) => {
            let keep = 0;
 
            // Find a child cell which has data
            const table = header.closest("table");
            Eif (table) {
                const children = table.querySelectorAll(`tr td:nth-child(${i + 1})`);
                children.forEach((cell) => {
                    if (cell.innerHTML !== "") {
                        keep++;
                    }
                });
 
                if (keep === 0) {
                    header.classList.add("emptyColumn");
                    children.forEach(cell => cell.classList.add("emptyColumn"));
                } else {
                    header.classList.remove("emptyColumn");
                    children.forEach(cell => cell.classList.remove("emptyColumn"));
                }
            }
        });
    }
 
    // Rebuilds content and recalculates what sections should be displayed
    // Repopulate the UI with the current viewModel
    public rebuildSections(viewModel: HeaderModel): void {
        this.viewModel = viewModel;
 
        // Summary
        this.viewModel.summary.rows.forEach((row: Row) => {
            this.setRowValue(row, "SUM");
        });
 
        // Received
        this.emptyTableUI("receivedHeaders");
        this.viewModel.receivedHeaders.rows.forEach((receivedRow: ReceivedRow) => {
            const row: HTMLTableRowElement = document.createElement("tr");
            const receivedHeadersTable = document.getElementById("receivedHeaders");
            Eif (receivedHeadersTable) {
                receivedHeadersTable.appendChild(row); // Must happen before we append cells to appease IE7
            }
            this.appendCell(row, receivedRow.hop.value, "", "", "hop_header");
            this.appendCell(row, receivedRow.from.value, "", "", "from_header");
            this.appendCell(row, receivedRow.by.value, "", "", "by_header");
            this.appendCell(row, receivedRow.date.value, "", "", "date_header");
            let labelClass = "hotBarLabel";
            Eif (receivedRow.delaySort.value !== null && typeof receivedRow.delaySort.value === "number" && receivedRow.delaySort.value < 0) {
                labelClass += " negativeCell";
            }
 
            const hotBar =
                "<div class='hotBarContainer'>" +
                "   <div class='" + labelClass + "'>" + receivedRow.delay + "</div>" +
                "   <div class='hotBarBar' style='width:" + receivedRow.percent + "%'></div>" +
                "</div>";
            this.appendCell(row, "", hotBar, "hotBarCell", "delay_header");
            this.appendCell(row, receivedRow.with.value, "", "", "with_header");
            this.appendCell(row, receivedRow.id.value, "", "extraCol", "id_header");
            this.appendCell(row, receivedRow.for.value, "", "extraCol", "for_header");
            this.appendCell(row, receivedRow.via.value, "", "extraCol", "via_header");
        });
 
        // Calculate heights for the hotbar cells (progress bars in Delay column)
        // Not clear why we need to do this
        const hotBarCells = document.querySelectorAll(".hotBarCell");
        hotBarCells.forEach(cell => {
            const height = (cell as HTMLElement).offsetHeight;
            Iif (height) {
                const container = cell.querySelector(".hotBarContainer") as HTMLElement;
                if (container) {
                    container.style.height = height + "px";
                }
            }
        });
 
        const receivedRows = document.querySelectorAll("#receivedHeaders tr:nth-child(odd)");
        receivedRows.forEach(row => row.classList.add("oddRow"));
        this.hideEmptyColumns("receivedHeaders");
 
        // Forefront AntiSpam Report
        this.viewModel.forefrontAntiSpamReport.rows.forEach((row: Row) => {
            this.setRowValue(row, "FFAS");
        });
 
        // AntiSpam Report
        this.viewModel.antiSpamReport.rows.forEach((row: Row) => {
            this.setRowValue(row, "AS");
        });
 
        // Other
        this.emptyTableUI("otherHeaders");
        this.viewModel.otherHeaders.rows.forEach((otherRow: OtherRow) => {
            const row: HTMLTableRowElement = document.createElement("tr");
            const otherHeadersTable = document.getElementById("otherHeaders");
            if (otherHeadersTable) {
                otherHeadersTable.appendChild(row); // Must happen before we append cells to appease IE7
            }
            this.appendCell(row, otherRow.number.toString(), "", "", "number_header");
            this.appendCell(row, otherRow.header, otherRow.url, "", "header_header");
            this.appendCell(row, otherRow.value, "", "allowBreak", "value_header");
        });
 
        const otherRows = document.querySelectorAll("#otherHeaders tr:nth-child(odd)");
        otherRows.forEach(row => row.classList.add("oddRow"));
 
        // Original headers
        DomUtils.setText("#originalHeaders", this.viewModel.originalHeaders);
 
        this.recalculateVisibility();
    }
 
    private makeSortableColumn(tableName: string, column: Column): HTMLTableCellElement {
        const header = document.createElement("th");
        Eif (header !== null) {
            header.setAttribute("role", "columnheader");
            header.setAttribute("aria-sort", "none");
            header.setAttribute("id", column.id + "_header"); // Add unique ID for headers attribute
 
            const headerButton = document.createElement("button");
            Eif (headerButton !== null) {
                headerButton.setAttribute("class", "tableHeaderButton");
                headerButton.setAttribute("id", column.id);
                headerButton.setAttribute("type", "button");
                headerButton.innerHTML = column.label;
                Eif (column.class !== null) {
                    headerButton.setAttribute("class", "tableHeaderButton " + column.class);
                }
 
                headerButton.addEventListener("click", () => {
                    Eif (this.viewModel[tableName] instanceof DataTable) {
                        const dataTable = this.viewModel[tableName] as DataTable;
                        dataTable.doSort(column.id);
                        this.setArrows(dataTable.tableName, dataTable.sortColumn,
                            dataTable.sortOrder);
                        this.rebuildSections(this.viewModel);
                    }
                });
 
                const arrowSpan = document.createElement("span");
                arrowSpan.setAttribute("aria-hidden", "true");
                arrowSpan.classList.add("sortArrow");
 
                // Now that everything is built, put it together
                headerButton.appendChild(arrowSpan);
                header.appendChild(headerButton);
            }
        }
 
        return header;
    }
 
    private addColumns(tableName: string, columns: Column[]): void {
        const tableHeader = document.createElement("thead");
        const table = document.getElementById(tableName);
        Eif (table) {
            table.appendChild(tableHeader);
 
            const headerRow = document.createElement("tr");
            headerRow.classList.add("tableHeader");
            headerRow.setAttribute("role", "row");
            tableHeader.appendChild(headerRow); // Must happen before we append cells to appease IE7
 
            columns.forEach((column: Column) => {
                const sortableColumn = this.makeSortableColumn(tableName, column);
                Eif (sortableColumn) {
                    headerRow.appendChild(sortableColumn);
                }
            });
        }
    }
 
    private hideExtraColumns(): void {
        this.showExtra = false;
        DomUtils.addClass("#leftArrow", "hiddenElement");
        DomUtils.removeClass("#rightArrow", "hiddenElement");
    }
 
    private showExtraColumns(): void {
        this.showExtra = true;
        DomUtils.addClass("#rightArrow", "hiddenElement");
        DomUtils.removeClass("#leftArrow", "hiddenElement");
    }
 
    private toggleExtraColumns(): void {
        if (this.showExtra) {
            this.hideExtraColumns();
        } else {
            this.showExtraColumns();
        }
 
        this.recalculateVisibility();
    }
 
    // Helper method to initialize a table section using the unified TableSection approach
    private initializeTableSection(section: TableSection, sectionProperty: keyof HeaderModel): void {
        // Create resizable pane using TableSection properties, but with proper closure
        this.makeResizablePane(section.tableName, section.paneClass, section.displayName, (table: Table) => {
            // Use table.viewModel[sectionProperty] to get the current section with data
            const currentSection = table.viewModel[sectionProperty] as TableSection;
            return currentSection.exists();
        });
 
        // Handle DataTable-specific initialization (sortable tables)
        if (section instanceof DataTable) {
            const dataTable = section as DataTable;
 
            // Special handling for received headers
            if (dataTable.tableName === "receivedHeaders") {
                const receivedColumns = [
                    new Column("hop", mhaStrings.mhaReceivedHop, ""),
                    new Column("from", mhaStrings.mhaReceivedSubmittingHost, ""),
                    new Column("by", mhaStrings.mhaReceivedReceivingHost, ""),
                    new Column("date", mhaStrings.mhaReceivedTime, ""),
                    new Column("delay", mhaStrings.mhaReceivedDelay, ""),
                    new Column("with", mhaStrings.mhaReceivedType, ""),
                    new Column("id", mhaStrings.mhaReceivedId, "extraCol"),
                    new Column("for", mhaStrings.mhaReceivedFor, "extraCol"),
                    new Column("via", mhaStrings.mhaReceivedVia, "extraCol")
                ];
                this.addColumns(dataTable.tableName, receivedColumns);
                this.setupReceivedHeadersUI();
            }
 
            // Special handling for other headers
            if (dataTable.tableName === "otherHeaders") {
                const otherColumns = [
                    new Column("number", mhaStrings.mhaNumber, ""),
                    new Column("header", mhaStrings.mhaHeader, ""),
                    new Column("value", mhaStrings.mhaValue, "")
                ];
                this.addColumns(dataTable.tableName, otherColumns);
            }
        }
 
        // Handle SummaryTable-specific initialization
        if (section instanceof SummaryTable) {
            const summaryTable = section as SummaryTable;
            this.makeSummaryTable(`#${summaryTable.tableName}`, summaryTable.rows, summaryTable.tag);
        }
 
        // Add accessibility features
        this.addTableAccessibility(section);
    }
 
    private setupReceivedHeadersUI(): void {
        const withColumn = document.querySelector("#receivedHeaders #with");
        Eif (withColumn !== null) {
            const leftSpan = document.createElement("span");
            leftSpan.setAttribute("id", "leftArrow");
            leftSpan.classList.add("collapsibleArrow");
            leftSpan.classList.add("hiddenElement");
            leftSpan.innerHTML = "&lArr;";
 
            const rightSpan = document.createElement("span");
            rightSpan.setAttribute("id", "rightArrow");
            rightSpan.classList.add("collapsibleArrow");
            rightSpan.innerHTML = "&rArr;";
 
            withColumn.appendChild(leftSpan);
            withColumn.appendChild(rightSpan);
        }
 
        const arrows = document.querySelectorAll("#receivedHeaders .collapsibleArrow");
        arrows.forEach(arrow => {
            arrow.addEventListener("click", (event) => {
                this.toggleExtraColumns();
                event.stopPropagation();
            });
        });
    }
 
    public resetArrows(): void {
        this.setArrows("receivedHeaders", "hop", 1);
        this.setArrows("otherHeaders", "number", 1);
    }
 
    // Initialize UI with an empty viewModel using unified TableSection approach
    public initializeTableUI(viewModel: HeaderModel): void {
        this.viewModel = viewModel;
 
        // Original headers (not a TableSection, handle separately)
        this.makeResizablePane("originalHeaders", "sectionHeader", mhaStrings.mhaOriginalHeaders, (table: Table) => {
            return table.viewModel.originalHeaders.length > 0;
        });
        this.toggleCollapse("originalHeaders"); // start this section hidden
 
        // Initialize all TableSection-based tables using unified approach
        this.initializeTableSection(this.viewModel.summary, "summary");
        this.initializeTableSection(this.viewModel.receivedHeaders, "receivedHeaders");
        this.initializeTableSection(this.viewModel.forefrontAntiSpamReport, "forefrontAntiSpamReport");
        this.initializeTableSection(this.viewModel.antiSpamReport, "antiSpamReport");
        this.initializeTableSection(this.viewModel.otherHeaders, "otherHeaders");
 
        this.resetArrows();
        this.rebuildSections(this.viewModel);
    }
 
    // Rebuilds the UI with a new viewModel
    // Used by mha.ts and Default.ts to rebuild with new viewModel
    public rebuildTables(viewModel: HeaderModel): void {
        this.viewModel = viewModel;
        this.rebuildSections(this.viewModel);
        this.hideExtraColumns();
    }
}