-
Notifications
You must be signed in to change notification settings - Fork 2k
/
recline.js
1836 lines (1702 loc) · 57.1 KB
/
recline.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// importScripts('lib/underscore.js');
onmessage = function(message) {
function parseCSV(rawCSV) {
var patterns = new RegExp((
// Delimiters.
"(\\,|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\,\\r\\n]*))"
), "gi");
var rows = [[]], matches = null;
while (matches = patterns.exec(rawCSV)) {
var delimiter = matches[1];
if (delimiter.length && (delimiter !== ",")) rows.push([]);
if (matches[2]) {
var value = matches[2].replace(new RegExp("\"\"", "g"), "\"");
} else {
var value = matches[3];
}
rows[rows.length - 1].push(value);
}
if(_.isEqual(rows[rows.length -1], [""])) rows.pop();
var docs = [];
var headers = _.first(rows);
_.each(_.rest(rows), function(row, rowIDX) {
var doc = {};
_.each(row, function(cell, idx) {
doc[headers[idx]] = cell;
})
docs.push(doc);
})
return docs;
}
var docs = parseCSV(message.data.data);
var req = new XMLHttpRequest();
req.onprogress = req.upload.onprogress = function(e) {
if(e.lengthComputable) postMessage({ percent: (e.loaded / e.total) * 100 });
};
req.onreadystatechange = function() { if (req.readyState == 4) postMessage({done: true, response: req.responseText}) };
req.open('POST', message.data.url);
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify({docs: docs}));
};
// adapted from https://github.com/harthur/costco. heather rules
var costco = function() {
function evalFunction(funcString) {
try {
eval("var editFunc = " + funcString);
} catch(e) {
return {errorMessage: e+""};
}
return editFunc;
}
function previewTransform(docs, editFunc, currentColumn) {
var preview = [];
var updated = mapDocs($.extend(true, {}, docs), editFunc);
for (var i = 0; i < updated.docs.length; i++) {
var before = docs[i]
, after = updated.docs[i]
;
if (!after) after = {};
if (currentColumn) {
preview.push({before: JSON.stringify(before[currentColumn]), after: JSON.stringify(after[currentColumn])});
} else {
preview.push({before: JSON.stringify(before), after: JSON.stringify(after)});
}
}
return preview;
}
function mapDocs(docs, editFunc) {
var edited = []
, deleted = []
, failed = []
;
var updatedDocs = _.map(docs, function(doc) {
try {
var updated = editFunc(_.clone(doc));
} catch(e) {
failed.push(doc);
return;
}
if(updated === null) {
updated = {_deleted: true};
edited.push(updated);
deleted.push(doc);
}
else if(updated && !_.isEqual(updated, doc)) {
edited.push(updated);
}
return updated;
});
return {
edited: edited,
docs: updatedDocs,
deleted: deleted,
failed: failed
};
}
function updateDocs(editFunc) {
var dfd = $.Deferred();
util.notify("Download entire database into Recline. This could take a while...", {persist: true, loader: true});
couch.request({url: app.baseURL + "api/json"}).then(function(docs) {
util.notify("Updating " + docs.docs.length + " documents. This could take a while...", {persist: true, loader: true});
var toUpdate = costco.mapDocs(docs.docs, editFunc).edited;
costco.uploadDocs(toUpdate).then(
function(updatedDocs) {
util.notify(updatedDocs.length + " documents updated successfully");
recline.initializeTable(app.offset);
dfd.resolve(updatedDocs);
},
function(err) {
util.notify("Errorz! " + err);
dfd.reject(err);
}
);
});
return dfd.promise();
}
function updateDoc(doc) {
return couch.request({type: "PUT", url: app.baseURL + "api/" + doc._id, data: JSON.stringify(doc)})
}
function uploadDocs(docs) {
var dfd = $.Deferred();
if(!docs.length) dfd.resolve("Failed: No docs specified");
couch.request({url: app.baseURL + "api/_bulk_docs", type: "POST", data: JSON.stringify({docs: docs})})
.then(
function(resp) {ensureCommit().then(function() {
var error = couch.responseError(resp);
if (error) {
dfd.reject(error);
} else {
dfd.resolve(resp);
}
})},
function(err) { dfd.reject(err.responseText) }
);
return dfd.promise();
}
function ensureCommit() {
return couch.request({url: app.baseURL + "api/_ensure_full_commit", type:'POST', data: "''"});
}
function deleteColumn(name) {
var deleteFunc = function(doc) {
delete doc[name];
return doc;
}
return updateDocs(deleteFunc);
}
function uploadCSV() {
var file = $('#file')[0].files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var payload = {
url: window.location.href + "/api/_bulk_docs", // todo more robust url composition
data: event.target.result
};
var worker = new Worker('script/costco-csv-worker.js');
worker.onmessage = function(event) {
var message = event.data;
if (message.done) {
var error = couch.responseError(JSON.parse(message.response))
console.log('e',error)
if (error) {
app.emitter.emit(error, 'error');
} else {
util.notify("Data uploaded successfully!");
recline.initializeTable(app.offset);
}
util.hide('dialog');
} else if (message.percent) {
if (message.percent === 100) {
util.notify("Waiting for CouchDB...", {persist: true, loader: true})
} else {
util.notify("Uploading... " + message.percent + "%");
}
} else {
util.notify(JSON.stringify(message));
}
};
worker.postMessage(payload);
};
} else {
util.notify('File not selected. Please try again');
}
};
return {
evalFunction: evalFunction,
previewTransform: previewTransform,
mapDocs: mapDocs,
updateDocs: updateDocs,
updateDoc: updateDoc,
uploadDocs: uploadDocs,
deleteColumn: deleteColumn,
ensureCommit: ensureCommit,
uploadCSV: uploadCSV
};
}();
this.recline = this.recline || {};
// Models module following classic module pattern
recline.Model = function($) {
var my = {};
// A Dataset model.
//
// Other than standard list of Backbone attributes it has two important attributes:
//
// * currentDocuments: a DocumentList containing the Documents we have currently loaded for viewing (you update currentDocuments by calling getRows)
// * docCount: total number of documents in this dataset (obtained on a fetch for this Dataset)
my.Dataset = Backbone.Model.extend({
__type__: 'Dataset',
initialize: function() {
this.currentDocuments = new my.DocumentList();
this.docCount = null;
},
// AJAX method with promise API to get rows (documents) from the backend.
//
// Resulting DocumentList are used to reset this.currentDocuments and are
// also returned.
//
// :param numRows: passed onto backend getDocuments.
// :param start: passed onto backend getDocuments.
//
// this does not fit very well with Backbone setup. Backbone really expects you to know the ids of objects your are fetching (which you do in classic RESTful ajax-y world). But this paradigm does not fill well with data set up we have here.
// This also illustrates the limitations of separating the Dataset and the Backend
getDocuments: function(numRows, start) {
var self = this;
var dfd = $.Deferred();
this.backend.getDocuments(this.id, numRows, start).then(function(rows) {
var docs = _.map(rows, function(row) {
return new my.Document(row);
});
self.currentDocuments.reset(docs);
dfd.resolve(self.currentDocuments);
});
return dfd.promise();
},
toTemplateJSON: function() {
var data = this.toJSON();
data.docCount = this.docCount;
return data;
}
});
my.Document = Backbone.Model.extend({
__type__: 'Document'
});
my.DocumentList = Backbone.Collection.extend({
__type__: 'DocumentList',
// webStore: new WebStore(this.url),
model: my.Document
});
// Backends section
// ================
my.setBackend = function(backend) {
Backbone.sync = backend.sync;
};
// Backend which just caches in memory
//
// Does not need to be a backbone model but provides some conveniences
my.BackendMemory = Backbone.Model.extend({
// Initialize a Backend with a local in-memory dataset.
//
// NB: We can handle one and only one dataset at a time.
//
// :param dataset: the data for a dataset on which operations will be
// performed. Its form should be a hash with metadata and data
// attributes.
//
// - metadata: hash of key/value attributes of any kind (but usually with title attribute)
// - data: hash with 2 keys:
// - headers: list of header names/labels
// - rows: list of hashes, each hash being one row. A row *must* have an id attribute which is unique.
//
// Example of data:
//
// {
// headers: ['x', 'y', 'z']
// , rows: [
// {id: 0, x: 1, y: 2, z: 3}
// , {id: 1, x: 2, y: 4, z: 6}
// ]
// };
initialize: function(dataset) {
// deep copy
this._datasetAsData = $.extend(true, {}, dataset);
_.bindAll(this, 'sync');
},
getDataset: function() {
var dataset = new my.Dataset({
id: this._datasetAsData.metadata.id
});
// this is a bit weird but problem is in sync this is set to parent model object so need to give dataset a reference to backend explicitly
dataset.backend = this;
return dataset;
},
sync: function(method, model, options) {
var self = this;
if (method === "read") {
var dfd = $.Deferred();
// this switching on object type is rather horrible
// think may make more sense to do work in individual objects rather than in central Backbone.sync
if (model.__type__ == 'Dataset') {
var dataset = model;
var rawDataset = this._datasetAsData;
dataset.set(rawDataset.metadata);
dataset.set({
headers: rawDataset.data.headers
});
dataset.docCount = rawDataset.data.rows.length;
dfd.resolve(dataset);
}
return dfd.promise();
} else if (method === 'update') {
var dfd = $.Deferred();
if (model.__type__ == 'Document') {
_.each(this._datasetAsData.data.rows, function(row, idx) {
if(row.id === model.id) {
self._datasetAsData.data.rows[idx] = model.toJSON();
}
});
dfd.resolve(model);
}
return dfd.promise();
} else if (method === 'delete') {
var dfd = $.Deferred();
if (model.__type__ == 'Document') {
this._datasetAsData.data.rows = _.reject(this._datasetAsData.data.rows, function(row) {
return (row.id === model.id);
});
dfd.resolve(model);
}
return dfd.promise();
} else {
alert('Not supported: sync on BackendMemory with method ' + method + ' and model ' + model);
}
},
getDocuments: function(datasetId, numRows, start) {
if (start === undefined) {
start = 0;
}
if (numRows === undefined) {
numRows = 10;
}
var dfd = $.Deferred();
rows = this._datasetAsData.data.rows;
var results = rows.slice(start, start+numRows);
dfd.resolve(results);
return dfd.promise();
}
});
// Webstore Backend for connecting to the Webstore
//
// Initializing model argument must contain a url attribute pointing to
// relevant Webstore table.
//
// Designed to only attach to one dataset and one dataset only ...
// Could generalize to support attaching to different datasets
my.BackendWebstore = Backbone.Model.extend({
getDataset: function(id) {
var dataset = new my.Dataset({
id: id
});
dataset.backend = this;
return dataset;
},
sync: function(method, model, options) {
if (method === "read") {
// this switching on object type is rather horrible
// think may make more sense to do work in individual objects rather than in central Backbone.sync
if (this.__type__ == 'Dataset') {
var dataset = this;
// get the schema and return
var base = this.backend.get('url');
var schemaUrl = base + '/schema.json';
var jqxhr = $.ajax({
url: schemaUrl,
dataType: 'jsonp',
jsonp: '_callback'
});
var dfd = $.Deferred();
jqxhr.then(function(schema) {
headers = _.map(schema.data, function(item) {
return item.name;
});
dataset.set({
headers: headers
});
dataset.docCount = schema.count;
dfd.resolve(dataset, jqxhr);
});
return dfd.promise();
}
}
},
getDocuments: function(datasetId, numRows, start) {
if (start === undefined) {
start = 0;
}
if (numRows === undefined) {
numRows = 10;
}
var base = this.get('url');
var jqxhr = $.ajax({
url: base + '.json?_limit=' + numRows,
dataType: 'jsonp',
jsonp: '_callback',
cache: true
});
var dfd = $.Deferred();
jqxhr.then(function(results) {
dfd.resolve(results.data);
});
return dfd.promise();
}
});
// DataProxy Backend for connecting to the DataProxy
//
// Example initialization:
//
// BackendDataProxy({
// model: {
// url: {url-of-data-to-proxy},
// type: xls || csv,
// format: json || jsonp # return format (defaults to jsonp)
// dataproxy: {url-to-proxy} # defaults to http://jsonpdataproxy.appspot.com
// }
// })
my.BackendDataProxy = Backbone.Model.extend({
defaults: {
dataproxy: 'http://jsonpdataproxy.appspot.com'
, type: 'csv'
, format: 'jsonp'
},
getDataset: function(id) {
var dataset = new my.Dataset({
id: id
});
dataset.backend = this;
return dataset;
},
sync: function(method, model, options) {
if (method === "read") {
// this switching on object type is rather horrible
// think may make more sense to do work in individual objects rather than in central Backbone.sync
if (this.__type__ == 'Dataset') {
var dataset = this;
// get the schema and return
var base = this.backend.get('dataproxy');
var data = this.backend.toJSON();
delete data['dataproxy'];
// TODO: should we cache for extra efficiency
data['max-results'] = 1;
var jqxhr = $.ajax({
url: base
, data: data
, dataType: 'jsonp'
});
var dfd = $.Deferred();
jqxhr.then(function(results) {
dataset.set({
headers: results.fields
});
dfd.resolve(dataset, jqxhr);
});
return dfd.promise();
}
} else {
alert('This backend only supports read operations');
}
},
getDocuments: function(datasetId, numRows, start) {
if (start === undefined) {
start = 0;
}
if (numRows === undefined) {
numRows = 10;
}
var base = this.get('dataproxy');
var data = this.toJSON();
delete data['dataproxy'];
data['max-results'] = numRows;
var jqxhr = $.ajax({
url: base
, data: data
, dataType: 'jsonp'
// , cache: true
});
var dfd = $.Deferred();
jqxhr.then(function(results) {
var _out = _.map(results.data, function(row) {
var tmp = {};
_.each(results.fields, function(key, idx) {
tmp[key] = row[idx];
});
return tmp;
});
dfd.resolve(_out);
});
return dfd.promise();
}
});
return my;
}(jQuery);
var util = function() {
var templates = {
transformActions: '<li><a data-action="transform" class="menuAction" href="JavaScript:void(0);">Global transform...</a></li>'
, columnActions: ' \
<li><a data-action="bulkEdit" class="menuAction" href="JavaScript:void(0);">Transform...</a></li> \
<li><a data-action="deleteColumn" class="menuAction" href="JavaScript:void(0);">Delete this column</a></li> \
'
, rowActions: '<li><a data-action="deleteRow" class="menuAction" href="JavaScript:void(0);">Delete this row</a></li>'
, cellEditor: ' \
<div class="menu-container data-table-cell-editor"> \
<textarea class="data-table-cell-editor-editor" bind="textarea">{{value}}</textarea> \
<div id="data-table-cell-editor-actions"> \
<div class="data-table-cell-editor-action"> \
<button class="okButton btn primary">Update</button> \
<button class="cancelButton btn danger">Cancel</button> \
</div> \
</div> \
</div> \
'
, editPreview: ' \
<div class="expression-preview-table-wrapper"> \
<table> \
<thead> \
<tr> \
<th class="expression-preview-heading"> \
before \
</th> \
<th class="expression-preview-heading"> \
after \
</th> \
</tr> \
</thead> \
<tbody> \
{{#rows}} \
<tr> \
<td class="expression-preview-value"> \
{{before}} \
</td> \
<td class="expression-preview-value"> \
{{after}} \
</td> \
</tr> \
{{/rows}} \
</tbody> \
</table> \
</div> \
'
};
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
function inURL(url, str) {
var exists = false;
if ( url.indexOf( str ) > -1 ) {
exists = true;
}
return exists;
}
function registerEmitter() {
var Emitter = function(obj) {
this.emit = function(obj, channel) {
if (!channel) var channel = 'data';
this.trigger(channel, obj);
};
};
MicroEvent.mixin(Emitter);
return new Emitter();
}
function listenFor(keys) {
var shortcuts = { // from jquery.hotkeys.js
8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del",
96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta"
}
window.addEventListener("keyup", function(e) {
var pressed = shortcuts[e.keyCode];
if(_.include(keys, pressed)) app.emitter.emit("keyup", pressed);
}, false);
}
function observeExit(elem, callback) {
var cancelButton = elem.find('.cancelButton');
// TODO: remove (commented out as part of Backbon-i-fication
// app.emitter.on('esc', function() {
// cancelButton.click();
// app.emitter.clear('esc');
// });
cancelButton.click(callback);
}
function show( thing ) {
$('.' + thing ).show();
$('.' + thing + '-overlay').show();
}
function hide( thing ) {
$('.' + thing ).hide();
$('.' + thing + '-overlay').hide();
// TODO: remove or replace (commented out as part of Backbon-i-fication
// if (thing === "dialog") app.emitter.clear('esc'); // todo more elegant solution
}
function position( thing, elem, offset ) {
var position = $(elem.target).position();
if (offset) {
if (offset.top) position.top += offset.top;
if (offset.left) position.left += offset.left;
}
$('.' + thing + '-overlay').show().click(function(e) {
$(e.target).hide();
$('.' + thing).hide();
});
$('.' + thing).show().css({top: position.top + $(elem.target).height(), left: position.left});
}
function render( template, target, options ) {
if ( !options ) options = {data: {}};
if ( !options.data ) options = {data: options};
var html = $.mustache( templates[template], options.data );
if (target instanceof jQuery) {
var targetDom = target;
} else {
var targetDom = $( "." + target + ":first" );
}
if( options.append ) {
targetDom.append( html );
} else {
targetDom.html( html );
}
// TODO: remove (commented out as part of Backbon-i-fication
// if (template in app.after) app.after[template]();
}
function notify(message, options) {
if (!options) var options = {};
var tmplData = _.extend({
msg: message,
category: 'warning'
},
options);
var _template = ' \
<div class="alert-message {{category}} fade in" data-alert="alert"><a class="close" href="#">×</a> \
<p>{{msg}} \
{{#loader}} \
<img src="images/small-spinner.gif" class="notification-loader"> \
{{/loader}} \
</p> \
</div>';
var _templated = $.mustache(_template, tmplData);
_templated = $(_templated).appendTo($('.data-explorer .alert-messages'));
if (!options.persist) {
setTimeout(function() {
$(_templated).remove();
}, 3000);
}
}
function formatMetadata(data) {
out = '<dl>';
$.each(data, function(key, val) {
if (typeof(val) == 'string' && key[0] != '_') {
out = out + '<dt>' + key + '<dd>' + val;
} else if (typeof(val) == 'object' && key != "geometry" && val != null) {
if (key == 'properties') {
$.each(val, function(attr, value){
out = out + '<dt>' + attr + '<dd>' + value;
})
} else {
out = out + '<dt>' + key + '<dd>' + val.join(', ');
}
}
});
out = out + '</dl>';
return out;
}
function getBaseURL(url) {
var baseURL = "";
if ( inURL(url, '_design') ) {
if (inURL(url, '_rewrite')) {
var path = url.split("#")[0];
if (path[path.length - 1] === "/") {
baseURL = "";
} else {
baseURL = '_rewrite/';
}
} else {
baseURL = '_rewrite/';
}
}
return baseURL;
}
var persist = {
restore: function() {
$('.persist').each(function(i, el) {
var inputId = $(el).attr('id');
if(localStorage.getItem(inputId)) $('#' + inputId).val(localStorage.getItem(inputId));
})
},
save: function(id) {
localStorage.setItem(id, $('#' + id).val());
},
clear: function() {
$('.persist').each(function(i, el) {
localStorage.removeItem($(el).attr('id'));
})
}
}
// simple debounce adapted from underscore.js
function delay(func, wait) {
return function() {
var context = this, args = arguments;
var throttler = function() {
delete app.timeout;
func.apply(context, args);
};
if (!app.timeout) app.timeout = setTimeout(throttler, wait);
};
};
function resetForm(form) {
$(':input', form)
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
function largestWidth(selector, min) {
var min_width = min || 0;
$(selector).each(function(i, n){
var this_width = $(n).width();
if (this_width > min_width) {
min_width = this_width;
}
});
return min_width;
}
function getType(obj) {
if (obj === null) {
return 'null';
}
if (typeof obj === 'object') {
if (obj.constructor.toString().indexOf("Array") !== -1) {
return 'array';
} else {
return 'object';
}
} else {
return typeof obj;
}
}
function lookupPath(path) {
var docs = app.apiDocs;
try {
_.each(path, function(node) {
docs = docs[node];
})
} catch(e) {
util.notify("Error selecting documents" + e);
docs = [];
}
return docs;
}
function nodePath(docField) {
if (docField.children('.object-key').length > 0) return docField.children('.object-key').text();
if (docField.children('.array-key').length > 0) return docField.children('.array-key').text();
if (docField.children('.doc-key').length > 0) return docField.children('.doc-key').text();
return "";
}
function selectedTreePath() {
var nodes = []
, parent = $('.chosen');
while (parent.length > 0) {
nodes.push(nodePath(parent));
parent = parent.parents('.doc-field:first');
}
return _.compact(nodes).reverse();
}
// TODO refactor handlers so that they dont stack up as the tree gets bigger
function handleTreeClick(e) {
var clicked = $(e.target);
if(clicked.hasClass('expand')) return;
if (clicked.children('.array').length > 0) {
var field = clicked;
} else if (clicked.siblings('.array').length > 0) {
var field = clicked.parents('.doc-field:first');
} else {
var field = clicked.parents('.array').parents('.doc-field:first');
}
$('.chosen').removeClass('chosen');
field.addClass('chosen');
return false;
}
var createTreeNode = {
"string": function (obj, key) {
var val = $('<div class="doc-value string-type"></div>');
if (obj[key].length > 45) {
val.append($('<span class="string-type"></span>')
.text(obj[key].slice(0, 45)))
.append(
$('<span class="expand">...</span>')
.click(function () {
val.html('')
.append($('<span class="string-type"></span>')
.text(obj[key].length ? obj[key] : " ")
)
})
)
}
else {
var val = $('<div class="doc-value string-type"></div>');
val.append(
$('<span class="string-type"></span>')
.text(obj[key].length ? obj[key] : " ")
)
}
return val;
}
, "number": function (obj, key) {
var val = $('<div class="doc-value number"></div>')
val.append($('<span class="number-type">' + obj[key] + '</span>'))
return val;
}
, "null": function (obj, key) {
var val = $('<div class="doc-value null"></div>')
val.append($('<span class="null-type">' + obj[key] + '</span>'))
return val;
}
, "boolean": function (obj, key) {
var val = $('<div class="fue null"></div>')
val.append($('<span class="null-type">' + obj[key] + '</span>'))
return val;
}
, "array": function (obj, key, indent) {
if (!indent) indent = 1;
var val = $('<div class="doc-value array"></div>')
$('<span class="array-type">[</span><span class="expand" style="float:left">...</span><span class="array-type">]</span>')
.click(function (e) {
var n = $(this).parent();
var cls = 'sub-'+key+'-'+indent
n.html('')
n.append('<span style="padding-left:'+((indent - 1) * 10)+'px" class="array-type">[</span>')
for (i in obj[key]) {
var field = $('<div class="doc-field"></div>').click(handleTreeClick);
n.append(
field
.append('<div class="array-key '+cls+'" >'+i+'</div>')
.append(createTreeNode[getType(obj[key][i])](obj[key], i, indent + 1))
)
}
n.append('<span style="padding-left:'+((indent - 1) * 10)+'px" class="array-type">]</span>')
$('div.'+cls).width(largestWidth('div.'+cls))
})
.appendTo($('<div class="array-type"></div>').appendTo(val))
return val;
}
, "object": function (obj, key, indent) {
if (!indent) indent = 1;
var val = $('<div class="doc-value object"></div>')
$('<span class="object-type">{</span><span class="expand" style="float:left">...</span><span class="object-type">}</span>')
.click(function (e) {
var n = $(this).parent();
n.html('')
n.append('<span style="padding-left:'+((indent - 1) * 10)+'px" class="object-type">{</span>')
for (i in obj[key]) {
var field = $('<div class="doc-field"></div>').click(handleTreeClick);
var p = $('<div class="id-space" style="margin-left:'+(indent * 10)+'px"/>');
var di = $('<div class="object-key">'+i+'</div>')
field.append(p)
.append(di)
.append(createTreeNode[getType(obj[key][i])](obj[key], i, indent + 1))
n.append(field)
}
n.append('<span style="padding-left:'+((indent - 1) * 10)+'px" class="object-type">}</span>')
di.width(largestWidth('div.object-key'))
})
.appendTo($('<div class="object-type"></div>').appendTo(val))
return val;
}
}
function renderTree(doc) {
var d = $('div#document-editor');
for (i in doc) {
var field = $('<div class="doc-field"></div>').click(handleTreeClick);
$('<div class="id-space" />').appendTo(field);
field.append('<div class="doc-key doc-key-base">'+i+'</div>')
field.append(createTreeNode[getType(doc[i])](doc, i));
d.append(field);
}
$('div.doc-key-base').width(largestWidth('div.doc-key-base'))
}
return {
inURL: inURL,
registerEmitter: registerEmitter,
listenFor: listenFor,
show: show,
hide: hide,
position: position,
render: render,
notify: notify,
observeExit: observeExit,
formatMetadata:formatMetadata,
getBaseURL:getBaseURL,
resetForm: resetForm,
delay: delay,
persist: persist,
lookupPath: lookupPath,
selectedTreePath: selectedTreePath,
renderTree: renderTree
};
}();
this.recline = this.recline || {};
// Views module following classic module pattern
recline.View = function($) {
var my = {};
// Parse a URL query string (?xyz=abc...) into a dictionary.
function parseQueryString(q) {
var urlParams = {},