summaryrefslogtreecommitdiff
path: root/src/www/js/localstorage.js
blob: 3c6a0fa1261f9698d2c3838d1646f076ead8d50f (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


// See http://diveintohtml5.info/storage.html

function supports_html5_storage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
    return false;
  }
}

var fakedLocalStorage = [] // a shared substitute for persistent localStorage

// An interface to localStorage, to store JSON data under a unique prefix
function appLocalStorage(appPrefix,privateStorage) {

    function parse(s) {
	try { return JSON.parse(s) } catch(e) { return null }
    }

    function methods(storage) {
	return {
	    get: function (name,def) {
		var id=appPrefix+name
		return storage[id] && parse(storage[id]) || def;
	    },
	    put: function (name,value) {
		var id=appPrefix+name;
		storage[id]=JSON.stringify(value);
	    },
	    remove: function(name) {
		var id=appPrefix+name;
		delete storage[id]
	    },
	    ls: function(prefix) {
		var pre=appPrefix+prefix
		var files=[]
		for(var i in storage)
		    if(hasPrefix(i,pre)) files.push(i.substr(pre.length))
		files.sort()
		return files
	    },
	    get count() { return this.get("count",0); },
	    set count(v) { this.put("count",v); }
	}
    }

    function get_html5_storage() {
	try {
	    return 'localStorage' in window
		   && window['localStorage']
		   || fakedLocalStorage
	} catch (e) {
	    return fakedLocalStorage; // fake it
	}
    }

    return methods(privateStorage || get_html5_storage())
}