All files / src/web layout.js

95.91% Statements 94/98
97.14% Branches 34/35
88.23% Functions 15/17
96.7% Lines 88/91

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            1x   1x   1x               79x 79x 79x 79x 79x   79x 79x 79x 78x   1x     79x 79x 79x   79x 79x     79x 1x 1x   78x 78x             79x 79x 12x     12x 12x 12x           79x                             15x 15x 15x 15x 15x 15x 15x 15x 55x 11x     38x 15x 15x   15x 1x   15x     15x 1x     15x 15x 3x 3x 3x 3x 2x   1x     3x 5x     12x           28x 28x 28x                                 1x 1x 1x         69x 69x                                   68x 68x 68x 68x 68x   68x 5x 5x   5x     68x 68x 68x 68x       45x 45x 45x 45x 2x 2x 2x   2x      
import { toast } from "./toast.js";
import { errorText } from "./reporting.js";
import { noteFeature } from "./analytics.js";
import { navbarHeightOf } from "./floating-panel.js";
 
/** Steps the drawing buffer grows in, as a multiple of the base canvas size. */
const CanvasScaleStep = 0.25;
/** Below this width the side pictures are not worth a border; the monitor takes the whole width. */
const NarrowWindow = 700;
/** Clearance between the monitor and the LED panel below it. */
const LedPanelGap = 10;
 
/**
 * Where everything goes for a given window: the monitor picture, the canvas
 * within it, and (for a mode with maxCanvasScale) how large a drawing buffer
 * to ask for. Pure, so the geometry is testable on its own.
 */
export function fitMonitor(displayConfig, viewport, canvasNative) {
    const imageOrigHeight = displayConfig.imageHeight;
    const imageOrigWidth = displayConfig.imageWidth;
    const desiredAspectRatio = imageOrigWidth / imageOrigHeight;
    const minWidth = imageOrigWidth / 4;
    const minHeight = imageOrigHeight / 4;
 
    let width = Math.max(minWidth, viewport.innerWidth - viewport.borderReservedSize * 2);
    let height = Math.max(minHeight, viewport.innerHeight - viewport.navbarHeight - viewport.bottomReservedSize);
    if (width / height <= desiredAspectRatio) {
        height = width / desiredAspectRatio;
    } else {
        width = height * desiredAspectRatio;
    }
 
    const containerScale = width / imageOrigWidth;
    const scaledVisibleWidth = displayConfig.visibleWidth * containerScale;
    const scaledVisibleHeight = displayConfig.visibleHeight * containerScale;
 
    const canvasAspect = canvasNative.width / canvasNative.height;
    const visibleAspect = scaledVisibleWidth / scaledVisibleHeight;
 
    let finalCanvasWidth, finalCanvasHeight;
    if (canvasAspect > visibleAspect) {
        finalCanvasWidth = scaledVisibleWidth;
        finalCanvasHeight = scaledVisibleWidth / canvasAspect;
    } else {
        finalCanvasHeight = scaledVisibleHeight;
        finalCanvasWidth = scaledVisibleHeight * canvasAspect;
    }
 
    // A mode that reconstructs detail wants to draw at the size it will be
    // seen at, up to the limit it asks for. Drawing more than the display
    // can show costs fragments and buys nothing, and for an expensive
    // shader that is the difference between comfortable and not.
    let backing = null;
    if (displayConfig.maxCanvasScale) {
        const wanted = (finalCanvasWidth * viewport.devicePixelRatio) / displayConfig.canvasWidth;
        // Quantised, because resize fires continuously while a window is
        // dragged and every distinct value reallocates the drawing buffer.
        const quantised = Math.round(wanted / CanvasScaleStep) * CanvasScaleStep;
        const scale = Math.min(displayConfig.maxCanvasScale, Math.max(1, quantised));
        backing = {
            width: Math.round(displayConfig.canvasWidth * scale),
            height: Math.round(displayConfig.canvasHeight * scale),
        };
    }
 
    return {
        monitor: { width, height },
        canvas: {
            width: finalCanvasWidth,
            height: finalCanvasHeight,
            left: displayConfig.canvasLeft * containerScale,
            top: displayConfig.canvasTop * containerScale,
        },
        backing,
    };
}
 
