All files / src/web rewind-ui.js

96.63% Statements 115/119
78.78% Branches 26/33
100% Functions 20/20
100% Lines 110/110

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        1x                           14x 14x 14x 14x 23x   14x 14x 14x 14x   14x 14x 14x 14x 14x   14x 14x 14x 1x 1x         23x 23x         2x 2x 2x         14x   13x 13x   12x 12x 12x 12x 12x             12x 12x   12x     12x 12x 12x 12x   1x 1x 1x                 6x     6x 6x   6x             5x 5x 5x         3x                 14x   14x 14x 14x 14x         27x 27x         12x 12x 12x 12x 12x 12x 12x 12x                 25x         30x 30x 30x 30x       25x 25x 58x         14x 14x 14x         11x 11x 21x 21x 21x 21x   21x 21x 21x 21x   21x 21x         36x   2x 2x 2x 2x   6x 6x 6x 6x   15x 15x 15x 8x   15x   8x 8x 8x 5x   8x       5x 5x        
import { renderThumbnails, executeUntilFrame } from "./rewind-thumbnail.js";
import { RewindBuffer } from "../rewind.js";
import { RewindCaptureInterval } from "./emulation-loop.js";
 
const RewindBufferSnapshots = 30;
 
/**
 * Rewind scrubber UI — a filmstrip overlay showing thumbnails of recent
 * emulator states, allowing the user to click to restore any of them.
 */
export class RewindUI {
    /**
     * @param {object} options
     * @param {object} options.processor - Cpu6502 instance
     * @param {object} options.video - Video instance
     * @param {object} options.loop - the emulation loop: says when to capture, and is held while the panel is open
     */
    constructor({ processor, video, loop }) {
        this.rewindBuffer = new RewindBuffer(RewindBufferSnapshots);
        this.processor = processor;
        this.video = video;
        this.loop = loop;
        loop.addEventListener("rewind-capture", () => this.capture());
 
        this.panel = document.getElementById("rewind-panel");
        this.filmstrip = document.getElementById("rewind-filmstrip");
        this.closeBtn = document.getElementById("rewind-close");
        this.openBtn = document.getElementById("rewind-open");
 
        this.isOpen = false;
        this.resumeLoop = null;
        this.selectedIndex = -1;
        this.snapshots = [];
        this.savedState = null;
 
        this._onKeyDown = this._onKeyDown.bind(this);
        this.closeBtn.addEventListener("click", () => this.close());
        this.openBtn.addEventListener("click", (e) => {
            e.preventDefault();
            this.open();
        });
    }
 
    capture() {
        this.rewindBuffer.push(this.processor.snapshotState());
        this.updateButtonState();
    }
 
    /** Forget everything captured, as on a hard reset. */
    reset() {
        this.close();
        this.rewindBuffer.clear();
        this.updateButtonState();
    }
 
    /** Open the rewind scrubber panel. */
    open() {
        if (this.isOpen) return;
 
        this.snapshots = this.rewindBuffer.getAll();
        if (this.snapshots.length === 0) return;
 
        this.resumeLoop = this.loop.pause("the rewind panel");
        this.isOpen = true;
        try {
            this.savedState = this.processor.snapshotState();
            const thumbnails = renderThumbnails(
                this.processor,
                this.snapshots,
                this.video,
                RewindCaptureInterval,
                this.savedState,
            );
            this._populateFilmstrip(thumbnails);
            this.panel.hidden = false;
            // Use capture phase so keys don't leak to the emulator's keyboard handler
            document.addEventListener("keydown", this._onKeyDown, true);
 
            // Select the newest snapshot ("now") and jump to it
            this.selectedIndex = this.snapshots.length - 1;
            this._restoreAndPaint(this.selectedIndex);
            this._updateSelectionHighlight();
            this.filmstrip.scrollLeft = this.filmstrip.scrollWidth;
        } catch (e) {
            Iif (this.savedState) this.processor.restoreState(this.savedState);
            this._closePanel();
            throw e;
        }
    }
 
