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