All files / src/web local-disc.js

100% Statements 17/17
87.5% Branches 7/8
66.66% Functions 2/3
100% Lines 15/15

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                          6x   6x 6x 5x   1x   6x 6x 12x 12x 12x   7x 2x 2x       6x 6x    
import { DiscLayout } from "../disc.js";
import { blankImage, discFor, guessDiscTypeFromName } from "../fdc.js";
import { stringToUint8Array, uint8ArrayToString } from "../binary.js";
 
/**
 * Create or open a disc held in the browser's local storage.
 * @param {string} name - The file name with extension
 * @param {string} [layout] - one of DiscLayout; by default the image is asked what it is
 * @param {function(*): void} [onSaveError] - called with whatever was thrown, the first time a write
 *   cannot be stored
 * @returns {Disc} The loaded disc object
 */
export function localDisc(name, layout = DiscLayout.auto, onSaveError = () => {}) {
    const discName = "disc_" + name;
    let data;
    const dataString = window.localStorage[discName];
    if (!dataString) {
        data = blankImage(guessDiscTypeFromName(name), name);
    } else {
        data = stringToUint8Array(dataString);
    }
    let reportedSaveError = false;
    const onChange = (data) => {
        try {
            const str = uint8ArrayToString(data);
            window.localStorage.setItem(discName, str);
        } catch (e) {
            if (reportedSaveError) return;
            reportedSaveError = true;
            onSaveError(e);
        }
    };
    // A fresh disc is kept at once, so it is still there to list if nothing is ever written to it.
    if (!dataString) onChange(data);
    return discFor(name, data, onChange, layout);
}