All files / Scripts/ui newDesktopFrame.ts

0% Statements 0/277
0% Branches 0/120
0% Functions 0/36
0% Lines 0/269

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import "../../Content/fluentCommon.css";
import "../../Content/newDesktopFrame.css";
 
import { HeaderModel } from "../HeaderModel";
import { mhaStrings } from "../mhaStrings";
import { Poster } from "../Poster";
import { OtherRow } from "../row/OtherRow";
import { ReceivedRow } from "../row/ReceivedRow";
import { Row } from "../row/Row";
import { SummaryRow } from "../row/SummaryRow";
import { TabNavigation } from "../TabNavigation";
import { DomUtils } from "./domUtils";
import { ViolationUI } from "./ViolationUI";
import { RuleViolation, ViolationGroup } from "../rules/types/AnalysisTypes";
import { escapeAndHighlight, getViolationsForRow } from "../rules/ViolationUtils";
 
// This is the "new" UI rendered in newDesktopFrame.html
 
// Overlay element for loading display
let overlayElement: HTMLElement | null = null;
 
function postError(error: unknown, message: string): void {
    Poster.postMessageToParent("LogError", { error: JSON.stringify(error), message: message });
}
 
function initializeFluentUI(): void {
    // Store references for overlay control
    overlayElement = DomUtils.getElement("#loading-overlay");
 
    // Override click so user can't dismiss overlay
    if (overlayElement) {
        overlayElement.addEventListener("click", function (e: Event): void {
            e.preventDefault();
            e.stopImmediatePropagation();
        });
    }
 
    // Set up original headers toggle button
    const buttonElement = DomUtils.getElement("#orig-header-btn");
    if (buttonElement) {
        buttonElement.addEventListener("click", function (event: Event): void {
            if (event.currentTarget) {
                const currentTarget = event.currentTarget as HTMLElement;
                const btnIcon = currentTarget.querySelector(".fluent-icon--add, .fluent-icon--remove");
                const originalHeaders = DomUtils.getElement("#original-headers");
                const isExpanded = buttonElement.getAttribute("aria-expanded") === "true";
 
                if (!isExpanded) {
                    buttonElement.setAttribute("aria-expanded", "true");
                    if (originalHeaders) originalHeaders.style.display = "block";
                    if (btnIcon) {
                        btnIcon.classList.remove("fluent-icon--add");
                        btnIcon.classList.add("fluent-icon--remove");
                    }
                } else {
                    buttonElement.setAttribute("aria-expanded", "false");
                    if (originalHeaders) originalHeaders.style.display = "none";
                    if (btnIcon) {
                        btnIcon.classList.remove("fluent-icon--remove");
                        btnIcon.classList.add("fluent-icon--add");
                    }
                }
            }
        });
    }
 
    // Show summary by default
    DomUtils.showElement(".header-view[data-content='summary-view']");
    document.getElementById("summary-btn")!.focus();
 
    // Wire up click events for nav buttons
    DomUtils.getElements("#nav-bar .nav-button").forEach((button: Element) => {
        button.addEventListener("click", function (this: HTMLElement): void {
            // Fix for Bug 1691252 - To set aria-label dynamically on click based on button name
            const currentActive = DomUtils.getElement("#nav-bar .is-active");
            if (currentActive) {
                const activeButtonLabel = currentActive.querySelector(".button-label") as HTMLElement;
                if (activeButtonLabel) {
                    const activeButtonText = activeButtonLabel.textContent?.trim() || "";
                    currentActive.setAttribute("aria-label", activeButtonText);
                }
            }
 
            // Remove active from current active and hide its label
            if (currentActive) {
                currentActive.classList.remove("is-active");
            }
            DomUtils.hideAllElements("#nav-bar .button-label");
 
            // Add active class to clicked button and show its label
            this.classList.add("is-active");
            const thisLabel = this.querySelector(".button-label") as HTMLElement;
            if (thisLabel) thisLabel.style.display = "block";
 
            // Get content marker
            const content = this.getAttribute("data-content");
 
            // Fix for Bug 1691252 - To set aria-label as button after selection like "Summary Selected"
            const buttonText = thisLabel?.textContent?.trim() || "";
            const ariaLabel = buttonText + " Selected";
            this.setAttribute("aria-label", ariaLabel);
 
            // Hide all header views
            DomUtils.hideAllElements(".header-view");
 
            // Show the selected content view
            if (content) {
                DomUtils.showElement(`.header-view[data-content='${content}']`);
            }
        });
    });
 
    // Initialize label visibility - only show active button label
    DomUtils.hideAllElements("#nav-bar .button-label");
    const activeLabel = DomUtils.getElement("#nav-bar .is-active .button-label");
    if (activeLabel) activeLabel.style.display = "block";
 
    // Initialize iframe tab navigation handling
    TabNavigation.initializeIFrameTabHandling();
}
 