    /**
     * Close the rewind panel, committing the selected snapshot.
     * The emulator resumes from the exact snapshot state.
     */
    commit() {
        Iif (!this.isOpen) return;
        // Re-restore the snapshot so the CPU resumes from the exact point,
        // not from the state advanced by executeUntilFrame during preview.
        Eif (this.selectedIndex >= 0 && this.selectedIndex < this.snapshots.length) {
            this.processor.restoreState(this.snapshots[this.selectedIndex]);
        }
        this._closePanel();
    }
 
    /**
     * Close the rewind panel, restoring the state from before it was opened.
     */
    cancel() {
        Iif (!this.isOpen) return;
        this._renderState(this.savedState);
        this._closePanel();
    }
 
    /** Alias for cancel — closing the panel without explicit commit cancels. */
    close() {
        this.cancel();
    }
 
    /**
     * Restore the emulator to the snapshot at the given index and update
     * both the main display and the filmstrip selection highlight.
     * @param {number} index - index into the snapshots array
     */
    selectSnapshot(index) {
        Iif (index < 0 || index >= this.snapshots.length) return;
 
        this.selectedIndex = index;
        this._restoreAndPaint(index);
        this._updateSelectionHighlight();
        this._scrollToSelected();
    }
 
    /** Update the disabled state of the Rewind menu item. */
    updateButtonState() {
        Eif (this.openBtn) {
            this.openBtn.classList.toggle("disabled", this.rewindBuffer.length === 0);
        }
    }
 
    _closePanel() {
        this.isOpen = false;
        this.panel.hidden = true;
        this.filmstrip.innerHTML = "";
        this.snapshots = [];
        this.savedState = null;
        document.removeEventListener("keydown", this._onKeyDown, true);
        this.resumeLoop?.();
        this.resumeLoop = null;
    }
 
    /**
     * Render a snapshot's frame to the display without advancing CPU state.
     * Restores the snapshot, runs to vsync for a complete frame, paints it,
     * then re-restores the snapshot so the CPU stays at the exact point.
     */
    _restoreAndPaint(index) {
        this._renderState(this.snapshots[index]);
    }
 
    /** Render a state to the display, restoring it afterwards. */
    _renderState(state) {
        this.processor.restoreState(state);
        executeUntilFrame(this.processor, this.video);
        this.video.paint();
        this.processor.restoreState(state);
    }
 
    _updateSelectionHighlight() {
        const thumbs = this.filmstrip.querySelectorAll(".rewind-thumb");
        for (const thumb of thumbs) {
            thumb.classList.toggle("selected", Number(thumb.dataset.index) === this.selectedIndex);
        }
    }
 
    _scrollToSelected() {
        const selected = this.filmstrip.querySelector(".rewind-thumb.selected");
        Eif (selected) {
            selected.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
        }
    }
 
    _populateFilmstrip(thumbnails) {
        this.filmstrip.innerHTML = "";
        for (const { canvas, index, ageSeconds } of thumbnails) {
            const wrapper = document.createElement("div");
            wrapper.className = "rewind-thumb";
            wrapper.dataset.index = index;
            wrapper.appendChild(canvas);
 
            const label = document.createElement("span");
            label.className = "rewind-thumb-label";
            label.textContent = ageSeconds === 0 ? "now" : `-${ageSeconds}s`;
            wrapper.appendChild(label);
 
            wrapper.addEventListener("click", () => this.selectSnapshot(index));
            this.filmstrip.appendChild(wrapper);
        }
    }
 
    _onKeyDown(e) {
        switch (e.key) {
            case "Escape":
                e.preventDefault();
                e.stopPropagation();
                this.cancel();
                break;
            case "Enter":
                e.preventDefault();
                e.stopPropagation();
                this.commit();
                break;
            case "ArrowLeft":
                e.preventDefault();
                e.stopPropagation();
                if (this.selectedIndex > 0) {
                    this.selectSnapshot(this.selectedIndex - 1);
                }
                break;
            case "ArrowRight":
                e.preventDefault();
                e.stopPropagation();
                if (this.selectedIndex < this.snapshots.length - 1) {
                    this.selectSnapshot(this.selectedIndex + 1);
                }
                break;
            default:
                // Block keys from reaching the emulator but allow browser
                // shortcuts (Tab, accessibility keys, etc.) to work normally
                e.stopPropagation();
                break;
        }
    }
}