All files / src/web local-disc.js

96% Statements 24/25
75% Branches 9/12
66.66% Functions 2/3
95.65% Lines 22/23

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                          6x   6x 6x 5x 5x 5x     5x 5x 5x     1x 1x   6x 6x 12x 12x 12x   7x 7x 2x 2x       6x 6x    
import { DiscLayout } from "../disc.js";
import { 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) {
        console.log("Creating browser-local disc " + name);
        const discType = guessDiscTypeFromName(name);
        Iif (!discType.byteSize) {
            throw new Error(`Cannot create blank disc of type ${discType.extension} - unknown size`);
        }
        data = new Uint8Array(discType.byteSize);
        Eif (discType.supportsCatalogue) {
            discType.setDiscName(data, name);
        }
    } else {
        console.log("Loading browser-local disc " + name);
        data = stringToUint8Array(dataString);
    }
    let reportedSaveError = false;
    const onChange = (data) => {
        try {
            const str = uint8ArrayToString(data);
            window.localStorage.setItem(discName, str);
        } catch (e) {
            console.log(`Unable to save browser-local disc ${name}: ${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);
}