-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathapp.js
More file actions
4501 lines (4112 loc) · 143 KB
/
app.js
File metadata and controls
4501 lines (4112 loc) · 143 KB
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
(function() {
var window = this,
$ = jQuery;
function ns( namespace ) {
return (namespace || "").split(".").reduce( function( space, name ) {
return space[ name ] || ( space[ name ] = { ns: ns } );
}, this );
}
var app = ns("app");
var acx = ns("acx");
/**
* object iterator, returns an array with one element for each property of the object
* @function
*/
acx.eachMap = function(obj, fn, thisp) {
var ret = [];
for(var n in obj) {
ret.push(fn.call(thisp, n, obj[n], obj));
}
return ret;
};
/**
* augments the first argument with the properties of the second and subsequent arguments
* like {@link $.extend} except that existing properties are not overwritten
*/
acx.augment = function() {
var args = Array.prototype.slice.call(arguments),
src = (args.length === 1) ? this : args.shift(),
augf = function(n, v) {
if(! (n in src)) {
src[n] = v;
}
};
for(var i = 0; i < args.length; i++) {
$.each(args[i], augf);
}
return src;
};
/**
* tests whether the argument is an array
* @function
*/
acx.isArray = $.isArray;
/**
* tests whether the argument is an object
* @function
*/
acx.isObject = function (value) {
return Object.prototype.toString.call(value) == "[object Object]";
};
/**
* tests whether the argument is a function
* @function
*/
acx.isFunction = $.isFunction;
/**
* tests whether the argument is a date
* @function
*/
acx.isDate = function (value) {
return Object.prototype.toString.call(value) == "[object Date]";
};
/**
* tests whether the argument is a regexp
* @function
*/
acx.isRegExp = function (value) {
return Object.prototype.toString.call(value) == "[object RegExp]";
};
/**
* tests whether the value is blank or empty
* @function
*/
acx.isEmpty = function (value, allowBlank) {
return value === null || value === undefined || ((acx.isArray(value) && !value.length)) || (!allowBlank ? value === '' : false);
};
/**
* data type for performing chainable geometry calculations<br>
* can be initialised x,y | {x, y} | {left, top}
*/
acx.vector = function(x, y) {
return new acx.vector.prototype.Init(x, y);
};
acx.vector.prototype = {
Init : function(x, y) {
x = x || 0;
this.y = isFinite(x.y) ? x.y : (isFinite(x.top) ? x.top : (isFinite(y) ? y : 0));
this.x = isFinite(x.x) ? x.x : (isFinite(x.left) ? x.left : (isFinite(x) ? x : 0));
},
add : function(i, j) {
var d = acx.vector(i, j);
return new this.Init(this.x + d.x, this.y + d.y);
},
sub : function(i, j) {
var d = acx.vector(i, j);
return new this.Init(this.x - d.x, this.y - d.y);
},
addX : function(i) {
return new this.Init(this.x + i, this.y);
},
addY : function(j) {
return new this.Init(this.x, this.y + j);
},
mod : function(fn) { // runs a function against the x and y values
return new this.Init({x: fn.call(this, this.x, "x"), y: fn.call(this, this.y, "y")});
},
/** returns true if this is within a rectangle formed by the points p and q */
within : function(p, q) {
return ( this.x >= ((p.x < q.x) ? p.x : q.x) && this.x <= ((p.x > q.x) ? p.x : q.x) &&
this.y >= ((p.y < q.y) ? p.y : q.y) && this.y <= ((p.y > q.y) ? p.y : q.y) );
},
asOffset : function() {
return { top: this.y, left: this.x };
},
asSize : function() {
return { height: this.y, width: this.x };
}
};
acx.vector.prototype.Init.prototype = acx.vector.prototype;
/**
* short cut functions for working with vectors and jquery.
* Each function returns the equivalent jquery value in a two dimentional vector
*/
$.fn.vSize = function() { return acx.vector(this.width(), this.height()); };
$.fn.vOuterSize = function(margin) { return acx.vector(this.outerWidth(margin), this.outerHeight(margin)); };
$.fn.vScroll = function() { return acx.vector(this.scrollLeft(), this.scrollTop()); };
$.fn.vOffset = function() { return acx.vector(this.offset()); };
$.fn.vPosition = function() { return acx.vector(this.position()); };
$.Event.prototype.vMouse = function() { return acx.vector(this.pageX, this.pageY); };
/**
* object extensions (ecma5 compatible)
*/
acx.augment(Object, {
keys: function(obj) {
var ret = [];
for(var n in obj) if(Object.prototype.hasOwnProperty.call(obj, n)) ret.push(n);
return ret;
}
});
/**
* Array prototype extensions
*/
acx.augment(Array.prototype, {
'contains' : function(needle) {
return this.indexOf(needle) !== -1;
},
// returns a new array consisting of all the members that are in both arrays
'intersection' : function(b) {
var ret = [];
for(var i = 0; i < this.length; i++) {
if(b.contains(this[i])) {
ret.push(this[i]);
}
}
return ret;
},
'remove' : function(value) {
var i = this.indexOf(value);
if(i !== -1) {
this.splice(i, 1);
}
}
});
/**
* String prototype extensions
*/
acx.augment(String.prototype, {
'contains' : function(needle) {
return this.indexOf(needle) !== -1;
},
'equalsIgnoreCase' : function(match) {
return this.toLowerCase() === match.toLowerCase();
},
'escapeHtml' : function() {
return this.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
},
'escapeJS' : function() {
var meta = {'"':'\\"', '\\':'\\\\', '/':'\\/', '\b':'\\b', '\f':'\\f', '\n':'\\n', '\r':'\\r', '\t':'\\t'},
xfrm = function(c) { return meta[c] || "\\u" + c.charCodeAt(0).toString(16).zeroPad(4); };
return this.replace(new RegExp('(["\\\\\x00-\x1f\x7f-\uffff])', 'g'), xfrm);
},
'escapeRegExp' : function() {
var ret = "", esc = "\\^$*+?.()=|{,}[]-";
for ( var i = 0; i < this.length; i++) {
ret += (esc.contains(this.charAt(i)) ? "\\" : "") + this.charAt(i);
}
return ret;
},
'zeroPad' : function(len) {
return ("0000000000" + this).substring(this.length - len + 10);
}
});
$.fn.forEach = Array.prototype.forEach;
// joey / jquery integration
$.joey = function( obj ) {
return $( window.joey( obj ) );
};
window.joey.plugins.push( function( obj ) {
if( obj instanceof jQuery ) {
return obj[0];
}
});
})();
/**
* base class for creating inheritable classes
* based on resigs 'Simple Javascript Inheritance Class' (based on base2 and prototypejs)
* modified with static super and auto config
* @name Class
* @constructor
*/
(function( $, app ){
var ux = app.ns("ux");
var initializing = false, fnTest = /\b_super\b/;
ux.Class = function(){};
ux.Class.extend = function(prop) {
function Class() {
if(!initializing) {
var args = Array.prototype.slice.call(arguments);
this.config = $.extend( function(t) { // automatically construct a config object based on defaults and last item passed into the constructor
return $.extend(t._proto && t._proto() && arguments.callee(t._proto()) || {}, t.defaults);
} (this) , args.pop() );
this.init && this.init.apply(this, args); // automatically run the init function when class created
}
}
initializing = true;
var prototype = new this();
initializing = false;
var _super = this.prototype;
prototype._proto = function() {
return _super;
};
for(var name in prop) {
prototype[name] = typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() { this._super = _super[name]; return fn.apply(this, arguments); };
})(name, prop[name]) : prop[name];
}
Class.prototype = prototype;
Class.constructor = Class;
Class.extend = arguments.callee; // make class extendable
return Class;
};
})( this.jQuery, this.app );
(function( app ) {
var ut = app.ns("ut");
ut.option_template = function(v) { return { tag: "OPTION", value: v, text: v }; };
ut.require_template = function(f) { return f.require ? { tag: "SPAN", cls: "require", text: "*" } : null; };
var sib_prefix = ['B','ki','Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
ut.byteSize_template = function(n) {
var i = 0;
while( n >= 1000 ) {
i++;
n /= 1024;
}
return (i === 0 ? n.toString() : n.toFixed( 3 - parseInt(n,10).toString().length )) + ( sib_prefix[ i ] || "..E" );
};
var sid_prefix = ['','k','M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
ut.count_template = function(n) {
var i = 0;
while( n >= 1000 ) {
i++;
n /= 1000;
}
return i === 0 ? n.toString() : ( n.toFixed( 3 - parseInt(n,10).toString().length ) + ( sid_prefix[ i ] || "..E" ) );
};
})( this.app );
(function( app ) {
var ux = app.ns("ux");
ux.Observable = ux.Class.extend((function() {
return {
init: function() {
this.observers = {};
for( var opt in this.config ) { // automatically install observers that are defined in the configuration
if( opt.indexOf( 'on' ) === 0 ) {
this.on( opt.substring(2) , this.config[ opt ] );
}
}
},
_getObs: function( type ) {
return ( this.observers[ type.toLowerCase() ] || ( this.observers[ type.toLowerCase() ] = [] ) );
},
on: function( type, fn, params, thisp ) {
this._getObs( type ).push( { "cb" : fn, "args" : params || [] , "cx" : thisp || this } );
return this;
},
fire: function( type ) {
var params = Array.prototype.slice.call( arguments, 1 );
this._getObs( type ).slice().forEach( function( ob ) {
ob["cb"].apply( ob["cx"], ob["args"].concat( params ) );
} );
return this;
},
removeAllObservers: function() {
this.observers = {};
},
removeObserver: function( type, fn ) {
var obs = this._getObs( type ),
index = obs.reduce( function(p, t, i) { return (t.cb === fn) ? i : p; }, -1 );
if(index !== -1) {
obs.splice( index, 1 );
}
return this; // make observable functions chainable
},
hasObserver: function( type ) {
return !! this._getObs( type ).length;
}
};
})());
})( this.app );
(function( app ) {
var ux = app.ns("ux");
var extend = ux.Observable.extend;
var instance = function() {
if( ! ("me" in this) ) {
this.me = new this();
}
return this.me;
};
ux.Singleton = ux.Observable.extend({});
ux.Singleton.extend = function() {
var Self = extend.apply( this, arguments );
Self.instance = instance;
return Self;
};
})( this.app );
(function( $, app ) {
var ux = app.ns("ux");
/**
* Provides drag and drop functionality<br>
* a DragDrop instance is created for each usage pattern and then used over and over again<br>
* first a dragObj is defined - this is the jquery node that will be dragged around<br>
* second, the event callbacks are defined - these allow you control the ui during dragging and run functions when successfully dropping<br>
* thirdly drop targets are defined - this is a list of DOM nodes, the constructor works in one of two modes:
* <li>without targets - objects can be picked up and dragged around, dragStart and dragStop events fire</li>
* <li>with targets - as objects are dragged over targets dragOver, dragOut and DragDrop events fire
* to start dragging call the DragDrop.pickup_handler() function, dragging stops when the mouse is released.
* @constructor
* The following options are supported
* <dt>targetSelector</dt>
* <dd>an argument passed directly to jquery to create a list of targets, as such it can be a CSS style selector, or an array of DOM nodes<br>if target selector is null the DragDrop does Drag only and will not fire dragOver dragOut and dragDrop events</dd>
* <dt>pickupSelector</dt>
* <dd>a jquery selector. The pickup_handler is automatically bound to matched elements (eg clicking on these elements starts the drag). if pickupSelector is null, the pickup_handler must be manually bound <code>$(el).bind("mousedown", dragdrop.pickup_handler)</code></dd>
* <dt>dragObj</dt>
* <dd>the jQuery element to drag around when pickup is called. If not defined, dragObj must be set in onDragStart</dd>
* <dt>draggingClass</dt>
* <dd>the class(es) added to items when they are being dragged</dd>
* The following observables are supported
* <dt>dragStart</dt>
* <dd>a callback when start to drag<br><code>function(jEv)</code></dd>
* <dt>dragOver</dt>
* <dd>a callback when we drag into a target<br><code>function(jEl)</code></dd>
* <dt>dragOut</dt>
* <dd>a callback when we drag out of a target, or when we drop over a target<br><code>function(jEl)</code></dd>
* <dt>dragDrop</dt>
* <dd>a callback when we drop on a target<br><code>function(jEl)</code></dd>
* <dt>dragStop</dt>
* <dd>a callback when we stop dragging<br><code>function(jEv)</code></dd>
*/
ux.DragDrop = ux.Observable.extend({
defaults : {
targetsSelector : null,
pickupSelector: null,
dragObj : null,
draggingClass : "dragging"
},
init: function(options) {
this._super(); // call the class initialiser
this.drag_handler = this.drag.bind(this);
this.drop_handler = this.drop.bind(this);
this.pickup_handler = this.pickup.bind(this);
this.targets = [];
this.dragObj = null;
this.dragObjOffset = null;
this.currentTarget = null;
if(this.config.pickupSelector) {
$(this.config.pickupSelector).bind("mousedown", this.pickup_handler);
}
},
drag : function(jEv) {
jEv.preventDefault();
var mloc = acx.vector( this.lockX || jEv.pageX, this.lockY || jEv.pageY );
this.dragObj.css(mloc.add(this.dragObjOffset).asOffset());
if(this.targets.length === 0) {
return;
}
if(this.currentTarget !== null && mloc.within(this.currentTarget[1], this.currentTarget[2])) {
return;
}
if(this.currentTarget !== null) {
this.fire('dragOut', this.currentTarget[0]);
this.currentTarget = null;
}
for(var i = 0; i < this.targets.length; i++) {
if(mloc.within(this.targets[i][1], this.targets[i][2])) {
this.currentTarget = this.targets[i];
break;
}
}
if(this.currentTarget !== null) {
this.fire('dragOver', this.currentTarget[0]);
}
},
drop : function(jEv) {
$(document).unbind("mousemove", this.drag_handler);
$(document).unbind("mouseup", this.drop_handler);
this.dragObj.removeClass(this.config.draggingClass);
if(this.currentTarget !== null) {
this.fire('dragOut', this.currentTarget[0]);
this.fire('dragDrop', this.currentTarget[0]);
}
this.fire('dragStop', jEv);
this.dragObj = null;
},
pickup : function(jEv, opts) {
$.extend(this.config, opts);
this.fire('dragStart', jEv);
this.dragObj = this.dragObj || this.config.dragObj;
this.dragObjOffset = this.config.dragObjOffset || acx.vector(this.dragObj.offset()).sub(jEv.pageX, jEv.pageY);
this.lockX = this.config.lockX ? jEv.pageX : 0;
this.lockY = this.config.lockY ? jEv.pageY : 0;
this.dragObj.addClass(this.config.draggingClass);
if(!this.dragObj.get(0).parentNode || this.dragObj.get(0).parentNode.nodeType === 11) { // 11 = document fragment
$(document.body).append(this.dragObj);
}
if(this.config.targetsSelector) {
this.currentTarget = null;
var targets = ( this.targets = [] );
// create an array of elements optimised for rapid collision detection calculation
$(this.config.targetsSelector).each(function(i, el) {
var jEl = $(el);
var tl = acx.vector(jEl.offset());
var br = tl.add(jEl.width(), jEl.height());
targets.push([jEl, tl, br]);
});
}
$(document).bind("mousemove", this.drag_handler);
$(document).bind("mouseup", this.drop_handler);
this.drag_handler(jEv);
}
});
})( this.jQuery, this.app );
(function( app ) {
var ux = app.ns("ux");
ux.FieldCollection = ux.Observable.extend({
defaults: {
fields: [] // the collection of fields
},
init: function() {
this._super();
this.fields = this.config.fields;
},
validate: function() {
return this.fields.reduce(function(r, field) {
return r && field.validate();
}, true);
},
getData: function(type) {
return this.fields.reduce(function(r, field) {
r[field.name] = field.val(); return r;
}, {});
}
});
})( this.app );
(function( $, app ) {
var data = app.ns("data");
var ux = app.ns("ux");
data.Model = ux.Observable.extend({
defaults: {
data: null
},
init: function() {
this.set( this.config.data );
},
set: function( key, value ) {
if( arguments.length === 1 ) {
this._data = $.extend( {}, key );
} else {
key.split(".").reduce(function( ptr, prop, i, props) {
if(i === (props.length - 1) ) {
ptr[prop] = value;
} else {
if( !(prop in ptr) ) {
ptr[ prop ] = {};
}
return ptr[prop];
}
}, this._data );
}
},
get: function( key ) {
return key.split(".").reduce( function( ptr, prop ) {
return ( ptr && ( prop in ptr ) ) ? ptr[ prop ] : undefined;
}, this._data );
},
});
})( this.jQuery, this.app );
(function( app ) {
var data = app.ns("data");
var ux = app.ns("ux");
data.DataSourceInterface = ux.Observable.extend({
/*
properties
meta = { total: 0 },
headers = [ { name: "" } ],
data = [ { column: value, column: value } ],
sort = { column: "name", dir: "desc" }
events
data: function( DataSourceInterface )
*/
_getSummary: function(res) {
this.summary = i18n.text("TableResults.Summary", res._shards.successful, res._shards.total, (typeof res.hits.total === 'object') ? res.hits.total.value : res.hits.total, (res.took / 1000).toFixed(3));
},
_getMeta: function(res) {
this.meta = { total: res.hits.total, shards: res._shards, tool: res.took };
}
});
})( this.app );
(function( app ) {
var data = app.ns("data");
data.ResultDataSourceInterface = data.DataSourceInterface.extend({
results: function(res) {
this._getSummary(res);
this._getMeta(res);
this._getData(res);
this.sort = {};
this.fire("data", this);
},
_getData: function(res) {
var columns = this.columns = [];
this.data = res.hits.hits.map(function(hit) {
var row = (function(path, spec, row) {
for(var prop in spec) {
if(acx.isObject(spec[prop])) {
arguments.callee(path.concat(prop), spec[prop], row);
} else if(acx.isArray(spec[prop])) {
if(spec[prop].length) {
arguments.callee(path.concat(prop), spec[prop][0], row)
}
} else {
var dpath = path.concat(prop).join(".");
if(! columns.contains(dpath)) {
columns.push(dpath);
}
row[dpath] = (spec[prop] || "null").toString();
}
}
return row;
})([ hit._type ], hit, {});
row._source = hit;
return row;
}, this);
}
});
})( this.app );
(function( app ) {
/*
notes on elasticsearch terminology used in this project
indices[index] contains one or more
types[type] contains one or more
documents contain one or more
paths[path]
each path contains one element of data
each path maps to one field
eg PUT, "/twitter/tweet/1"
{
user: "mobz",
date: "2011-01-01",
message: "You know, for browsing elasticsearch",
name: {
first: "Ben",
last: "Birch"
}
}
creates
1 index: twitter
this is the collection of index data
1 type: tweet
this is the type of document (kind of like a table in sql)
1 document: /twitter/tweet/1
this is an actual document in the index ( kind of like a row in sql)
5 paths: [ ["user"], ["date"], ["message"], ["name","first"], ["name","last"] ]
since documents can be heirarchical this maps a path from a document root to a piece of data
5 fields: [ "user", "date", "message", "first", "last" ]
this is an indexed 'column' of data. fields are not heirarchical
the relationship between a path and a field is called a mapping. mappings also contain a wealth of information about how es indexes the field
notes
1) a path is stored as an array, the dpath is <index> . <type> . path.join("."),
which can be considered the canonical reference for a mapping
2) confusingly, es uses the term index for both the collection of indexed data, and the individually indexed fields
so the term index_name is the same as field_name in this sense.
*/
var data = app.ns("data");
var ux = app.ns("ux");
var coretype_map = {
"string" : "string",
"keyword" : "string",
"text" : "string",
"byte" : "number",
"short" : "number",
"long" : "number",
"integer" : "number",
"float" : "number",
"double" : "number",
"ip" : "number",
"date" : "date",
"boolean" : "boolean",
"binary" : "binary",
"multi_field" : "multi_field"
};
var default_property_map = {
"string" : { "store" : "no", "index" : "analysed" },
"number" : { "store" : "no", "precision_steps" : 4 },
"date" : { "store" : "no", "format" : "dateOptionalTime", "index": "yes", "precision_steps": 4 },
"boolean" : { "store" : "no", "index": "yes" },
"binary" : { },
"multi_field" : { }
};
// parses metatdata from a cluster, into a bunch of useful data structures
data.MetaData = ux.Observable.extend({
defaults: {
state: null // (required) response from a /_cluster/state request
},
init: function() {
this._super();
this.refresh(this.config.state);
},
getIndices: function(alias) {
return alias ? this.aliases[alias] : this.indicesList;
},
// returns an array of strings containing all types that are in all of the indices passed in, or all types
getTypes: function(indices) {
var indices = indices || [], types = [];
this.typesList.forEach(function(type) {
for(var i = 0; i < indices.length; i++) {
if(! this.indices[indices[i]].types.contains(type))
return;
}
types.push(type);
}, this);
return types;
},
refresh: function(state) {
// currently metadata expects all like named fields to have the same type, even when from different types and indices
var aliases = this.aliases = {};
var indices = this.indices = {};
var types = this.types = {};
var fields = this.fields = {};
var paths = this.paths = {};
function createField( mapping, index, type, path, name ) {
var dpath = [ index, type ].concat( path ).join( "." );
var field_name = mapping.index_name || path.join( "." );
var field = paths[ dpath ] = fields[ field_name ] || $.extend({
field_name : field_name,
core_type : coretype_map[ mapping.type ],
dpaths : []
}, default_property_map[ coretype_map[ mapping.type ] ], mapping );
if (field.type === "multi_field" && typeof field.fields !== "undefined") {
for (var subField in field.fields) {
field.fields[ subField ] = createField( field.fields[ subField ], index, type, path.concat( subField ), name + "." + subField );
}
}
if (fields.dpaths) {
field.dpaths.push(dpath);
}
return field;
}
function getFields(properties, type, index, listeners) {
(function procPath(prop, path) {
for (var n in prop) {
if ("properties" in prop[n]) {
procPath( prop[ n ].properties, path.concat( n ) );
} else {
var field = createField(prop[n], index, type, path.concat(n), n);
listeners.forEach( function( listener ) {
listener[ field.field_name ] = field;
} );
}
}
})(properties, []);
}
for (var index in state.metadata.indices) {
indices[index] = {
types : [], fields : {}, paths : {}, parents : {}
};
indices[index].aliases = state.metadata.indices[index].aliases;
indices[index].aliases.forEach(function(alias) {
(aliases[alias] || (aliases[alias] = [])).push(index);
});
var mapping = state.metadata.indices[index].mappings;
for (var type in mapping) {
indices[index].types.push(type);
if ( type in types) {
types[type].indices.push(index);
} else {
types[type] = {
indices : [index], fields : {}
};
}
getFields(mapping[type].properties, type, index, [fields, types[type].fields, indices[index].fields]);
if ( typeof mapping[type]._parent !== "undefined") {
indices[index].parents[type] = mapping[type]._parent.type;
}
}
}
this.aliasesList = Object.keys(aliases);
this.indicesList = Object.keys(indices);
this.typesList = Object.keys(types);
this.fieldsList = Object.keys(fields);
}
});
})( this.app );
(function( app ) {
var data = app.ns("data");
var ux = app.ns("ux");
data.MetaDataFactory = ux.Observable.extend({
defaults: {
cluster: null // (required) an app.services.Cluster
},
init: function() {
this._super();
var _cluster = this.config.cluster;
this.config.cluster.get("_cluster/state", function(data) {
this.metaData = new app.data.MetaData({state: data});
this.fire("ready", this.metaData, { originalData: data, "k": 1 }); // TODO originalData needed for legacy ui.FilterBrowser
}.bind(this), function() {
var _this = this;
_cluster.get("_all", function( data ) {
clusterState = {routing_table:{indices:{}}, metadata:{indices:{}}};
for(var k in data) {
clusterState["routing_table"]["indices"][k] = {"shards":{"1":[{
"state":"UNASSIGNED",
"primary":false,
"node":"unknown",
"relocating_node":null,
"shard":'?',
"index":k
}]}};
clusterState["metadata"]["indices"][k] = {};
clusterState["metadata"]["indices"][k]["mappings"] = data[k]["mappings"];
clusterState["metadata"]["indices"][k]["aliases"] = $.makeArray(Object.keys(data[k]["aliases"]));
clusterState["metadata"]["indices"][k]["settings"] = data[k]["settings"];
clusterState["metadata"]["indices"][k]["fields"] = {};
}
_this.metaData = new app.data.MetaData({state: clusterState});
_this.fire("ready", _this.metaData, {originalData: clusterState});
});
}.bind(this));
}
});
})( this.app );
(function( app ) {
var data = app.ns("data");
var ux = app.ns("ux");
data.Query = ux.Observable.extend({
defaults: {
cluster: null, // (required) instanceof app.services.Cluster
size: 50 // size of pages to return
},
init: function() {
this._super();
this.cluster = this.config.cluster;
this.refuid = 0;
this.refmap = {};
this.indices = [];
this.types = [];
this.search = {
query: { bool: { must: [], must_not: [], should: [] } },
from: 0,
size: this.config.size,
sort: [],
aggs: {},
version: true
};
this.defaultClause = this.addClause();
this.history = [ this.getState() ];
},
clone: function() {
var q = new data.Query({ cluster: this.cluster });
q.restoreState(this.getState());
for(var uqid in q.refmap) {
q.removeClause(uqid);
}
return q;
},
getState: function() {
return $.extend(true, {}, { search: this.search, indices: this.indices, types: this.types });
},
restoreState: function(state) {
state = $.extend(true, {}, state || this.history[this.history.length - 1]);
this.indices = state.indices;
this.types = state.types;
this.search = state.search;
},
getData: function() {
return JSON.stringify(this.search);
},
query: function() {
var state = this.getState();
this.cluster.post(
(this.indices.join(",") || "_all") + "/" + ( this.types.length ? this.types.join(",") + "/" : "") + "_search",
this.getData(),
function(results) {
if(results === null) {
alert(i18n.text("Query.FailAndUndo"));
this.restoreState();
return;
}
this.history.push(state);
this.fire("results", this, results);
}.bind(this));
},
loadParents: function(res,metadata){
//create data for mget
var data = { docs :[] };
var indexToTypeToParentIds = {};
res.hits.hits.forEach(function(hit) {
if (typeof hit.fields != "undefined"){
if (typeof hit.fields._parent != "undefined"){
var parentType = metadata.indices[hit._index].parents[hit._type];
if (typeof indexToTypeToParentIds[hit._index] == "undefined"){
indexToTypeToParentIds[hit._index] = new Object();
}
if (typeof indexToTypeToParentIds[hit._index][hit._type] == "undefined"){
indexToTypeToParentIds[hit._index][hit._type] = new Object();
}
if (typeof indexToTypeToParentIds[hit._index][hit._type][hit.fields._parent] == "undefined"){
indexToTypeToParentIds[hit._index][hit._type][hit.fields._parent] = null;
data.docs.push({ _index:hit._index, _type:parentType, _id:hit.fields._parent});
}
}
}
});
//load parents
var state = this.getState();
this.cluster.post("_mget",JSON.stringify(data),
function(results) {
if(results === null) {
alert(i18n.text("Query.FailAndUndo"));
this.restoreState();
return;
}
this.history.push(state);
var indexToTypeToParentIdToHit = new Object();
results.docs.forEach(function(doc) {
if (typeof indexToTypeToParentIdToHit[doc._index] == "undefined"){
indexToTypeToParentIdToHit[doc._index] = new Object();
}
if (typeof indexToTypeToParentIdToHit[doc._index][doc._type] == "undefined"){
indexToTypeToParentIdToHit[doc._index][doc._type] = new Object();
}
indexToTypeToParentIdToHit[doc._index][doc._type][doc._id] = doc;
});
res.hits.hits.forEach(function(hit) {
if (typeof hit.fields != "undefined"){
if (typeof hit.fields._parent != "undefined"){
var parentType = metadata.indices[hit._index].parents[hit._type];
hit._parent = indexToTypeToParentIdToHit[hit._index][parentType][hit.fields._parent];
}
}
});
this.fire("resultsWithParents", this, res);
}.bind(this));
},
setPage: function(page) {
this.search.from = this.config.size * (page - 1);
},
setSort: function(index, desc) {
var sortd = {}; sortd[index] = { order: desc ? 'asc' : 'desc' };
this.search.sort.unshift( sortd );
for(var i = 1; i < this.search.sort.length; i++) {
if(Object.keys(this.search.sort[i])[0] === index) {
this.search.sort.splice(i, 1);
break;