aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/storage.js
blob: ff4222ade5fa166d7bc8ba76e31202da002d125e (plain)
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
// ==========================================================================
// Plyr storage
// ==========================================================================

import support from './support';
import utils from './utils';

// Get contents of local storage
function get() {
    const store = window.localStorage.getItem(this.config.storage.key);

    if (utils.is.empty(store)) {
        return {};
    }

    return JSON.parse(store);
}

// Save a value back to local storage
function set(object) {
    // Bail if we don't have localStorage support or it's disabled
    if (!support.storage || !this.config.storage.enabled) {
        return;
    }

    // Can only store objectst
    if (!utils.is.object(object)) {
        return;
    }

    // Get current storage
    const storage = get.call(this);

    // Update the working copy of the values
    utils.extend(storage, object);

    // Update storage
    window.localStorage.setItem(this.config.storage.key, JSON.stringify(storage));
}

// Setup localStorage
function setup() {
    let value = null;
    let storage = {};

    // Bail if we don't have localStorage support or it's disabled
    if (!support.storage || !this.config.storage.enabled) {
        return storage;
    }

    // Clean up old volume
    // https://github.com/sampotts/plyr/issues/171
    window.localStorage.removeItem('plyr-volume');

    // load value from the current key
    value = window.localStorage.getItem(this.config.storage.key);

    if (!value) {
        // Key wasn't set (or had been cleared), move along
    } else if (/^\d+(\.\d+)?$/.test(value)) {
        // If value is a number, it's probably volume from an older
        // version of this. See: https://github.com/sampotts/plyr/pull/313
        // Update the key to be JSON
        set({
            volume: parseFloat(value),
        });
    } else {
        // Assume it's JSON from this or a later version of plyr
        storage = JSON.parse(value);
    }

    return storage;
}

export default { setup, set, get };