// Add document-level click handler to close callouts and popovers when clicking outside
document.addEventListener("click", function(event: Event) {
    const target = event.target as HTMLElement;
 
    // Don't close if clicking on a list item (that will handle its own toggle)
    if (target.closest(".hop-list-item")) {
        return;
    }
 
    // Don't close popovers if clicking inside them or their trigger buttons
    if (target.closest(".details-overlay-popup") || target.closest(".show-diagnostics-popover-btn")) {
        return;
    }
 
    closeAllPopups();
});
 
// Add escape key handler to close callouts and popovers
document.addEventListener("keydown", function(event: KeyboardEvent) {
    if (event.key === "Escape") {
        closeAllPopups();
    }
});
 
function closeAllPopups()
{
    document.querySelectorAll(".details-overlay-popup.is-shown").forEach(callout => {
        callout.classList.remove("is-shown");
        callout.classList.add("is-hidden");
    });
}
 
function updateStatus(message: string) {
    DomUtils.setText("#status-message", message);
    if (overlayElement) {
        overlayElement.style.display = "block";
    }
}
 
function addCalloutEntry(name: string, value: string | number | null, parent: HTMLElement) {
    if (value) {
        const clone = DomUtils.cloneTemplate("hop-entry-template");
        DomUtils.setTemplateText(clone, ".hop-label", name + ": ");
        DomUtils.setTemplateText(clone, ".hop-value", String(value));
        parent.appendChild(clone);
    }
}
 
async function buildViews(headers: string) {
    const viewModel = await HeaderModel.create(headers);
 
    buildSummaryTab(viewModel);
    buildReceivedTab(viewModel);
    buildAntispamTab(viewModel);
    buildOtherTab(viewModel);
}
 
function buildSummaryTab(viewModel: HeaderModel) {
    const summaryList = document.querySelector(".summary-list") as HTMLElement;
 
    viewModel.summary.rows.forEach((row: SummaryRow) => {
        if (row.value) {
            const clone = DomUtils.cloneTemplate("summary-row-template");
            DomUtils.setTemplateText(clone, ".section-header", row.label);
 
            const highlightedContent = escapeAndHighlight(row.value, viewModel.violationGroups);
            DomUtils.setTemplateHTML(clone, "code", highlightedContent);
 
            // Add rule violation display in summary section
            const sectionHeader = clone.querySelector(".section-header") as HTMLElement;
            const rowViolations = getViolationsForRow(row, viewModel.violationGroups);
 
            if (sectionHeader && rowViolations.length > 0) {
                rowViolations.forEach((violation: RuleViolation) => {
                    sectionHeader.appendChild(document.createTextNode(" "));
                    sectionHeader.appendChild(ViolationUI.createInlineViolation(violation));
                });
            }
 
            summaryList.appendChild(clone);
        }
    });
 
    // Save original headers and show ui
    DomUtils.setText("#original-headers textarea", viewModel.originalHeaders);
    if (viewModel.originalHeaders) {
        DomUtils.showElement(".orig-header-ui");
    }
 
    const diagnosticsSection = document.querySelector(".ui-diagnostics-report-section") as HTMLElement;
    const diagnosticsContent = ViolationUI.buildDiagnosticsSection(viewModel.violationGroups);
    if (diagnosticsContent) {
        diagnosticsSection.appendChild(diagnosticsContent);
    }
}
 
