1/*  DokuWiki MoaiEditor Localstorage.js file
2    Author  : MoaiTools <info@moaitools.org>
3    License : GPL 3 (http://www.gnu.org/licenses/gpl.html) */
4
5/*  Storage of client-side user settings.
6
7    Users:
8        - Button.storage            -- button mode/state    valid: list of mode names
9        - Buttons.dividerPos        -- divider position     valid: [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
10        - Editor._index             -- index of editor      valid: integer (handles invalid indexes by itself, even negative ones)
11        - Toc.depthValue            -- Toc depth            valid: [2,3,4,5]
12        - Main.enabled              -- editor enabled       valid: ['on','off']
13        - Main.isHidden             -- editor hidden        valid: [0,1]
14        - Layout.linewrap           -- editor linewrap      valid: ['off','soft']
15*/
16MoaiEditor.LocalStorage = class {
17
18    constructor(varname, deflt=null, valid=null) {
19        this.varname = DOKU_BASE+'__dokuwiki__moaied__'+varname;
20        this.default = deflt;
21        this.valid = valid;
22    }
23    // ┌───────────────────────────────────┐
24    // │ Public                            │
25    // └───────────────────────────────────┘
26    set value(value) {
27        if (this.localStorageFailed())
28            return null;
29        localStorage.setItem(this.varname, value);
30    }
31
32    get value() {
33        if (this.localStorageFailed())
34            return this.default;
35        var value = this._get();
36        // If value needs to be integer
37        const isnum = /^\d+$/.test(value);
38        if (this.valid === 'integer'  &&  isnum)
39            return value;
40        // If value needs to be among a list of given values
41        else if (this.valid.constructor === Array  &&  this._inList(value))
42            return value;
43        // If it did not pass the validation
44        return this.default;
45    }
46    // ┌───────────────────────────────────┐
47    // │ Private                           │
48    // └───────────────────────────────────┘
49    _inList(value) {
50        for (let v of this.valid)
51            if (v == value)
52                return true;
53         return false;
54    }
55
56    _get() {
57        var value = localStorage[this.varname];
58        if (!value) {
59            localStorage.setItem(this.varname, this.default);
60            value = this.default;
61        }
62        return value;
63    }
64
65    localStorageFailed() {
66        if (typeof(Storage) === "undefined") {
67            console.warn("MoaiEditor :: Local Storage is not available in your browser.");
68            return true;
69        }
70        return false;
71    }
72}; // End Class
73