-
Notifications
You must be signed in to change notification settings - Fork 2
/
lawnchair.js
505 lines (457 loc) · 16.9 KB
/
lawnchair.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/**
* Lawnchair!
* ---
* clientside json store
*
*/
var Lawnchair = function (options, callback) {
// ensure Lawnchair was called as a constructor
if (!(this instanceof Lawnchair)) return new Lawnchair(options, callback);
// lawnchair requires json
if (!JSON) throw 'JSON unavailable! Include http://www.json.org/json2.js to fix.'
// options are optional; callback is not
if (arguments.length <= 2) {
callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1];
options = (typeof arguments[0] === 'function') ? {} : arguments[0] || {};
} else {
throw 'Incorrect # of ctor args!'
}
// default configuration
this.record = options.record || 'record' // default for records
this.name = options.name || 'records' // default name for underlying store
// mixin first valid adapter
var adapter
// if the adapter is passed in we try to load that only
if (options.adapter) {
// the argument passed should be an array of prefered adapters
// if it is not, we convert it
if(typeof(options.adapter) === 'string'){
options.adapter = [options.adapter];
}
// iterates over the array of passed adapters
for(var j = 0, k = options.adapter.length; j < k; j++){
// itirates over the array of available adapters
for (var i = Lawnchair.adapters.length-1; i >= 0; i--) {
if (Lawnchair.adapters[i].adapter === options.adapter[j]) {
adapter = Lawnchair.adapters[i].valid() ? Lawnchair.adapters[i] : undefined;
if (adapter) break
}
}
if (adapter) break
}
// otherwise find the first valid adapter for this env
}
else {
for (var i = 0, l = Lawnchair.adapters.length; i < l; i++) {
adapter = Lawnchair.adapters[i].valid() ? Lawnchair.adapters[i] : undefined
if (adapter) break
}
}
// we have failed
if (!adapter) throw 'No valid adapter.'
// yay! mixin the adapter
for (var j in adapter)
this[j] = adapter[j]
// call init for each mixed in plugin
for (var i = 0, l = Lawnchair.plugins.length; i < l; i++)
Lawnchair.plugins[i].call(this)
// init the adapter
this.init(options, callback)
}
Lawnchair.adapters = []
/**
* queues an adapter for mixin
* ===
* - ensures an adapter conforms to a specific interface
*
*/
Lawnchair.adapter = function (id, obj) {
// add the adapter id to the adapter obj
// ugly here for a cleaner dsl for implementing adapters
obj['adapter'] = id
// methods required to implement a lawnchair adapter
var implementing = 'adapter valid init keys save batch get exists all remove nuke'.split(' ')
, indexOf = this.prototype.indexOf
// mix in the adapter
for (var i in obj) {
if (indexOf(implementing, i) === -1) throw 'Invalid adapter! Nonstandard method: ' + i
}
// if we made it this far the adapter interface is valid
// insert the new adapter as the preferred adapter
Lawnchair.adapters.splice(0,0,obj)
}
Lawnchair.plugins = []
/**
* generic shallow extension for plugins
* ===
* - if an init method is found it registers it to be called when the lawnchair is inited
* - yes we could use hasOwnProp but nobody here is an asshole
*/
Lawnchair.plugin = function (obj) {
for (var i in obj)
i === 'init' ? Lawnchair.plugins.push(obj[i]) : this.prototype[i] = obj[i]
}
/**
* helpers
*
*/
Lawnchair.prototype = {
isArray: Array.isArray || function(o) { return Object.prototype.toString.call(o) === '[object Array]' },
/**
* this code exists for ie8... for more background see:
* http://www.flickr.com/photos/westcoastlogic/5955365742/in/photostream
*/
indexOf: function(ary, item, i, l) {
if (ary.indexOf) return ary.indexOf(item)
for (i = 0, l = ary.length; i < l; i++) if (ary[i] === item) return i
return -1
},
// awesome shorthand callbacks as strings. this is shameless theft from dojo.
lambda: function (callback) {
return this.fn(this.record, callback)
},
// first stab at named parameters for terse callbacks; dojo: first != best // ;D
fn: function (name, callback) {
return typeof callback == 'string' ? new Function(name, callback) : callback
},
// returns a unique identifier (by way of Backbone.localStorage.js)
// TODO investigate smaller UUIDs to cut on storage cost
uuid: function () {
var S4 = function () {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
},
// a classic iterator
each: function (callback) {
var cb = this.lambda(callback)
// iterate from chain
if (this.__results) {
for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i)
}
// otherwise iterate the entire collection
else {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i)
})
}
return this
}
// --
};
/**
* Expose nodeJS module
*/
if (typeof module !== 'undefined' && module.exports) {
module.exports = Lawnchair;
}
// window.name code courtesy Remy Sharp: http://24ways.org/2009/breaking-out-the-edges-of-the-browser
Lawnchair.adapter('window-name', (function() {
if (typeof window==='undefined') {
window = { top: { } }; // node/optimizer compatibility
}
// edited from the original here by elsigh
// Some sites store JSON data in window.top.name, but some folks (twitter on iPad)
// put simple strings in there - we should make sure not to cause a SyntaxError.
var data = {}
try {
data = JSON.parse(window.top.name)
} catch (e) {}
return {
valid: function () {
return typeof window.top.name != 'undefined'
},
init: function (options, callback) {
data[this.name] = data[this.name] || {index:[],store:{}}
this.index = data[this.name].index
this.store = data[this.name].store
this.fn(this.name, callback).call(this, this)
return this
},
keys: function (callback) {
this.fn('keys', callback).call(this, this.index)
return this
},
save: function (obj, cb) {
// data[key] = value + ''; // force to string
// window.top.name = JSON.stringify(data);
var key = obj.key || this.uuid()
this.exists(key, function(exists) {
if (!exists) {
if (obj.key) delete obj.key
this.index.push(key)
}
this.store[key] = obj
try {
window.top.name = JSON.stringify(data) // TODO wow, this is the only diff from the memory adapter
} catch(e) {
// restore index/store to previous value before JSON exception
if (!exists) {
this.index.pop();
delete this.store[key];
}
throw e;
}
if (cb) {
obj.key = key
this.lambda(cb).call(this, obj)
}
})
return this
},
batch: function (objs, cb) {
var r = []
for (var i = 0, l = objs.length; i < l; i++) {
this.save(objs[i], function(record) {
r.push(record)
})
}
if (cb) this.lambda(cb).call(this, r)
return this
},
get: function (keyOrArray, cb) {
var r;
if (this.isArray(keyOrArray)) {
r = []
for (var i = 0, l = keyOrArray.length; i < l; i++) {
r.push(this.store[keyOrArray[i]])
}
} else {
r = this.store[keyOrArray]
if (r) r.key = keyOrArray
}
if (cb) this.lambda(cb).call(this, r)
return this
},
exists: function (key, cb) {
this.lambda(cb).call(this, !!(this.store[key]))
return this
},
all: function (cb) {
var r = []
for (var i = 0, l = this.index.length; i < l; i++) {
var obj = this.store[this.index[i]]
obj.key = this.index[i]
r.push(obj)
}
this.fn(this.name, cb).call(this, r)
return this
},
remove: function (keyOrArray, cb) {
var del = this.isArray(keyOrArray) ? keyOrArray : [keyOrArray]
for (var i = 0, l = del.length; i < l; i++) {
var key = del[i].key ? del[i].key : del[i]
var where = this.indexOf(this.index, key)
if (where < 0) continue /* key not present */
delete this.store[key]
this.index.splice(where, 1)
}
window.top.name = JSON.stringify(data)
if (cb) this.lambda(cb).call(this)
return this
},
nuke: function (cb) {
this.store = data[this.name].store = {}
this.index = data[this.name].index = []
window.top.name = JSON.stringify(data)
if (cb) this.lambda(cb).call(this)
return this
}
}
/////
})());
/**
* dom storage adapter
* ===
* - originally authored by Joseph Pecoraro
*
*/
//
// TODO does it make sense to be chainable all over the place?
// chainable: nuke, remove, all, get, save, all
// not chainable: valid, keys
//
Lawnchair.adapter('dom', (function() {
var storage = window.localStorage
// the indexer is an encapsulation of the helpers needed to keep an ordered index of the keys
var indexer = function(name) {
return {
// the key
key: name + '._index_',
// returns the index
all: function() {
var a = storage.getItem(JSON.stringify(this.key))
if (a) {
a = JSON.parse(a)
}
if (a === null) storage.setItem(JSON.stringify(this.key), JSON.stringify([])) // lazy init
return JSON.parse(storage.getItem(JSON.stringify(this.key)))
},
// adds a key to the index
add: function (key) {
var a = this.all()
a.push(key)
storage.setItem(JSON.stringify(this.key), JSON.stringify(a))
},
// deletes a key from the index
del: function (key) {
var a = this.all(), r = []
// FIXME this is crazy inefficient but I'm in a strata meeting and half concentrating
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] != key) r.push(a[i])
}
storage.setItem(JSON.stringify(this.key), JSON.stringify(r))
},
// returns index for a key
find: function (key) {
var a = this.all()
for (var i = 0, l = a.length; i < l; i++) {
if (key === a[i]) return i
}
return false
}
}
}
// adapter api
return {
// ensure we are in an env with localStorage
valid: function () {
return !!storage && function() {
// in mobile safari if safe browsing is enabled, window.storage
// is defined but setItem calls throw exceptions.
var success = true
var value = Math.random()
try {
storage.setItem(value, value)
} catch (e) {
success = false
}
storage.removeItem(value)
return success
}()
},
init: function (options, callback) {
this.indexer = indexer(this.name)
if (callback) this.fn(this.name, callback).call(this, this)
},
save: function (obj, callback) {
var key = obj.key ? this.name + '.' + obj.key : this.name + '.' + this.uuid()
// now we kil the key and use it in the store colleciton
delete obj.key;
storage.setItem(key, JSON.stringify(obj))
// if the key is not in the index push it on
if (this.indexer.find(key) === false) this.indexer.add(key)
obj.key = key.slice(this.name.length + 1)
if (callback) {
this.lambda(callback).call(this, obj)
}
return this
},
batch: function (ary, callback) {
var saved = []
// not particularily efficient but this is more for sqlite situations
for (var i = 0, l = ary.length; i < l; i++) {
this.save(ary[i], function(r){
saved.push(r)
})
}
if (callback) this.lambda(callback).call(this, saved)
return this
},
// accepts [options], callback
keys: function(callback) {
if (callback) {
var name = this.name
var indices = this.indexer.all();
var keys = [];
//Checking for the support of map.
if(Array.prototype.map) {
keys = indices.map(function(r){ return r.replace(name + '.', '') })
} else {
for (var key in indices) {
keys.push(key.replace(name + '.', ''));
}
}
this.fn('keys', callback).call(this, keys)
}
return this // TODO options for limit/offset, return promise
},
get: function (key, callback) {
if (this.isArray(key)) {
var r = []
for (var i = 0, l = key.length; i < l; i++) {
var k = this.name + '.' + key[i]
var obj = storage.getItem(k)
if (obj) {
obj = JSON.parse(obj)
obj.key = key[i]
}
r.push(obj)
}
if (callback) this.lambda(callback).call(this, r)
} else {
var k = this.name + '.' + key
var obj = storage.getItem(k)
if (obj) {
obj = JSON.parse(obj)
obj.key = key
}
if (callback) this.lambda(callback).call(this, obj)
}
return this
},
exists: function (key, cb) {
var exists = this.indexer.find(this.name+'.'+key) === false ? false : true ;
this.lambda(cb).call(this, exists);
return this;
},
// NOTE adapters cannot set this.__results but plugins do
// this probably should be reviewed
all: function (callback) {
var idx = this.indexer.all()
, r = []
, o
, k
for (var i = 0, l = idx.length; i < l; i++) {
k = idx[i] //v
o = JSON.parse(storage.getItem(k))
o.key = k.replace(this.name + '.', '')
r.push(o)
}
if (callback) this.fn(this.name, callback).call(this, r)
return this
},
remove: function (keyOrArray, callback) {
var self = this;
if (this.isArray(keyOrArray)) {
// batch remove
var i, done = keyOrArray.length;
var removeOne = function(i) {
self.remove(keyOrArray[i], function() {
if ((--done) > 0) { return; }
if (callback) {
self.lambda(callback).call(self);
}
});
};
for (i=0; i < keyOrArray.length; i++)
removeOne(i);
return this;
}
var key = this.name + '.' +
((keyOrArray.key) ? keyOrArray.key : keyOrArray)
this.indexer.del(key)
storage.removeItem(key)
if (callback) this.lambda(callback).call(this)
return this
},
nuke: function (callback) {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) {
this.remove(r[i]);
}
if (callback) this.lambda(callback).call(this)
})
return this
}
}})());