function buildReceivedTab(viewModel: HeaderModel) {
    const receivedList = document.querySelector(".received-list") as HTMLElement;
 
    if (viewModel.receivedHeaders.rows.length > 0) {
        const listClone = DomUtils.cloneTemplate("received-list-template");
        receivedList.appendChild(listClone);
        const list = receivedList.querySelector("ul") as HTMLElement;
 
        let firstRow = true;
        viewModel.receivedHeaders.rows.forEach((row: ReceivedRow, index) => {
            // Fix for Bug 1846002 - Added attr ID to set focus for the first element in the list
            const itemClone = DomUtils.cloneTemplate("list-item-template");
            const listItem = itemClone.querySelector("li") as HTMLElement;
            listItem.id = "received" + index;
            list.appendChild(itemClone);
 
            if (firstRow) {
                const listItemElement = listItem;
                if (listItemElement) {
                    const clone = DomUtils.cloneTemplate("first-row-template");
                    DomUtils.setTemplateText(clone, ".from-value", String(row.from));
                    DomUtils.setTemplateText(clone, ".to-value", String(row.by));
                    listItemElement.appendChild(clone);
                }
                firstRow = false;
            } else {
                const progressClone = DomUtils.cloneTemplate("progress-icon-template");
 
                // Set the progress value for fluent-progress
                const percent = Number(row.percent.value ?? 0);
                const progressElement = progressClone.querySelector(".hop-progress") as HTMLElement;
                if (progressElement) {
                    progressElement.setAttribute("value", String(percent));
                    progressElement.setAttribute("max", "100");
                }
 
                // Set the description text
                const delayText = row.delay.value !== null ? String(row.delay.value) : "";
                DomUtils.setTemplateText(progressClone, ".progress-description", delayText);
 
                listItem.appendChild(progressClone);
 
                const listItemElement = listItem;
                if (listItemElement) {
                    const clone = DomUtils.cloneTemplate("secondary-text-template");
                    DomUtils.setTemplateText(clone, ".to-value", String(row.by));
                    listItemElement.appendChild(clone);
                }
            }
 
            // Add selection target using HTML template
            const selectionClone = DomUtils.cloneTemplate("selection-target-template");
            listItem.appendChild(selectionClone);
 
            const calloutClone = DomUtils.cloneTemplate("hop-template");
 
            // Add callout header to the tooltip content
            const calloutContent = calloutClone.querySelector(".hop-details-content") as HTMLElement;
            if (calloutContent) {
                const headerClone = DomUtils.cloneTemplate("hop-header-template");
                calloutContent.appendChild(headerClone);
            }
 
            listItem.appendChild(calloutClone);
 
            // Add callout entries
            addCalloutEntry("From", row.from.value, calloutContent);
            addCalloutEntry("To", row.by.value, calloutContent);
            addCalloutEntry("Time", row.date.value, calloutContent);
            addCalloutEntry("Type", row.with.value, calloutContent);
            addCalloutEntry("ID", row.id.value, calloutContent);
            addCalloutEntry("For", row.for.value, calloutContent);
            addCalloutEntry("Via", row.via.value, calloutContent);
 
            // Attach generic overlay popup logic
            const overlay = listItem.querySelector(".details-overlay-popup") as HTMLElement;
            if (overlay) {
                attachOverlayPopup(listItem, overlay);
            }
        });
    }
}
 
/**
 * Generic function to attach an overlay popup to a trigger element.
 * @param trigger - The element that triggers the popup (e.g., listItem).
 * @param overlay - The overlay element to show/hide.
 */
function attachOverlayPopup(trigger: HTMLElement, overlay: HTMLElement): void {
    function showOverlay(): void {
        closeAllPopups();
        // Show this overlay
        overlay.classList.remove("is-hidden");
        overlay.classList.add("is-shown");
 
        // Position the overlay relative to the trigger
        const triggerRect: DOMRect = trigger.getBoundingClientRect();
        const viewportWidth: number = window.innerWidth;
        const viewportHeight: number = window.innerHeight;
        const leftPosition: number = (viewportWidth - overlay.offsetWidth) / 2;
        let topPosition: number = triggerRect.bottom + 15; // 15px gap for arrow
        if (topPosition + overlay.offsetHeight > viewportHeight - 10) {
            topPosition = viewportHeight - overlay.offsetHeight - 10;
        }
        if (topPosition < 10) {
            topPosition = 10;
        }
        overlay.style.left = `${leftPosition}px`;
        overlay.style.top = `${topPosition}px`;
    }
 
    function hideOverlay(): void {
        overlay.classList.remove("is-shown");
        overlay.classList.add("is-hidden");
    }
 
    // Click handler
    trigger.addEventListener("click", function(event: MouseEvent): void {
        const target = event.target as HTMLElement;
        if (target.closest(".details-overlay-popup")) return;
        event.preventDefault();
        if (overlay.classList.contains("is-shown")) {
            hideOverlay();
        } else {
            showOverlay();
        }
    });
 
    // Keyboard handler
    trigger.addEventListener("keydown", function(event: KeyboardEvent): void {
        if (event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            if (overlay.classList.contains("is-shown")) {
                hideOverlay();
            } else {
                showOverlay();
            }
        }
    });
 
    // Make trigger focusable
    trigger.setAttribute("tabindex", "0");
}
 
function buildAntispamTab(viewModel: HeaderModel) {
    const antispamList = document.querySelector(".antispam-list") as HTMLElement;
 
    // Forefront
    if (viewModel.forefrontAntiSpamReport.rows.length > 0) {
        DomUtils.appendTemplate("forefront-header-template", antispamList);
 
        // Create table for antispam data
        const antispamTable = document.createElement("table");
        antispamTable.className = "fluent-table";
        const antispamTbody = document.createElement("tbody");
        antispamTable.appendChild(antispamTbody);
        antispamList.appendChild(antispamTable);
 
        viewModel.forefrontAntiSpamReport.rows.forEach((antispamrow: Row) => {
            antispamTbody.appendChild(createRow("table-row-template",antispamrow, viewModel.violationGroups));
        });
    }
 
    // Microsoft
    if (viewModel.antiSpamReport.rows.length > 0) {
        DomUtils.appendTemplate("microsoft-header-template", antispamList);
 
        // Create table for antispam data
        const antispamTable = document.createElement("table");
        antispamTable.className = "fluent-table";
        const antispamTbody = document.createElement("tbody");
        antispamTable.appendChild(antispamTbody);
        antispamList.appendChild(antispamTable);
 
        viewModel.antiSpamReport.rows.forEach((antispamrow: Row) => {
            antispamTbody.appendChild(createRow("table-row-template", antispamrow, viewModel.violationGroups));
        });
    }
}
 