/** Keeps the monitor and canvas fitted to the window, and wires the page furniture around them. */
export class Layout {
    constructor({ screenCanvas, display, embed, sidebars = {} }) {
        this.screenCanvas = screenCanvas;
        this.display = display;
        this.cubMonitor = document.getElementById("cub-monitor");
        this.cubMonitorPic = document.getElementById("cub-monitor-pic");
        this.borderReservedSize = embed ? 0 : 100;
        this.bottomReservedSize = embed ? 0 : 68;
        this.touchKeyboardRoom = null;
        if (embed) {
            for (const el of document.querySelectorAll(".embed-hide")) el.style.display = "none";
            document.body.style.backgroundColor = "transparent";
        }
 
        window.addEventListener("resize", () => this.resize());
        window.setTimeout(() => this.resize(), 1);
        window.setTimeout(() => this.resize(), 500);
 
        this.bindSidebar(".sidebar.left", sidebars.left, (div, img) => {
            div.style.left = -img.naturalWidth - 5 + "px";
        });
        this.bindSidebar(".sidebar.right", sidebars.right, (div, img) => {
            div.style.right = -img.naturalWidth - 5 + "px";
        });
        this.bindSidebar(".sidebar.bottom", sidebars.bottom, (div, img) => {
            div.style.bottom = -img.naturalHeight + "px";
        });
 
        const fullscreenItem = document.getElementById("fs");
        if (document.fullscreenEnabled) {
            fullscreenItem.addEventListener("click", async (event) => {
                event.preventDefault();
                try {
                    await screenCanvas.requestFullscreen();
                    noteFeature(fullscreenItem, "enter");
                } catch (error) {
                    toast(`Could not go fullscreen: ${errorText(error)}`, { title: "Fullscreen" });
                }
            });
            document.addEventListener("fullscreenchange", () => {
                if (!document.fullscreenElement) noteFeature(fullscreenItem, "leave");
            });
        } else {
            fullscreenItem.closest("li").hidden = true;
        }
    }
 
    /** What the LED panel, or the on-screen keyboard in its place, needs below the monitor. */
    bottomRoom() {
        Iif (this.touchKeyboardRoom !== null) return this.touchKeyboardRoom.below;
        const panel = document.getElementById("leds");
        return Math.max(this.bottomReservedSize, (panel?.offsetHeight ?? 0) + LedPanelGap);
    }
 
    /**
     * The on-screen keyboard hides the LED panel and needs `room.below` the monitor instead and `room.beside` it on
     * each side, or null when closed.
     */
    reserveForTouchKeyboard(room) {
        this.touchKeyboardRoom = room;
        this.resize();
    }
 
    /**
     * Where the screen goes across the window as it is now, worked out afresh rather than read from the page: the
     * picture of the BBC's screen, inside the monitor's bezel.
     */
    screenBounds() {
        const { monitor, canvas } = this._fit();
        const left = (window.innerWidth - monitor.width) / 2 + canvas.left;
        return { left, right: left + canvas.width };
    }
 
    _fit() {
        // The display config can change when the display mode switches.
        const displayConfig = this.display.filterClass.getDisplayConfig();
        return fitMonitor(
            displayConfig,
            {
                innerWidth: window.innerWidth,
                innerHeight: window.innerHeight,
                navbarHeight: navbarHeightOf(document.getElementById("header-bar")),
                borderReservedSize: Math.max(
                    window.innerWidth <= NarrowWindow ? 0 : this.borderReservedSize,
                    this.touchKeyboardRoom?.beside ?? 0,
                ),
                bottomReservedSize: this.bottomReservedSize && this.bottomRoom(),
                devicePixelRatio: window.devicePixelRatio || 1,
            },
            { width: this.screenCanvas.getAttribute("width"), height: this.screenCanvas.getAttribute("height") },
        );
    }
 
    resize() {
        const fitted = this._fit();
        this.cubMonitor.style.height = fitted.monitor.height + "px";
        this.cubMonitor.style.width = fitted.monitor.width + "px";
        this.cubMonitorPic.style.height = fitted.monitor.height + "px";
        this.cubMonitorPic.style.width = fitted.monitor.width + "px";
 
        if (fitted.backing && this.screenCanvas.width !== fitted.backing.width) {
            this.screenCanvas.width = fitted.backing.width;
            this.screenCanvas.height = fitted.backing.height;
            // Resizing threw the drawing buffer away.
            this.display.video.paint();
        }
 
        this.screenCanvas.style.width = fitted.canvas.width + "px";
        this.screenCanvas.style.height = fitted.canvas.height + "px";
        this.screenCanvas.style.left = fitted.canvas.left + "px";
        this.screenCanvas.style.top = fitted.canvas.top + "px";
    }
 
    bindSidebar(selector, url, onload) {
        const div = document.querySelector(selector);
        const img = div.querySelector("img");
        img.style.display = "none";
        if (!url) return;
        img.addEventListener("load", () => {
            onload(div, img);
            img.style.display = "";
        });
        img.src = url;
    }
}