Welcome to mirror list, hosted at ThFree Co, Russian Federation.

index.js « src « persist « packages « alpinejs - github.com/gohugoio/hugo-mod-jslibs-dist.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fcb308fc8b246aa4d7df742e5e1dec1a4e33cf48 (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

export default function (Alpine) {
    Alpine.magic('persist', (el, { interceptor }) => {
        let alias
        let storage = localStorage

        return interceptor((initialValue, getter, setter, path, key) => {
            let lookup = alias || `_x_${path}`

            let initial = storageHas(lookup, storage)
                ? storageGet(lookup, storage)
                : initialValue

            setter(initial)

            Alpine.effect(() => {
                let value = getter()

                storageSet(lookup, value, storage)

                setter(value)
            })

            return initial
        }, func => {
            func.as = key => { alias = key; return func },
            func.using = target => { storage = target; return func }
        })
    })
}

function storageHas(key, storage) {
    return storage.getItem(key) !== null
}

function storageGet(key, storage) {
    return JSON.parse(storage.getItem(key, storage))
}

function storageSet(key, value, storage) {
    storage.setItem(key, JSON.stringify(value))
}