function buildOtherTab(viewModel: HeaderModel) {
    const otherList = document.querySelector(".other-list") as HTMLElement;
 
    viewModel.otherHeaders.rows.forEach((otherRow: OtherRow) => {
        if (otherRow.value) {
            otherList.appendChild(createRow("other-row-template", otherRow, viewModel.violationGroups));
        }
    });
}
 
function hideStatus(): void {
    if (overlayElement) {
        overlayElement.style.display = "none";
    }
}
 
async function renderItem(headers: string): Promise<void> {
    // Hide loading status as soon as we start rendering
    hideStatus();
 
    // Empty data
    DomUtils.clearElement(".summary-list");
    DomUtils.setText("#original-headers code", "");
    DomUtils.hideElement(".orig-header-ui");
    DomUtils.clearElement(".received-list");
    DomUtils.clearElement(".antispam-list");
    DomUtils.clearElement(".other-list");
    DomUtils.setText("#error-display .error-text", "");
    DomUtils.hideElement("#error-display");
 
    // Build views with the loaded data
    await buildViews(headers);
}
 
// Handles rendering of an error.
// Does not log the error - caller is responsible for calling PostError
function showError(error: unknown, message: string): void {
    console.error("Error:", error);
    DomUtils.setText("#error-display .error-text", message);
    DomUtils.showElement("#error-display");
}
 
function eventListener(event: MessageEvent): void {
    if (!event || event.origin !== Poster.site()) return;
 
    if (event.data) {
        switch (event.data.eventName) {
            case "showError":
                showError(JSON.parse(event.data.data.error), event.data.data.message);
                break;
            case "updateStatus":
                updateStatus(event.data.data);
                break;
            case "renderItem":
                renderItem(event.data.data);
                break;
        }
    }
}
 
// Initialize when DOM is ready
document.addEventListener("DOMContentLoaded", function() {
    try {
        initializeFluentUI();
        updateStatus(mhaStrings.mhaLoading);
        window.addEventListener("message", eventListener, false);
        Poster.postMessageToParent("frameActive");
    }
    catch (e) {
        postError(e, "Failed initializing frame");
        showError(e, "Failed initializing frame");
    }
});
 
/**
 * Set up table row with optional popover buttons
 */
function createRow(
    template: string,
    row: Row,
    violationGroups: ViolationGroup[]) {
    const clone = DomUtils.cloneTemplate(template);
    DomUtils.setTemplateHTML(clone, ".row-header", row.url || row.label || row.header);
    DomUtils.setTemplateAttribute(clone, ".row-header", "id", row.id);
    DomUtils.setTemplateAttribute(clone, ".cell-main-content", "aria-labelledby", row.id);
 
    if (row.valueUrl) {
        DomUtils.setTemplateHTML(clone, ".cell-main-content", row.valueUrl);
    } else {
        const highlightedContent = escapeAndHighlight(row.value, violationGroups);
        DomUtils.setTemplateHTML(clone, ".cell-main-content", highlightedContent);
    }
 
    const effectiveViolations = getViolationsForRow(row, violationGroups);
    if (effectiveViolations.length > 0) {
        const diagnosticsList = clone.querySelector(".diagnostics-list") as HTMLElement;
        effectiveViolations.forEach(v => diagnosticsList.appendChild(ViolationUI.createViolationCard(v)));
 
        const popoverBtn = clone.querySelector(".show-diagnostics-popover-btn") as HTMLElement;
        const popover = clone.querySelector(".details-overlay-popup") as HTMLElement;
        if (popoverBtn && popover) {
            popover.id = `popover-${row.id}`;
 
            const severities = effectiveViolations.map(v => v.rule.severity);
            const highestSeverity = severities.includes("error") ? "error" : severities.includes("warning") ? "warning" : "info";
            popoverBtn.setAttribute("data-severity", highestSeverity);
            popoverBtn.id = `popover-btn-${row.id}`;
            popoverBtn.setAttribute("aria-describedby", popover.id);
            popoverBtn.setAttribute("aria-label", `Show rule violations for ${row.label || row.header}`);
 
            attachOverlayPopup(popoverBtn, popover as HTMLElement);
        }
    }
 
    return clone;
}