-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoyant.min.js
More file actions
1375 lines (1375 loc) · 734 KB
/
voyant.min.js
File metadata and controls
1375 lines (1375 loc) · 734 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
/* This file created by JSCacher. Last modified: Fri Mar 22 16:10:30 UTC 2024 */
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.createTemplateTagFirstArg=function(a){return a.raw=a};$jscomp.createTemplateTagFirstArgWithRaw=function(a,b){a.raw=b;return a};$jscomp.arrayIteratorImpl=function(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}};$jscomp.arrayIterator=function(a){return{next:$jscomp.arrayIteratorImpl(a)}};$jscomp.makeIterator=function(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):$jscomp.arrayIterator(a)};
$jscomp.owns=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};$jscomp.getGlobal=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(a,b){var c=$jscomp.propertyToPolyfillSymbol[b];if(null==c)return a[b];c=a[c];return void 0!==c?c:a[b]};
$jscomp.polyfill=function(a,b,c,d){b&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(a,b,c,d):$jscomp.polyfillUnisolated(a,b,c,d))};$jscomp.polyfillUnisolated=function(a,b,c,d){c=$jscomp.global;a=a.split(".");for(d=0;d<a.length-1;d++){var e=a[d];if(!(e in c))return;c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:b})};
$jscomp.polyfillIsolated=function(a,b,c,d){var e=a.split(".");a=1===e.length;d=e[0];d=!a&&d in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var f=0;f<e.length-1;f++){var g=e[f];if(!(g in d))return;d=d[g]}e=e[e.length-1];c=$jscomp.IS_SYMBOL_NATIVE&&"es6"===c?d[e]:null;b=b(c);null!=b&&(a?$jscomp.defineProperty($jscomp.polyfills,e,{configurable:!0,writable:!0,value:b}):b!==c&&(void 0===$jscomp.propertyToPolyfillSymbol[e]&&(c=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[e]=$jscomp.IS_SYMBOL_NATIVE?
$jscomp.global.Symbol(e):$jscomp.POLYFILL_PREFIX+c+"$"+e),$jscomp.defineProperty(d,$jscomp.propertyToPolyfillSymbol[e],{configurable:!0,writable:!0,value:b})))};$jscomp.assign=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.assign?Object.assign:function(a,b){for(var c=1;c<arguments.length;c++){var d=arguments[c];if(d)for(var e in d)$jscomp.owns(d,e)&&(a[e]=d[e])}return a};$jscomp.polyfill("Object.assign",function(a){return a||$jscomp.assign},"es6","es3");
$jscomp.underscoreProtoCanBeSet=function(){var a={a:!0},b={};try{return b.__proto__=a,b.a}catch(c){}return!1};$jscomp.setPrototypeOf=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf:$jscomp.underscoreProtoCanBeSet()?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null;$jscomp.generator={};
$jscomp.generator.ensureIteratorResultIsObject_=function(a){if(!(a instanceof Object))throw new TypeError("Iterator result "+a+" is not an object");};$jscomp.generator.Context=function(){this.isRunning_=!1;this.yieldAllIterator_=null;this.yieldResult=void 0;this.nextAddress=1;this.finallyAddress_=this.catchAddress_=0;this.finallyContexts_=this.abruptCompletion_=null};
$jscomp.generator.Context.prototype.start_=function(){if(this.isRunning_)throw new TypeError("Generator is already running");this.isRunning_=!0};$jscomp.generator.Context.prototype.stop_=function(){this.isRunning_=!1};$jscomp.generator.Context.prototype.jumpToErrorHandler_=function(){this.nextAddress=this.catchAddress_||this.finallyAddress_};$jscomp.generator.Context.prototype.next_=function(a){this.yieldResult=a};
$jscomp.generator.Context.prototype.throw_=function(a){this.abruptCompletion_={exception:a,isException:!0};this.jumpToErrorHandler_()};$jscomp.generator.Context.prototype.return=function(a){this.abruptCompletion_={return:a};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.jumpThroughFinallyBlocks=function(a){this.abruptCompletion_={jumpTo:a};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.yield=function(a,b){this.nextAddress=b;return{value:a}};
$jscomp.generator.Context.prototype.yieldAll=function(a,b){a=$jscomp.makeIterator(a);var c=a.next();$jscomp.generator.ensureIteratorResultIsObject_(c);if(c.done)this.yieldResult=c.value,this.nextAddress=b;else return this.yieldAllIterator_=a,this.yield(c.value,b)};$jscomp.generator.Context.prototype.jumpTo=function(a){this.nextAddress=a};$jscomp.generator.Context.prototype.jumpToEnd=function(){this.nextAddress=0};
$jscomp.generator.Context.prototype.setCatchFinallyBlocks=function(a,b){this.catchAddress_=a;void 0!=b&&(this.finallyAddress_=b)};$jscomp.generator.Context.prototype.setFinallyBlock=function(a){this.catchAddress_=0;this.finallyAddress_=a||0};$jscomp.generator.Context.prototype.leaveTryBlock=function(a,b){this.nextAddress=a;this.catchAddress_=b||0};
$jscomp.generator.Context.prototype.enterCatchBlock=function(a){this.catchAddress_=a||0;a=this.abruptCompletion_.exception;this.abruptCompletion_=null;return a};$jscomp.generator.Context.prototype.enterFinallyBlock=function(a,b,c){c?this.finallyContexts_[c]=this.abruptCompletion_:this.finallyContexts_=[this.abruptCompletion_];this.catchAddress_=a||0;this.finallyAddress_=b||0};
$jscomp.generator.Context.prototype.leaveFinallyBlock=function(a,b){b=this.finallyContexts_.splice(b||0)[0];if(b=this.abruptCompletion_=this.abruptCompletion_||b){if(b.isException)return this.jumpToErrorHandler_();void 0!=b.jumpTo&&this.finallyAddress_<b.jumpTo?(this.nextAddress=b.jumpTo,this.abruptCompletion_=null):this.nextAddress=this.finallyAddress_}else this.nextAddress=a};$jscomp.generator.Context.prototype.forIn=function(a){return new $jscomp.generator.Context.PropertyIterator(a)};
$jscomp.generator.Context.PropertyIterator=function(a){this.object_=a;this.properties_=[];for(var b in a)this.properties_.push(b);this.properties_.reverse()};$jscomp.generator.Context.PropertyIterator.prototype.getNext=function(){for(;0<this.properties_.length;){var a=this.properties_.pop();if(a in this.object_)return a}return null};$jscomp.generator.Engine_=function(a){this.context_=new $jscomp.generator.Context;this.program_=a};
$jscomp.generator.Engine_.prototype.next_=function(a){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_.next,a,this.context_.next_);this.context_.next_(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.return_=function(a){this.context_.start_();var b=this.context_.yieldAllIterator_;if(b)return this.yieldAllStep_("return"in b?b["return"]:function(c){return{value:c,done:!0}},a,this.context_.return);this.context_.return(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.throw_=function(a){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_["throw"],a,this.context_.next_);this.context_.throw_(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.yieldAllStep_=function(a,b,c){try{var d=a.call(this.context_.yieldAllIterator_,b);$jscomp.generator.ensureIteratorResultIsObject_(d);if(!d.done)return this.context_.stop_(),d;var e=d.value}catch(f){return this.context_.yieldAllIterator_=null,this.context_.throw_(f),this.nextStep_()}this.context_.yieldAllIterator_=null;c.call(this.context_,e);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.nextStep_=function(){for(;this.context_.nextAddress;)try{var a=this.program_(this.context_);if(a)return this.context_.stop_(),{value:a.value,done:!1}}catch(b){this.context_.yieldResult=void 0,this.context_.throw_(b)}this.context_.stop_();if(this.context_.abruptCompletion_){a=this.context_.abruptCompletion_;this.context_.abruptCompletion_=null;if(a.isException)throw a.exception;return{value:a.return,done:!0}}return{value:void 0,done:!0}};
$jscomp.generator.Generator_=function(a){this.next=function(b){return a.next_(b)};this.throw=function(b){return a.throw_(b)};this.return=function(b){return a.return_(b)};this[Symbol.iterator]=function(){return this}};$jscomp.generator.createGenerator=function(a,b){b=new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(b));$jscomp.setPrototypeOf&&a.prototype&&$jscomp.setPrototypeOf(b,a.prototype);return b};
$jscomp.asyncExecutePromiseGenerator=function(a){function b(d){return a.next(d)}function c(d){return a.throw(d)}return new Promise(function(d,e){function f(g){g.done?d(g.value):Promise.resolve(g.value).then(b,c).then(f,e)}f(a.next())})};$jscomp.asyncExecutePromiseGeneratorFunction=function(a){return $jscomp.asyncExecutePromiseGenerator(a())};$jscomp.asyncExecutePromiseGeneratorProgram=function(a){return $jscomp.asyncExecutePromiseGenerator(new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(a)))};
function Bubblelines(a){this.container=a.container;this.externalClickHandler=a.clickHandler;this.INTERVAL=50;this.DISMISS_DELAY=2500;this.UNIFORM_LINE_LENGTH=!0;this.SEPARATE_LINES_FOR_TERMS=!1;this.MAX_LINE_WIDTH=this.MAX_LABEL_WIDTH=0;this.DRAW_TITLES=!0;this.DRAW_SHORT_TITLES=!1;this.graphSeparation=this.MIN_GRAPH_SEPARATION=50;this.yIndex=0;this.mouseOver=!1;this.clearToolTipId=this.intervalId=null;this.overBubbles=[];this.lastClickedBubbles={};this.ctx=this.canvas=this.dragInfo=null;this.maxDocLength=
2;this.maxFreq={term:null,value:0};this.maxRadius=0;this.cache=new Ext.util.MixedCollection;this.currentTerms={};this.termsFilter=[];this.bubbleSpacing=50;this.initialized=!1}
Bubblelines.prototype={constructor:Bubblelines,initializeCanvas:function(){var a=this.container,b=a.getHeight(),c=a.getWidth();this.DRAW_SHORT_TITLES=500>c;var d=Ext.id("bubblelines");a.add({xtype:"container",width:c,height:b,html:'\x3ccanvas id\x3d"'+d+'" width\x3d"'+c+'" height\x3d"'+b+'"\x3e\x3c/canvas\x3e',border:!1,listeners:{afterrender:{fn:function(e){this.canvas=document.getElementById(d);this.ctx=this.canvas.getContext("2d");this.canvas.addEventListener("click",this.clickHandler.bind(this),
!1);this.canvas.addEventListener("mousedown",this.mouseDownHandler.bind(this),!1);this.canvas.addEventListener("mouseup",this.mouseUpHandler.bind(this),!1);this.canvas.addEventListener("mousemove",this.moveHandler.bind(this),!1);this.canvas.addEventListener("mouseenter",this.mouseEnterHandler.bind(this),!1);this.canvas.addEventListener("mouseleave",this.mouseLeaveHandler.bind(this),!1)},single:!0,scope:this}}});a.updateLayout();this.initialized=!0},doBubblelinesLayout:function(){if(this.initialized){var a=
this.container.getWidth();this.DRAW_SHORT_TITLES=500>a;this.setTitleWidthsAndMaxTitleWidth();for(var b=Ext.DomQuery.jsSelect("div:not(div[class*\x3dterm])",this.container.el.dom),c=0;c<b.length;c++)Ext.fly(b[c]).setWidth(a);this.canvas.width=a;b=75;this.DRAW_SHORT_TITLES&&(b=50);this.setMaxLineWidth(a-this.MAX_LABEL_WIDTH-b);this.setLineLengths();this.recache();this.setCanvasHeight();this.drawGraph()}},addDocToCache:function(a){this.cacheBubbles(a);this.calculateBubbleRadii(a);a.lineLength=600;a.freqCounts=
{};!1===this.cache.containsKey(a.id)?this.cache.add(a):this.cache.replace(a.id,a);this.cache.sort("index","ASC")},addTermsToDoc:function(a,b){var c;for(c in a)var d=c;this.currentTerms[d]=!0;b=this.cache.get(b);Ext.apply(b.terms,a);this.cacheBubbles(b)?this.recache():this.calculateBubbleRadii(b)},cacheBubbles:function(a){var b=!1,c;for(c in a.terms){for(var d=a.terms[c],e=d.distributions.length,f=a.lineLength/e,g=[],h=0,k=0,l=0,m=0;m<e;m++){var n=d.distributions[m];n>k&&(k=n);g.push({id:Ext.id(null,
"bub"),x:l,freq:n,radius:0,bin:m,tokenPositions:d.positions.slice(h,h+=n)});l+=f}a.terms[c].maxDistribution=k;a.terms[c].pos=g;k>this.maxFreq.value&&(b=!0,this.setMaxFreq({term:c,value:k}))}return b},calculateBubbleRadii:function(a,b){var c=Math.log(this.maxFreq.value),d=Math.log(2)/2,e;for(e in a.terms){var f=a.terms[e];if(f&&(null==b||e==b))for(var g=0;g<f.pos.length;g++){var h=f.pos[g];h.radius=0<h.freq?Math.max(Math.log(h.freq),d)/c*this.maxRadius:0}}},recache:function(){this.cache.each(function(a){this.cacheBubbles(a);
this.calculateBubbleRadii(a)},this)},getTotalHeight:function(){var a=this.maxRadius;this.cache.each(function(b,c,d){a+=b.height},this);return a},setCanvasHeight:function(){this.calculateGraphHeights();var a=this.getTotalHeight(),b=this.container.dom;if(void 0!==b){b=Ext.DomQuery.jsSelect("div",b);for(var c=0;c<b.length;c++)Ext.fly(b[c]).setHeight(a)}this.canvas&&(this.canvas.height=a)},setMaxLineWidth:function(a){this.maxRadius=a/30;this.MAX_LINE_WIDTH=a-this.maxRadius/2},calculateGraphHeights:function(){var a=
.5*this.maxRadius;if(this.SEPARATE_LINES_FOR_TERMS){var b=this.termsFilter;this.cache.each(function(d,e,f){e=this.maxRadius*b.length;for(f=0;f<b.length;f++)d.terms[b[f]]||(e-=this.maxRadius);0==e&&(e=this.maxRadius);d.height=e+a},this)}else{var c=Math.max(this.maxRadius,this.MIN_GRAPH_SEPARATION);this.cache.each(function(d,e,f){d.height=c+a},this)}},findLongestDocument:function(a){a=a.getTotalWordTokens();a>this.maxDocLength&&(this.maxDocLength=a)},getTitleWidth:function(a){var b=a.title;this.DRAW_SHORT_TITLES&&
(b=this.cache.indexOf(a)+1+")");this.ctx.textBaseline="top";this.ctx.font="bold 12px Verdana";return this.ctx.measureText(b).width},setTitleWidthsAndMaxTitleWidth:function(){this.cache.each(function(a,b){b=this.getTitleWidth(a);a.titleWidth=b;b>this.MAX_LABEL_WIDTH&&(this.MAX_LABEL_WIDTH=b)},this)},setLineLengths:function(){this.cache.each(function(a,b){b=this.UNIFORM_LINE_LENGTH?this.MAX_LINE_WIDTH:Math.log(a.getTotalWordTokens())/Math.log(this.maxDocLength)*this.MAX_LINE_WIDTH;a.lineLength=b},this)},
drawGraph:function(a){null!=this.intervalId&&clearInterval(this.intervalId);this.mouseOver?this.intervalId=setInterval(this.doDraw.bind(this,[a]),this.INTERVAL):setTimeout(this.doDraw.bind(this,[a]),5)},doDraw:function(a){this.clearCanvas();this.yIndex=this.maxRadius;!0===a&&(this.yIndex+=30);this.cache.each(this.drawDocument,this);!0===a?this.drawLegend():this.drawToolTip();this.doDrag()},drawDocument:function(a,b,c){if(!a.hidden){var d=a.lineLength,e=this.MAX_LABEL_WIDTH-a.titleWidth,f=5;this.ctx.textBaseline=
"top";this.ctx.font="bold 12px Verdana";if(null!=this.dragInfo&&this.dragInfo.oldIndex==b)this.ctx.fillStyle="rgba(128, 128, 128, 0.5)",f+=e,this.ctx.fillText(a.title,f,this.yIndex),this.SEPARATE_LINES_FOR_TERMS&&(this.yIndex+=a.height);else{c=function(){f=g.MAX_LABEL_WIDTH+g.maxRadius;g.ctx.strokeStyle="rgba(128, 128, 128, 1.0)";g.ctx.fillStyle="rgba(128, 128, 128, 1.0)";g.ctx.lineWidth=.25;g.ctx.beginPath();g.ctx.moveTo(f,g.yIndex-6);g.ctx.lineTo(f,g.yIndex+6);g.ctx.stroke();g.ctx.beginPath();g.ctx.moveTo(f,
g.yIndex);g.ctx.lineTo(f+d,g.yIndex);g.ctx.stroke();g.ctx.beginPath();g.ctx.moveTo(f+d,g.yIndex-6);g.ctx.lineTo(f+d,g.yIndex+6);g.ctx.stroke()};this.DRAW_TITLES&&(f+=e,this.ctx.fillStyle="rgba(128, 128, 128, 1.0)",e=a.title,this.DRAW_SHORT_TITLES&&(e=b+1+")"),this.ctx.fillText(e,f,this.yIndex));this.yIndex+=4;var g=this;this.SEPARATE_LINES_FOR_TERMS?null!=this.termsFilter&&0!==this.termsFilter.length||c():c();e=2*Math.PI;var h=0;a.freqCounts={};var k=a.terms,l=null!=this.lastClickedBubbles[b],m=0,
n;for(n in k)if(-1!==this.termsFilter.indexOf(n)){var u=k[n];if(u){m++;this.SEPARATE_LINES_FOR_TERMS&&c();var w=0,p=u.color.join(",");this.ctx.strokeStyle="rgba("+p+", 1)";this.ctx.fillStyle="rgba("+p+", 0.35)";this.ctx.lineWidth=.25;h+=u.rawFreq;w+=u.rawFreq;for(var q=l&&this.lastClickedBubbles[b][n],r=0;r<u.pos.length;r++){var v=u.pos[r];if(0<v.radius){var x=!1;q&&this.lastClickedBubbles[b][n]==v.id&&(this.ctx.strokeStyle="rgba(0, 0, 0, 0.75)",this.ctx.fillStyle="rgba("+p+", 0.5)",this.ctx.lineWidth=
1,x=!0);this.ctx.beginPath();this.ctx.arc(v.x+f,this.yIndex,v.radius,0,e,!0);this.ctx.closePath();this.ctx.fill();this.ctx.stroke();x&&(this.ctx.strokeStyle="rgba("+p+", 1)",this.ctx.fillStyle="rgba("+p+", 0.35)",this.ctx.lineWidth=.25)}}a.freqCounts[n]=w;this.SEPARATE_LINES_FOR_TERMS&&(this.ctx.fillStyle="rgba(0, 0, 0, 1.0)",this.ctx.font="10px Verdana",this.ctx.fillText(w,f+d+5,this.yIndex-4),this.yIndex+=this.maxRadius)}}this.SEPARATE_LINES_FOR_TERMS&&0==m&&(c(),this.ctx.fillStyle="rgba(0, 0, 0, 1.0)",
this.ctx.font="10px Verdana",this.ctx.fillText(0,f+d+5,this.yIndex-4),this.yIndex+=this.maxRadius);f+=d;this.SEPARATE_LINES_FOR_TERMS||(this.ctx.fillStyle="rgba(0, 0, 0, 1.0)",this.ctx.font="10px Verdana",this.ctx.fillText(h,f+5,this.yIndex-4))}this.yIndex=this.SEPARATE_LINES_FOR_TERMS?this.yIndex+.5*this.maxRadius:this.yIndex+a.height;this.yIndex-=4}},drawLegend:function(){var a=this.MAX_LABEL_WIDTH+this.maxRadius;this.ctx.textBaseline="top";this.ctx.font="16px serif";this.typeStore&&this.typeStore.each(function(b){var c=
b.get("color").join(",");this.ctx.fillStyle="rgb("+c+")";b=b.get("type");this.ctx.fillText(b,a,5);b=this.ctx.measureText(b).width;a+=b+8},this)},drawToolTip:function(){if(0<this.overBubbles.length){this.ctx.lineWidth=.5;this.ctx.fillStyle="rgba(224, 224, 224, 0.8)";this.ctx.strokeStyle="rgba(0, 0, 0, 0.8)";var a=this.overBubbles[0].x,b=this.overBubbles[0].y;a+110>this.canvas.width&&(a-=110);if(null==this.overBubbles[0].label){var c=this.cache.get(this.overBubbles[0].docIndex);var d=1;for(var e in c.freqCounts)d++;
d*=16;b+d>this.canvas.height&&(b-=d);this.ctx.fillRect(a,b,110,d);this.ctx.strokeRect(a,b,110,d);a+=10;b+=10;this.ctx.fillStyle="rgba(0, 0, 0, 0.8)";this.ctx.font="10px Verdana";for(e in c.freqCounts)this.ctx.fillText(e+": "+c.freqCounts[e],a,b,90),b+=16}else for(d=16*this.overBubbles.length+10,b+d>this.canvas.height&&(b-=d),this.ctx.fillRect(a,b,110,d),this.ctx.strokeRect(a,b,110,d),a+=10,b+=10,this.ctx.fillStyle="rgba(0, 0, 0, 0.8)",this.ctx.font="10px Verdana",c=0;c<this.overBubbles.length;c++)e=
this.overBubbles[c],this.ctx.fillText(e.label+": "+e.freq,a,b,90),b+=16;null==this.clearToolTipId&&(this.clearToolTipId=setTimeout(this.clearToolTip.bind(this),this.DISMISS_DELAY))}},clearToolTip:function(){this.overBubbles=[];clearTimeout(this.clearToolTipId);this.clearToolTipId=null},mouseEnterHandler:function(a){this.mouseOver=!0;this.drawGraph()},mouseLeaveHandler:function(a){this.mouseOver=!1;null!=this.intervalId&&clearInterval(this.intervalId);this.overBubbles=[];this.drawGraph()},moveHandler:function(a){this.clearToolTip();
this.overBubbles=[];var b=a.layerX-this.MAX_LABEL_WIDTH,c=a.layerY,d=.25*this.maxRadius,e=-1;this.cache.each(function(n,u,w){if(c<d)return!1;d+=n.height;if(c<d)return e=u,!1},this);if(null!=this.dragInfo)this.dragInfo.x=a.layerX,this.dragInfo.y=c,e>=this.cache.getCount()?e=this.cache.getCount()-1:0>e&&(e=c+this.maxRadius>this.canvas.height?this.cache.getCount()-1:0),this.dragInfo.newIndex=e,document.body.style.cursor="move";else if(0<=e&&e<this.cache.getCount())if(0<=b){var f=!1;b-=this.maxRadius;
var g=this.cache.get(e);if(b>=g.lineLength)this.overBubbles=[{docIndex:e,x:a.layerX+10,y:a.layerY+10}];else{b=Math.round(b/(g.lineLength/this.bubbleSpacing));var h=this.maxRadius;0<e&&(h=d-(this.cache.get(e).height-.75*this.maxRadius));h=Math.round((c-h)/this.maxRadius);var k=0,l;for(l in g.terms)if(-1!==this.termsFilter.indexOf(l)){var m=g.terms[l];m?(this.SEPARATE_LINES_FOR_TERMS&&k==h||!this.SEPARATE_LINES_FOR_TERMS)&&m.pos[b]&&0<m.pos[b].radius&&(f=!0,this.overBubbles.push({label:l,type:m,docId:g.id,
docIndex:e,xIndex:b,yIndex:h,freq:m.pos[b].freq,id:m.pos[b].id,tokenPositions:m.pos[b].tokenPositions,x:a.layerX+10,y:a.layerY+10})):this.SEPARATE_LINES_FOR_TERMS&&k--;k++}}document.body.style.cursor=f?"pointer":"auto"}else document.body.style.cursor="move";else document.body.style.cursor="auto"},mouseDownHandler:function(a){var b=a.layerX,c=a.layerY;if(b<this.MAX_LABEL_WIDTH){var d=.25*this.maxRadius,e=-1;this.cache.each(function(f,g,h){if(c<d)return!1;d+=f.height;if(c<d)return e=g,!1},this);0<=
e&&e<this.cache.getCount()&&(this.dragInfo={oldIndex:e,newIndex:e,xOffset:b-5,yOffset:5,x:b,y:c})}},mouseUpHandler:function(a){this.dragInfo=null},doDrag:function(){if(null!=this.dragInfo){for(var a={},b=0;b<this.cache.getCount();b++)b<this.dragInfo.oldIndex&&b<this.dragInfo.newIndex?a[b]=b:b<this.dragInfo.oldIndex&&b>=this.dragInfo.newIndex?a[b]=b+1:b==this.dragInfo.oldIndex?a[b]=this.dragInfo.newIndex:b>this.dragInfo.oldIndex&&b>this.dragInfo.newIndex?a[b]=b:b>this.dragInfo.oldIndex&&b<=this.dragInfo.newIndex&&
(a[b]=b-1);this.dragInfo.oldIndex=this.dragInfo.newIndex;this.cache.reorder(a);a=this.cache.get(this.dragInfo.oldIndex);this.ctx.fillStyle="rgba(128, 128, 128, 1)";this.ctx.textBaseline="top";this.ctx.font="bold 12px Verdana";this.ctx.fillText(a.title,this.dragInfo.x-this.dragInfo.xOffset,this.dragInfo.y-this.dragInfo.yOffset)}},clickHandler:function(a){this.lastClickedBubbles={};if(0<this.overBubbles.length&&this.overBubbles[0].label){a=[];for(var b=[],c=[],d=0;d<this.overBubbles.length;d++){var e=
this.overBubbles[d];c.push({term:e.label,docIndex:e.docIndex,docId:e.docId,tokenPositions:e.tokenPositions});null==this.lastClickedBubbles[e.docIndex]&&(this.lastClickedBubbles[e.docIndex]={});this.lastClickedBubbles[e.docIndex][e.label]=e.id;a.push(e.docId+":"+e.label);b.push(e.tokenPositions)}b=Ext.flatten(b);b.sort();void 0!==this.externalClickHandler&&this.externalClickHandler(c)}this.overBubbles=[]},setMaxFreq:function(a){null==a&&(a=this.findMaxFreq());this.maxFreq=a},findMaxFreq:function(){var a=
{term:"",value:0};this.cache.each(function(b){for(var c in b.terms){var d=b.terms[c].maxDistribution;d>a.value&&(a={term:c,value:d})}},this);return a},getNewColor:function(){for(var a=null,b=0;b<this.colors.length&&(a=this.colors[b],-1!=this.typeStore.findExact("color",a));b++)a=null;null==a&&(a=[128,128,128]);return a},removeAllTerms:function(){this.cache.each(function(a){a.terms={}},this);this.currentTerms={};this.termsFilter=[]},removeTerm:function(a){delete this.currentTerms[a];var b=!1;this.cache.each(function(f){for(var g in f.terms)g==
a&&(this.maxFreq.term==a&&(this.maxFreq={term:null,value:0},b=!0),delete f.terms[g])},this);for(var c in this.lastClickedBubbles){var d=this.lastClickedBubbles[c],e;for(e in d)e==a&&delete this.lastClickedBubbles[c][e]}b&&(this.setMaxFreq(),this.calculateBubbleRadii(),this.drawGraph())},clearCanvas:function(){this.canvas.width=this.canvas.width}};function Knots(a){this.container=a.container;this.externalClickHandler=a.clickHandler;this.MAX_LINE_LENGTH=0;this.LINE_SIZE=2.5;this.progressiveDraw=!0;this.progDrawDone=!1;this.drawStep=0;this.mouseOver=!1;this.refreshInterval=100;this.forceRedraw=!1;this.lastDrawTime=(new Date).getTime();this.intervalId=null;this.startAngle=315;this.angleIncrement=15;this.ctx=this.canvas=null;this.currentDoc={terms:{},lineLength:void 0};this.maxDocLength=0;this.offset={x:0,y:0};this.termsFilter=[];this.initialized=
!1;this.audio=a.audio;this.audioCtx=null}
Knots.prototype={constructor:Knots,initializeCanvas:function(){var a=this.container,b=a.getHeight()-5,c=a.getWidth();this.MAX_LINE_LENGTH=Math.sqrt(c*c+b*b);var d=Ext.id("knots");a.add({xtype:"container",width:c,height:b,html:'\x3ccanvas id\x3d"'+d+'" width\x3d"'+c+'" height\x3d"'+b+'"\x3e\x3c/canvas\x3e',border:!1,listeners:{afterrender:{fn:function(e){this.canvas=document.getElementById(d);this.ctx=this.canvas.getContext("2d");this.canvas.addEventListener("click",this.clickHandler.bind(this),!1);
this.canvas.addEventListener("mousedown",this.mouseDownHandler.bind(this),!1);this.canvas.addEventListener("mouseup",this.mouseUpHandler.bind(this),!1);this.canvas.addEventListener("mousemove",this.moveHandler.bind(this),!1)},single:!0,scope:this}}});a.updateLayout();this.initialized=!0},doLayout:function(){if(this.initialized){var a=this.container.getWidth(),b=this.container.getHeight()-5;this.canvas.width=a;this.canvas.height=b;this.recache();this.buildGraph()}},buildGraph:function(a){null!=this.intervalId&&
(this.progDrawDone=!1,clearInterval(this.intervalId));this.forceRedraw=!0;this.drawStep=a||0;for(var b in this.currentDoc.terms)this.currentDoc.terms[b].done=!1;this.progressiveDraw?this.intervalId=setInterval(this.doDraw.createDelegate(this,[!1]),50):this.doDraw(!1)},drawGraph:function(a){null!=this.intervalId&&(this.progDrawDone=!1,clearInterval(this.intervalId));this.forceRedraw=!0;this.progressiveDraw?this.intervalId=setInterval(this.doDraw.createDelegate(this,[a]),50):this.doDraw(!1,a)},doDraw:function(a){var b=
(new Date).getTime();if(this.forceRedraw||b-this.lastDrawTime>=this.refreshInterval)if(this.forceRedraw=!1,this.clearCanvas(),this.ctx.save(),this.ctx.translate(this.offset.x,this.offset.y),this.drawDocument(this.currentDoc),this.originOpacity=.5,this.originColor="128,128,128",this.ctx.lineWidth=15*Math.abs(this.originOpacity-1),this.ctx.fillStyle="rgba("+this.originColor+",1.0)",this.ctx.strokeStyle="rgba("+this.originColor+","+this.originOpacity+")",this.ctx.beginPath(),this.ctx.arc(0,0,2*this.LINE_SIZE,
0,2*Math.PI,!0),this.ctx.closePath(),this.ctx.fill(),a||this.ctx.stroke(),this.ctx.restore(),this.ctx.lineWidth=1,!0===a&&this.drawLegend(),this.lastDrawTime=(new Date).getTime(),this.progressiveDraw){a=!0;for(var c in this.currentDoc.terms)a=a&&this.currentDoc.terms[c].done;(this.progDrawDone=a)?(clearInterval(this.intervalId),this.intervalId=null,this.muteTerms()):this.drawStep++}},setAudio:function(a){(this.audio=a)||this.muteTerms()},muteTerms:function(){for(t in this.currentDoc.terms)this.currentDoc.terms[t].audio&&
(this.currentDoc.terms[t].audio.gainNode.gain.value=0)},drawDocument:function(a){a=a.terms;for(var b in a)if(-1!=this.termsFilter.indexOf(b)){var c=a[b];if(c&&c.pos){var d=[[0,0],[0,0]];if(this.progressiveDraw){var e=this.drawStep+1;c.pos.length<=this.drawStep?(c.done=!0,e=c.pos.length,c.audio&&(c.audio.gainNode.gain.value=0)):(this.audio&&c.audio&&(c.audio.gainNode.gain.value=.1,setTimeout(function(){c.audio.gainNode.gain.value=0},.75*this.refreshInterval)),c.done=!1);for(var f=0;f<e;f++){var g=
c.pos[f];this.drawPolygon(g,d,c.color);d=[[g.polygon[0][3],g.polygon[1][3]],[g.polygon[0][2],g.polygon[1][2]]]}}else for(f=0;f<c.pos.length;f++)g=c.pos[f],this.drawPolygon(g,d,c.color),d=[[g.polygon[0][3],g.polygon[1][3]],[g.polygon[0][2],g.polygon[1][2]]]}}},drawPolygon:function(a,b,c){var d=a.polygon[0],e=a.polygon[1];this.ctx.beginPath();this.ctx.moveTo(b[0][0],b[0][1]);this.ctx.lineTo(d[0],e[0]);this.ctx.lineTo(d[1],e[1]);this.ctx.lineTo(b[1][0],b[1][1]);this.ctx.closePath();this.ctx.fillStyle=
"rgba("+c+", 0.6)";this.ctx.fill();this.ctx.beginPath();this.ctx.moveTo(d[0],e[0]);this.ctx.lineTo(d[1],e[1]);this.ctx.lineTo(d[2],e[2]);this.ctx.lineTo(d[3],e[3]);this.ctx.closePath();a.over&&(this.ctx.fillStyle="rgba("+c+", 1.0)");this.ctx.fill()},drawLegend:function(){var a=5;this.ctx.textBaseline="top";this.ctx.font="16px serif";this.termStore.each(function(b){var c=b.get("color");this.ctx.fillStyle="rgb("+c+")";b=b.get("term");this.ctx.fillText(b,a,5);b=this.ctx.measureText(b).width;a+=b+8},
this)},setCurrentDoc:function(a){this.currentDoc=a;this.cacheCurrentDocument()},addTerms:function(a){Ext.apply(this.currentDoc.terms,a);this.recache()},removeTerm:function(a){this.currentDoc.terms[a].audio&&this.currentDoc.terms[a].audio.oscillator.stop();delete this.currentDoc.terms[a];this.recache()},removeAllTerms:function(){for(term in this.currentDoc.terms)this.currentDoc.terms[term].audio&&this.currentDoc.terms[term].audio.oscillator.stop();this.currentDoc.terms={};this.recache()},recache:function(){this.MAX_LINE_LENGTH=
Math.sqrt(this.canvas.width*this.canvas.width+this.canvas.height*this.canvas.height);this.cacheCurrentDocument();this.determineGraphSizeAndPosition()},cacheCurrentDocument:function(){var a=this.MAX_LINE_LENGTH;this.currentDoc.lineLength=a;if(this.audio&&null==this.audioCtx)try{this.audioCtx=new (window.AudioContext||window.webkitAudioContext)}catch(e){}for(var b in this.currentDoc.terms){if(this.audio&&this.audioCtx&&!this.currentDoc.terms[b].audio){var c=this.audioCtx.createOscillator(),d=this.audioCtx.createGain();
c.connect(d);d.connect(this.audioCtx.destination);c.frequency.value=500*Math.random()+150;c.start();d.gain.value=0;this.currentDoc.terms[b].audio={oscillator:c,gainNode:d}}this.cacheTurns(this.currentDoc.terms[b],a)}},cacheTurns:function(a,b){if(0<a.rawFreq){var c=this.currentDoc,d=a.term,e=[];a=a.positions;for(var f=a[a.length-1],g=this.startAngle,h=this.angleIncrement,k,l,m=0,n=0,u=k=0;u<a.length;u++){var w=a[u],p=w/f*b,q=p-k;k=m;l=n;n=this.findEndPoint([m,n],q,g);m=n[0];n=n[1];k=this.getPolygonFromLine([k,
l],[m,n],g,this.LINE_SIZE);e.push({tokenId:w,polygon:k,over:!1});k=p;g+=h}c.terms[d].pos=e;c.terms[d].done=!1}},findEndPoint:function(a,b,c){c=this.degreesToRadians(c);return[a[0]+b*Math.cos(c),a[1]+b*Math.sin(c)]},determineGraphSizeAndPosition:function(){var a=this.findBoundingBoxForGraph(),b=a.maxX-a.minX,c=a.maxY-a.minY,d=Math.min(this.canvas.width/b,this.canvas.height/c);d-=.05;this.offset.x=Math.abs(a.minX*d-(this.canvas.width/2-b*d/2));this.offset.y=Math.abs(a.minY*d-(this.canvas.height/2-c*
d/2));this.MAX_LINE_LENGTH=Math.sqrt(this.canvas.width*this.canvas.width+this.canvas.height*this.canvas.height)*d;this.cacheCurrentDocument()},findBoundingBoxForGraph:function(){var a=null,b=null,c=null,d=null,e;for(e in this.currentDoc.terms)for(var f=this.currentDoc.terms[e].pos,g=0;g<f.length;g++){var h=f[g].polygon;h=this.getBoundingBox(h[0],h[1]);if(null==a||h[0]<a)a=h[0];if(null==b||h[2]>b)b=h[2];if(null==c||h[1]<c)c=h[1];if(null==d||h[3]>d)d=h[3]}return{minX:a,minY:c,maxX:b,maxY:d}},getBoundingBox:function(a,
b){return[Math.min(a[0],a[2]),Math.min(b[0],b[2]),Math.max(a[0],a[2]),Math.max(b[0],b[2])]},degreesToRadians:function(a){return Math.PI/180*a},clickHandler:function(a){var b=a.layerX-this.offset.x;a=a.layerY-this.offset.y;var c=null,d=0,e;for(e in this.currentDoc.terms)if(-1!=this.termsFilter.indexOf(e))for(var f=this.currentDoc.terms[e].pos,g=0;g<f.length;g++){var h=f[g].polygon;if(this.isPointInPolygon(h[0],h[1],b,a)){c=e;d=f[g].tokenId;break}}c&&void 0!==this.externalClickHandler&&this.externalClickHandler({term:c,
tokenId:d})},moveHandler:function(a){var b=a.layerX-this.offset.x,c=a.layerY-this.offset.y;if(null!=this.dragInfo)document.body.style.cursor="move",this.dragInfo.lastX=this.dragInfo.x,this.dragInfo.lastY=this.dragInfo.y,this.dragInfo.x=a.layerX,this.dragInfo.y=a.layerY,b=this.dragInfo.y-this.dragInfo.lastY,this.offset.x+=this.dragInfo.x-this.dragInfo.lastX,this.offset.y+=b;else{this.mouseOver=!1;for(var d in this.currentDoc.terms)if(-1!=this.termsFilter.indexOf(d)){a=this.currentDoc.terms[d].pos;
for(var e=0;e<a.length;e++)if(this.mouseOver)this.currentDoc.terms[d].pos[e].over=!1;else{var f=a[e].polygon;this.isPointInPolygon(f[0],f[1],b,c)?this.mouseOver=this.currentDoc.terms[d].pos[e].over=!0:this.currentDoc.terms[d].pos[e].over=!1}}if(this.mouseOver){if(document.body.style.cursor="pointer",!this.progressiveDraw||this.progressiveDraw&&this.progDrawDone)clearInterval(this.intervalId),this.intervalId=setInterval(this.doDraw.createDelegate(this,[!1]),50)}else if(document.body.style.cursor="auto",
!this.progressiveDraw||this.progressiveDraw&&this.progDrawDone)clearInterval(this.intervalId),this.doDraw(!1)}},mouseDownHandler:function(a){var b=a.layerX;a=a.layerY;this.dragInfo={lastX:b,lastY:a,x:b,y:a}},mouseUpHandler:function(a){this.dragInfo=null},getPolygonFromLine:function(a,b,c,d){var e=c+90,f=c-90;c=this.findEndPoint(a,d,e);a=this.findEndPoint(a,d,f);f=this.findEndPoint(b,d,f);b=this.findEndPoint(b,d,e);return[[c[0],a[0],f[0],b[0]],[c[1],a[1],f[1],b[1]]]},isPointInPolygon:function(a,b,
c,d){var e,f=3,g=!1;for(e=0;4>e;e++)(b[e]<d&&b[f]>=d||b[f]<d&&b[e]>=d)&&a[e]+(d-b[e])/(b[f]-b[e])*(a[f]-a[e])<c&&(g=!g),f=e;return g},clearCanvas:function(){this.canvas.width=this.canvas.width}};function Cirrus(a){function b(h){h="#"==h.charAt(0)?h.substring(1,7):h;var k=[];k.push(parseInt(h.substring(0,2),16));k.push(parseInt(h.substring(2,4),16));k.push(parseInt(h.substring(4,6),16));return k}var c=this;this.config=a;var d=Ext.id(null,"cirrusCanvas");if(null==this.config.containerId)alert("You must provide a valid container ID!");else{var e="#"+this.config.containerId,f=null,g=null;this.clear=function(){this.canvas.width=this.canvas.width};this.addWords=function(h){f.addWords(h)};this.arrangeWords=
function(){f.arrangeWords()};this.clearAll=function(){f.setWords([]);f.grid=[];this.clear()};this.resizeWords=function(){c.setCanvasDimensions();f.resetWordCoordinates();f.calculateSizeAdjustment();f.resizeWords();f.arrangeWords();g=null};this.setCanvasDimensions=function(){var h=$(e)[0],k=Math.max(h.offsetHeight,h.clientHeight);this.canvas.width=Math.max(h.offsetWidth,h.clientWidth);this.canvas.height=k};$(document).ready(function(){if(0==$("#"+c.config.containerId).length)alert("You must provide a valid container ID!");
else{c.canvas=document.createElement("canvas");c.canvas.setAttribute("id",d);c.canvas.setAttribute("tabIndex",1);c.setCanvasDimensions();$(e).append(c.canvas);d="#"+d;c.context=c.canvas.getContext("2d");c.wordData=[];c.useFadeEffect=!0;c.colors=[[116,116,181],[139,163,83],[189,157,60],[171,75,75],[174,61,155]];f=new WordController(c);for(var h in c.config){"words"==h&&(c.wordData=c.config[h]);"layout"==h&&("circle"==c.config[h]?f.layout=f.CIRCLE:"square"==c.config[h]&&(f.layout=f.SQUARE));if("colors"==
h&&$.isArray(c.config[h])&&0<c.config[h].length){c.colors=[];for(var k in c.config[h])c.colors.push(b(c.config[h][k]))}"background"==h&&$(d).css("background-color",c.config[h]);"fade"==h&&("true"==c.config[h]?c.useFadeEffect=!0:"false"==c.config[h]&&(c.useFadeEffect=!1));"smoothness"==h&&(f.wordsToArrange=Math.max(1,Math.min(20,parseInt(c.config[h]))))}0<c.wordData.length&&(c.clear(),f.addWords(c.wordData),f.arrangeWords());$(window).resize(function(){null!=g&&clearTimeout(g);g=setTimeout(c.resizeWords,
1E3)});$(d).keypress(function(l){114==l.which&&f.arrangeWords()});$(d).click(function(l){l=f.handleWordClick(l);void 0!==l&&c.config.clickHandler&&c.config.clickHandler({term:l.text,value:l.value})});$(d).mouseover(function(l){f.startUpdates()});$(d).mouseout(function(l){f.stopUpdates()});$(d).mousemove(function(l){f.handleMouseMove(l)})}})}};function Word(a,b,c,d,e){this.relativeSize=this.rotation=this.width=this.height=0;this.mask=null;this.size=0;this.text=a;this.color=c;this.origSize=b;this.rolloverText=d;this.value=e||0;this.ty=this.tx=this.y=this.x=0;this.fontFamily="Arial";this.fontSize=12;this.alpha=1;this.isOver=this.live=!1;this.draw=function(f){f.save();f.fillStyle="rgba("+this.color[0]+","+this.color[1]+","+this.color[2]+","+this.alpha+")";f.textBaseline="alphabetic";f.font=this.fontSize+"px "+this.fontFamily;f.translate(this.x+
this.tx,this.y+this.ty);f.rotate(this.rotation);f.fillText(this.text,0,0);f.restore()}};function WordController(a){function b(r){for(var v=Math.log(10*r.relativeSize)*Math.LOG10E,x=(v+r.relativeSize)/2,z=0,L=0;L<r.text.length;L++){var H=r.text.charAt(L);z="f"==H||"i"==H||"j"==H||"l"==H||"r"==H||"t"==H?z+v/3:"m"==H||"w"==H?z+v/(4/3):z+v/1.9}return x*z}function c(){p.sort(function(r,v){return r.origSize>v.origSize?-1:r.origSize<v.origSize?1:0})}function d(){for(var r=0;r<p.length;r++){var v=p[r];var x=v;var z=f.sizeAdjustment;z*=b(x);x=(Math.sqrt(6)*Math.sqrt(6*Math.pow(x.text.length,
2)+z*x.text.length)-6*x.text.length)/(2*x.text.length);v.fontSize=x>f.minFontSize?x:f.minFontSize;v.fontFamily="Impact";x=v;g.context.save();g.context.textBaseline="alphabetic";g.context.font=x.fontSize+"px "+x.fontFamily;x.width=g.context.measureText(x.text).width;x.height=Math.ceil(1.15*g.context.measureText("m").width);g.context.restore();v.tx=0;v.ty=v.height;x=0;f.getWordOrientation()===f.MIXED&&null==v.text.match(/\s/)&&.66<Math.random()&&(x=v.height,v.height=v.width,v.width=x,0==Math.round(Math.random())?
(x=90,v.ty=0):(x=-90,v.ty=v.height,v.tx=v.width));v.size=Math.max(v.height,v.width);v.rotation=Math.PI/180*x;g.context.fillStyle=g.canvas.style.backgroundColor;g.context.fillRect(0,0,g.canvas.width,g.canvas.height);v.draw(g.context);x=g.context.getImageData(v.x,v.y,v.width,v.height);z=[];for(var L=0;L<v.width;L++){var H=Math.floor(L/f.COARSENESS)*f.COARSENESS;null==z[H]&&(z[H]={});for(var F=0;F<v.height;F++){var I=Math.floor(F/f.COARSENESS)*f.COARSENESS;var E=4*(L+F*x.width);E=[x.data[E],x.data[E+
1],x.data[E+2],x.data[E+3]];"rgb("+E[0]+", "+E[1]+", "+E[2]+")"!=g.canvas.style.backgroundColor&&(z[H][I]=!0);z[H][I]&&(F=I+f.COARSENESS)}}v.mask=z}}function e(){g.clear();for(var r=p.length;r--;){var v=p[r];v.alpha=1;v.live&&v.draw(g.context)}r=$(g.canvas);if(null!=n){r.css("cursor","pointer");g.context.save();g.context.textBaseline="alphabetic";g.context.font="12px Arial";v=g.context.measureText(n.text).width;var x=g.context.measureText(n.value).width;v=(v>x?v:x)+20;x=u+15;var z=w+25,L=r.width();
r=r.height();x+v>=L&&(x-=v);z+40>=r&&(z-=40);g.context.fillStyle="rgba(255,255,255,0.9)";g.context.strokeStyle="rgba(100,100,100,0.9)";g.context.translate(x,z);g.context.fillRect(0,0,v,40);g.context.strokeRect(0,0,v,40);g.context.fillStyle="rgba(0,0,0,0.9)";g.context.fillText(n.text+":",8,18);g.context.fillText(n.value,8,30);g.context.restore()}else r.css("cursor","default")}var f=this,g=a;this.CIRCLE=0;this.ratio=1;var h=this.CIRCLE;this.getLayout=function(){return h};this.setLayout=function(r){h=
r};this.HORIZONTAL=0;var k=this.MIXED=1;this.getWordOrientation=function(){return k};this.setWordOrientation=function(r){k=r};this.UPDATE_RATE=25;this.COARSENESS=5;this.grid=[];var l=0,m;this.doingArrange=!1;this.wordsToArrange=5;var n=null,u=0,w=0,p=[];this.getWords=function(){return p};this.setWords=function(r){p=r};this.sizeAdjustment=100;this.minFontSize=12;this.largestWordSize=0;this.smallestWordSize=1E4;var q={};this.addWords=function(r){for(var v=!1,x=0;x<r.length;x++){var z=r[x];var L=null==
z.color||""==z.color?g.colors[Math.floor(Math.random()*g.colors.length)]:z.color;var H=null==z.size||""==z.size?Math.floor(40*Math.random()):parseFloat(z.size);var F=z.word,I=z.label,E=z.value;z=!1;null==q[F]&&(q[F]=!0,H>f.largestWordSize&&(f.largestWordSize=H,z=!0),H<f.smallestWordSize&&(f.smallestWordSize=.8*H,z=!0),F=new Word(F,H,L,I,E),p.push(F));v=z||v}c();this.setRelativeSizes();this.calculateSizeAdjustment();v?this.resizeWords():d()};this.resetWordCoordinates=function(){g.clear();clearTimeout(m);
for(var r=0;r<p.length;r++){var v=p[r];v.x=0;v.y=0;v.tx=0;v.ty=0}};this.calculateSizeAdjustment=function(){this.ratio=g.canvas.width/g.canvas.height;var r=g.canvas.width*g.canvas.height;this.minFontSize=1E5>r?8:12;for(var v=0,x=0;x<p.length;x++){var z=b(p[x]);v+=z}this.sizeAdjustment=r/v};this.setRelativeSizes=function(){for(var r=0;r<p.length;r++){var v=p[r],x=this.smallestWordSize;v.relativeSize=.1+(v.origSize-x)/(this.largestWordSize-x)*.9}};this.resizeWords=function(){g.clear();d();c()};this.arrangeWords=
function(){clearTimeout(m);g.clear();this.toggleLoadingText();if(0<p.length){var r=function(H,F,I){for(var E=0;E<I.width;E+=this.COARSENESS)for(var D=0;D<I.height;D+=this.COARSENESS)I.mask[E]&&I.mask[E][D]&&(this.grid[E+H]||(this.grid[E+H]=[]),this.grid[E+H][D+F]=I)},v=function(H){H.alpha+=.25;H.draw(g.context)},x=function(H,F,I,E){r(H,F,I);I.x=H;I.y=F;I.live=!0;E&&I.draw(g.context)},z=function(H,F,I,E,D){for(var J=0;J<=E;J+=this.COARSENESS)for(var N=0;N<=I;N+=this.COARSENESS)if(D[J]&&D[J][N]&&null!=
this.grid[J+H]&&null!=this.grid[J+H][N+F])return!0;return!1},L=function(){var H=this.wordsToArrange-1,F=g.canvas.width,I=g.canvas.height,E=.5*F,D=.5*I;do{var J=p[l];if(void 0!==J){for(var N=Math.random()*Math.PI,B=.25*Math.random()*J.size,O=.5*(Math.random()-.5),M=.5*J.width,A=.5*J.height;;){var G=Math.floor((E+Math.cos(N)*B*this.ratio-M)/this.COARSENESS)*this.COARSENESS;var K=Math.floor((D+Math.sin(N)*B-A)/this.COARSENESS)*this.COARSENESS;var P=G+M>=F||K+A>=I?!0:z(G,K,J.height,J.width,J.mask);if(!P)break;
N+=O;B+=.05}x(G,K,J);if(g.useFadeEffect)for(G=J.alpha=0;G<l;G++)K=p[G],1>K.alpha&&v(K);else J.alpha=1,J.draw(g.context)}l++;if(l>=p.length){clearTimeout(m);this.doingArrange=!1;this.toggleLoadingText(!1);e();break}}while(H--)};this.grid=[];l=0;L=L.createDelegate(this);z=z.createDelegate(this);x=x.createDelegate(this);v=v.createDelegate(this);r=r.createDelegate(this);this.doingArrange=!0;m=setInterval(L,50)}else alert("Error: There are no words to arrange.")};this.toggleLoadingText=function(r){g.context.save();
g.context.fillStyle=r?"black":g.canvas.style.backgroundColor;g.context.textBaseline="top";g.context.font="10px Arial";r=g.context.measureText("Loading").width+10;g.context.fillText("Loading",g.canvas.width-r,10);g.context.restore()};this.startUpdates=function(){m=setInterval(e,f.UPDATE_RATE)};this.stopUpdates=function(){null!=n&&(n=null,e());clearTimeout(m)};this.handleMouseMove=function(r){if(!this.doingArrange){for(var v=p.length;v--;)p[v].isOver=!1;var x=$(g.canvas).offset(),z=(r.pageX-x.left)%
this.COARSENESS;v=r.pageX-x.left-z;z=(r.pageY-x.top)%this.COARSENESS;r=r.pageY-x.top-z;n=this.findWordByCoords(v,r);null!=n&&(n.isOver=!0,u=v,w=r)}};this.handleWordClick=function(r){var v=$(g.canvas).offset(),x=(r.pageX-v.left)%this.COARSENESS,z=r.pageX-v.left-x;x=(r.pageY-v.top)%this.COARSENESS;r=this.findWordByCoords(z,r.pageY-v.top-x);if(null!=r)return{text:r.text,value:r.value}};this.findWordByCoords=function(r,v){var x=null;null!=this.grid[r]&&(null!=this.grid[r][v]?x=this.grid[r][v]:null!=this.grid[r][v+
this.COARSENESS]&&(x=this.grid[r][v+this.COARSENESS]));null==x&&null!=this.grid[r+this.COARSENESS]&&(null!=this.grid[r+this.COARSENESS][v]?x=this.grid[r+this.COARSENESS][v]:null!=this.grid[r+this.COARSENESS][v+this.COARSENESS]&&(x=this.grid[r+this.COARSENESS][v+this.COARSENESS]));return x}}
Function.prototype.createDelegate=function(a,b,c){var d=this;return function(){var e=b||arguments;if(!0===c)e=Array.prototype.slice.call(arguments,0),e=e.concat(b);else if("number"==typeof c){e=Array.prototype.slice.call(arguments,0);var f=[c,0].concat(b);Array.prototype.splice.apply(e,f)}return d.apply(a||window,e)}};var doubletree={};
(function(){function a(e,f,g){if(e.children){g&&(e.info.origIDs?(e.info.ids={},c(e.info.ids,e.info.origIDs),e.info.count=Object.keys(e.info.ids).length):(e.info.origIDs={},c(e.info.origIDs,e.info.ids),e.info.origCount=Object.keys(e.info.origIDs).length));var h=Object.keys(f);g=0;for(var k=h.length;g<k;g++)delete e.info.ids[h[g]];e.info.count=Object.keys(e.info.ids).length;k=e.children.length;for(g=0;g<k;g++)h=e.children[g],b(h.info.ids,f)?e.children[g]=null:a(h,f,!1);e.children=e.children.filter(function(l){return null!=
l});e.info.continuations=e.children.length;f=d3.max(e.children.map(function(l){return l.maxChildren}));e.maxChildren=Math.max(e.children.length,f)}}function b(e,f){if(!e||!f)return!1;for(var g in e)if(!(g in f))return!1;return!0}function c(e,f){for(var g in f)e[g]=f[g]}function d(){}doubletree.DoubleTree=function(){function e(B){B.each(function(O,M){f.push(this.node())})}var f=[],g=600,h=400,k=!1,l={left:[],right:[]},m={alt:d,shift:d,click:d},n=!0,u=!0,w=doubletree.sortByStrFld("token"),p=doubletree.tokenText,
q=function(B){return doubletree.fieldText(B,"POS")},r=function(B){return"rgba(255,255,255,1)"},v=function(B){return"rgba(255,255,255,1)"},x=function(B){return"red"},z={node:{fill:"white",stroke:"steelblue","stroke-width":"1.5px"},branch:{stroke:"#aaa","stroke-width":"1.5px"}},L=!1,H=d3.dispatch("idsUpdated");H.on("idsUpdated",function(){this==E?(D.setIds(E.continuationIDs),D.updateContinuations()):this==D&&(E.setIds(D.continuationIDs),E.updateContinuations())});var F,I,E,D,J,N;e.init=function(B){d3.select(d3.selectAll(B)).call(this);
return e};e.redraw=function(){void 0!==F&&void 0!==I&&e.setupFromTries(F,I);return e};e.setupFromTries=function(B,O){F=B.getUniqRoot();I=O.getUniqRoot();var M=F.toTree(l.left),A=I.toTree(l.right);B=!0;0<Object.keys(A.pruned).length&&(a(A,A.pruned,B),a(M,A.pruned,B),B=!1);0<Object.keys(M.pruned).length&&(a(M,M.pruned,B),a(A,M.pruned,B));B={};for(var G in A.info)"continuations"!=G&&"ids"!=G&&"count"!=G&&(B[G]=A.info[G]);B["right continuations"]=A.info.continuations;B["left continuations"]=M.info.continuations;
B.ids={};c(B.ids,A.info.ids);c(B.ids,M.info.ids);B.count=Object.keys(B.ids).length;J=Object.keys(B.ids);if(A.info.origIDs||M.info.origIDs)B.origIDs={},c(B.origIDs,A.info.origIDs),c(B.origIDs,M.info.origIDs),B.origCount=Object.keys(B.origIDs).length;A.info=B;M.info=B;G=Math.max(M.maxChildren,A.maxChildren);if(isNaN(G)||0==G)return L=!1,e;u?N=d3.scaleLog().range([8,14]):(N=function(){return 14},N.domain=function(){});N.domain([Math.min(M.minCount,A.minCount),M.info.count]);var K=g-20-20,P=h-20-20;f.forEach(function(Q,
C){C=d3.select(Q).select("svg");null==C.node()?(C=d3.select(Q).append("svg").attr("width",K+20+20).attr("height",P+20+20).attr("cursor","move").call(d3.zoom().scaleExtent([1,1]).on("zoom",function(){var R=d3.event.transform.x+K/2,S=d3.event.transform.y+P/2;d3.select(Q).select("svg \x3e g").attr("transform","translate("+R+","+S+")")})),C.append("g").attr("transform","translate("+K/2+","+P/2+")")):(C.attr("width",K+20+20).attr("height",P+20+20),C.selectAll("g *").remove());E=new doubletree.Tree(C.select("g"),
g,h,M,!0,w,H,N,n,p,q,r,v,x,z);D=new doubletree.Tree(C.select("g"),g,h,A,!1,w,H,N,n,p,q,r,v,x,z)});E.handleAltPress=m.alt;D.handleAltPress=m.alt;E.handleShiftPress=m.shift;D.handleShiftPress=m.shift;E.handleClick=m.click;D.handleClick=m.click;L=!0;return e};e.setupFromArrays=function(B,O,M,A,G,K,P,Q){void 0==G&&F&&(G=F.caseSensitive());void 0==K&&F&&(K=F.fieldNames());void 0==P&&F&&(P=F.fieldDelim());void 0==Q&&F&&(Q=F.distinguishingFieldsArray());F=new doubletree.Trie(G,K,P,Q);I=new doubletree.Trie(G,
K,P,Q);G=O.length;for(K=0;K<G;K++){P=A?A[K]:K;Q=O[K];var C=B[K].slice(),R=M[K].slice();C.push(Q);C.reverse();R.unshift(Q);k?(I.addNgram(C,P),F.addNgram(R,P)):(F.addNgram(C,P),I.addNgram(R,P))}e.setupFromTries(F,I);return e};e.filteredIDs=function(){return J};e.search=function(B){E.search(B);D.search(B);B=d3.select(f[0]);var O=B.selectAll("text.foundText");if(O.empty())return 0;O=O[0].length;null!=B.selectAll("text.rtNdText.foundText").node()&&O--;return O};e.clearSearch=function(){E.clearSearch();
D.clearSearch();return e};e.updateTokenExtras=function(){E.showTokenExtras(n);D.showTokenExtras(n);var B=d3.select(f[0]).select('.tokenExtra[display\x3d"inline"]');B.empty()||"0px"==B.style("height")&&e.redraw();return e};e.visWidth=function(B){if(!arguments.length)return g;g=B;return e};e.visHeight=function(B){if(!arguments.length)return h;h=B;return e};e.prefixesOnRight=function(B){if(!arguments.length)return k;k=B;return e};e.filters=function(B){if(!arguments.length)return l;l=B;return e};e.handlers=
function(B){if(!arguments.length)return m;m=B;return e};e.showTokenExtra=function(B){if(!arguments.length)return n;n=B;return e};e.scaleLabels=function(B){if(!arguments.length)return u;u=B;return e};e.succeeded=function(){return L};e.sortFun=function(B){if(!arguments.length)return w;w=B;return e};e.nodeText=function(B){if(!arguments.length)return p;p=B;return e};e.tokenExtraText=function(B){if(!arguments.length)return q;q=B;return e};e.rectColor=function(B){if(!arguments.length)return r;r=B;return e};
e.rectBorderColor=function(B){if(!arguments.length)return v;v=B;return e};e.continuationColor=function(B){if(!arguments.length)return x;x=B;return e};e.basicStyles=function(B){if(!arguments.length)return z;Object.keys(z).forEach(function(O){O in B&&Object.keys(z[O]).forEach(function(M){M in B[O]&&(z[O][M]=B[O][M])})});return e};return e};doubletree.Tree=function(e,f,g,h,k,l,m,n,u,w,p,q,r,v,x){function z(A){A.children&&(A._children=A.children,A._children.forEach(z),A.children=null)}function L(A){A.parent&&
A.parent.children.forEach(function(G){G!=A&&z(G)})}function H(A,G){d3.event.altKey?M.handleAltPress(A,G):d3.event.shiftKey?M.handleShiftPress(A,G):(M.handleClick(A,G),A.parent&&(M.continuationIDs!=A.data.info.ids&&(M.setIds(A.data.info.ids),M.clickedNode=A.id,m.call("idsUpdated",M)),L(A),F(A,!0)))}function F(A,G){A.children?(A.children&&1==A.children.length&&F(A.children[0],!0),A._children=A.children,A.children=null):(A.children=A._children,A._children=null,A.children&&1==A.children.length&&F(A.children[0],
!1));G&&M.update(A)}function I(A){return k?-A:A}var E=u,D=q;f=f-20-20;g=g-20-20;var J=0,N;l||(l=doubletree.sortByStrFld("token"));J=0;var B=d3.tree().size([g,f]).nodeSize([40,40]),O=d3.linkHorizontal().x(function(A){return I(A.y)}).y(function(A){return A.x});e=e.append("g").attr("transform","translate(20,20)");this.readJSONTree=function(A){N=d3.hierarchy(A);N.x0=0;N.y0=0;N.children.forEach(z);this.update(N)};this.update=function(A){var G=B(N).descendants();G.forEach(function(C){var R=C.textSize;if(void 0==
R){R=0;for(var S=C.parent;null!=S;){var T=Ext.draw.TextMeasurer.measureText(S.data.name,"arial").width;R+=T;S=S.parent}C.textSize=R}C.y=25*C.depth+R});var K=e.selectAll("g.node_"+k).data(G,function(C){return C.id||(C.id=++J)}),P=K.enter().append("g").attr("class","node node_"+k).attr("cursor","pointer").attr("transform",function(C){return"translate("+I(A.y0)+","+A.x0+")"}).on("click",H);P.append("title").text(function(C){return doubletree.infoToText(C.data.info)});P.append("circle").attr("r",1E-6).style("fill",
function(C){return C._children?"#fff":x.node.fill}).style("stroke",function(C){return x.node.stroke});var Q=P.append("text").attr("class",function(C){return 0==C.depth?"rtNdText":""}).attr("x",function(C){return C.children||C._children?0:k?10:-10}).attr("text-anchor",function(C){return C.parent?C.children||C._children?k?"end":"start":k?"start":"end":"middle"}).style("font-size",function(C){return n(C.data.info.count)+"pt"});Q.append("tspan").attr("dy",".35em").attr("class","tokenText").text(function(C){return w(C.data.info,
1>C.depth)}).style("fill-opacity",1E-6);Q.append("tspan").attr("dx",".35em").attr("class","tokenExtra").text(function(C){return p(C.data.info,1>C.depth)}).style("fill-opacity",1E-6);this.drawRects();P=P.merge(K);P.transition().duration(200).attr("transform",function(C){return"translate("+I(C.y)+","+C.x+")"});P.select("circle").attr("r",function(C){return C.children||C._children?1E-6:4.5}).style("fill",function(C){return C._children?"#fff":x.node.fill}).style("stroke-width",x.node["stroke-width"]);
P.selectAll("tspan").style("fill-opacity",1);K=K.exit().transition().duration(200).attr("transform",function(C){return"translate("+I(A.y)+","+A.x+")"}).remove();K.select("circle").attr("r",1E-6);K.selectAll("tspan").style("fill-opacity",1E-6);K=e.selectAll("path.link_"+k).data(N.links(),function(C){return C.source.id+"-"+C.target.id});K.enter().insert("path","g").attr("class","link link_"+k).attr("d",function(C){C={x:A.x0,y:A.y0};return O({source:C,target:C})}).style("fill","none").style("stroke",
x.branch.stroke).style("stroke-width",x.branch["stroke-width"]).merge(K).transition().duration(200).attr("d",O);K.exit().transition().duration(200).attr("d",function(C){C={x:A.x0,y:A.y0};return O({source:C,target:C})}).remove();G.forEach(function(C){C.x0=C.x;C.y0=C.y});this.updateContinuations()};this.drawRects=function(){var A=E?"inline":"none";e.selectAll(".tokenExtra").attr("display",A);A=e.selectAll("g.node_"+k);A.selectAll("rect").remove();A.insert("rect","text").attr("class","nodeRect").attr("height",
function(){var G=this.parentElement.getBBox().height;6>G&&(G=6.1);return G-6}).attr("y",function(G){return G.parent?-.5*this.parentElement.getBBox().height/2:-.5*this.parentElement.getBBox().height/2-2}).attr("width",function(){return this.parentElement.getBBox().width}).attr("x",function(G){var K=this.parentElement.getBBox().width;return G.parent?k?-.5*K:0:-.33333*K}).style("stroke-opacity",1).style("stroke-width",1).style("stroke",function(G){return r(G.data.info)}).style("fill",function(G){return D(G.data.info)}).style("fill-opacity",
function(G){return 1})};var M=this;this.setIds=function(A){M.continuationIDs=A};this.updateContinuations=function(){e.selectAll("g.node_"+k+" text").classed("continuation",function(A){a:{var G=M.continuationIDs||{},K;for(K in A.data.info.ids)if(K in G){A=!0;break a}A=!1}return A}).style("fill",function(A){return d3.select(this).classed("continuation")?v(A.data.info):"#444"})};this.search=function(A){e.selectAll("g.node text").classed("foundText",function(G){return A.test(w(G.data.info))})};this.clearSearch=
function(){e.selectAll("g.node text").classed("foundText",!1)};this.showTokenExtras=function(A){if(0==arguments.length)return E;E=A;this.drawRects();return this};this.setRectColor=function(A){if(0==arguments.length)return D;D=A;this.drawRects();return this};this.handleAltPress=function(){};this.handleShifttPress=function(){};this.handleClick=function(){};this.readJSONTree(h);return this};doubletree.sortByStrFld=function(e){return function(f,g){var h=void 0==f.data.info[e],k=void 0==g.data.info[e];
if(h&&k)return 0;if(h)return-1;if(k)return 1;f=f.data.info[e].join(" ").toLowerCase();g=g.data.info[e].join(" ").toLowerCase();return f<g?-1:f>g?1:0}};doubletree.sortByCount=function(){return function(e,f){return f.data.info.count-e.data.info.count}};doubletree.sortByContinuations=function(){return function(e,f){return f.data.info.continuations-e.data.info.continuations}};doubletree.filterByMinCount=function(e){return function(f){return f.count>=e}};doubletree.filterByMaxCount=function(e){return function(f){return f.count<=
e}};doubletree.filterByPOS=function(e){var f=new RegExp(e);return function(g){return g.POS&&0<g.POS.filter(function(h){return-1<h.search(f)}).length}};doubletree.fieldText=function(e,f){return e[f]};doubletree.tokenText=function(e){var f="";void 0!==e.token&&(f=e.token);return f};doubletree.infoToText=function(e){var f="",g;for(g in e)f="ids"==g||"origIDs"==g?f+(g+"\t:\t"+Object.keys(e[g]).join(",")+"\n"):f+(g+"\t:\t"+e[g]+"\n");return f}})();doubletree=doubletree||{};
(function(){doubletree.Trie=function(a,b,c,d,e){function f(q,r,v){this.id=r;this.count=v;this.info={count:v,ids:{}};if(null==q)this.item=k;else{this.item=q;this.info.ids={};this.info.ids[r]=!0;q=q.split(n);for(var x in q)this.info[m[x]]=[q[x]]}this.nodes={};this.addNgram=function(z,L,H){H||(H=1);if(0<z.length){var F=z.shift();var I=F.split(n);var E=w&&this.item==k?"":I.filter(function(N,B){return-1<u.indexOf(m[B])}).map(function(N){return l?N.toLocaleLowerCase():N}).join(n)}else E=F=h;if(E in this.nodes&&
this.nodes[E]instanceof f){var D=this.nodes[E];D.info.count+=H;D.info.ids[L]=!0;for(var J in I)E=I[J],-1==D.info[m[J]].indexOf(E)&&D.info[m[J]].push(E)}else D=new f(F,L,H),this.nodes[E]=D;F!=h&&D.addNgram(z,L,H)};this.getUniqRoot=function(){if(this.item==k){var z=Object.keys(this.nodes);if(1==z.length)return this.nodes[z[0]]}return this};this.toTree=function(z){function L(F,I,E){var D={children:[]};D.name=E.item;D.info={};for(var J in E.info)if("Object"===typeof E.info[J]){D.info[J]={};for(var N in E.info[J])D.info[J][N]=
this.info[J][N]}else D.info[J]=E.info[J];D.pruned={};for(var B in E.nodes)J=E.nodes[B],N=F[I],!N||N&&N(J.info)?(D.children.push(L(F,I+1,J)),J.pruned!={}&&g(D.pruned,J.pruned)):g(D.pruned,J.info.ids);D.info.continuations=D.children.length;0==D.children.length?(D.children=null,D.maxChildren=0,D.maxLen=D.name?D.name.length:0,D.minCount=D.info.count):(F=d3.max(D.children.map(function(O){return O.maxChildren})),D.maxChildren=Math.max(D.children.length,F),F=d3.max(D.children.map(function(O){return O.maxLen})),
D.maxLen=Math.max(F,D.name.length),D.minCount=d3.min(D.children.map(function(O){return O.minCount})));return D}z||(z=[]);var H=JSON.parse(JSON.stringify(this));return L(z,0,H)}}function g(q,r){for(var v in r)q[v]=r[v]}var h=" ",k="_root_",l=!a&&!0;b||(b=["item"]);var m=b;n||(n="\t");var n=c;u||(u=[m[0]]);var u=d,w=e;void 0==w&&(w=!0);var p=new f(k,-1,0);this.addNgram=function(q,r,v){p.addNgram(q,r,v)};this.getUniqRoot=function(){var q=new doubletree.Trie(!l,m,n,u);q.trie(p.getUniqRoot());return q};
this.toTree=function(q,r){return p.toTree(q,r)};this.serialize=function(){return JSON.stringify(this)};this.deserialize=function(q){q=JSON.parse(q);h=q.endNG();k=q.rootName();l=q.caseSensitive();m=q.fieldNames();n=q.fieldDelim();u=q.distinguishingFieldsArray();p=q.trie()};this.endNG=function(){return h};this.rootName=function(){return k};this.trie=function(q){0<arguments.length&&(p=q);return p};this.caseSensitive=function(){return!l};this.fieldNames=function(){return m};this.fieldDelim=function(){return n};
this.distinguishingFieldsArray=function(){return u}}})();function TermsRadio(a){this.parent=a.parent;this.container=a.container;this.isSliderVisible=void 0==a.showSlider?!0:a.showSlider;this.chart=null;this.absMinFreq=this.absMaxFreq=0;this.allData=[];this.continueTransition=!0;this.counterSeries=[];this.displayData=[];this.isTransitioning=this.dragged=!1;this.lastSticky=this.lastSlippery=null;this.maxFont=30;this.numDataPoints=this.minFreq=0;this.numVisPoints=5;this.overlayQueue=[];this.recordsLength=this.records=0;this.reselectTop=!1;this.sliderDragSum=
this.shiftCount=0;this.titlesArray=[];this.transitionCall="draw";this.valFraction=1;this.win=0;this.bPadding=25;this.lPadding=40;this.rPadding=20;this.tPadding=10;this.sliderHeightRatio=.1;this.sliderHeight=0;this.sliderBPadding=10;this.largestH=this.largestW=0;this.xAxisEl=void 0;this.xAxis=d3.axisBottom();this.xScale=d3.scaleLinear();this.xSliderScale=d3.scaleLinear();this.yAxisEl=void 0;this.yAxis=d3.axisLeft();this.yScale=d3.scaleLinear();this.ySliderScale=d3.scaleLinear();this.fontScale=d3.scaleLinear();
this.opacityScale=d3.scaleLinear();this.container.on("resize",this.doResize,this)}
TermsRadio.prototype={constructor:TermsRadio,loadRecords:function(a){if(0<a.length)for(this.initData(a),this.prepareData(),a=this.shiftCount;0<a--;)this.displayData.shift();null!=this.chart?this.redraw():this.initializeChart()},highlightQuery:function(a,b){var c=null;"document"===this.parent.getApiParam("mode")&&(c=this.parent.getCorpus().getDocument(0).getId());a=this.buildParamsBundle({wordString:a,docId:c});b?this.manageOverlaySticky(a):this.manageOverlaySlippery(a)},highlightRecord:function(a,
b){a={wordString:a.get("term"),docId:a.get("docId")};a=this.buildParamsBundle(a);b?this.manageOverlaySticky(a):this.manageOverlaySlippery(a)},initData:function(a){this.records=a;this.recordsLength=this.records.length;this.numVisPoints=parseInt(this.parent.getApiParam("visibleBins"));this.shiftCount=parseInt(this.parent.getApiParam("position"));"document"===this.parent.getApiParam("mode")?(this.numDataPoints=this.records[0].get("distributions").length,a=parseInt(this.parent.getApiParam("bins")),this.numDataPoints!==
a&&(this.numDataPoints=a,this.loadStore())):this.numDataPoints=this.records[0].get("distributions").length;this.counterSeries=[];a=[];for(var b=this.absMaxFreq=0;b<this.numDataPoints;b++)for(var c=0;c<this.recordsLength;c++)this.records[c].get("distributions")[b]>this.absMaxFreq&&(this.absMaxFreq=this.records[c].get("distributions")[b]);this.absMinFreq=this.absMaxFreq;for(b=0;b<this.numDataPoints;b++)for(c=0;c<this.recordsLength;c++)this.records[c].get("distributions")[b]<=this.absMinFreq&&0!==this.records[c].get("distributions")[b]&&
(this.absMinFreq=this.records[c].get("distributions")[b]);0>this.absMinFreq&&(this.absMinFreq=0);this.minFreq=1.01*this.absMinFreq;for(b=0;b<this.numDataPoints;b++){for(c=0;c<this.recordsLength;c++){var d=this.records[c],e=d.get("distributions")[b];0<e&&a.push({freq:e,wordString:d.get("term"),counter:b,posInSeries:0,numInSeries:0,docId:d.get("docId")})}this.counterSeries.push(a);a=[]}},prepareData:function(){var a=[],b=[],c=[],d=[];this.allData=[];this.displayData=[];this.numDataPoints<this.numVisPoints&&
(this.numVisPoints=this.numDataPoints);this.shiftCount+this.numVisPoints>this.numDataPoints&&(this.shiftCount=this.numDataPoints-this.numVisPoints);for(var e=0;e<this.numDataPoints;e++){for(var f=0,g=0;g<this.counterSeries[e].length;g++){var h=0;0===f&&(b.push(this.counterSeries[e][g]),c.push({freq:this.counterSeries[e][g].freq,frequencyArray:b,numInSeries:0}),a.push(c),b=[],c=[],h=f=1);for(var k=0;k<a[e].length&&0===h;k++)this.counterSeries[e][g].freq===a[e][k].freq&&(h=a[e][k].numInSeries,this.counterSeries[e][g].posInSeries=
++h,a[e][k].numInSeries=h,a[e][k].frequencyArray.push(this.counterSeries[e][g]),h=1);0===h&&(d.push(this.counterSeries[e][g]),a[e].push({freq:this.counterSeries[e][g].freq,frequencyArray:d,numInSeries:0}),d=[])}(1>this.counterSeries[e].length||0===f)&&a.push([])}for(e=0;e<this.numDataPoints;e++)for(g=0;g<a[e].length;g++)for(++a[e][g].numInSeries,k=0;k<a[e][g].frequencyArray.length;k++)a[e][g].frequencyArray[k].numInSeries=a[e][g].numInSeries;for(e=0;e<this.numDataPoints;e++)this.allData.push({allDataInternal:a[e],
outerCounter:e});a=[];b=[];for(e=0;e<this.numVisPoints+this.shiftCount;e++){for(g=0;g<this.recordsLength;g++)this.allData[e].allDataInternal[g]&&b.push({freq:this.allData[e].allDataInternal[g].freq,inSeries:this.allData[e].allDataInternal[g].numInSeries,frequencyArray:this.allData[e].allDataInternal[g].frequencyArray,dotObject:[{counter:e,freq:this.allData[e].allDataInternal[g].freq}]});a.push(b);b=[]}for(e=0;e<this.numVisPoints+this.shiftCount;e++)this.displayData.push({displayInternal:a[e],outerCounter:e})},
manageMvtButtons:function(){this.parent.queryById("play").setPlaying(this.isTransitioning)},nextR:function(){for(var a=[],b=0;b<this.recordsLength;b++)this.allData[this.numVisPoints+this.shiftCount].allDataInternal[b]&&a.push({freq:this.allData[this.numVisPoints+this.shiftCount].allDataInternal[b].freq,inSeries:this.allData[this.numVisPoints+this.shiftCount].allDataInternal[b].numInSeries,frequencyArray:this.allData[this.numVisPoints+this.shiftCount].allDataInternal[b].frequencyArray,dotObject:[{counter:this.numVisPoints+
this.shiftCount,freq:this.allData[this.numVisPoints+this.shiftCount].allDataInternal[b].freq}]});this.displayData.push({displayInternal:a,outerCounter:this.numVisPoints+this.shiftCount})},toggleRightCheck:function(){this.numVisPoints+this.shiftCount<this.numDataPoints?(this.continueTransition=this.isTransitioning=!0,this.manageMvtButtons(),this.nextR(),this.shiftCount=++this.shiftCount,this.manageXScale(),this.parent.setApiParams({position:this.shiftCount}),this.transitionCall="right",this.animateVis(),
this.displayData.shift()):(this.continueTransition=this.isTransitioning=!1,this.manageMvtButtons())},nextL:function(){for(var a=[],b=0;b<this.recordsLength;b++)this.allData[this.shiftCount].allDataInternal[b]&&a.push({freq:this.allData[this.shiftCount].allDataInternal[b].freq,inSeries:this.allData[this.shiftCount].allDataInternal[b].numInSeries,frequencyArray:this.allData[this.shiftCount].allDataInternal[b].frequencyArray,dotObject:[{counter:this.shiftCount,freq:this.allData[this.shiftCount].allDataInternal[b].freq}]});
this.displayData.unshift({displayInternal:a,outerCounter:this.shiftCount})},startScroll:function(){var a=this;a.numDataPoints>a.numVisPoints&&0===a.shiftCount&&(a.isTransitioning=!0,this.manageMvtButtons(),setTimeout(function(){a.toggleRightCheck()},3E3))},initializeChart:function(){this.initChart();this.drawXAxis();this.drawYAxis();this.drawChart();this.isSliderVisible&&(this.drawSlider(),this.drawVerticalSlider(),this.redrawSliderOverlay());this.transitionCall="draw"},redraw:function(){this.transitionCall=
"redraw";this.updateFullPath();this.redrawXAxis();this.redrawYAxis();this.redrawChart();this.isSliderVisible&&(this.redrawSlider(),this.redrawVerticalSlider(),this.redrawSliderOverlay());this.redrawChartOverlay()},initChart:function(){var a=this.container.getHeight(),b=this.container.getWidth(),c=Ext.DomHelper.append(this.container.down("div[class$\x3dinnerCt]"),'\x3csvg class\x3d"chart" width\x3d"'+b+'" height\x3d"'+a+'"\x3e\x3c/svg\x3e');this.chart=d3.select(c);this.setSliderHeight();this.largestW=
b;this.largestH=a-this.getSliderHeight();a=this.tPadding+this.getSliderHeight();this.chart.append("clipPath").attr("id","clip1").append("rect").attr("class","clipping-rectangle").attr("x",0).attr("y",a).attr("width",b).attr("height",this.largestH);this.chart.append("g").attr("class","overlay").attr("clip-path","url(#clip1)");this.setTitleLength()},doResize:function(){if(this.chart){var a=this.container.getHeight(),b=this.container.getWidth();this.setSliderHeight();this.largestH=a-this.getSliderHeight();
this.largestW=b;this.chart.attr("height",a).attr("width",b);this.setTitleLength();this.chart.select("rect[class\x3dclipping-rectangle]").attr("x",0).attr("y",this.tPadding+this.getSliderHeight()).attr("width",b).attr("height",this.largestH);this.redraw()}},drawXAxis:function(){var a=this,b=this.container.getHeight();this.container.getWidth();this.manageAllXScales();this.xAxis=d3.axisBottom(a.xScale).ticks(Math.round(a.numVisPoints)).tickFormat(function(c){var d;"document"===a.parent.getApiParam("mode")&&
(d="Segment "+(parseInt(c)+1));"corpus"===a.parent.getApiParam("mode")&&(d=c+1+". "+a.titlesArray[c]);return d});this.xAxisEl=this.chart.append("g").attr("class","axisX").attr("transform","translate(0,"+(b-this.bPadding)+")").call(this.xAxis);this.styleXAxis()},styleXAxis:function(){this.xAxisEl.selectAll("text").style("font-family","sans-serif").style("font-size","11px");this.xAxisEl.selectAll("line").style("fill","none").style("stroke","black").style("shape-rendering","crispEdges");this.xAxisEl.selectAll("path").style("fill",
"none").style("stroke","black").style("shape-rendering","crispEdges")},redrawXAxis:function(){this.chart.selectAll("g[class\x3daxisX]").remove();this.drawXAxis()},drawYAxis:function(){var a=this.container.getHeight(),b=this.container.getWidth();this.manageAllYScales();var c=d3.scaleLinear().domain([200,700]).range([5,15]),d=d3.format(".2r");this.yAxis=d3.axisLeft(this.yScale).ticks(c(a)).tickFormat(function(e){var f=Math.log(e)/Math.log(10)+1E-6;return.7>Math.abs(f-Math.floor(f))?d(e):""}).tickSize(-b+
this.rPadding+this.lPadding);this.yAxisEl=this.chart.append("g").attr("class","axisY").attr("transform","translate("+this.lPadding+",0)").call(this.yAxis);this.yAxisEl.selectAll("text").style("font-family","sans-serif").style("font-size","11px");this.yAxisEl.selectAll("line").style("fill","none").style("stroke","black").style("shape-rendering","crispEdges").style("stroke-opacity",.05);this.yAxisEl.selectAll("path").style("fill","none").style("stroke","black").style("shape-rendering","crispEdges")},
redrawYAxis:function(){this.chart.selectAll("g[class\x3daxisY]").remove();this.drawYAxis()},drawChart:function(){var a=this;this.chart.selectAll("g[class\x3dsection]").data(a.displayData,function(b){return b.outerCounter}).enter().append("g").attr("class","section").attr("clip-path","url(#clip1)").selectAll("g").data(function(b){return b.displayInternal}).enter().append("g").attr("class","frequencies").on("mouseover",function(){d3.select(this).style("fill","red")}).on("mouseout",function(){d3.select(this).style("fill",
"black")}).selectAll("text").data(function(b){return b.frequencyArray}).enter().append("text").attr("class",function(b){return a.getSelectorFromTerm(b.wordString)}).attr("x",function(b){var c=.5/b.numInSeries-.5,d=b.posInSeries/b.numInSeries*.8;b=b.counter+a.callOffset()+c+d;return a.xScale(b)}).attr("y",function(b){return a.yScale(b.freq)}).attr("text-anchor","middle").attr("transform",function(b){var c=.5/b.numInSeries-.5,d=b.posInSeries/b.numInSeries*.8;c=b.counter+a.callOffset()+c+d;b=b.freq;
return"translate(0, 0) rotate(-20 "+a.xScale(c)+" "+a.yScale(b)+")"}).style("font-size",function(b){return a.fontScale(b.freq)+"px"}).style("fill-opacity",function(b){return a.opacityScale(b.freq)}).text(function(b){return b.wordString}).on("mouseover",function(b){d3.select(this).style("cursor","pointer").style("font-size",function(c){return a.fontScale(c.freq)*a.maxFont/a.fontScale(c.freq)+"px"});b=a.buildParamsBundle(b);a.manageOverlaySlippery(b)}).on("mouseout",function(b){d3.select(this).style("cursor",
"auto").style("font-size",function(c){return a.fontScale(c.freq)+"px"});b=a.buildParamsBundle(b);a.manageOverlaySlippery(b)}).on("click",function(b){b=a.buildParamsBundle(b);a.manageOverlaySticky(b)}).append("title").text(function(b){return b.wordString})},redrawChart:function(){this.chart.selectAll("g[class\x3dsection]").remove();this.drawChart()},drawVerticalSlider:function(){},redrawVerticalSlider:function(){this.chart.selectAll("rect[class\x3dminimap]").remove();this.drawVerticalSlider()},drawSlider:function(){this.container.getHeight();
var a=this.container.getWidth()-(this.rPadding+this.lPadding),b=this.lPadding,c=this.lPadding+(this.numVisPoints-1)/(this.numDataPoints-1)*a;this.chart.append("line").attr("class","slider axis").attr("x1",this.lPadding).attr("x2",this.container.getWidth()-this.rPadding).attr("y1",this.tPadding+this.sliderHeight).attr("y2",this.tPadding+this.sliderHeight).style("shape-rendering","crispEdges").style("stroke","black").style("stroke-width","1");this.chart.append("line").attr("class","slider axis").attr("x1",
this.lPadding).attr("x2",this.lPadding).attr("y1",this.tPadding+this.sliderHeight).attr("y2",this.tPadding).style("shape-rendering","crispEdges").style("stroke","black").style("stroke-width","1");this.chart.append("line").attr("class","slider").attr("id","before").attr("x1",a*(this.shiftCount-this.callOffset())/(this.numDataPoints-1)+b).attr("x2",a*(this.shiftCount-this.callOffset())/(this.numDataPoints-1)+b).attr("y1",this.tPadding+this.sliderHeight).attr("y2",this.tPadding).style("stroke","black").style("stroke-width",
"1");this.chart.append("line").attr("class","slider").attr("id","after").attr("x1",a*(this.shiftCount-this.callOffset())/(this.numDataPoints-1)+c).attr("x2",a*(this.shiftCount-this.callOffset())/(this.numDataPoints-1)+c).attr("y1",this.tPadding+this.sliderHeight).attr("y2",this.tPadding).style("stroke","black").style("stroke-width","1");b=this.chart.append("rect").attr("class","slider").attr("id","boxBefore").attr("x",this.lPadding).attr("y",this.tPadding).attr("height",this.sliderHeight).attr("width",
a*(this.shiftCount-this.callOffset())/(this.numDataPoints-1)).style("fill","silver").style("fill-opacity",.25).style("cursor","move");a=this.chart.append("rect").attr("class","slider").attr("id","boxAfter").attr("x",a*(this.shiftCount-this.callOffset())/(this.numDataPoints-1)+c).attr("y",this.tPadding).attr("height",this.sliderHeight).attr("width",a*(this.numDataPoints-this.numVisPoints-this.shiftCount+this.callOffset())/(this.numDataPoints-1)).style("fill","silver").style("fill-opacity",.25).style("cursor",
"move");var d=this;c=d3.drag().on("drag",function(e){if(!d.isTransitioning){this.drag=!0;e=d.parent.getWidth();var f=parseInt(d3.event.dx),g,h;d.sliderDragSum+=d3.event.dx;d.chart.selectAll("#before").attr("x1",function(){g=parseInt(this.getAttribute("x1"));parseInt(this.getAttribute("x1"));return parseInt(this.getAttribute("x1"))});d.chart.selectAll("#after").attr("x1",function(){h=parseInt(this.getAttribute("x1"));return parseInt(this.getAttribute("x1"))});if(g+f<d.lPadding||h+f>e-d.rPadding)f=
0;d.chart.select("#boxBefore").attr("width",function(){return parseInt(this.getAttribute("width"))+f});d.chart.select("#boxAfter").attr("x",function(){return parseInt(this.getAttribute("x"))+f}).attr("width",function(){return Math.max(0,parseInt(this.getAttribute("width"))-f)});d.chart.selectAll("#before").attr("x1",function(){return parseInt(this.getAttribute("x1"))+f}).attr("x2",function(){return parseInt(this.getAttribute("x2"))+f});d.chart.selectAll("#after").attr("x1",function(){return parseInt(this.getAttribute("x1"))+
f}).attr("x2",function(){return parseInt(this.getAttribute("x2"))+f})}}).on("end",function(e){if(this.drag){this.drag=!1;e=d3.scaleLinear().domain([0,d.container.getWidth()-(d.lPadding+d.rPadding)]).range([0,d.numDataPoints])(d.sliderDragSum);var f,g=d.shiftCount;0<e&&(f=Math.floor(e));0>e&&(f=Math.ceil(e));d.shiftCount+=f;0>d.shiftCount&&(d.shiftCount=0);d.shiftCount>d.numDataPoints-1&&(d.shiftCount=d.numDataPoints-1);d.shiftCount!==g&&(d.sliderDragSum=0,d.parent.setApiParams({position:d.shiftCount}),
d.prepareData(),d.redraw())}});b.call(c);a.call(c)},removeSlider:function(a){this.chart.selectAll("rect[class\x3dslider]").remove();this.chart.selectAll("line[class~\x3dslider]").remove();a&&this.chart.selectAll("g[class\x3dslider]").remove()},redrawSlider:function(){this.removeSlider();this.drawSlider()},animateVis:function(){var a=this;this.parent.getApiParam("mode");this.container.getHeight();var b=this.container.getWidth(),c=this.getDuration();if("left"===this.transitionCall||"right"===this.transitionCall){this.xAxisEl.transition().duration(c).ease(d3.easeLinear).call(this.xAxis);
this.styleXAxis();this.drawChart();this.chart.selectAll(".frequencies").transition().duration(c).ease(d3.easeLinear).selectAll("text").attr("x",function(f){return a.xScale(f.counter+(.5/f.numInSeries-.5)+f.posInSeries/f.numInSeries*.8)}).attr("transform",function(f){var g=f.freq;return"translate(0, 0) rotate(-20 "+a.xScale(f.counter+(.5/f.numInSeries-.5)+f.posInSeries/f.numInSeries*.8)+" "+a.yScale(g)+")"});b-=this.rPadding+this.lPadding;var d=this.lPadding,e=this.lPadding+(this.numVisPoints-1)/(this.numDataPoints-
1)*b;this.chart.select("#before").transition().duration(c).ease(d3.easeLinear).attr("x1",b*this.shiftCount/(this.numDataPoints-1)+d).attr("x2",b*this.shiftCount/(this.numDataPoints-1)+d).attr("y1",this.tPadding+this.getSliderHeight()).attr("y2",this.tPadding).on("end",function(){a.parent.isMasked()&&a.parent.unmask();a.continueTransition?setTimeout(function(){a.callTransition()},50):(a.isTransitioning=!1,a.manageMvtButtons())});this.chart.select("#after").transition().duration(c).ease(d3.easeLinear).attr("x1",
b*this.shiftCount/(this.numDataPoints-1)+e).attr("x2",b*this.shiftCount/(this.numDataPoints-1)+e).attr("y1",this.tPadding+this.getSliderHeight()).attr("y2",this.tPadding);this.chart.select("#boxBefore").transition().duration(c).ease(d3.easeLinear).attr("x",this.lPadding).attr("y",this.tPadding).attr("height",this.getSliderHeight()).attr("width",b*this.shiftCount/(this.numDataPoints-1));this.chart.select("#boxAfter").transition().duration(c).ease(d3.easeLinear).attr("x",b*this.shiftCount/(this.numDataPoints-
1)+e).attr("y",this.tPadding).attr("height",this.getSliderHeight()).attr("width",b*(this.numDataPoints-this.numVisPoints-this.shiftCount)/(this.numDataPoints-1))}this.redrawChartOverlay()},callTransition:function(){"left"===this.transitionCall&&this.toggleLeftCheck();"right"===this.transitionCall&&this.toggleRightCheck()},buildParamsBundle:function(a){var b=a.wordString,c={};if("document"===this.parent.getApiParam("mode")){a=a.docId;var d=this.parent.getCorpus().getDocument(a).getLexicalTokensCount()-
1;c.tokenIdStart=parseInt(d/this.numDataPoints);c.docIdType=a+":"+b}return{params:c,type:b}},manageOverlaySlippery:function(a){for(var b=a.type,c=this.getSelectorFromTerm(a.type),d="on",e=this.overlayQueue.length;0<=--e;)c===this.overlayQueue[e].selector&&(d="off");c===this.lastSticky&&(d="off",this.lastSticky=null);"on"===d&&(c!==this.lastSlippery?(d=this.prepareFullPath(b),a={word:b,selector:c,params:a,fullPath:d.path,pathMin:d.min,pathMax:d.max,colour:"red"},null!==this.lastSlippery&&(this.chartOverlayOff(this.lastSlippery),
this.isSliderVisible&&this.sliderOverlayOff(this.lastSlippery),this.lastSlippery=null),this.chartOverlayOn(a),this.isSliderVisible&&this.sliderOverlayOn(a),this.lastSlippery=c):(this.chartOverlayOff(c),this.isSliderVisible&&this.sliderOverlayOff(this.lastSlippery),this.lastSlippery=null))},manageOverlaySticky:function(a){a=a.type;this.transitionCall="draw";this.isTermSelected(a)?this.doTermDeselect(a,!0):this.doTermSelect(a,!0)},getTermIndex:function(a){var b=-1;a=this.getSelectorFromTerm(a);for(var c=
this.overlayQueue.length;0<=--c;)a===this.overlayQueue[c].selector&&(b=c);return b},isTermSelected:function(a){return-1!==this.getTermIndex(a)},doTermSelect:function(a,b){var c=this.getSelectorFromTerm(a),d=this.parent.getApiParam("selectedWords");d.push(a);this.parent.setApiParams({selectedWords:d});d=this.parent.getApplication().getColorForTerm(a,!0);if(!0===b)b=this.parent.query("[xtype\x3dlegend]")[0],b.getStore().add({name:a,mark:d,selector:c}),b.refresh();else{b=this.parent.query("[xtype\x3dlegend]")[0];
var e=b.getStore().findRecord("name",a);null!==e&&(e.set("mark",d),b.refresh())}b=this.prepareFullPath(a);a={word:a,selector:c,params:{params:{},type:a},fullPath:b.path,pathMin:b.min,pathMax:b.max,colour:d};c===this.lastSlippery&&(this.isSliderVisible&&this.sliderOverlayOff(c),this.lastSlippery=null);this.chart.select("g[class\x3dfrequency-line-"+c+"]").remove();this.overlayQueue.push(a);this.chartOverlayOn(a);this.isSliderVisible&&this.sliderOverlayOn(a)},doTermDeselect:function(a,b){var c=this.getSelectorFromTerm(a),
d=this.getTermIndex(a);!0===b&&(b=this.parent.query("[xtype\x3dlegend]")[0],d=b.getStore().findExact("name",a),b.getStore().removeAt(d),b.refresh());a=this.parent.getApiParam("selectedWords");b=0;for(var e=a.length;b<e;b++)a[b]===c&&(a.splice(b,1),this.parent.setApiParams({selectedWords:a}));this.chartOverlayOff(c);this.overlayQueue.splice(d,1);this.isSliderVisible&&this.sliderOverlayOff(c);this.lastSticky=c},prepareFullPath:function(a){for(var b=[],c=this.absMaxFreq,d=this.absMinFreq,e=0,f=this.allData.length;e<
f;e++){for(var g=foundB=0,h=this.allData[e].allDataInternal.length;g<h;g++)for(var k=0,l=this.allData[e].allDataInternal[g].frequencyArray.length;k<l;k++)if(this.allData[e].allDataInternal[g].frequencyArray[k].wordString===a){var m=this.allData[e].allDataInternal[g].frequencyArray[k].freq;b.push({x:e,y:m});m<c&&(c=m);m>d&&(d=m);foundB=1}0===foundB&&(g=this.minFreq,b.push({x:e,y:g}),g<c&&(c=g),g>d&&(d=g))}return{path:b,min:c,max:d}},updateFullPath:function(){for(var a=this.overlayQueue.length;0<a--;){var b=
this.prepareFullPath(this.overlayQueue[a].word);this.overlayQueue[a].fullPath=b.path;this.overlayQueue[a].pathMin=b.min;this.overlayQueue[a].pathMax=b.max}},buildSliderPath:function(a){var b=this;return d3.line().x(function(c){return b.xSliderScale(c.x)}).y(function(c){return b.ySliderScale(c.y)}).curve(d3.curveNatural)(a)},sliderOverlayOn:function(a){this.transitionSliderOverlay(a);this.chart.append("g").attr("class","slider").attr("id","slider-line-"+a.selector).append("path").attr("d",this.buildSliderPath(a.fullPath)).style("stroke",
a.colour).style("stroke-width",2).style("fill","none");this.redrawSlider()},sliderOverlayOff:function(a){this.chart.selectAll("g[id\x3dslider-line-"+a+"]").remove();this.transitionSliderOverlay()},redrawSliderOverlay:function(){for(var a=0;a<this.overlayQueue.length;a++)this.sliderOverlayOff(this.overlayQueue[a].selector),this.sliderOverlayOn(this.overlayQueue[a])},transitionSliderOverlay:function(a){this.updateYSliderScale(a||0);for(a=this.overlayQueue.length;0<a--;)this.chart.selectAll("g#slider-line-"+
this.overlayQueue[a].selector).select("path").transition().duration(300).ease(d3.easeLinear).attr("d",this.buildSliderPath(this.overlayQueue[a].fullPath))},preparePath:function(a){for(var b=[],c,d,e=0;3>e&&0<this.shiftCount-e;e++){for(var f=c=0;f<this.allData[this.shiftCount-(1+e)].allDataInternal.length;f++)for(var g=0;g<this.allData[this.shiftCount-(1+e)].allDataInternal[f].frequencyArray.length;g++)this.allData[this.shiftCount-(1+e)].allDataInternal[f].frequencyArray[g].wordString===a&&(c=this.yScale(this.allData[this.shiftCount-
(1+e)].allDataInternal[f].frequencyArray[g].freq),b.unshift({x:this.shiftCount-(1+e),y:c}),c=1);0===c&&(f=this.yScale(this.minFreq),b.unshift({x:this.shiftCount-(1+e),y:f}))}e=this.shiftCount;for(c=this.numVisPoints+this.shiftCount;e<c;e++){f=d=0;for(var h=this.allData[e].allDataInternal.length;f<h;f++){g=0;for(var k=this.allData[e].allDataInternal[f].frequencyArray.length;g<k;g++)this.allData[e].allDataInternal[f].frequencyArray[g].wordString===a&&(d=this.yScale(this.allData[e].allDataInternal[f].frequencyArray[g].freq),
b.push({x:e,y:d}),d=1)}0===d&&(f=this.yScale(this.minFreq),b.push({x:e,y:f}))}for(e=0;3>e&&this.numVisPoints+this.shiftCount+e<this.numDataPoints;e++){for(f=c=0;f<this.allData[this.numVisPoints+this.shiftCount+e].allDataInternal.length;f++)for(g=0;g<this.allData[this.numVisPoints+this.shiftCount+e].allDataInternal[f].frequencyArray.length;g++)this.allData[this.numVisPoints+this.shiftCount+e].allDataInternal[f].frequencyArray[g].wordString===a&&(d=this.yScale(this.allData[this.numVisPoints+this.shiftCount+
e].allDataInternal[f].frequencyArray[g].freq),b.push({x:this.numVisPoints+this.shiftCount+e,y:d}),c=1);0===c&&(f=this.yScale(this.minFreq),b.push({x:this.numVisPoints+this.shiftCount+e,y:f}))}return b},chartOverlayOn:function(a){var b=this;this.chart.selectAll("g[class\x3dsection]").selectAll("g[class\x3dfrequencies]").selectAll("text[class\x3d"+a.selector.replace(/'/g,"\\'")+"]").style("fill",a.colour).style("fill-opacity",1);var c=this.preparePath(a.word),d,e=d3.line().x(function(f){d=f.x;return b.xScale(f.x+
b.callOffset())}).y(function(f){return f.y}).curve(d3.curveNatural);a=this.chart.select(".overlay").append("g").attr("class","frequency-line-"+a.selector).append("path").attr("d",e(c)).style("stroke",a.colour).style("stroke-width",2).style("fill","none");c=this.xScale(d)-this.xScale(d+this.callOffset());"left"!==this.transitionCall&&"right"!==this.transitionCall||a.transition().duration(b.getDuration()).ease(d3.easeLinear).attr("transform","translate("+c+")")},chartOverlayOff:function(a){var b=this;
this.chart.selectAll("text."+a).style("fill","black").style("fill-opacity",function(c){return b.opacityScale(c.freq)});this.chart.select("g.frequency-line-"+a).remove()},redrawChartOverlay:function(){for(var a=0;a<this.overlayQueue.length;a++)this.chartOverlayOff(this.overlayQueue[a].selector),this.chartOverlayOn(this.overlayQueue[a])},manageAllYScales:function(){this.manageFontScale();this.manageOpacityScale();this.manageYScale();this.manageYSliderScale()},manageFontScale:function(){this.fontScale.domain([this.minFreq,
this.absMaxFreq*this.valFraction]).range([10,this.maxFont])},manageOpacityScale:function(){this.opacityScale.domain([0,this.absMaxFreq*this.valFraction]).range([.4,.8])},manageYScale:function(){"linear"==this.parent.getApiParam("yAxisScale")&&(this.yScale=d3.scaleLinear());"log"==this.parent.getApiParam("yAxisScale")&&(this.yScale=d3.scaleLog());this.yScale.domain([this.minFreq,this.absMaxFreq*this.valFraction*1.25]).rangeRound([this.container.getHeight()-this.bPadding,this.tPadding+this.getSliderHeight()])},
manageYSliderScale:function(){var a=this.tPadding,b=this.tPadding+this.getSliderHeight();"linear"==this.parent.getApiParam("yAxisScale")&&(this.ySliderScale=d3.scaleLinear());"log"==this.parent.getApiParam("yAxisScale")&&(this.ySliderScale=d3.scaleLog());this.ySliderScale.domain([this.minFreq,this.absMaxFreq]).rangeRound([b,a])},updateYSliderScale:function(a){a=a||0;for(var b=this.minFreq,c=0,d=this.overlayQueue.length;0<d--;)this.overlayQueue[d].pathMin<b&&(b=this.overlayQueue[d].pathMin),this.overlayQueue[d].pathMax>
c&&(c=this.overlayQueue[d].pathMax);0!=a&&a.pathMin<b&&(b=a.pathMin);0!=a&&a.pathMax>c&&(c=a.pathMax);this.ySliderScale.domain([b,c])},manageAllXScales:function(){this.manageXScale();this.manageXSliderScale()},manageXScale:function(){this.xScale.domain([this.shiftCount-.5,this.numVisPoints+this.shiftCount-.5]).range([this.lPadding,this.container.getWidth()-this.rPadding])},manageXSliderScale:function(){this.xSliderScale.domain([0,this.numDataPoints-1]).range([this.lPadding,this.container.getWidth()-
this.rPadding])},getSliderHeight:function(){return this.isSliderVisible?this.sliderHeight+this.sliderBPadding:0},setSliderHeight:function(){this.sliderHeight=Math.max(10,this.container.getHeight()*this.sliderHeightRatio)},hideSlider:function(){this.isSliderVisible=!1;this.removeSlider(!0);this.doResize()},showSlider:function(){this.isSliderVisible=!0;this.doResize()},setTitleLength:function(){this.titlesArray=[];for(var a=d3.scaleLinear().domain([350,1250]).range([10,40]),b=this.parent.getCorpus(),
c=0,d=b.getDocumentsCount();c<d;c++){var e=b.getDocument(c);e=e.getShortTitle();e.length<=a(this.container.getWidth())?this.titlesArray.push(e):(e=e.substring(0,a(this.container.getWidth())-3),this.titlesArray.push(e+"..."))}},callOffset:function(){if("draw"===this.transitionCall||"redraw"===this.transitionCall)var a=0;"left"===this.transitionCall&&(a=-1);"right"===this.transitionCall&&(a=1);return a},getSelectorFromTerm:function(a){if(void 0!==a){for(var b="tr",c=0;c<a.length;c++)b+="-"+a.charCodeAt(c);
return b}return""},getDuration:function(){return this.numDataPoints*(100-this.parent.getSpeed())}};Ext.define("Voyant.util.Api",{constructor:function(a){var b=[];if(!this.isApplication){var c=this.getApplication?this.getApplication():Voyant.application;if(this.mixins)for(e in this.mixins){var d=Ext.ClassManager.get(e);d&&d.api&&b.splice(0,0,d.api)}this.addParentApi(b,Ext.ClassManager.getClass(c));c.getApiParams&&b.push(c.getApiParams())}this.addParentApi(b,Ext.ClassManager.getClass(this));this.api={};b.forEach(function(f){for(e in f)this.api[e]={initial:f[e],value:f[e]}},this);b=Ext.Object.fromQueryString(document.location.search);
c=this.getXType?this.getXType():void 0;for(var e in b)this.api[e]?this.setApiParam(e,b[e]):c&&0<e.indexOf(".")&&(d=e.substring(e.indexOf(".")+1))&&d in this.api&&this.setApiParam(d,b[e]);if(a&&Ext.isObject(a.api)){for(e in a.api)this.api[e]&&this.setApiParam(e,a.api[e]);delete a.api}b.type&&"query"in this.api&&!this.getApiParam("query")&&this.setApiParam("query",b.type)},addParentApi:function(a,b){b.api&&a.splice(0,0,b.api);b.superclass&&this.addParentApi(a,b.superclass.self)},getApiParam:function(a,
b){return void 0!==this.api[a]?this.api[a].value:b},getApiParams:function(a,b){a=a||Object.keys(this.api);var c={};Ext.isString(a)&&(a=[a]);a.forEach(function(d){var e=this.getApiParam(d);if(b||!Ext.isEmpty(e))c[d]=e},this);return c},getModifiedApiParams:function(){var a={},b;for(b in this.api)this.api[b].initial!=this.api[b].value&&(a[b]=this.api[b].value);return a},setApiParams:function(a){for(var b in a)this.setApiParam(b,a[b])},setApiParam:function(a,b){this.api&&this.api[a]&&(this.api[a].value=
b)}});Ext.define("Voyant.util.Localization",{statics:{DEFAULT_LANGUAGE:"en",LANGUAGE:"en",AVAILABLE_LANGUAGES:"ar bs cz de en es fr he hr it ja pt ru sr".split(" "),i18n:{}},getLanguage:function(a){if(2===a.length)return-1!==Voyant.util.Localization.AVAILABLE_LANGUAGES.indexOf(a)?this.localize(a):a;var b=Voyant.util.Localization.AVAILABLE_LANGUAGES.map(function(d){return{text:this.localize(d).toLowerCase(),value:d}},this),c=a.toLowerCase();return(b=b.find(function(d){return d.text===c}))?b.value:a},localize:function(a,
b){return this._localizeObject(this,a,b)},_localizeObject:function(a,b,c){var d=this._localizeClass(Ext.ClassManager.getClass(a),b,c);if(d)return d;if(a.mixins)for(mixin in a.mixins)if(d=this._localizeClass(Ext.ClassManager.getClass(a.mixins[mixin]),b,c))return d;return a.superclass&&(d=this._localizeObject(a.superclass,b,c))?d:c&&void 0!=c["default"]?c["default"]:"["+b+"]"},_localizeClass:function(a,b,c){if(a&&a.i18n&&a.i18n[b]){var d=!1;a.i18n[b]&&(d=a.i18n[b]);return d?d.isTemplate?d.apply(c):
d:c&&void 0!=c["default"]?c["default"]:"["+b+"]"}return!1},getLanguageToolMenu:function(){return{type:"language",tooltip:this.localize("languageTitle"),xtype:"toolmenu",glyph:"xf1ab@FontAwesome",handler:this.showLanguageOptions,scope:this}},showLanguageOptions:function(){var a=this,b=Voyant.util.Localization.AVAILABLE_LANGUAGES.map(function(c){return{text:this.localize(c),value:c}},this);b.sort(function(c,d){return c.text.localeCompare(d.text)});b.splice(0,0,{text:this.localize("autoRecommended"),
value:""});(new Ext.window.Window({title:this.localize("languageTitle"),modal:!0,items:{xtype:"form",items:[{xtype:"combo",name:"lang",value:this.getApiParam("lang")||"",queryMode:"local",editable:!1,fieldLabel:this.localize("chooseLanguage"),width:450,labelAlign:"right",labelWidth:150,displayField:"text",valueField:"value",store:{fields:["text","value"],data:b}}],buttons:[{text:this.localize("cancelTitle"),ui:"default-toolbar",glyph:"xf00d@FontAwesome",flex:1,handler:function(c){c.up("window").close()}},
{text:this.localize("confirmTitle"),glyph:"xf00c@FontAwesome",flex:1,handler:function(c){var d=c.up("form");if(d.isDirty()){var e=a.getApplication(),f=e.getModifiedApiParams();e.getCorpus()?f.corpus=e.getCorpus().getAliasOrId():delete f.panels;delete f.lang;d=d.getValues();d.lang&&(f.lang=d.lang);location.assign("./?"+Ext.Object.toQueryString(f))}c.up("window").close()},scope:a}]},bodyPadding:5})).show()}});Ext.define("Voyant.util.Colors",{config:{palettes:void 0,colorTermAssociations:{},textColorsForBackgroundColors:{}},lastUsedPaletteIndex:-1,constructor:function(a){this.setPalettes({"default":[[0,0,255],[51,197,51],[255,0,255],[121,51,255],[28,255,255],[255,174,0],[30,177,255],[182,242,58],[255,0,164],[51,102,153],[34,111,52],[155,20,104],[109,43,157],[128,130,33],[111,76,10],[119,115,165],[61,177,169],[202,135,115],[194,169,204],[181,212,228],[182,197,174],[255,197,197],[228,200,124],[197,179,159]]});
this.resetColorTermAssociations();if(void 0!==d3){a=d3.scaleOrdinal(d3.schemeCategory10).range().map(function(f){return this.hexToRgb(f)},this);var b=d3.scaleOrdinal(d3.schemeCategory20).range().map(function(f){return this.hexToRgb(f)},this),c=d3.scaleOrdinal(d3.schemeCategory20b).range().map(function(f){return this.hexToRgb(f)},this),d=d3.scaleOrdinal(d3.schemeCategory20c).range().map(function(f){return this.hexToRgb(f)},this),e="#8dd3c7 #ffffb3 #bebada #fb8072 #80b1d3 #fdb462 #b3de69 #fccde5 #d9d9d9 #bc80bd #ccebc5 #ffed6f".split(" ").map(function(f){return this.hexToRgb(f)},
this);this.addColorPalette("d3_cat10",a);this.addColorPalette("d3_cat20a",b);this.addColorPalette("d3_cat20b",c);this.addColorPalette("d3_cat20c",d);this.addColorPalette("d3_set3",e)}a=Ext.create("Ext.chart.theme.Base").getColors().map(function(f){return this.hexToRgb(f)},this);this.addColorPalette("extjs",a)},resetColorTermAssociations:function(){this.lastUsedPaletteIndex=-1;this.setColorTermAssociations({});this.setTextColorsForBackgroundColors({})},rgbToHex:function(a){return"#"+(16777216+(a[0]<<
16)+(a[1]<<8)+a[2]).toString(16).slice(1)},hexToRgb:function(a){a=a.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,function(b,c,d,e){return c+c+d+d+e+e});return(a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a))?[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]:null},addColorPalette:function(a,b){this.getPalettes()[a]=b},getColorPalette:function(a,b){a=a||"default";a=this.getPalettes()[a];void 0===a&&(a=[]);if(b){b=[];for(var c=0;c<a.length;c++)b.push(this.rgbToHex(a[c]));return b}return a},
saveCustomColorPalette:function(a){var b=new Ext.Deferred;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",storeResource:Ext.encode(a)},success:function(c,d){c=Ext.util.JSON.decode(c.responseText).storedResource.id;this.addColorPalette(c,a);b.resolve(c,a)},failure:function(c){b.reject()},scope:this});return b.promise},loadCustomColorPalette:function(a){var b=new Ext.Deferred;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",retrieveResourceId:a},
success:function(c,d){c=Ext.util.JSON.decode(c.responseText).storedResource.resource;c=Ext.decode(c);this.addColorPalette(a,c);b.resolve(a,c)},failure:function(c){this.setApiParam("palette",void 0);b.reject()},scope:this});return b.promise},getColor:function(a,b,c){a=a||"default";a=this.getPalettes()[a];b>=a.length&&(b%=a.length);return c?this.rgbToHex(a[b]):a[b]},getColorForTerm:function(a,b,c){var d=a||"default";d=this.getPalettes()[d];void 0===d&&(console.warn("no palette found for",a),d=this.getPalettes()["default"]);
-1!=b.indexOf(":")&&(b=b.split(":")[1]);b=b.toLowerCase();a=this.getColorTermAssociations()[b];if(void 0===a){var e=this.lastUsedPaletteIndex+1;e%=d.length;a=d[e];this.getColorTermAssociations()[b]=a;this.lastUsedPaletteIndex=e}c&&(a=this.rgbToHex(a));return a},setColorForTerm:function(a,b){!1===Array.isArray(b)&&(b=this.hexToRgb(b));a=a.toLowerCase();this.getColorTermAssociations()[a]=b},getColorForEntityType:function(a,b){switch(a){case "person":a=5;break;case "location":a=6;break;case "organization":a=
2;break;case "misc":a=0;break;case "time":case "date":case "duration":a=4;break;case "money":a=1;break;default:a=8}a=this.getPalettes().d3_set3[a];b&&(a=this.rgbToHex(a));return a},getColorContrast:function(a,b){function c(g){return(0>g?-1:1)*Math.pow(Math.abs(g),2.4)}var d=$jscomp.makeIterator(b);b=d.next().value;var e=d.next().value;var f=d.next().value;d=.2126729*c(b)+.7151522*c(e)+.072175*c(f);a=$jscomp.makeIterator(a);b=a.next().value;e=a.next().value;f=a.next().value;a=.2126729*c(b)+.7151522*
c(e)+.072175*c(f);b=.022<=d?d:d+Math.pow(.022-d,1.414);a=.022<=a?a:a+Math.pow(.022-a,1.414);5E-4>Math.abs(a-b)?a=0:(a=a>b?Math.pow(a,.56)-Math.pow(b,.57):Math.pow(a,.65)-Math.pow(b,.62),a*=1.14);return 100*(.1>Math.abs(a)?0:0<a?a-.027:a+.027)},getTextColorForBackground:function(a){var b=this.getTextColorsForBackgroundColors()[a.join("")];if(void 0===b){b=[0,0,0];var c=[255,255,255],d=Math.abs(this.getColorContrast(a,b));b=Math.abs(this.getColorContrast(a,c))>d?c:b;this.getTextColorsForBackgroundColors()[a.join("")]=
b}return b}});Ext.define("Voyant.util.DetailedError",{extend:"Ext.Error",mixins:["Voyant.util.Localization"],config:{msg:void 0,error:void 0,details:void 0},statics:{i18n:{error:"Error"}},constructor:function(a){this.setMsg(a.msg);this.setError(a.error);this.setDetails(a.details);this.callParent(arguments)},show:function(a){window.showError?showError.call(this):this.showMsg(a)},showMsg:function(a){a=a||{};Ext.applyIf(a,{message:this.getMsg()+"\x3cp class\x3d'error'\x3e\n"+this.getError()+"\u2026 \x3ca href\x3d'#' onclick\x3d\"window.open('').document.write(unescape('\x3cpre\x3e"+
escape(this.getDetails())+"\x3c/pre\x3e')); return false;\"\x3emore\x3c/a\x3e\x3c/p\x3e",title:this.localize("error"),buttons:Ext.Msg.OK,icon:Ext.MessageBox.ERROR,autoScroll:!0});Ext.Msg.show(a)}});Ext.define("Voyant.util.ResponseError",{extend:"Voyant.util.DetailedError",config:{response:void 0},constructor:function(a){this.setResponse(a.response);Ext.applyIf(a,{msg:a.response.statusText,error:"object"===typeof a.response&&"responseText"in a.response?a.response.responseText.split(/(\r\n|\r|\n)/).shift():a.response,details:"object"===typeof a.response&&"responseText"in a.response?a.response.responseText:a.response});this.callParent(arguments)}});Ext.define("Voyant.util.SparkLine",{getSparkLine:function(a,b){if(2>a.length)return"";var c=Number.MAX_VALUE,d=Number.MIN_VALUE,e=!1;for(b=0;b<a.length;b++)a[b]<c&&(c=a[b]),a[b]>d&&(d=a[b]),!e&&-1<a[b].toString().indexOf(".")&&(e=!0);var f=(d-c).toString(),g=[];if(e){e=100;for(b=f.indexOf(".")+1;b<f.length;b++)if("0"==f.charAt(b))e*=10;else break;for(b=0;b<a.length;b++)g[b]=parseInt(a[b]*e);d=parseInt(d*e);c=parseInt(c*e)}else{e=1;for(b=f.length-1;-1<b;b--)if("0"==f.charAt(b))e*=10;else break;if(1!=
e){for(b=0;b<a.length;b++)g[b]=a[b]/e;d/=e;c/=e}else g=a}f=Math.floor(1800/((d.toString().length>c.toString().length?d.toString().length:c.toString().length)+1));c="http://chart.apis.google.com/chart?cht\x3dls\x26amp;chco\x3d0077CC\x26amp;chls\x3d1,0,0\x26amp;chds\x3d"+c+","+d;d=Math.ceil(a.length/f);e=0;var h="";a=5>a.length?5:10>a.length?4:20>a.length?3:50>a.length?2:1;for(b=0;b<d;b++){var k=g.slice(e,e+=f);h+="\x3cimg style\x3d'margin: 0; padding: 0;' border\x3d'0' src\x3d'"+c+"\x26amp;chs\x3d"+
a*k.length+"x15\x26amp;chd\x3dt:"+k.join(",")+"' alt\x3d'' class\x3d'chart-";1==d?h+="full":0<b&&b+1<d?h+"middle":h=0==b?h+"left":h+"right";h+="' /\x3e"}return h}});Ext.define("Voyant.util.Toolable",{requires:["Voyant.util.Localization","Voyant.util.Api"],statics:{i18n:{},api:{suppressTools:!1}},constructor:function(a){a=a||{};if(!(this.getApiParam&&"true"==this.getApiParam("suppressTools")||"header"in a&&!1===a.header)){var b=void 0,c=this.up("component");a.moreTools?(b=[],a.moreTools.forEach(function(g){g&&g!=this.xtype&&b.push(this.getMenuItemFromXtype(g))},this)):c&&c.getInitialConfig("moreTools")&&(b=[],c.getInitialConfig("moreTools").forEach(function(g){g&&
g!=this.xtype&&b.push(this.getMenuItemFromXtype(g))},this));b&&this.getApplication().getMoreTools&&b.push({xtype:"menuseparator"});if(this.getApplication().getMoreTools){b=b||[];var d=this.getApplication();c=d.getMoreTools();c.forEach(function(g){var h=[];g.items.forEach(function(k){h.push(this.getMenuItemFromXtype(k))},this);b.push({text:d.localize(g.i18n),glyph:g.glyph,menu:{items:h}})},this)}var e={save:{glyph:"xf08e@FontAwesome",fn:this.exportToolClick,items:void 0},plus:b?{glyph:"xf17a@FontAwesome",
items:b}:void 0,gear:this.showOptionsClick||this.getOptions?{glyph:"xf205@FontAwesome",fn:this.showOptionsClick?this.showOptionsClick:function(g){g.isXType("voyanttabpanel")&&(g=g.getActiveTab());Ext.create("Ext.window.Window",{title:g.localize("optionsTitle"),modal:!0,panel:g,items:{xtype:"form",items:g.getOptions(),listeners:{afterrender:function(h){var k=g.getApiParams(h.getForm().getFields().collect("name"));h.getForm().setValues(k)}},buttons:[{text:g.localize("reset"),glyph:"xf0e2@FontAwesome",
flex:1,panel:g,ui:"default-toolbar",handler:function(h){this.mixins&&this.mixins["Voyant.util.Api"]&&(this.mixins["Voyant.util.Api"].constructor.apply(this),this.getCorpus&&this.getCorpus()&&this.fireEvent("loadedCorpus",this,this.getCorpus()));h.up("window").close()},scope:g},{xtype:"tbfill"},{text:g.localize("cancelTitle"),ui:"default-toolbar",glyph:"xf00d@FontAwesome",flex:1,handler:function(h){h.up("window").close()}},{text:g.localize("confirmTitle"),glyph:"xf00c@FontAwesome",flex:1,panel:g,handler:function(h){var k=
h.up("form").getValues();this.setApiParams(k);var l=this.getApplication(),m=[];void 0!==k.stopList&&void 0!==k.stopListGlobal&&k.stopListGlobal&&m.push(["stopList",k.stopList]);void 0!==k.termColors&&void 0!==k.termColorsGlobal&&k.termColorsGlobal&&m.push(["termColors",k.termColors]);var n=new Ext.Deferred;k.categories&&""!==k.categories?l.loadCategoryData(k.categories).then(function(){},function(){k.categories=void 0}).finally(function(){m.push(["categories",k.categories]);n.resolve()}):n.resolve();
var u=new Ext.Deferred;void 0!==k.palette?(l.resetColorTermAssociations(),0===l.getColorPalette(k.palette).length?l.loadCustomColorPalette(k.palette).then(function(){},function(){k.palette="default"}).always(function(){m.push(["palette",k.palette]);u.resolve()}):(m.push(["palette",k.palette]),u.resolve())):u.resolve();Ext.Promise.all([n,u]).then(function(){var w=l.getCorpus();if(0<m.length){var p=l.getViewport().query("panel,chart");m.forEach(function(q){var r=q[0];q=q[1];l.setApiParam&&l.setApiParam(r,
q);for(var v=0;v<p.length;v++)p[v].setApiParam&&p[v].setApiParam(r,q)});w?l.dispatchEvent("loadedCorpus",this,w):l.dispatchEvent("apiParamsUpdated",this,k)}w?this.fireEvent("loadedCorpus",this,w):this.fireEvent("apiParamsUpdated",this,k);h.up("window").close()}.bind(this))},scope:g}]},bodyPadding:5}).show()}}:void 0,help:{glyph:"xf128@FontAwesome",fn:this.helpToolClick}};c=[];if(a.includeTools)for(var f in a.includeTools)"object"==typeof a.includeTools[f]&&c.push(a.includeTools[f]);for(f in e)a.includeTools&&
!a.includeTools[f]||!e[f]||c.push({type:f,tooltip:this.localize(f+"Tip"),callback:e[f].fn,xtype:"toolmenu",glyph:e[f].glyph,items:e[f].items});Ext.apply(this,{tools:c});this.on("afterrender",function(){var g=this.getHeader();if(g&&"Desktop"==Ext.os.deviceType&&!this.isXType("corpuscreator")&&!this.isXType("notebook")){var h=g.getEl();h.on("mouseover",function(){this.getHeader().getTools().forEach(function(k){k.show()})},this);h.on("mouseout",function(){this.getHeader().getTools().forEach(function(k){var l=
k.config.type||k.type;l&&"help"!==l&&k.hide()})},this);g.getTools().forEach(function(k,l){"help"!==k.config.type&&k.hide()})}},this)}},getMenuItemFromXtype:function(a){var b=this.getApplication().getToolConfigFromToolXtype(a);b&&b.tooltip&&delete b.tooltip;return Ext.apply(Ext.clone(b),{xtype:"menuitem",text:b.title,textAlign:"left",handler:function(){this.replacePanel(b.xtype)},scope:this})},maximizeToolClick:function(a){var b=Ext.getClass(a).getName().split(".");url=a.getBaseUrl()+"tool/"+b[b.length-
1]+"/";params=a.getModifiedApiParams();!params.corpus&&a.getCorpus&&a.getCorpus()&&(params.corpus=a.getCorpus().getId());params&&(url+="?"+Ext.Object.toQueryString(params));a.openUrl(url)},exportToolClick:function(a){a.isXType("voyanttabpanel")&&(a=a.getActiveTab());var b="beta.voyant-tools.org"==window.location.hostname?[{html:"\x3cp class\x3d'keyword' style\x3d'text-align: center; font-weight: bold; padding: 4px;'\x3ePlease note that this is the beta server and you should not count on corpora persisting (for bookmarks, embedding, etc.)."}]:
[],c=[{xtype:"radio",name:"export",inputValue:"embed",boxLabel:a.localize("exportViewHtmlEmbed")},{xtype:"radio",name:"export",inputValue:"biblio",boxLabel:a.localize("exportViewBiblio")},{xtype:"radio",name:"export",inputValue:"spyral",boxLabel:a.localize("exportViewSpyral")}];a.isXType("notebook")&&c.splice(2,1);a.getExtraViewExportItems&&a.getExtraViewExportItems().forEach(function(f){Ext.applyIf(f,{xtype:"radio",name:"export"});c.push(f)});b.push({xtype:"radio",name:"export",inputValue:"url",
boxLabel:"\x3ca href\x3d'"+a.getExportUrl.call(a)+"' target\x3d'_blank'\x3e"+a.localize("exportViewUrl")+"\x3c/a\x3e",checked:!0,listeners:{afterrender:function(){this.boxLabelEl.on("click",function(){this.up("window").close()},this)}}},{xtype:"fieldset",collapsible:!0,collapsed:!0,title:a.localize("exportViewFieldset"),items:c});var d=[];a.isXType("grid")&&(d.push({xtype:"radio",name:"export",inputValue:"gridCurrentHtml",boxLabel:a.localize("exportGridCurrentHtml")},{xtype:"radio",name:"export",
inputValue:"gridCurrentTsv",boxLabel:a.localize("exportGridCurrentTsv")}),a.getExportGridAll&&0==a.getExportGridAll()||d.push({xtype:"radio",name:"export",inputValue:"gridAllJson",boxLabel:a.localize("exportGridAllJson")},{xtype:"radio",name:"export",inputValue:"gridAllTsv",boxLabel:a.localize("exportGridAllTsv")}));a.getExtraDataExportItems&&a.getExtraDataExportItems().forEach(function(f){Ext.applyIf(f,{xtype:"radio",name:"export"});d.push(f)});0<d.length&&b.push({xtype:"fieldset",collapsible:!0,
collapsed:!0,title:a.localize("exportGridCurrent"),items:d});if((!a.getExportVisualization||a.getExportVisualization())&&0==a.isXType("grid")&&(a.down("chart")||a.getTargetEl().dom.querySelector("canvas")||a.getTargetEl().dom.querySelector("svg"))){var e=[{xtype:"radio",name:"export",inputValue:"png",boxLabel:a.localize("exportPng")},{xtype:"slider",width:200,value:1,minValue:.5,maxValue:10,increment:.5,labelAlign:"right",decimalPrecision:1,itemId:"scale",fieldLabel:(new Ext.Template(a.localize("scaleLabel"))).apply([1]),
listeners:{change:function(f,g){this.setFieldLabel((new Ext.Template(a.localize("scaleLabel"))).apply([g]))},changecomplete:function(f){f.previousSibling().setValue(!0)}}}];a.getTargetEl().dom.querySelector("svg")&&e.push({xtype:"radio",name:"export",inputValue:"svg",boxLabel:a.localize("exportSvg")});b.push({xtype:"fieldset",collapsible:!0,collapsed:!0,title:a.localize("exportVizTitle"),items:e})}Ext.create("Ext.window.Window",{title:a.localize("exportTitle"),modal:!0,items:{xtype:"form",items:b,
buttons:[{text:a.localize("exportTitle"),glyph:"xf08e@FontAwesome",flex:1,panel:a,handler:function(f){var g=f.up("form"),h="export"+Ext.String.capitalize(g.getValues()["export"]);Ext.isFunction(a[h])?a[h].call(a,a,g):Ext.Msg.show({title:a.localize("exportError"),message:a.localize("exportNoFunction"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR});f.up("window").close()},scope:a},{text:a.localize("cancelTitle"),glyph:"xf00d@FontAwesome",flex:1,handler:function(f){f.up("window").close()}}]},bodyPadding:5}).show()},
exportSvg:function(a){if(a=this.getTargetEl().dom.querySelector("svg"))a=d3.select(a).attr("version",1.1).attr("xmlns","http://www.w3.org/2000/svg").node().parentNode.innerHTML,Ext.Msg.show({title:this.localize("exportSvgTitle"),message:'\x3cimg src\x3d"data:image/svg+xml;base64,'+btoa(unescape(encodeURIComponent(a)))+'" style\x3d"float: right; max-width: 200px; max-height: 200px; border: thin dotted #ccc;"/\x3e'+this.localize("exportSvgMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,
value:a})},exportPngData:function(a){Ext.Msg.show({title:this.localize("exportPngTitle"),message:'\x3cimg class\x3d"thumb" src\x3d"'+a+'" style\x3d"float: right; max-width: 200px; max-height: 200px; border: thin dotted #ccc;"/\x3e'+this.localize("exportPngMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:'\x3cimg src\x3d"'+a+'" /\x3e'})},exportPng:function(a,b){var c=1;b&&(b.mask(a.localize("loading")),(a=b.queryById("scale"))&&a.getValue&&(c=a.getValue()));var d=this.down("draw")||
this.down("chart");if(d&&(d.isChart||d.isCanvas)){var e=d.innerElement.getSize();a=Array.prototype.slice.call(d.items.items);var f=d.surfaceZIndexes,g;for(g=1;g<a.length;g++){var h=a[g];var k=f[h.type];for(d=g-1;0<=d&&f[a[d].type]>k;)a[d+1]=a[d],d--;a[d+1]=h}var l=document.createElement("canvas");f=Ext.getClassName(a[0]);c*=a[0].devicePixelRatio;var m=l.getContext("2d");l.width=Math.ceil(e.width*c);l.height=Math.ceil(e.height*c);for(d=0;d<a.length;d++)if(h=a[d],Ext.getClassName(h)===f)for(e=h.getRect(),
surfaceSize=h.el.getSize(),g=0;g<h.canvases.length;g++){var n=h.canvases[g];k=n.getOffsetsTo(n.getParent());m.drawImage(n.dom,(e[0]+k[0])*c,(e[1]+k[1])*c,surfaceSize.width*c,surfaceSize.height*c)}b&&b.isVisible()&&b.unmask();return this.exportPngData(l.toDataURL())}d=this.getTargetEl().dom;if(n=d.querySelector("canvas")){if(1==c)return c=n.toDataURL("image/png"),b&&b.isVisible()&&b.unmask(),this.exportPngData(c);l=document.createElement("canvas");m=l.getContext("2d");l.width=Math.ceil(n.width*c);
l.height=Math.ceil(n.height*c);var u=new Image;u.src=n.toDataURL("image/png");u.panel=this;u.onload=function(){m.drawImage(u,0,0,l.width,l.height);p=l.toDataURL("image/png");b&&b.isVisible()&&b.unmask();this.panel.exportPngData.call(this.panel,p)}}else if(g=d.querySelector("svg")){a=d.offsetWidth*c;d=d.offsetHeight*c;g=g.cloneNode(!0);g.setAttribute("version",1.1);g.setAttribute("xmlns","http://www.w3.org/2000/svg");g.setAttribute("width",a);g.setAttribute("height",d);for(h=[];0<g.children.length;)h.push(g.removeChild(g.children[0]));
var w=document.createElement("g");w.setAttribute("style","transform-box: fill-box;");w.setAttribute("transform","scale("+c+")");g.appendChild(w);h.forEach(function(r){w.appendChild(r)});var p="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(g.outerHTML)));n=Ext.DomHelper.createDom({tag:"canvas",width:a,height:d});var q=n.getContext("2d");u=new Image;u.src=p;u.panel=this;u.onload=function(){q.drawImage(u,0,0);p=n.toDataURL("image/png");b&&b.isVisible()&&b.unmask();return this.panel.exportPngData.call(this.panel,
p)}}},exportUrl:function(){this.openUrl(this.getExportUrl())},exportEmbed:function(){var a=0==this.isXType("voyantheader");Ext.Msg.show({title:this.localize("exportViewEmbedTitle"),message:this.localize("exportViewEmbedMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:"\x3c!--\tExported from Voyant Tools (voyant-tools.org).\nThe iframe src attribute below uses a relative protocol to better function with both\nhttp and https sites, but if you're embedding this into a local web page (file protocol)\nyou should add an explicit protocol (https if you're using voyant-tools.org, otherwise\nit depends on this server.\nFeel free to change the height and width values or other styling below: --\x3e\n\x3ciframe style\x3d'width: "+
(a?this.getWidth()+"px":"100%")+"; height: "+(a?this.getHeight()+"px":"800px")+";' src\x3d'"+this.getExportUrl(a)+"'\x3e\x3c/iframe\x3e"})},exportBiblio:function(){var a=new Date,b=this.getExportUrl(),c=this.isXType("voyantheader")?"Voyant Tools":this.localize("title");Ext.Msg.show({title:this.localize("exportBiblioTitle"),minHeight:525,message:'\x3cfieldset\x3e\x3clegend\x3eMLA\x3c/legend\x3e\x3cdiv class\x3d"x-selectable"\x3eSinclair, St\u00e9fan and Geoffrey Rockwell. "'+c+'." \x3ci\x3eVoyant Tools\x3c/i\x3e. '+
Ext.Date.format(a,"Y")+". Web. "+Ext.Date.format(a,"j M Y")+". \x26lt;"+b+'\x26gt;.\x3c/div\x3e\x3c/fieldset\x3e\x3cbr \x3e\x3cfieldset\x3e\x3clegend\x3eChicago\x3c/legend\x3e\x3cdiv class\x3d"x-selectable"\x3eSt\u00e9fan Sinclair and Geoffrey Rockwell, "'+c+'", \x3ci\x3eVoyant Tools\x3c/i\x3e, accessed '+Ext.Date.format(a,"F j, Y")+", "+b+'.\x3c/div\x3e\x3c/fieldset\x3e\x3cbr \x3e\x3cfieldset\x3e\x3clegend\x3eAPA\x3c/legend\x3e\x3cdiv class\x3d"x-selectable"\x3eSinclair, S. \x26amp; G. Rockwell. ('+
Ext.Date.format(a,"Y")+"). "+c+". \x3ci\x3eVoyant Tools\x3c/i\x3e. Retrieved "+Ext.Date.format(a,"F j, Y")+", from "+b+'\x3c/div\x3e\x3c/fieldset\x3e\x3cbr \x3e\x3cfieldset\x3e\x3clegend\x3eBibTeX\x3c/legend\x3e\x3cdiv class\x3d"x-selectable"\x3e'+this.getExportBibTex()+"\x3c/div\x3e\x3c/fieldset\x3e",buttons:Ext.Msg.OK,icon:Ext.Msg.INFO}).getEl().query("fieldset \x3e div",!1).forEach(function(d){d.on("click",function(e,f){var g=window.document;window.getSelection&&g.createRange?(e=window.getSelection(),
g=g.createRange(),g.selectNodeContents(f),e.removeAllRanges(),e.addRange(g)):g.body.createTextRange&&(g=g.body.createTextRange(),g.moveToElementText(f),g.select())})})},exportSpyral:function(){var a=Ext.getClassName(this).split(".").pop(),b=this.getApplication().getModifiedApiParams();0==this.isXType("voyantheader")&&(delete b.panels,Ext.apply(b,this.getModifiedApiParams()),delete b.corpus);var c=b&&"debug"in b;delete b.view;delete b.debug;a="['\x3ch1\x3eSpyral Notebook Imported from Voyant Tools\x3c/h1\x3e','\x3cp\x3eThe proceeding code loads your corpus and tool. You can use this as a base to create your own notebook. Don\\'t forget to save your changes by clicking on the cloud icon!\x3c/p\x3e','loadCorpus(\""+
this.getApplication().getCorpus().getAliasOrId()+'").tool("'+("VoyantHeader"==a?"":a)+'"'+(0<Object.keys(b).length?","+Ext.encode(b):"")+");']";this.openUrl(this.getApplication().getBaseUrl()+"spyral/?run\x3dtrue\x26"+(c?"debug\x3dtrue\x26":"")+"inputJsonArrayOfEncodedBase64\x3d"+btoa(encodeURIComponent(a)).replace(/=/g,"%3D"))},exportGridCurrentJson:function(a,b){function c(e){var f={};d.forEach(function(g){f[g.text]=e.get(g.dataIndex)});values.push(f)}b=a.getStore();b.getFields();var d=a.getColumnManager().headerCt.getVisibleGridColumns().filter(function(e){return e.dataIndex&&
0<e.dataIndex.trim().length});values=[];b.buffered?b.data.forEach(c):b.each(c);Ext.Msg.show({title:this.localize("exportDataTitle"),message:this.localize("exportDataJsonMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:Ext.encode(values)})},exportGridCurrentTsv:function(a,b){function c(g){var h=[];d.forEach(function(k){k=g.get(k.dataIndex);Ext.isString(k)&&(k=k.replace(/\s+/g," "));h.push(k)});f+=h.join("\t")+"\n"}b=a.getStore();var d=a.getColumnManager().headerCt.getVisibleGridColumns().filter(function(g){return g.dataIndex&&
0<g.dataIndex.trim().length}),e=[];d.forEach(function(g){e.push(g.text)});var f=e.join("\t")+"\n";b.buffered?b.data.forEach(c):b.each(c);Ext.Msg.show({title:this.localize("exportDataTitle"),message:this.localize("exportDataTsvMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:f})},exportGridCurrentHtml:function(a,b){function c(f){d+="\t\t\x3ctr\x3e\n";e.forEach(function(g){g=f.get(g.dataIndex);Ext.isString(g)&&(g=g.replace(/&/g,"\x26amp;").replace(/</g,"\x26lt;").replace(/>/g,
"\x26lg;"));d+="\t\t\t\x3ctd\x3e"+g+"\x3c/td\x3e\n"});d+="\t\t\x3c/tr\x3e\n"}b=a.getStore();b.getFields();var d="\x3ctable\x3e\n\t\x3cthead\x3e\n\t\t\x3ctr\x3e\n",e=a.getColumnManager().headerCt.getVisibleGridColumns().filter(function(f){return f.dataIndex&&0<f.dataIndex.trim().length});e.forEach(function(f){d+="\t\t\t\x3ctd\x3e"+f.text+"\x3c/td\x3e\n"});d+="\t\t\x3c/tr\x3e\n\t\x3c/thead\x3e\n\t\x3ctbody\x3e\n";b.buffered?b.data.forEach(c):b.each(c);d+="\t\x3c/tbody\x3e\n\x3c/table\x3e";Ext.Msg.show({title:this.localize("exportDataTitle"),
message:this.localize("exportDataHtmlMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:d})},exportGridAllJson:function(a,b){Ext.Msg.confirm(this.localize("exportAllTitle"),this.localize("exportAllJsonWarning"),function(c){"yes"==c&&(c={start:0},Ext.applyIf(c,a.getStore().getProxy().getExtraParams()),this.openUrl(this.getTromboneUrl()+"?"+Ext.Object.toQueryString(c)))},this)},exportGridAllTsv:function(a,b){Ext.Msg.confirm(this.localize("exportAllTitle"),this.localize("exportAllTsvWarning"),
function(c){"yes"==c&&(c={start:0,template:this.getXType()+"2tsv",outputFormat:"text"},Ext.applyIf(c,a.getStore().getProxy().getExtraParams()),this.openUrl(this.getTromboneUrl()+"?"+Ext.Object.toQueryString(c)))},this)},getExportUrl:function(a){var b=this.getApplication().getModifiedApiParams(),c=Ext.getClassName(this).split(".").pop();0==this.isXType("voyantheader")&&(delete b.panels,Ext.apply(b,this.getModifiedApiParams()),a||(b.view=c));b.corpus||(b.corpus=this.getApplication().getCorpus().getAliasOrId());
return this.getApplication().getBaseUrl()+(a?"tool/"+c+"/":"")+"?"+Ext.Object.toQueryString(b)},getExportBibTex:function(){var a=this.getExportUrl(),b=this.getApplication().getCorpus(),c=this.isXType("voyantheader")?"Voyant Tools":this.localize("title"),d="Voyant Tools analysis of ";d=""===b.getTitle()?d+"a corpus":d+('the corpus "'+b.getTitle()+'"');!1===this.isXType("voyantheader")&&(d+=" using the "+this.localize("title")+" tool");var e=new Date;b=Ext.Date.format(e,"Y-m-d");var f=new Date(this.getApplication().getCorpus().getCreatedTime()),
g=this.getApiParam("lang")||"en";e=["@misc{voyanttools_"+e.getTime()+","];e.push("title \x3d {"+c+"},");e.push("author \x3d {Sinclair, St\u00e9fan and Rockwell, Geoffrey},");e.push("year \x3d "+f.getFullYear()+",");e.push("url \x3d {"+a+"},");e.push("urldate \x3d {"+b+"},");e.push("publisher \x3d {Voyant Tools},");e.push("copyright \x3d {CC BY 4.0},");e.push("abstract \x3d {"+d+"},");e.push("language \x3d {"+g+"},");return e.join("\x3cbr/\x3e\x26nbsp;\x26nbsp;")+"\x3cbr/\x3e}"},helpToolClick:function(a){a.isXType("voyanttabpanel")&&
(a=a.getActiveTab());var b=a.localize("help",{"default":!1})||a.localize("helpTip");b==a._localizeClass(Ext.ClassManager.get("Voyant.util.Toolable"),"helpTip")?a.openUrl(a.getBaseUrl()+"docs/#!/guide/"+a.getXType()):Ext.Msg.alert(a.localize("title"),b+"\x3cp\x3e\x3ca href\x3d'"+a.getBaseUrl()+"docs/"+(a.isXType("voyantheader")?"":"#!/guide/"+a.getXType())+"' target\x3d'voyantdocs'\x3e"+a.localize("moreHelp")+"\x3c/a\x3e\x3c/p\x3e")},replacePanel:function(a){var b=this.getApplication().getCorpus();
this.getInitialConfig();if(this.isXType("voyantheader")&&this.getApplication().getViewComponent){var c=this.getApplication().getViewComponent();c.removeAll(!0);c.add({xtype:a});b&&this.getApplication().dispatchEvent("loadedCorpus",c,b);c=Ext.Object.fromQueryString(document.location.search);var d=this.getApplication().getBaseUrl();d+="?corpus\x3d"+b.getAliasOrId();d+="\x26view\x3d"+a;for(var e in c)"corpus"!==e&&"view"!==e&&(d+="\x26"+e+"\x3d"+c[e]);window.history.pushState({corpus:b.getAliasOrId(),
view:a},"",d)}else c=this.isXType("voyantheader")&&this.getApplication().getViewComponent?this.getApplication().getViewComponent():this.up("component"),c.remove(this,!0),a=c.add({xtype:a}),c.isXType("voyanttabpanel")&&c.setActiveTab(a),b&&a.fireEvent("loadedCorpus",a,b);this.getApplication().dispatchEvent("panelChange",this)}});
Ext.define("Voyant.util.ToolMenu",{extend:"Ext.panel.Tool",alias:"widget.toolmenu",renderTpl:['\x3cdiv class\x3d"x-menu-tool-hover"\x3e\x3c/div\x3e\x3ctpl if\x3d"glyph"\x3e\x3cspan id\x3d"{id}-toolEl" class\x3d"{baseCls}-glyph {childElCls}" role\x3d"presentation" style\x3d"font-family: {glyphFontFamily}; \x3ctpl if\x3d"Ext.os.name\x3d\x3d\'iOS\'"\x3emargin-right: 15px; \x3c/tpl\x3e"\x3e\x26#{glyph}\x3c/span\x3e\x3ctpl else\x3e\x3cimg id\x3d"{id}-toolEl" src\x3d"{blank}" class\x3d"{baseCls}-img {baseCls}-{type}{childElCls}" role\x3d"presentation"/\x3e\x3c/tpl\x3e'],privates:{onClick:function(){var a=
this.callParent(arguments);a&&this.showToolMenu.call(this);return a},onDestroy:function(){Ext.destroyMembers(this,"toolMenu");this.callParent()}},showToolMenu:function(){if(this.items&&0<this.items.length){if(!this.toolMenu||this.toolMenu.destroyed)this.toolMenu=new Ext.menu.Menu({items:this.items});this.toolMenu.showAt(0,0);this.toolMenu.showAt(this.getX()+this.getWidth()-this.toolMenu.getWidth(),this.getY()+this.getHeight()+10)}},initComponent:function(){this.callParent(arguments);var a=this.glyph||
"xf12e@FontAwesome";if("string"===typeof a){var b=a.split("@");a=b[0];b=b[1]}else"object"===typeof a&&a.glyphConfig&&(b=a.glyphConfig.split("@"),a=b[0],b=b[1]);Ext.applyIf(this.renderData,{baseCls:this.baseCls,blank:Ext.BLANK_IMAGE_URL,type:this.type,glyph:a,glyphFontFamily:b})}});Ext.define("Voyant.util.Transferable",{transferable:["transfer"],transfer:function(a,b){if(a.transferable)for(var c=0;c<a.transferable.length;c++){var d=a.transferable[c];b[d]=Ext.bind(a[d],b)}if(a.mixins)for(mixin in a.mixins)this.transfer(a.mixins[mixin],b)}});Ext.define("Voyant.util.Variants",{extend:"Ext.Base",constructor:function(a){this.variants=a;this.map={};this.variants.forEach(function(b,c){b.forEach(function(d){this.map[d]=c},this)},this)},getVariants:function(a){var b=[];Ext.isString(a)&&(a=[a]);Ext.isArray(a)&&a.forEach(function(c){void 0!=this.map[c]&&b.push.apply(b,this.variants[this.map[c]])},this);return b}});Ext.define("Voyant.util.Downloadable",{mixins:["Voyant.util.Localization"],statics:{i18n:{},api:{documentFormat:void 0,documentFilename:void 0}},downloadFromCorpusId:function(a){var b=this;Ext.create("Ext.window.Window",{title:this.localize("exportTitle"),modal:!0,items:{xtype:"form",items:{xtype:"downloadoptions"},listeners:{afterrender:function(c){c.getForm().setValues(b.getApiParams(["documentFilename","documentFormat"]))}},buttons:[{text:this.localize("cancelButton"),glyph:"xf00d@FontAwesome",
flex:1,ui:"default-toolbar",handler:function(c){c.up("window").close()}},{text:this.localize("downloadButton"),glyph:"xf00c@FontAwesome",flex:1,handler:function(c){var d=c.up("form").getValues();b.setApiParams(d);b.openDownloadCorpus(a);c.up("window").close()},scope:this}]},bodyPadding:5}).show()},openDownloadCorpus:function(a){a=this.getTromboneUrl()+"?corpus\x3d"+a+"\x26tool\x3dcorpus.CorpusExporter\x26outputFormat\x3dzip\x26zipFilename\x3dDownloadedVoyantCorpus-"+a+".zip"+(this.getApiParam("documentFormat")?
"\x26documentFormat\x3d"+this.getApiParam("documentFormat"):"")+(this.getApiParam("documentFilename")?"\x26documentFilename\x3d"+this.getApiParam("documentFilename"):"");this.openUrl(a)}});Ext.define("Voyant.util.Storage",{MAX_LENGTH:95E4,storeResource:function(a,b){var c=Ext.encode(b);if(c.length>this.MAX_LENGTH){var d=new Ext.Deferred,e=Math.ceil(c.length/this.MAX_LENGTH),f=[];for(b=0;b<e;b++)f.push(a+"-chunk"+b);this._doStore(a+"-hasChunks",Ext.encode(f)).then(function(){for(var g=0,h=0,k=0;k<e;k++){var l=c.substr(h,this.MAX_LENGTH);this._doStore(f[k],l).then(function(){g++;g==e&&d.resolve()},function(){d.reject()},null,this);h+=this.MAX_LENGTH}},function(){d.reject()},null,this);
return d.promise}return this._doStore(a,c)},_doStore:function(a,b){var c=new Ext.Deferred;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",resourceId:a,storeResource:b}}).then(function(d){c.resolve()},function(d){c.reject()});return c.promise},getStoredResource:function(a){var b=new Ext.Deferred;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",verifyResourceId:a+"-hasChunks"}}).then(function(c){(c=Ext.decode(c.responseText))&&c.storedResource&&
c.storedResource.id&&""!=c.storedResource.id?this._doGetStored(c.storedResource.id,!1).then(function(d){for(var e="",f={},g=0;g<d.length;g++)this._doGetStored(d[g],!0).then(function(h){f[h[0]]=h[1];h=!0;for(var k=d.length-1;0<=k;k--)if(void 0===f[d[k]]){h=!1;break}if(h){for(k=0;k<d.length;k++)e+=f[d[k]];b.resolve(Ext.decode(e))}},function(){b.reject()},null,this)},function(){b.reject()},null,this):this._doGetStored(a,!1).then(function(d){b.resolve(d)},function(){b.reject()},null,this)},function(){b.reject()},
null,this);return b.promise},_doGetStored:function(a,b){var c=new Ext.Deferred;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",retrieveResourceId:a,failQuietly:!0}}).then(function(d){var e=Ext.decode(d.responseText);d=e.storedResource.id;e=e.storedResource.resource;0==e.length?c.reject():1!=b?(e=Ext.decode(e),c.resolve(e)):c.resolve([d,e])},function(){c.reject()},null,this);return c.promise}});Ext.define("Voyant.util.DiacriticsRemover",{diacriticsMap:{},constructor:function(){var a=[{base:"A",letters:"A\u24b6\uff21\u00c0\u00c1\u00c2\u1ea6\u1ea4\u1eaa\u1ea8\u00c3\u0100\u0102\u1eb0\u1eae\u1eb4\u1eb2\u0226\u01e0\u00c4\u01de\u1ea2\u00c5\u01fa\u01cd\u0200\u0202\u1ea0\u1eac\u1eb6\u1e00\u0104\u023a\u2c6f"},{base:"AA",letters:"\ua732"},{base:"AE",letters:"\u00c6\u01fc\u01e2"},{base:"AO",letters:"\ua734"},{base:"AU",letters:"\ua736"},{base:"AV",letters:"\ua738\ua73a"},{base:"AY",letters:"\ua73c"},
{base:"B",letters:"B\u24b7\uff22\u1e02\u1e04\u1e06\u0243\u0182\u0181"},{base:"C",letters:"C\u24b8\uff23\u0106\u0108\u010a\u010c\u00c7\u1e08\u0187\u023b\ua73e"},{base:"D",letters:"D\u24b9\uff24\u1e0a\u010e\u1e0c\u1e10\u1e12\u1e0e\u0110\u018b\u018a\u0189\ua779\u00d0"},{base:"DZ",letters:"\u01f1\u01c4"},{base:"Dz",letters:"\u01f2\u01c5"},{base:"E",letters:"E\u24ba\uff25\u00c8\u00c9\u00ca\u1ec0\u1ebe\u1ec4\u1ec2\u1ebc\u0112\u1e14\u1e16\u0114\u0116\u00cb\u1eba\u011a\u0204\u0206\u1eb8\u1ec6\u0228\u1e1c\u0118\u1e18\u1e1a\u0190\u018e"},
{base:"F",letters:"F\u24bb\uff26\u1e1e\u0191\ua77b"},{base:"G",letters:"G\u24bc\uff27\u01f4\u011c\u1e20\u011e\u0120\u01e6\u0122\u01e4\u0193\ua7a0\ua77d\ua77e"},{base:"H",letters:"H\u24bd\uff28\u0124\u1e22\u1e26\u021e\u1e24\u1e28\u1e2a\u0126\u2c67\u2c75\ua78d"},{base:"I",letters:"I\u24be\uff29\u00cc\u00cd\u00ce\u0128\u012a\u012c\u0130\u00cf\u1e2e\u1ec8\u01cf\u0208\u020a\u1eca\u012e\u1e2c\u0197"},{base:"J",letters:"J\u24bf\uff2a\u0134\u0248"},{base:"K",letters:"K\u24c0\uff2b\u1e30\u01e8\u1e32\u0136\u1e34\u0198\u2c69\ua740\ua742\ua744\ua7a2"},
{base:"L",letters:"L\u24c1\uff2c\u013f\u0139\u013d\u1e36\u1e38\u013b\u1e3c\u1e3a\u0141\u023d\u2c62\u2c60\ua748\ua746\ua780"},{base:"LJ",letters:"\u01c7"},{base:"Lj",letters:"\u01c8"},{base:"M",letters:"M\u24c2\uff2d\u1e3e\u1e40\u1e42\u2c6e\u019c"},{base:"N",letters:"N\u24c3\uff2e\u01f8\u0143\u00d1\u1e44\u0147\u1e46\u0145\u1e4a\u1e48\u0220\u019d\ua790\ua7a4"},{base:"NJ",letters:"\u01ca"},{base:"Nj",letters:"\u01cb"},{base:"O",letters:"O\u24c4\uff2f\u00d2\u00d3\u00d4\u1ed2\u1ed0\u1ed6\u1ed4\u00d5\u1e4c\u022c\u1e4e\u014c\u1e50\u1e52\u014e\u022e\u0230\u00d6\u022a\u1ece\u0150\u01d1\u020c\u020e\u01a0\u1edc\u1eda\u1ee0\u1ede\u1ee2\u1ecc\u1ed8\u01ea\u01ec\u00d8\u01fe\u0186\u019f\ua74a\ua74c"},
{base:"OI",letters:"\u01a2"},{base:"OO",letters:"\ua74e"},{base:"OU",letters:"\u0222"},{base:"OE",letters:"\u008c\u0152"},{base:"oe",letters:"\u009c\u0153"},{base:"P",letters:"P\u24c5\uff30\u1e54\u1e56\u01a4\u2c63\ua750\ua752\ua754"},{base:"Q",letters:"Q\u24c6\uff31\ua756\ua758\u024a"},{base:"R",letters:"R\u24c7\uff32\u0154\u1e58\u0158\u0210\u0212\u1e5a\u1e5c\u0156\u1e5e\u024c\u2c64\ua75a\ua7a6\ua782"},{base:"S",letters:"S\u24c8\uff33\u1e9e\u015a\u1e64\u015c\u1e60\u0160\u1e66\u1e62\u1e68\u0218\u015e\u2c7e\ua7a8\ua784"},
{base:"T",letters:"T\u24c9\uff34\u1e6a\u0164\u1e6c\u021a\u0162\u1e70\u1e6e\u0166\u01ac\u01ae\u023e\ua786"},{base:"TZ",letters:"\ua728"},{base:"U",letters:"U\u24ca\uff35\u00d9\u00da\u00db\u0168\u1e78\u016a\u1e7a\u016c\u00dc\u01db\u01d7\u01d5\u01d9\u1ee6\u016e\u0170\u01d3\u0214\u0216\u01af\u1eea\u1ee8\u1eee\u1eec\u1ef0\u1ee4\u1e72\u0172\u1e76\u1e74\u0244"},{base:"V",letters:"V\u24cb\uff36\u1e7c\u1e7e\u01b2\ua75e\u0245"},{base:"VY",letters:"\ua760"},{base:"W",letters:"W\u24cc\uff37\u1e80\u1e82\u0174\u1e86\u1e84\u1e88\u2c72"},
{base:"X",letters:"X\u24cd\uff38\u1e8a\u1e8c"},{base:"Y",letters:"Y\u24ce\uff39\u1ef2\u00dd\u0176\u1ef8\u0232\u1e8e\u0178\u1ef6\u1ef4\u01b3\u024e\u1efe"},{base:"Z",letters:"Z\u24cf\uff3a\u0179\u1e90\u017b\u017d\u1e92\u1e94\u01b5\u0224\u2c7f\u2c6b\ua762"},{base:"a",letters:"a\u24d0\uff41\u1e9a\u00e0\u00e1\u00e2\u1ea7\u1ea5\u1eab\u1ea9\u00e3\u0101\u0103\u1eb1\u1eaf\u1eb5\u1eb3\u0227\u01e1\u00e4\u01df\u1ea3\u00e5\u01fb\u01ce\u0201\u0203\u1ea1\u1ead\u1eb7\u1e01\u0105\u2c65\u0250"},{base:"aa",letters:"\ua733"},
{base:"ae",letters:"\u00e6\u01fd\u01e3"},{base:"ao",letters:"\ua735"},{base:"au",letters:"\ua737"},{base:"av",letters:"\ua739\ua73b"},{base:"ay",letters:"\ua73d"},{base:"b",letters:"b\u24d1\uff42\u1e03\u1e05\u1e07\u0180\u0183\u0253"},{base:"c",letters:"c\u24d2\uff43\u0107\u0109\u010b\u010d\u00e7\u1e09\u0188\u023c\ua73f\u2184"},{base:"d",letters:"d\u24d3\uff44\u1e0b\u010f\u1e0d\u1e11\u1e13\u1e0f\u0111\u018c\u0256\u0257\ua77a"},{base:"dz",letters:"\u01f3\u01c6"},{base:"e",letters:"e\u24d4\uff45\u00e8\u00e9\u00ea\u1ec1\u1ebf\u1ec5\u1ec3\u1ebd\u0113\u1e15\u1e17\u0115\u0117\u00eb\u1ebb\u011b\u0205\u0207\u1eb9\u1ec7\u0229\u1e1d\u0119\u1e19\u1e1b\u0247\u025b\u01dd"},
{base:"f",letters:"f\u24d5\uff46\u1e1f\u0192\ua77c"},{base:"g",letters:"g\u24d6\uff47\u01f5\u011d\u1e21\u011f\u0121\u01e7\u0123\u01e5\u0260\ua7a1\u1d79\ua77f"},{base:"h",letters:"h\u24d7\uff48\u0125\u1e23\u1e27\u021f\u1e25\u1e29\u1e2b\u1e96\u0127\u2c68\u2c76\u0265"},{base:"hv",letters:"\u0195"},{base:"i",letters:"i\u24d8\uff49\u00ec\u00ed\u00ee\u0129\u012b\u012d\u00ef\u1e2f\u1ec9\u01d0\u0209\u020b\u1ecb\u012f\u1e2d\u0268\u0131"},{base:"j",letters:"j\u24d9\uff4a\u0135\u01f0\u0249"},{base:"k",letters:"k\u24da\uff4b\u1e31\u01e9\u1e33\u0137\u1e35\u0199\u2c6a\ua741\ua743\ua745\ua7a3"},
{base:"l",letters:"l\u24db\uff4c\u0140\u013a\u013e\u1e37\u1e39\u013c\u1e3d\u1e3b\u017f\u0142\u019a\u026b\u2c61\ua749\ua781\ua747"},{base:"lj",letters:"\u01c9"},{base:"m",letters:"m\u24dc\uff4d\u1e3f\u1e41\u1e43\u0271\u026f"},{base:"n",letters:"n\u24dd\uff4e\u01f9\u0144\u00f1\u1e45\u0148\u1e47\u0146\u1e4b\u1e49\u019e\u0272\u0149\ua791\ua7a5"},{base:"nj",letters:"\u01cc"},{base:"o",letters:"o\u24de\uff4f\u00f2\u00f3\u00f4\u1ed3\u1ed1\u1ed7\u1ed5\u00f5\u1e4d\u022d\u1e4f\u014d\u1e51\u1e53\u014f\u022f\u0231\u00f6\u022b\u1ecf\u0151\u01d2\u020d\u020f\u01a1\u1edd\u1edb\u1ee1\u1edf\u1ee3\u1ecd\u1ed9\u01eb\u01ed\u00f8\u01ff\u0254\ua74b\ua74d\u0275"},
{base:"oi",letters:"\u01a3"},{base:"ou",letters:"\u0223"},{base:"oo",letters:"\ua74f"},{base:"p",letters:"p\u24df\uff50\u1e55\u1e57\u01a5\u1d7d\ua751\ua753\ua755"},{base:"q",letters:"q\u24e0\uff51\u024b\ua757\ua759"},{base:"r",letters:"r\u24e1\uff52\u0155\u1e59\u0159\u0211\u0213\u1e5b\u1e5d\u0157\u1e5f\u024d\u027d\ua75b\ua7a7\ua783"},{base:"s",letters:"s\u24e2\uff53\u00df\u015b\u1e65\u015d\u1e61\u0161\u1e67\u1e63\u1e69\u0219\u015f\u023f\ua7a9\ua785\u1e9b"},{base:"t",letters:"t\u24e3\uff54\u1e6b\u1e97\u0165\u1e6d\u021b\u0163\u1e71\u1e6f\u0167\u01ad\u0288\u2c66\ua787"},
{base:"tz",letters:"\ua729"},{base:"u",letters:"u\u24e4\uff55\u00f9\u00fa\u00fb\u0169\u1e79\u016b\u1e7b\u016d\u00fc\u01dc\u01d8\u01d6\u01da\u1ee7\u016f\u0171\u01d4\u0215\u0217\u01b0\u1eeb\u1ee9\u1eef\u1eed\u1ef1\u1ee5\u1e73\u0173\u1e77\u1e75\u0289"},{base:"v",letters:"v\u24e5\uff56\u1e7d\u1e7f\u028b\ua75f\u028c"},{base:"vy",letters:"\ua761"},{base:"w",letters:"w\u24e6\uff57\u1e81\u1e83\u0175\u1e87\u1e85\u1e98\u1e89\u2c73"},{base:"x",letters:"x\u24e7\uff58\u1e8b\u1e8d"},{base:"y",letters:"y\u24e8\uff59\u1ef3\u00fd\u0177\u1ef9\u0233\u1e8f\u00ff\u1ef7\u1e99\u1ef5\u01b4\u024f\u1eff"},
{base:"z",letters:"z\u24e9\uff5a\u017a\u1e91\u017c\u017e\u1e93\u1e95\u01b6\u0225\u0240\u2c6c\ua763"}];this.diacriticsMap={};for(var b=0;b<a.length;b++)for(var c=a[b].letters,d=0;d<c.length;d++)this.diacriticsMap[c[d]]=a[b].base},removeDiacritics:function(a){return a.replace(/[^\u0000-\u007E]/g,function(b){return this.diacriticsMap[b]||b}.bind(this))}});Ext.define("Voyant.data.model.AnalysisToken",{extend:"Ext.data.Model",idProperty:"term",fields:[{name:"term"},{name:"rawFreq",type:"int"},{name:"relativeFreq",type:"number"},{name:"cluster",type:"int"},{name:"clusterCenter",type:"boolean"},{name:"vector"}]});Ext.define("Voyant.data.model.Context",{extend:"Ext.data.Model",fields:[{name:"id"},{name:"docIndex",type:"int"},{name:"position",type:"int"},{name:"docId"},{name:"left"},{name:"keyword"},{name:"term"},{name:"right"}],getDocIndex:function(){return this.get("docIndex")},getLeft:function(){return this.get("left")},getMiddle:function(){return this.get("middle")},getHighlightedMiddle:function(){return"\x3cspan class\x3d'keyword'\x3e"+this.getMiddle()+"\x3c/span\x3e"},getRight:function(){return this.get("right")},
getPosition:function(){return this.get("position")},getHighlightedContext:function(){return this.getLeft()+this.getHighlightedMiddle()+this.getRight()}});Ext.define("Voyant.data.model.CorpusFacet",{extend:"Ext.data.Model",idProperty:"label",fields:[{name:"facet"},{name:"label"},{name:"inDocumentsCount",type:"int"}],getLabel:function(){return this.get("label")},getFacet:function(){return this.get("facet")},getInDocumentsCount:function(){return this.get("inDocumentsCount")}});Ext.define("Voyant.data.model.CorpusCollocate",{extend:"Ext.data.Model",fields:[{name:"term"},{name:"rawFreq",type:"int"},{name:"contextTerm"},{name:"contextTermRawFreq",type:"int"}],getTerm:function(){return this.getKeyword()},getRawFreq:function(){return this.getKeywordRawFreq()},getKeyword:function(){return this.get("term")},getKeywordRawFreq:function(){return this.get("rawFreq")},getContextTerm:function(){return this.get("contextTerm")},getContextTermRawFreq:function(){return this.get("contextTermRawFreq")}});Ext.define("Voyant.data.model.CorpusTerm",{extend:"Ext.data.Model",idProperty:"term",fields:[{name:"id"},{name:"rawFreq",type:"int"},{name:"inDocumentsCount",type:"int"},{name:"relativeFreq",type:"float"},{name:"relativePeakedness",type:"float"},{name:"relativeSkewness",type:"float"},{name:"comparisonRelativeFreqDifference",type:"float"},{name:"distributions"},{name:"typeTokenRatio-lexical",type:"float",calculate:function(a){return a["typesCount-lexical"]/a["tokensCount-lexical"]}}],getTerm:function(){return this.get("term")},
getRawFreq:function(){return parseInt(this.get("rawFreq"))},getInDocumentsCount:function(){return parseInt(this.get("inDocumentsCount"))},getDistributions:function(){return this.get("distributions")},show:function(a){show(this.getString(a))},getString:function(){return this.getTerm()+": "+this.getRawFreq()}});Ext.define("Voyant.data.model.CorpusNgram",{extend:"Ext.data.Model",fields:[{name:"term"},{name:"length",type:"int"},{name:"rawFreq",type:"int"},{name:"distributions"}],getTerm:function(){return this.get("term")}});Ext.define("Voyant.data.model.Dimension",{extend:"Ext.data.Model",fields:[{name:"percentage",type:"number"}]});Ext.define("Voyant.data.model.Document",{extend:"Ext.data.Model",fields:[{name:"corpus"},{name:"id"},{name:"author"},{name:"pubDate"},{name:"publisher"},{name:"pubPlace"},{name:"keyword"},{name:"collection"},{name:"index",type:"int"},{name:"tokensCount-lexical",type:"int"},{name:"typesCount-lexical",type:"int"},{name:"typeTokenRatio-lexical",type:"float",calculate:function(a){return a["typesCount-lexical"]/a["tokensCount-lexical"]}},{name:"lastTokenStartOffset-lexical",type:"int"},{name:"title"},
{name:"language",convert:function(a){return Ext.isEmpty(a)?"":a}},{name:"sentencesCount",type:"int"},{name:"averageWordsPerSentence",type:"float",calculate:function(a){return a.sentencesCount?a["tokensCount-lexical"]/a.sentencesCount:0}},{name:"css",type:"string"}],getLexicalTokensCount:function(){return this.get("tokensCount-lexical")},getLexicalTypeTokenRatio:function(){return this.get("typeTokenRatio-lexical")},loadDocumentTerms:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)&&(a={limit:a});
Ext.applyIf(a,{limit:0});var c=this.getDocumentTerms();c.load({params:a,callback:function(d,e,f){f?b.resolve(c):b.reject(e)}});return b.promise},loadTokens:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)&&(a={limit:a});Ext.applyIf(a,{limit:0});var c=this.getTokens({});c.load({params:a,callback:function(d,e,f){f?b.resolve(c):b.reject(e)}});return b.promise},getTokens:function(a){a=a||{};Ext.applyIf(a,{proxy:{}});Ext.applyIf(a.proxy,{extraParams:{}});Ext.applyIf(a.proxy.extraParams,{docIndex:this.get("index")});
Ext.apply(a,{docId:this.get("id")});return this.get("corpus").getTokens(a)},getDocumentTerms:function(a){a=a||{};Ext.applyIf(a,{proxy:{}});Ext.applyIf(a.proxy,{extraParams:{}});Ext.applyIf(a.proxy.extraParams,{docIndex:this.get("index")});return a.corpus?a.corpus.getDocumentTerms(a):this.get("corpus").getDocumentTerms(a)},getIndex:function(){return this.get("index")},getId:function(){return this.get("id")},getFullLabel:function(){var a=this.getAuthor();return this.getTitle()+(a?"("+a+")":"")},getTitle:function(){var a=
this.get("title");void 0===a&&(a="");a=Ext.isArray(a)?a.join("; "):a;return a=a.trim().replace(/\s+/g," ")},getTruncated:function(a,b){if(a.length>b){var c=a.lastIndexOf("/");-1<c&&(a=a.substr(c+1));if(a.length>b){c=a.indexOf(" ",b-5);if(0>c||c>b)c=b;a=a.substring(0,c)+"\u2026"}}return a},getShortTitle:function(){var a=this.getTitle();a=a.replace(/\.(html?|txt|xml|docx?|pdf|rtf|\/)$/,"");a=a.replace(/^(the|a|le|l'|un|une)\s/,"");return this.getTruncated(a,25)},getTinyTitle:function(){return this.getTruncated(this.getShortTitle(),
10)},getShortLabel:function(){var a=this.getAuthor(25);return parseInt(this.getIndex())+1+") \x3ci\x3e"+this.getShortTitle()+"\x3c/i\x3e"+(a?" ("+a+")":"")},getTinyLabel:function(){return parseInt(this.getIndex())+1+") "+this.getTinyTitle()},getPubDate:function(){return this.get("pubDate")},getPublisher:function(){return this.get("publisher")},getPubPlace:function(){return this.get("pubPlace")},getKeyword:function(){return this.getMultiple("keyword")},getCollection:function(){return this.getMultiple("collection")},
getAuthor:function(a){return this.getMultiple("author")},getMultiple:function(a,b){a=this.get(a)||"";a=Ext.isArray(a)?a.join("; "):a;a=a.trim().replace(/\s+/g," ");return b?this.getTruncated(a,b):a},getCorpusId:function(){return this.get("corpus").getAliasOrId()},isPlainText:function(){return this.get("extra.Content-Type")&&RegExp("plain","i").test(this.get("extra.Content-Type"))?!0:!1},getAverageWordsPerSentence:function(){return this.get("averageWordsPerSentence")},show:function(){show(this.getFullLabel())},
getCorpus:function(){return this.get("corpus")},getText:function(a){a=a||{};Ext.apply(a,{docIndex:this.get("index")});return this.getCorpus().getText(a)},getPlainText:function(a){a=a||{};Ext.apply(a,{template:"docTokens2plainText",docIndex:this.get("index")});return this.getCorpus().getText(a)},getLemmasArray:function(a){a=a||{};a.docId=this.getId();return this.getCorpus().getLemmasArray(a)},getEntities:function(a){a=a||{};Ext.applyIf(a,{proxy:{}});Ext.applyIf(a.proxy,{extraParams:{}});Ext.applyIf(a.proxy.extraParams,
{docIndex:this.get("index")});return Ext.create("Voyant.data.store.DocumentEntities",Ext.apply(a,{corpus:this.getCorpus(),docId:this.getId()}))},loadEntities:function(a){var b=new Ext.Deferred;this.getEntities().load({params:a,callback:function(c,d,e){e?b.resolve(c):b.reject(d.error.response)}});return b.promise},getCSS:function(){return this.get("css")||this.get("parent_css")}});Ext.define("Voyant.data.model.DocumentEntity",{extend:"Ext.data.Model",fields:[{name:"term"},{name:"docIndex",type:"int"},{name:"rawFreq",type:"int"},{name:"type"},{name:"positions"},{name:"offsets"}],getTerm:function(){return this.get("term")},getDocIndex:function(){return this.get("docIndex")},getRawFreq:function(){return this.get("rawFreq")},getPositions:function(){return this.get("positions")},getOffsets:function(){return this.get("offsets")}});Ext.define("Voyant.data.model.DocumentQueryMatch",{extend:"Ext.data.Model",fields:[{name:"id"},{name:"count",type:"int"},{name:"query"},{name:"distributions"}],getCount:function(){return this.get("count")},getDistributions:function(){return this.get("distributions")},getDocIds:function(){return this.get("docIds")}});Ext.define("Voyant.data.model.DocumentTerm",{extend:"Ext.data.Model",fields:[{name:"id"},{name:"term"},{name:"docIndex",type:"int"},{name:"docId"},{name:"rawFreq",type:"int"},{name:"relativeFreq",type:"float"},{name:"tfidf",type:"float"},{name:"zscore",type:"float"},{name:"zscoreRatio",type:"float"},{name:"distributions"}],getTerm:function(){return this.get("term")},getDocIndex:function(){return this.get("docIndex")},getRawFreq:function(){return this.get("rawFreq")},getRelativeFreq:function(){return this.get("relativeFreq")},
getDistributions:function(){return this.get("distributions")}});Ext.define("Voyant.data.model.PrincipalComponent",{extend:"Ext.data.Model",fields:[{name:"eigenValue",type:"number"},{name:"eigenVectors"}]});Ext.define("Voyant.data.model.RelatedTerm",{extend:"Ext.data.Model",fields:[{name:"source"},{name:"target"},{name:"rawFreq",type:"int"}],getSource:function(){return this.get("source")},getTarget:function(){return this.get("target")},show:function(a){show(this.getString(a))},getString:function(){return this.getSource()+"-"+this.getTarget()}});Ext.define("Voyant.data.model.StatisticalAnalysis",{extend:"Ext.data.Model",requires:["Voyant.data.model.PrincipalComponent","Voyant.data.model.Dimension","Voyant.data.model.AnalysisToken"],fields:[{name:"id"}],getPrincipalComponents:function(){var a=[];this.data.principalComponents.forEach(function(b){a.push(Ext.create("Voyant.data.model.PrincipalComponent",b))});return a},getDimensions:function(){var a=[];this.data.dimensions.forEach(function(b){a.push(Ext.create("Voyant.data.model.Dimension",{percentage:b}))});
return a},getTokens:function(){var a=[];this.data.tokens.forEach(function(b){a.push(Ext.create("Voyant.data.model.AnalysisToken",b))});return a}});Ext.define("Voyant.data.model.Token",{extend:"Ext.data.Model",fields:[{name:"id"},{name:"docId"},{name:"docIndex",type:"int"},{name:"token"},{name:"rawFreq"},{name:"tokenType"},{name:"position",type:"int"},{name:"startOffset",type:"int"},{name:"endOffset",type:"int"}],statics:{getInfoFromElement:function(a){if(a&&a.id)return a=a.id.split("_"),{docIndex:parseInt(a[1]),position:parseInt(a[2])}}},isWord:function(){return"lexical"==this.getTokenType()},isStopword:function(){return"true"==this.get("stopword")},
getTokenType:function(){return this.get("tokenType")},getId:function(){return["",this.getDocIndex(),this.getPosition()].join("_")},getDocIndex:function(){return this.get("docIndex")},getDocId:function(){return this.get("docId")},getTerm:function(){return this.get("term")},getTermWithLineSpacing:function(a){var b=this.getTerm();return b=a?b.replace(/(\r\n|\r|\n)\s*/g,"\x3cbr /\x3e"):b.replace(/<\/?(.|\n|\r)*?>/gm,"\x3cbr /\x3e\x3cbr /\x3e").replace(/>\s+</g,"\x3e\x3c").replace(/<br \/><br \/>(<br \/>)+/g,
"\x3cbr /\x3e\x3cbr /\x3e")},getPosition:function(){return this.get("position")},getDocumentRawFreq:function(){return this.get("rawFreq")}});Ext.define("Voyant.data.model.TermCorrelation",{extend:"Ext.data.Model",fields:[{name:"source"},{name:"target"},{name:"correlation",type:"float"},{name:"significance",type:"float"},{name:"sourceTerm",calculate:function(a){return a.source.term}},{name:"targetTerm",calculate:function(a){return a.target.term}},{name:"source-distributions",calculate:function(a){return a.source.distributions}},{name:"target-distributions",calculate:function(a){return a.target.distributions}}],getSource:function(){return this.get("source")},
getTarget:function(){return this.get("target")},show:function(a){show(this.getString(a))},getString:function(){return this.getSource()+"-"+this.getTarget()}});Ext.define("Voyant.data.store.VoyantStore",{mixins:["Voyant.util.Localization"],config:{corpus:void 0,parentPanel:void 0},statics:{i18n:{maxTime:"This tool has exceeded the maximum run time and has returned partial results."}},constructor:function(a,b){var c=this;a=a||{};Ext.applyIf(a,{remoteSort:!0,autoLoad:!1,pagePurgeCount:0,pageSize:100,leadingBufferZone:200});a.proxy=a.proxy||{};Ext.applyIf(a.proxy,{type:"ajax",url:Voyant.application.getTromboneUrl(),actionMethods:{read:"POST"},timeout:b["proxy.timeout"]||
3E4,reader:{type:"json",rootProperty:b["proxy.reader.rootProperty"],totalProperty:b["proxy.reader.totalProperty"],metaProperty:b["proxy.reader.metaProperty"]||"metaData"},simpleSortMode:!0,listeners:{exception:function(d,e,f){c.parentPanel&&c.parentPanel.showError&&c.parentPanel.showError(f)},endprocessresponse:function(d,e,f){f.wasSuccessful()&&(d=d.getReader().initialConfig.rootProperty.split(".")[0],(e=JSON.parse(e.responseText)[d])&&e.messages&&(e=e.messages[0],e="maxTime"===e.code?c.localize("maxTime"):
e.message,c.parentPanel&&c.parentPanel.toastInfo?c.parentPanel.toastInfo(e):console.warn("VoyantStore server message: "+e)))}}});a.proxy.extraParams=a.proxy.extraParams||{};Ext.applyIf(a.proxy.extraParams,{tool:b["proxy.extraParams.tool"]});void 0!==a.parentPanel&&(Ext.applyIf(a.proxy.extraParams,{forTool:a.parentPanel.xtype}),this.setParentPanel(a.parentPanel),a.parentPanel.on("loadedCorpus",function(d,e){this.setCorpus(e)},this),a.listeners=a.listeners||{},a.listeners.beforeload={fn:function(d,
e){var f=this.getParentPanel(),g=d.getProxy();if(void 0!==f){d=f.getApiParams();e=e?1===e?{}:e:{};e.params=e.params||{};g&&this.isBufferedStore&&(Ext.Array.from(this.previouslySetExtraParams).forEach(function(k){g.setExtraParam(k,void 0)}),this.previouslySetExtraParams=[]);for(var h in d)g&&this.isBufferedStore&&(this.previouslySetExtraParams.push(h),g.setExtraParam(h,d[h])),e.params[h]=d[h]}},scope:this});Ext.apply(this,a)},setCorpus:function(a){a&&this.getProxy&&this.getProxy()&&this.getProxy().setExtraParam("corpus",
Ext.isString(a)?a:a.getId());this.callParent(arguments)},getString:function(a){a=this.getCount();return"This store contains "+this.getCount()+" items"+(0<a?" with these fields: "+this.getAt(0).getFields().map(function(b){return b.getName()}).join(", "):"")+"."}});Ext.define("Voyant.data.store.CAAnalysisMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.StatisticalAnalysis",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.CA","proxy.reader.rootProperty":"correspondenceAnalysis","proxy.reader.totalProperty":"correspondenceAnalysis.totalTerms"}]);a.proxy.extraParams.withDistributions=!0}});
Ext.define("Voyant.data.store.CAAnalysis",{extend:"Ext.data.Store",mixins:["Voyant.data.store.CAAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CAAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CAAnalysisBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.CAAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CAAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.ContextsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.Context",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentContexts","proxy.reader.rootProperty":"documentContexts.contexts","proxy.reader.totalProperty":"documentContexts.total"}])}});
Ext.define("Voyant.data.store.Contexts",{extend:"Ext.data.Store",mixins:["Voyant.data.store.ContextsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.ContextsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.ContextsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.ContextsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.ContextsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CorpusCollocatesMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.CorpusCollocate",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.CorpusCollocates","proxy.reader.rootProperty":"corpusCollocates.collocates","proxy.reader.totalProperty":"corpusCollocates.total"}])}});
Ext.define("Voyant.data.store.CorpusCollocates",{extend:"Ext.data.Store",mixins:["Voyant.data.store.CorpusCollocatesMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusCollocatesMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.CorpusCollocatesBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.CorpusCollocatesMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusCollocatesMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CorpusFacetsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:Voyant.data.model.CorpusFacet,constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.CorpusFacets","proxy.reader.rootProperty":"corpusFacets.facets","proxy.reader.totalProperty":"corpusFacets.total"}])}});
Ext.define("Voyant.data.store.CorpusFacets",{extend:"Ext.data.Store",mixins:["Voyant.data.store.CorpusFacetsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusFacetsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CorpusFacetsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.CorpusFacetsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusFacetsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CorpusTermsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:Voyant.data.model.CorpusTerm,constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.CorpusTerms","proxy.reader.rootProperty":"corpusTerms.terms","proxy.reader.totalProperty":"corpusTerms.total"}])},show:function(a){show(this.getString(a))}});
Ext.define("Voyant.data.store.CorpusTerms",{extend:"Ext.data.Store",mixins:["Voyant.data.store.CorpusTermsMixin"],model:Voyant.data.model.CorpusTerm,constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusTermsMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.CorpusTermsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.CorpusTermsMixin"],model:Voyant.data.model.CorpusTerm,constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusTermsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.DocumentQueryMatchesMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.DocumentQueryMatch",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentsFinder","proxy.reader.rootProperty":"documentsFinder.queries","proxy.reader.totalProperty":void 0,"proxy.reader.metaProperty":"documentsFinder.corpus"}])}});
Ext.define("Voyant.data.store.DocumentQueryMatches",{extend:"Ext.data.Store",mixins:["Voyant.data.store.DocumentQueryMatchesMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentQueryMatchesMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.DocumentQueryMatchesBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.DocumentQueryMatchesMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentQueryMatchesMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.DocumentTermsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.DocumentTerm",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentTerms","proxy.reader.rootProperty":"documentTerms.terms","proxy.reader.totalProperty":"documentTerms.total"}])}});
Ext.define("Voyant.data.store.DocumentTerms",{extend:"Ext.data.Store",mixins:["Voyant.data.store.DocumentTermsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentTermsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.DocumentTermsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.DocumentTermsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentTermsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.DocumentEntitiesMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.DocumentEntity",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentEntities","proxy.reader.rootProperty":"documentEntities.entities","proxy.reader.totalProperty":"documentEntities.total"}])}});
Ext.define("Voyant.data.store.DocumentEntities",{extend:"Ext.data.Store",mixins:["Voyant.data.store.DocumentEntitiesMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentEntitiesMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.DocumentEntitiesBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.DocumentEntitiesMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentEntitiesMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.DocumentsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.Document",statics:{i18n:{}},sorters:{property:"index",direction:"ASC"},remoteSort:!0,constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentsMetadata","proxy.reader.rootProperty":"documentsMetadata.documents","proxy.reader.totalProperty":"documentsMetadata.total"}])},listeners:{load:function(a,b,c,d){if(c){var e=
a.getCorpus();b.forEach(function(f){f.set("corpus",e)})}}},getDocument:function(a){return Ext.isNumber(a)?this.getAt(a):this.getById(a)}});Ext.define("Voyant.data.store.Documents",{extend:"Ext.data.Store",mixins:["Voyant.data.store.DocumentsMixin"],model:"Voyant.data.model.Document",constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentsMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.DocumentsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.DocumentsMixin"],model:"Voyant.data.model.Document",constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocumentsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.PCAAnalysisMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.StatisticalAnalysis",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.PCA","proxy.reader.rootProperty":"pcaAnalysis","proxy.reader.totalProperty":"pcaAnalysis.totalTerms"}]);a.proxy.extraParams.withDistributions=!0}});
Ext.define("Voyant.data.store.PCAAnalysis",{extend:"Ext.data.Store",mixins:["Voyant.data.store.PCAAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.PCAAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.PCAAnalysisBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.PCAAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.PCAAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.DocSimAnalysisMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.StatisticalAnalysis",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentSimilarity","proxy.reader.rootProperty":"documentSimilarity","proxy.reader.totalProperty":"documentSimilarity.total"}]);a.proxy.extraParams.withDistributions=!0}});
Ext.define("Voyant.data.store.DocSimAnalysis",{extend:"Ext.data.Store",mixins:["Voyant.data.store.DocSimAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocSimAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.DocSimAnalysisBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.DocSimAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.DocSimAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CorpusNgramsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.CorpusNgram",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.CorpusNgrams","proxy.reader.rootProperty":"corpusNgrams.ngrams","proxy.reader.totalProperty":"corpusNgrams.total","proxy.timeout":9E4}])}});
Ext.define("Voyant.data.store.CorpusNgrams",{extend:"Ext.data.Store",mixins:["Voyant.data.store.CorpusNgramsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusNgramsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.CorpusNgramsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.CorpusNgramsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.CorpusNgramsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.RelatedTermsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.RelatedTerm",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.SemanticGraph","proxy.reader.rootProperty":"semanticGraph.edges","proxy.reader.totalProperty":"semanticGraph.total"}])}});
Ext.define("Voyant.data.store.RelatedTerms",{extend:"Ext.data.Store",mixins:["Voyant.data.store.RelatedTermsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.RelatedTermsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.RelatedTermsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.RelatedTermsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.RelatedTermsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.TermCorrelationsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.TermCorrelation",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.CorpusTermCorrelations","proxy.extraParams.withDistributions":"true","proxy.reader.rootProperty":"termCorrelations.correlations","proxy.reader.totalProperty":"termCorrelations.total","proxy.timeout":9E4}])}});
Ext.define("Voyant.data.store.TermCorrelations",{extend:"Ext.data.Store",mixins:["Voyant.data.store.TermCorrelationsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.TermCorrelationsMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.TermCorrelationsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.TermCorrelationsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.TermCorrelationsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.TokensMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.Token",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.DocumentTokens","proxy.reader.rootProperty":"documentTokens.tokens","proxy.reader.totalProperty":"documentTokens.total"}])}});
Ext.define("Voyant.data.store.Tokens",{extend:"Ext.data.Store",mixins:["Voyant.data.store.TokensMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.TokensMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.TokensBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.TokensMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.TokensMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.TSNEAnalysisMixin",{mixins:["Voyant.data.store.VoyantStore"],model:"Voyant.data.model.StatisticalAnalysis",constructor:function(a){this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"corpus.TSNE","proxy.reader.rootProperty":"tsneAnalysis","proxy.reader.totalProperty":"tsneAnalysis.totalTerms"}]);a.proxy.extraParams.withDistributions=!0;a.proxy.extraParams.noCache=1}});
Ext.define("Voyant.data.store.TSNEAnalysis",{extend:"Ext.data.Store",mixins:["Voyant.data.store.TSNEAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.TSNEAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.store.TSNEAnalysisBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.TSNEAnalysisMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.TSNEAnalysisMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.model.NotebookFacet",{extend:"Ext.data.Model",idProperty:"label",fields:[{name:"facet"},{name:"label"},{name:"inDocumentsCount",type:"int"}],getLabel:function(){return this.get("label")},getFacet:function(){return this.get("facet")},getInDocumentsCount:function(){return this.get("inDocumentsCount")}});
Ext.define("Voyant.data.store.NotebookFacetsMixin",{mixins:["Voyant.data.store.VoyantStore"],model:Voyant.data.model.NotebookFacet,constructor:function(a){a.facet&&(void 0===a.proxy&&(a.proxy={}),void 0===a.proxy.extraParams&&(a.proxy.extraParams={}),a.proxy.extraParams.facet=a.facet,a.proxy.extraParams.noCache=1,delete a.facet);this.mixins["Voyant.data.store.VoyantStore"].constructor.apply(this,[a,{"proxy.extraParams.tool":"notebook.CatalogueFacets","proxy.reader.rootProperty":"catalogue.facets",
"proxy.reader.totalProperty":"catalogue.total"}])}});Ext.define("Voyant.data.store.NotebookFacets",{extend:"Ext.data.Store",mixins:["Voyant.data.store.NotebookFacetsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.NotebookFacetsMixin"].constructor.apply(this,[a]);this.callParent([a])}});
Ext.define("Voyant.data.store.NotebookFacetsBuffered",{extend:"Ext.data.BufferedStore",mixins:["Voyant.data.store.NotebookFacetsMixin"],constructor:function(a){a=a||{};this.mixins["Voyant.data.store.NotebookFacetsMixin"].constructor.apply(this,[a]);this.callParent([a])}});Ext.define("Voyant.data.table.Table",{alternateClassName:["VoyantTable"],config:{rows:[],headers:[],rowsMap:{},headersMap:{},rowKey:void 0,model:void 0},clone:function(){var a=new VoyantTable;a.setRows(Ext.clone(this.getRows()));a.setHeaders(Ext.clone(this.getHeaders()));a.setRowsMap(Ext.clone(this.getRowsMap()));a.setHeadersMap(Ext.clone(this.getHeadersMap()));a.setRowKey(Ext.clone(this.getRowKey()));return a},constructor:function(a,b){a=a||{};if(a.fromBlock){if(b=Voyant.notebook.Notebook.getDataFromBlock(a.fromBlock))b=
b.trim(),a.rows=[],b.split(/\n+/).forEach(function(f,g){f=f.split("\t");0!=g||a.noHeaders?a.rows.push(f):a.headers=f})}else if(a.count&&Ext.isArray(a.count)){var c={};a.count.forEach(function(f){c[f]=c[f]?c[f]+1:1});b=[];for(var d in c)b.push([d,c[d]]);b.sort(function(f,g){return g[1]-f[1]});a.limit&&b.length>a.limit&&b.splice(a.limit);a.orientation&&"horizontal"==a.orientation?(a.headers=b.map(function(f){return f[0]}),a.rows=[b.map(function(f){return f[1]})]):(a.headers=a.headers?a.headers:["Item",
"Count"],a.rows=b)}else if(a.isStore||a.store){d=a.store?a.store:a;if(b&&b.headers)a.headers=b.headers;else if(b=d.getAt(0))a.headers=b.getFields().map(function(f){return f.getName()});a.rows=[];d.each(function(f){var g=f.getData();f=a.headers.map(function(h){return g[h]});a.rows.push(f)},this)}!a.rows&&Ext.isArray(a)&&(a.rows=a);this.getHeaders()||(a.headers||a.noHeaders||!a.rows?this.setHeaders(Ext.Array.from(a.headers)):this.setHeaders(a.rows.shift()));this.setRows(Ext.Array.from(a.rows));this.setRowKey(a.rowKey?
a.rowKey:this.getHeaders()[0]);0==this.getHeaders().length&&(b=this.getRow(0,!1))&&this.setHeaders(b.map(function(f,g){return g}));var e={};this.getHeaders().forEach(function(f,g){e[f]=g});this.setHeadersMap(e);this.reMapRows();this.callParent()},addRow:function(a){if(Ext.isArray(a))if(Ext.isObject(a)){var b=this.getRows().length,c;for(c in a)this.updateCell(b,c,a[c])}else Ext.isArray(a)&&(this.getRows().push(a),b=this.getColumnIndex(this.getRowKey()),void 0!==b&&void 0!==a[b]&&(this.getRowsMap()[a[b]]=
this.getRows().length-1))},eachRecord:function(a,b){for(var c,d=0,e=this.getRows().length;d<e&&(c=this.getRecord(d),!1!==a.call(b||c,c,d,e));d++);},eachRow:function(a,b,c){for(var d,e=0,f=this.getRows().length;e<f&&(d=this.getRow(e,b),!1!==a.call(c||d,d,e,f));e++);},getRow:function(a,b){a=this.getRowIndex(a);if(b){var c={},d=this.getHeaders();Ext.Array.from(this.getRows()[a]).forEach(function(e,f){c[d[f]||f]=e},this);return c}return this.getRows()[a]},getRecord:function(a){if(this.model)return new this.model(this.getRow(a,
!0))},mapRows:function(a,b,c){var d=[];this.eachRow(function(e,f){d.push(a.call(c||this,e,f))},b,this);return d},updateCell:function(a,b,c,d){var e=this.getRows();a=Ext.isNumber(a)?a:this.getRowIndex(a);var f=this.getColumnIndex(b);void 0===e[a]&&(e[a]=[]);e[a][f]=void 0===e[a][f]||d?c:e[a][f]+c;this.getHeaders()[f]===this.getRowKey()&&(this.getRowsMap()[b]=a)},getRowIndex:function(a){if(Ext.isNumber(a))return a;if(Ext.isString(a)){var b=this.getRowsMap();a in b||(b[a]=this.getRows().length,this.getRows().push(Array(this.getHeaders().length)));
return b[a]}},getColumnIndex:function(a){var b=this.getHeaders();if(Ext.isNumber(a))return void 0===b[a]&&(b[a]=a,this.getRows().forEach(function(c){c.splice(a,0,void 0)})),a;if(Ext.isString(a))return a in this.getHeadersMap()||(this.getHeaders().push(a),this.getHeadersMap()[a]=this.getHeaders().length-1,this.getRows().forEach(function(c){c.push(void 0)})),this.getHeadersMap()[a]},getColumnHeader:function(a){a=this.getColumnIndex(a);return this.getHeaders()[a]},getColumnSum:function(a){return Ext.Array.sum(this.getColumnValues(a,
!0))},getColumnMean:function(a){return Ext.Array.mean(this.getColumnValues(a,!0))},getColumnMax:function(a){return Ext.Array.max(this.getColumnValues(a,!0))},getColumnMin:function(a){return Ext.Array.min(this.getColumnValues(a,!0))},getColumnValues:function(a,b){var c=this.getColumnIndex(a),d=[];this.eachRow(function(e){d.push(e[c])});return b?Ext.Array.clean(d):d},reMapRows:function(){var a=this.getRowKey(),b={};this.eachRow(function(c,d){a in c&&(b[c[a]]=d)},!0);this.setRowsMap(b)},sortByColumn:function(a){var b=
this.getRows(),c=Ext.Array.from(a).map(function(d){if(Ext.isObject(d))for(key in d)return{index:this.getColumnIndex(key),direction:-1<d[key].indexOf("asc")?"asc":"desc"};else return{index:this.getColumnIndex(d),direction:"desc"}},this);b.sort(function(d,e){for(var f=0,g=c.length;f<g;f++){var h=c[f].index;if(d[h]!=e[h])return"asc"==c[f].direction?d[h]>e[h]?1:-1:d[h]>e[h]?-1:1}});this.reMapRows();return this},loadCorrespondenceAnalysis:function(a){return this._doAnalysisLoad("table.CA","Voyant.data.store.CAAnalysis",
a)},loadPrincipalComponentAnalysis:function(a){return this._doAnalysisLoad("table.PCA","Voyant.data.store.PCAAnalysis",a)},loadTSNEAnalysis:function(a){return this._doAnalysisLoad("table.TSNE","Voyant.data.store.TSNEAnalysis",a)},_doAnalysisLoad:function(a,b,c){c=c||{};var d=new Ext.Deferred;Ext.apply(c,{columnHeaders:!0,rowHeaders:!0,tool:a,analysisInput:this.toTsv(),inputFormat:"tsv"});var e=Ext.create(b,{noCorpus:!0});e.load({params:c,callback:function(f,g,h){h?d.resolve(e,f):d.reject(g.error.response)}});
return d.promise},embed:function(a,b){!b&&Ext.isObject(a)&&(b=a,a=this.embeddable[0]);b=b||{};var c=Ext.Array.from(b.headers||this.getHeaders()).map(function(f){return this.getColumnHeader(f)},this);c={rowkey:this.getRowKey(),config:b,headers:c};if("headers"in b){var d=Ext.Array.from(b.headers).map(function(f){return this.getColumnIndex(f)},this),e=[];this.getRows().forEach(function(f){e.push(d.map(function(g){return f[g]}))});Ext.apply(c,{rows:e})}else Ext.apply(c,{rows:this.getRows()});Ext.apply(b,
{tableJson:JSON.stringify(c)});delete b.axes;delete b.series;embed.call(this,a,b)},toTsv:function(a){var b=this.getHeaders().join("\t");this.getRows().forEach(function(c,d){a&&Ext.isNumber(a)&&d>a||(b+="\n"+c.map(function(e){return Ext.isString(e)?e.replace(/(\n|\t)/g,""):e}).join("\t"))});return b},getString:function(a){a=a||{};var b="\x3ctable class\x3d'voyant-table' style\x3d'"+(a.width?" width: "+a.width:"")+"' id\x3d'"+(a.id?a.id:Ext.id())+"'\x3e",c=this.getHeaders();if(c.length){b+="\x3cthead\x3e\x3ctr\x3e";
for(var d=0,e=c.length;d<e;d++)b+="\x3cth\x3e"+c[d]+"\x3c/th\x3e";b+="\x3c/tr\x3e\x3c/thead\x3e"}b+="\x3ctbody\x3e";d=0;for(e=Ext.isNumber(a)?a:this.getRows().length;d<e;d++)(a=this.getRow(d))&&Ext.isArray(a)&&(b+="\x3ctr\x3e",a.forEach(function(f){b+="\x3ctd\x3e"+f+"\x3c/td\x3e"}),b+="\x3c/tr\x3e");return b+="\x3c/tbody\x3e\x3c/table\x3e"}});Ext.define("Voyant.data.util.NetworkGraph",{alternateClassName:["NetworkGraph"],config:{edges:[],nodes:[]},constructor:function(a,b){a=a||{};this.setEdges(Ext.Array.from(a.edges));this.setNodes(Ext.Array.from(a.nodes));this.callParent([a])},addEdge:function(a,b,c){this.getEdges().push(Ext.isObject(a)?a:{source:a,target:b,value:c})},getNode:function(a){return Ext.Array.binarySearch(this.getNodes(),a,void 0,void 0,function(b,c){return b.term<c.term?-1:b.term>c.term?1:0})},embed:function(a,b){!b&&Ext.isObject(a)&&
(b=a,a=this.embeddable[0]);b=b||{};var c={edges:this.getEdges(),nodes:this.getNodes(),config:b};if(b.limit&&c.edges.length>b.limit){c.edges=c.edges.slice(0,b.limit);var d={};c.edges.forEach(function(f){d["_"+f.source]=!0;d["_"+f.target]=!0});var e=[];c.nodes.forEach(function(f){"_"+f.term in d&&e.push(f)});c.nodes=e}Ext.apply(b,{jsonData:JSON.stringify(c)});embed.call(this,a,b)},getString:function(a){return this.getEdges().map(function(b){b.source+"-"+b.target}).join("; ")}});Ext.define("Voyant.data.util.Geonames",{mixins:["Voyant.util.Localization"],statics:{i18n:{}},config:{data:{},queries:void 0,corpus:void 0,isIncrementalLoadingOccurrences:!1,previousParams:{}},constructor:function(a,b){a=a||{};this.callParent([a]);this.setCorpus(a.corpus)},load:function(a,b){this.setPreviousParams(a);b=b||new Ext.Deferred;var c=this,d={corpus:this.getCorpus().getAliasOrId(),queries:this.getQueries(),tool:"corpus.Dreamscape",limit:200};Ext.apply(d,a||{});a.noOverwrite||c.setData({});
Ext.Ajax.request({url:Voyant.application.getTromboneUrl(),params:d,scope:this}).then(function(e){(e=Ext.JSON.decode(e.responseText))&&e.dreamscape&&e.dreamscape.progress&&new Voyant.widget.ProgressMonitor({progress:e.dreamscape.progress,maxMillisSinceStart:36E5,tool:"corpus.Dreamscape",success:function(){c.load.call(c,a,b)},failure:function(f){Voyant.application.showResponseError(c.localize("failedToFetchGeonames"),f);b.reject()},scope:c});e&&e.dreamscape&&!e.dreamscape.progress&&(a.noOverwrite||
c.setData(e.dreamscape),b.resolve(e))},function(e){Voyant.application.showResponseError(c.localize("failedToFetchGeonames"),e);b.reject()});return b.promise},getCitiesCount:function(){return Object.keys(this.getData().locations.locations).length},getTotalCitiesCount:function(){return this.getData().locations.total},hasMoreCities:function(){return this.getCitiesCount()<this.getTotalCitiesCount()},eachCity:function(a,b,c){var d=this.getData().locations.locations,e=[],f;for(f in d)e.push(Ext.apply(d[f],
{id:f}));e.sort(function(g,h){return g.rawFreq==h.rawFreq?g.label-h.label:h.rawFreq-g.rawFreq});c&&e.length>c&&(e=e.slice(0,c));e.forEach(function(g){a.call(b,g)})},getConnectionsCount:function(){return this.getData().connections.connections.length},getTotalConnectionsCount:function(){return this.getData().connections.total},eachConnection:function(a,b,c){var d=this.getData().connections.connections,e=this.getData().locations.locations;orderedConnections=[];for(var f=0,g=d.length;f<g&&!(a.call(b,
{source:Ext.apply({id:d[f].source},e[d[f].source]),target:Ext.apply({id:d[f].target},e[d[f].target]),rawFreq:d[f].rawFreq}),f>c);f++);},getConnectionOccurrence:function(a){if(this.getData().locations){var b=this.getData().connectionOccurrences,c=b.connectionOccurrences;locations=this.getData().locations.locations;if(!this.getIsIncrementalLoadingOccurrences()&&c.length<b.total&&a+100>c.length){this.setIsIncrementalLoadingOccurrences(!0);var d=this;b={};Ext.apply(b,this.getPreviousParams);Ext.apply(b,
{start:c.length,noOverwrite:!0,suppressLocations:!0,suppressConnections:!0});this.load(b).then(function(e){d.setIsIncrementalLoadingOccurrences(!1);d.getData().connectionOccurrences.connectionOccurrences=c.concat(e.dreamscape.connectionOccurrences.connectionOccurrences)})}return c&&c[a]?(b=c[a],b.index=a,Ext.apply(b.source,locations[b.source.location]),Ext.apply(b.target,locations[b.target.location]),b):null}},getAllConnectionOccurrences:function(a,b){debugger;for(var c=[],d=0;d<this.getTotalConnectionsCount();d++){var e=
this.getConnectionOccurrence(d);e&&e.target.id==b&&e.source.id==a&&c.push(e)}return c}});Ext.define("Voyant.data.util.DocumentEntities",{extend:"Ext.Base",mixins:["Voyant.util.Localization"],statics:{i18n:{identifyingDocEnts:"Identifying Document Entities",error:"Error Identifying Document Entities",retry:"Retry Failed Documents",done:"Done",statusDone:"Done",statusFailed:"Failed",statusQueued:"Queued",statusStarted:"Started",status413:"Your document is too large for this service"}},config:{progressWindow:void 0,updateDelay:5E3,timeoutId:void 0},entitiesColors:{date:"#80b1d3",time:"#80b1d3",
duration:"#80b1d3",person:"#fdb462",organization:"#bebada",gpe:"#bebada",loc:"#b3de69",location:"#b3de69",money:"#ffffb3",misc:"#8dd3c7",product:void 0,cardinal:void 0,quantity:void 0,event:void 0,fac:void 0,language:void 0,law:void 0,norp:void 0,percent:void 0,work_of_art:void 0,unknown:void 0,set:void 0},constructor:function(a,b){this.mixins["Voyant.util.Localization"].constructor.apply(this,arguments);this.initConfig();this.callParent();return this.load(a,b)},load:function(a,b){a=Ext.apply({tool:"corpus.DocumentEntities",
corpus:Voyant.application.getCorpus().getId(),noCache:!0},a||{});this.doLoad(a,b,!0)},doLoad:function(a,b,c){var d=this;Ext.Ajax.request({url:Voyant.application.getTromboneUrl(),params:a}).then(function(e){e=Ext.decode(e.responseText).documentEntities;var f=d._getProgressFromStatus(e.status),g=f[0]===f[1],h=f[2],k=-1!==f[3].indexOf("413");c&&g&&!h?((f=d.getProgressWindow())&&f.close(),d._addEntitiesToCategories(e.entities),b.call(d,e.entities)):(d.updateProgress(e.status,f),g?(f=d.getProgressWindow(),
f.down("#identifyingMessage").getEl().down("div.x-mask-msg-text").setStyle("backgroundImage","none"),f.down("#doneButton").setHidden(!1),h&&!k?f.down("#retryButton").setHidden(!1).setDisabled(!1).setHandler(function(l){d.load(Ext.apply({retryFailures:!0},a),b);l.setDisabled(!0)},d):(f.down("#retryButton").setHidden(!0),c&&f.close()),d._addEntitiesToCategories(e.entities),b.call(d,e.entities)):(delete a.retryFailures,d.setTimeoutId(Ext.defer(d.doLoad,d.getUpdateDelay(),d,[a,b,!1]))))},function(e){Voyant.application.showError(d.localize("error"));
console.warn(e);b.call(d,null)})},_getProgressFromStatus:function(a){var b=a.length,c=0,d=!1,e=[];a.forEach(function(f){"done"===f[1]?c++:0===f[1].indexOf("failed")&&(c++,d=!0,f=f[1].match(/\d\d\d$/),null!==f&&e.push(f[0]))});return[c,b,d,e]},updateProgress:function(a,b){void 0===this.getProgressWindow()&&this.setProgressWindow(Ext.create("Ext.window.Window",{title:this.localize("identifyingDocEnts"),width:400,height:300,minimizable:!0,closeAction:"destroy",layout:{type:"vbox",align:"stretch",pack:"center"},
items:[{itemId:"identifyingMessage",xtype:"container",html:'\x3cdiv style\x3d"text-align: center" class\x3d"x-mask-msg-text"\x3e'+this.localize("identifyingDocEnts")+"\x3c/div\x3e",flex:.5,margin:"20 10 10 10"},{itemId:"progressBar",xtype:"progressbar",height:20,margin:"0 10 10 10"},{xtype:"dataview",flex:1,margin:"0 10 10 10",scrollable:"y",itemId:"documentStatus",store:Ext.create("Ext.data.ArrayStore",{fields:["docTitle","statusIcon","statusText"]}),itemSelector:".doc",tpl:'\x3ctpl for\x3d"."\x3e,\x3cdiv class\x3d"doc"\x3e,\x3ci class\x3d"fa {statusIcon}" style\x3d"margin-right: 5px;"\x3e\x3c/i\x3e,\x3cspan class\x3d"" style\x3d""\x3e{docTitle}\x3c/span\x3e,\x3cspan style\x3d"float: right"\x3e{statusText}\x3c/span\x3e,\x3c/div\x3e,\x3c/tpl\x3e'.split(",")}],
tools:[{type:"restore",itemId:"restoreButton",hidden:!0,handler:function(f,g,h,k){f=h.up("window");f.expand();f.anchorTo(Ext.getBody(),"c-c",[0,-f.getBox().height],{duration:250});k.hide()}}],buttons:[{itemId:"retryButton",xtype:"button",text:this.localize("retry"),hidden:!0},{itemId:"doneButton",xtype:"button",text:this.localize("done"),hidden:!0,handler:function(f){f.up("window").close()}}],listeners:{minimize:function(f){f.collapse(Ext.Component.DIRECTION_BOTTOM,!1);f.anchorTo(Ext.getBody(),"br-br",
[0,0],{duration:250});f.down("#restoreButton").show()},destroy:function(f){clearTimeout(this.getTimeoutId());this.setProgressWindow(void 0)},scope:this}}));var c=b[0];b=b[1];var d=this.getProgressWindow();d.down("#progressBar").updateProgress(c/b,c+" / "+b);var e=Voyant.application.getCorpus().getDocuments();a=a.map(function(f,g){g=e.getById(f[0]).getShortTitle();f=f[1];var h="fa-spinner",k="";0===f.indexOf("failed")?(h="fa-exclamation-triangle",k=-1!==f.indexOf("413")?this.localize("status413"):
this.localize("statusFailed"),console.log("ner: "+g+", "+f)):"done"===f?(h="fa-check",k=""):"queued"===f&&(h="fa-clock-o",k="");return[g,h,k]},this);d.down("#documentStatus").getStore().loadData(a);d.setTitle(this.localize("identifyingDocEnts")+" "+c+" / "+b);d.show()},_addEntitiesToCategories:function(a){var b={};a.forEach(function(d){void 0===b[d.type]&&(b[d.type]=[]);b[d.type].push(d.term)});var c=Voyant.application.getCategoriesManager();Object.keys(b).forEach(function(d){var e=this.entitiesColors[d];
void 0!==e&&(c.addCategory(d),c.addTerms(d,b[d]),c.setCategoryFeature(d,"color",e))},this)}});Ext.define("Voyant.data.model.Corpus",{alternateClassName:["Corpus"],mixins:["Voyant.util.Transferable","Voyant.util.Localization"],transferable:"loadCorpusTerms loadTokens getPlainText getText getWords getString getLemmasArray".split(" "),requires:["Voyant.util.ResponseError","Voyant.data.store.CorpusTerms","Voyant.data.store.Documents"],extend:"Ext.data.Model",config:{documentsStore:void 0},statics:{i18n:{}},fields:[{name:"documentsCount",type:"int"},{name:"lexicalTokensCount",type:"int"},{name:"lexicalTypesCount",
type:"int"},{name:"createdTime",type:"int"},{name:"createdDate",type:"date",dateFormat:"c"},{name:"title",type:"string"},{name:"subTitle",type:"string"},{name:"languagueCodes",type:"string"}],constructor:function(a,b){a=a||{};b=b||{};this.callParent([]);var c=new Ext.Deferred;if(Ext.isString(a))0==/\s/.test(a)&&-1==a.indexOf(":")?Ext.apply(b,{corpus:a}):Ext.apply(b,{input:a});else if(Ext.isArray(a))Ext.apply(b,{input:a});else if(Ext.isObject(a))Ext.apply(b,a);else return Voyant.application.showError(this.localize("badDataTypeCorpus")+
": ("+typeof a+") "+a),Ext.defer(function(){c.reject(this.localize("badDataTypeCorpus")+": ("+typeof a+") "+a)},50,this),c.promise;if(Ext.isObject(b)){if(!b.corpus&&!b.input&&!b.inlineData)return Voyant.application.showError(this.localize("noCorpusOrInput")+": "+b),Ext.defer(function(){c.reject(this.localize("noCorpusOrInput")+": "+b)},50,this),c.promise;Ext.apply(b,{tool:"corpus.CorpusMetadata"});var d=this;Ext.Ajax.request({url:Voyant.application.getTromboneUrl(),params:b}).then(function(e){d.set(Ext.JSON.decode(e.responseText).corpus.metadata);
if(b.title||b.subTitle)d.set("title",b.title),d.set("subTitle",b.subTitle);return d},function(e){Voyant.application.showResponseError(d.localize("failedCreateCorpus"),e);c.reject(d.localize("failedCreateCorpus"))}).then(function(e){0==e.getDocumentsCount()&&Voyant.application.showError(d.localize("thisCorpus")+" "+d.localize("isEmpty")+".");!("docsLimit"in b)||!1!==b.docsLimit&&0<b.docsLimit?d.getDocuments().load({params:{limit:"docsLimit"in b?b.docsLimit:d.getDocumentsCount()},callback:function(f,
g,h){h?(d.setDocumentsStore(this),c.resolve(e)):c.reject(g)}}):c.resolve(e)})}else Voyant.application.showError(this.localize("badDataTypeCorpus")+": ("+typeof b+") "+b),Ext.defer(function(){c.reject(this.localize("badDataTypeCorpus")+": ("+typeof b+") "+b)},50,this);return c.promise},getId:function(){return this.get("id")},getAliasOrId:function(){return this.get("alias")||this.get("id")},loadCorpusTerms:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)&&(a={limit:a});Ext.applyIf(a,{limit:0});
var c=this.getCorpusTerms();c.load({params:a,callback:function(d,e,f){f?b.resolve(c):b.reject(e)}});return b.promise},loadTokens:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)&&(a={limit:a});Ext.applyIf(a,{limit:0});var c=this.getTokens();c.load({params:a,callback:function(d,e,f){f?b.resolve(c):b.reject(e)}});return b.promise},getCorpusTerms:function(a){return Ext.create("Voyant.data.store.CorpusTerms",Ext.apply(a||{},{corpus:this}))},getTokens:function(a){return Ext.create("Voyant.data.store.Tokens",
Ext.apply(a||{},{corpus:this}))},each:function(a,b){this.getDocuments().each(function(c,d){a.call(b||c,c,d)})},map:function(a,b){return this.getDocuments().getRange().map(function(c,d){return a.call(b||c,c,d)},b||this)},getCorpusCollocates:function(a){return Ext.create("Voyant.data.store.CorpusCollocates",Ext.apply(a||{},{corpus:this}))},getDocumentQueryMatches:function(a){return Ext.create("Voyant.data.store.DocumentQueryMatches",Ext.apply(a||{},{corpus:this}))},getDocumentTerms:function(a){return Ext.create("Voyant.data.store.DocumentTerms",
Ext.apply(a||{},{corpus:this}))},getDocumentEntities:function(a){return Ext.create("Voyant.data.store.DocumentEntities",Ext.apply(a||{},{corpus:this}))},loadContexts:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)&&(a={limit:a});Ext.applyIf(a,{limit:0});var c=this.getContexts();c.load({params:a,callback:function(d,e,f){f?b.resolve(c):b.reject(e)}});return b.promise},getContexts:function(a){return Ext.create("Voyant.data.store.Contexts",Ext.apply(a||{},{corpus:this}))},getDocuments:function(a){return this.getDocumentsStore()?
this.getDocumentsStore():Ext.create("Voyant.data.store.Documents",Ext.apply(a||{},{corpus:this}))},getDocument:function(a){if(this.getDocumentsStore()){if(a instanceof Voyant.data.model.Document)return a;if(Ext.isNumeric(a))return this.getDocumentsStore().getAt(parseInt(a));if(Ext.isString(a))return this.getDocumentsStore().getById(a)}return this.getDocumentsStore().getDocument(a)},getDocumentsCount:function(){return this.get("documentsCount")},getWordTokensCount:function(){return this.get("lexicalTokensCount")},
getWordTypesCount:function(){return this.get("lexicalTypesCount")},getCreatedTime:function(){return this.get("createdTime")},requiresPassword:function(){var a=this.getNoPasswordAccess();return"NONE"==a||"NONCONSUMPTIVE"==a},getNoPasswordAccess:function(){return this.get("noPasswordAccess")},getTitle:function(){return this.get("title")},getSubTitle:function(){return this.get("subTitle")},getRelatedWords:function(a){return Ext.create("Voyant.data.store.RelatedTerms",Ext.apply(a||{},{corpus:this}))},
loadRelatedWords:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)&&(a={limit:a});Ext.applyIf(a,{limit:0});this.getRelatedWords().load({params:a,callback:function(c,d,e){e?b.resolve(c):b.reject(d.error.response)}});return b.promise},getText:function(a){var b=new Ext.Deferred;a=a||{};Ext.isNumber(a)?a={limit:a}:Ext.isString(a)&&(a={limit:parseInt(a)});Ext.applyIf(a,{limit:0,outputFormat:"text",template:"docTokens2text"});Ext.apply(a,{tool:"corpus.DocumentTokens",corpus:this.getAliasOrId()});
Ext.Ajax.request({url:Voyant.application.getTromboneUrl(),params:a,success:function(c,d){c=c.responseText.trim();a.transformCase&&(-1<a.transformCase.indexOf("lower")?c=c.toLowerCase():-1<a.transformCase.indexOf("upper")&&(c=c.toUpperCase()));b.resolve(c)},failure:function(c,d){b.reject(c)},scope:this});return b.promise},getPlainText:function(a){a=a||{};Ext.isNumber(a)?a={limit:a}:Ext.isString(a)&&(a={limit:parseInt(a)});Ext.apply(a,{template:"docTokens2plainText"});return this.getText(a)},getWords:function(a){a=
a||{};Ext.isNumber(a)?a={limit:a}:Ext.isString(a)&&(a={limit:parseInt(a)});Ext.applyIf(a,{template:"docTokens2words"});return this.getText(a)},getWordsArray:function(a){var b=new Ext.Deferred;this.getWords(a).then(function(c){b.resolve(c.split(" "))});return b.promise},getLemmasArray:function(a){a=a||{};var b=new Ext.Deferred;Ext.applyIf(a,{template:"docTokens2lemmas",withPosLemmas:!0,noOthers:!0});this.getWords(a).then(function(c){c=c.split(" ").map(function(d){return d.substring(0,d.indexOf("/"))});
b.resolve(c)});return b.promise},getReadability:function(a,b){b=b||{};var c="corpus.";switch(void 0===a?"coleman-liau":a){case "automated":c+="DocumentAutomatedReadabilityIndex";break;case "coleman-liau":c+="DocumentColemanLiauIndex";break;case "dale-chall":c+="DocumentDaleChallIndex";break;case "fog":c+="DocumentFOGIndex";break;case "lix":c+="DocumentLIXIndex";break;case "smog":c+="DocumentSMOGIndex"}Ext.apply(b,{corpus:this.getId(),tool:c});var d=new Ext.Deferred;this.getId();Ext.Ajax.request({url:Voyant.application.getTromboneUrl(),
params:b}).then(function(e){e=Ext.JSON.decode(e.responseText);var f;for(f in e)if(0===f.indexOf("document")){var g=f;break}if(g){var h;for(h in e[g]){var k=h;break}var l=k.substring(0,k.length-2);g=e[g][k].map(function(m){return{docIndex:m.docIndex,docId:m.docId,text:m.text,readability:m[l]}});d.resolve(g)}else d.reject()},function(e){d.reject()});return d.promise},getString:function(a){var b=this.getDocumentsCount(),c=this.localize("thisCorpus");if(0==b)c+=" "+this.localize("isEmpty")+".";else{c+=
" ";c=1<b?c+(new Ext.XTemplate(this.localize("hasNdocuments"))).apply({count:Ext.util.Format.number(b,"0,000")}):c+this.localize("has1document");c+=" "+(new Ext.XTemplate(this.localize("widthNwordsAndNTypes"))).apply({words:Ext.util.Format.number(this.getWordTokensCount(),"0,000"),types:Ext.util.Format.number(this.getWordTypesCount(),"0,000")})+".";c+=" "+this.localize("created")+" ";var d=this.get("createdDate"),e=new Date;!0===Ext.Array.each([["year",Ext.Date.YEAR],["month",Ext.Date.MONTH],["day",
Ext.Date.DAY],["hour",Ext.Date.HOUR],["minute",Ext.Date.MINUTE],["second",Ext.Date.SECOND]],function(f){if(Ext.Date.diff(d,e,f[1])>("second"==f[0]?1:0)){var g=Ext.Date.diff(d,e,f[1]);c+="\x3cspan class\x3d'info-tip' data-qtip\x3d'"+Ext.Date.format(d,"Y-m-d, H:i:s")+"'\x3e";c=1==g?c+(new Ext.XTemplate(this.localize(f[0]+"Ago"))).apply({count:g,date:d}):c+(new Ext.XTemplate(this.localize(f[0]+"sAgo"))).apply({count:g,date:d});c+="\x3c/span\x3e";return!1}},this)&&(c+=this.localize("now"));c+=".";c+=
""}!0===a&&(c+=" ("+this.getId()+")");return c}});Ext.define("Voyant.widget.CorpusSelector",{extend:"Ext.form.field.ComboBox",mixins:["Voyant.util.Localization","Voyant.util.Api"],alias:"widget.corpusselector",statics:{i18n:{},api:{openMenu:void 0}},constructor:function(a){a=a||{};this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);var b=[["shakespeare","Shakespeare's Plays"],["austen","Austen's Novels"],["frank","Mary Shelley's Frankenstein"]];this.getApiParam("openMenu")?b=this.getStoreItemsFromDefinition(this.getApiParam("openMenu")):
Voyant.application&&Voyant.application.getOpenMenu&&Voyant.application.getOpenMenu()&&(b=Voyant.application.getOpenMenu(),b=decodeURIComponent(b),b=b.replace(/\+/g," "),'"'==b.charAt(0)&&'"'==b.charAt(b.length-1)&&(b=b.substring(1,b.length-1)),b=this.getStoreItemsFromDefinition(b));Ext.applyIf(a,{fieldLabel:this.localize("chooseCorpus"),labelWidth:125,width:330,labelAlign:"right",name:"corpus",queryMode:"local",store:b});this.callParent([a])},initComponent:function(a){a=a||{};this.callParent([a])},
getStoreItemsFromDefinition:function(a){var b=[];a=a.split(";");for(var c=0;c<a.length;c++){var d=a[c].split(":");d[0]&&b.push([d[0],d[1]?d[1]:d[0]])}return b}});Ext.define("Voyant.widget.ListEditor",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.listeditor",layout:"hbox",margin:"0 0 5px 0",statics:{i18n:{}},initComponent:function(a){var b=this.up("window").panel.getApiParam(this.name),c=b?[{name:b,value:b}]:[];c.splice(0,0,{name:this.localize("none"),value:""},{name:this.localize("new"),value:"new"});Ext.apply(this,{items:[{xtype:"combo",queryMode:"local",value:b,triggerAction:"all",editable:!0,fieldLabel:this.localize(this.name+
"Label"),labelAlign:"right",name:this.name,displayField:"name",valueField:"value",store:{fields:["name","value"],data:c}},{width:10},{xtype:"tbspacer"},{xtype:"button",text:this.localize("editList"),ui:"default-toolbar",handler:this.editList,scope:this}]});this.callParent(arguments)},editList:function(){var a=this.up("window").panel,b=this.down("combo").getValue();Ext.Ajax.request({url:a.getTromboneUrl(),params:{tool:"resource.KeywordsManager",list:b},success:function(c){c=Ext.util.JSON.decode(c.responseText).keywords.keywords.sort().join("\n");
Ext.Msg.show({title:this.localize("editListTitle"),message:this.localize("editListMessage"),buttons:Ext.Msg.OKCANCEL,buttonText:{ok:this.localize("ok"),cancel:this.localize("cancel")},icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:c,original:c,fn:function(d,e,f){"ok"==d&&f.original!=e&&(d=this.down("combo"),0==Ext.String.trim(e).length?d.setValue("empty"):Ext.Ajax.request({url:a.getTromboneUrl(),params:{tool:"resource.StoredResource",storeResource:e},combo:d,success:function(g,h){var k=Ext.util.JSON.decode(g.responseText);
g=h.combo.getStore();k="keywords-"+k.storedResource.id;g.add({name:k,value:k});h.combo.setValue(k);h.combo.updateLayout()},scope:this}))},scope:this})},scope:this})}});Ext.define("Voyant.widget.StopListOption",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.stoplistoption",layout:"hbox",margin:"0 0 5px 0",statics:{stoplists:{ar:"stop.ar.txt",bg:"stop.bu.txt",br:"stop.br.txt",ca:"stop.ca.txt",ckb:"stop.ku.txt",cn:"stop.zh.txt",cz:"stop.cz.txt",de:"stop.de.txt",el:"stop.el.txt",en:"stop.en.txt",es:"stop.es.txt",eu:"stop.eu.txt",fa:"stop.fa.txt",fr:"stop.fr.txt",ga:"stop.ga.txt",gl:"stop.gl.txt",grc:"stop.grc.txt",he:"stop.he.txt",
hi:"stop.hi.txt",hu:"stop.hu.txt",hy:"stop.hy.txt",id:"stop.id.txt",it:"stop.it.txt",ja:"stop.ja.txt",la:"stop.la.txt",lv:"stop.lv.txt",lt:"stop.lt.txt",mu:"stop.multi.txt",nl:"stop.nl.txt",no:"stop.no.txt",pt:"stop.pt.txt",ro:"stop.ro.txt",ru:"stop.ru.txt",se:"stop.sv.txt",th:"stop.th.txt",tr:"stop.tr.txt",uk:"stop.uk.txt"},i18n:{}},initComponent:function(a){var b=this.up("window").panel.getApiParam("stopList"),c=[];for(id in Voyant.widget.StopListOption.stoplists)c.push({name:this.localize(id),
value:Voyant.widget.StopListOption.stoplists[id]});c.sort(function(d,e){return d.name<e.name?-1:1});c.splice(0,0,{name:this.localize("auto"),value:"auto"},{name:this.localize("none"),value:""},{name:this.localize("new"),value:"new"});Ext.apply(this,{items:[{xtype:"combo",queryMode:"local",value:b,triggerAction:"all",editable:!0,fieldLabel:this.localize("label"),labelAlign:"right",name:"stopList",displayField:"name",valueField:"value",store:{fields:["name","value"],data:c}},{width:10},{xtype:"tbspacer"},
{xtype:"button",text:this.localize("editList"),ui:"default-toolbar",handler:this.editList,scope:this},{width:10},{xtype:"checkbox",name:"stopListGlobal",checked:!0,boxLabel:this.localize("applyGlobally")}]});this.callParent(arguments)},editList:function(){var a=this.up("window").panel,b=this.down("combo").getValue(),c=a.getApplication&&a.getApplication().getCorpus?a.getApplication().getCorpus().getId():void 0;"auto"!=b||c?Ext.Ajax.request({url:a.getTromboneUrl(),params:{tool:"resource.KeywordsManager",
stopList:b,corpus:c},success:function(d){d=Ext.util.JSON.decode(d.responseText).keywords.keywords.sort().join("\n");Ext.Msg.show({title:this.localize("editStopListTitle"),message:this.localize("editStopListMessage"),buttons:Ext.Msg.OKCANCEL,buttonText:{ok:this.localize("ok"),cancel:this.localize("cancel")},icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:d,original:d,fn:function(e,f,g){f=f.toLowerCase();"ok"==e&&g.original!=f&&(e=this.down("combo"),0==Ext.String.trim(f).length?e.setValue("empty"):Ext.Ajax.request({url:a.getTromboneUrl(),
params:{tool:"resource.StoredResource",storeResource:f,corpus:c},combo:e,success:function(h,k){var l=Ext.util.JSON.decode(h.responseText);h=k.combo.getStore();l="keywords-"+l.storedResource.id;h.add({name:l,value:l});k.combo.setValue(l);k.combo.updateLayout()},scope:this}))},scope:this})},scope:this}):Ext.Msg.show({title:this.localize("noEditAutoTitle"),message:this.localize("noEditAutoMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR})}});Ext.define("Voyant.widget.TermColorsOption",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.termcolorsoption",layout:"hbox",margin:"0 0 5px 0",statics:{i18n:{label:"Term Colors",none:"None",categories:"Categories Only",categoriesTerms:"Categories and Terms",applyGlobally:"apply globally"}},initComponent:function(a){Ext.apply(this,{items:[{xtype:"combo",queryMode:"local",value:"categories",fieldLabel:this.localize("label"),labelAlign:"right",name:"termColors",displayField:"name",
valueField:"value",store:{fields:["name","value"],data:[{name:this.localize("categories"),value:"categories"},{name:this.localize("categoriesTerms"),value:"terms"},{name:this.localize("none"),value:""}]}},{width:20},{xtype:"checkbox",name:"termColorsGlobal",checked:!0,boxLabel:this.localize("applyGlobally")}],listeners:{boxready:function(b){var c=b.up("window").panel.getApiParam("termColors");b.down("combo").setValue(c)}}});this.callParent(arguments)}});
Ext.define("Voyant.widget.ColoredTermField",{extend:"Ext.grid.column.Template",alias:"widget.coloredtermfield",config:{useCategoriesMenu:!1},initComponent:function(){var a=this.up("gridpanel");this.getUseCategoriesMenu()&&(this.categoriesMenu=Ext.create("Voyant.categories.CategoriesMenu",{panel:a,listeners:{categorySet:function(c,d){c=a.getStore();c.removeAll();c.load()}}}),a.on("rowcontextmenu",function(c,d,e,f,g){g.preventDefault();c=a.getSelection().map(function(h){return h.get("term")});this.categoriesMenu.setTerms(c);
this.categoriesMenu.showAt(g.getXY())},this));var b=this.dataIndex;Ext.apply(this,{tpl:new Ext.XTemplate('\x3cspan style\x3d"{[this.getColorStyle(values.'+b+')]}; padding: 1px 3px; border-radius: 2px;"\x3e{'+b+"}\x3c/span\x3e",{getColorStyle:function(c){var d=a.getApiParam("termColors");return void 0!==d&&""!==d&&"categories"===d&&0<a.getApplication().getCategoriesManager().getCategoriesForTerm(c).length||"terms"===d?(c=a.getApplication().getColorForTerm(c),d=a.getApplication().getTextColorForBackground(c),
"background-color: rgb("+c.join(",")+"); color: rgb("+d.join(",")+")"):"color: rgb(0,0,0)"}})});this.callParent(arguments)}});Ext.define("Voyant.widget.QuerySearchField",{extend:"Ext.form.field.Tag",mixins:["Voyant.util.Localization"],alias:"widget.querysearchfield",statics:{i18n:{}},config:{corpus:void 0,tokenType:"lexical",isDocsMode:!1,inDocumentsCountOnly:void 0,stopList:void 0,showAggregateInDocumentsCount:!1,clearOnQuery:!1,parentPanel:void 0,currentOriginalRawQueryPlan:void 0},hasCorpusLoadedListener:!1,isClearing:!1,constructor:function(a){a=a||{};Ext.applyIf(a,{minWidth:100,maxWidth:200,matchFieldWidth:!1,minChars:2,
displayField:"term",valueField:"term",filterPickList:!0,createNewOnEnter:!0,createNewOnBlur:!1,autoSelect:!1,tpl:['\x3cul class\x3d"x-list-plain"\x3e\x3ctpl for\x3d"."\x3e','\x3cli role\x3d"option" class\x3d"x-boundlist-item" style\x3d"white-space: nowrap;"\x3e'+(a.itemTpl?a.itemTpl:a.inDocumentsCountOnly?"\x3ctpl\x3e\x3ctpl if\x3d\"term.charAt(0)\x3d\x3d'@'\"\x3e{term}\x3c/tpl\x3e\x3ctpl if\x3d\"term.charAt(0)!\x3d'@'\"\x3e{term} ({inDocumentsCount})\x3c/tpl\x3e\x3c/tpl\x3e":"\x3ctpl\x3e\x3ctpl if\x3d\"term.charAt(0)\x3d\x3d'@'\"\x3e{term}\x3c/tpl\x3e\x3ctpl if\x3d\"term.charAt(0)!\x3d'@'\"\x3e{term} ({rawFreq})\x3c/tpl\x3e\x3c/tpl\x3e")+
"\x3c/li\x3e","\x3c/tpl\x3e\x3c/ul\x3e"],triggers:{help:{weight:2,cls:"fa-trigger form-fa-help-trigger",handler:function(){Ext.Msg.show({title:this.localize("querySearch"),message:this.getIsDocsMode()?this.localize("querySearchDocsModeTip"):this.localize("querySearchTip"),buttons:Ext.OK,icon:Ext.Msg.INFO})},scope:"this"}}});a.showAggregateInDocumentsCount&&(a.triggers.count={cls:"fa-trigger",handler:"onHelpClick",scope:"this",hidden:!0});a.clearOnQuery&&this.setClearOnQuery(a.clearOnQuery);this.callParent(arguments)},
initComponent:function(a){var b=this;b.on("beforequery",function(d){if(d.query){d.query=d.query.trim();var e=d.query.toLowerCase();this.setCurrentOriginalRawQueryPlan(d.query);if("@"!=d.query.charAt(0)){"^"==d.query.charAt(0)&&(d.query=d.query.substring(1),d.cancel=0==d.query.length);"*"==d.query.charAt(0)&&(d.query="."+d.query);if("*"==d.query.charAt(d.query.length-1)||"|"==d.query.charAt(d.query.length-1))d.query=d.query.substring(0,d.query.length-1),d.cancel=0==d.query.length;"."==d.query.charAt(0)&&
(d.cancel=d.query.length<(/\W/.test(d.query.charAt(1))?5:4));try{new RegExp(d.query)}catch(k){d.cancel=!0}-1<d.query.indexOf('"')&&(-1==d.query.indexOf(" ")&&(d.cancel=!0),2!=(d.query.match(/"/)||[]).length&&(d.cancel=!0));-1<d.query.indexOf("*")?-1==d.query.indexOf(" ")&&-1==d.query.indexOf("|")&&(d.query+=",^"+d.query):d.query=d.query+"*"+(-1==d.query.indexOf(" ")&&-1==d.query.indexOf("|")?",^"+d.query+"*":"")}else"@"==d.query&&(d.cancel=!0);var f=b.getParentPanel();if(0==d.cancel&&f){var g="@"==
e.charAt(0)?e.substring(1):e,h;for(h in f.getApplication().getCategoriesManager().getCategories())-1<h.toLowerCase().indexOf(g)&&(d.query="@"+h+("@"==e.charAt(0)?"":","+d.query))}}},this);b.on("change",function(d,e){b.isClearing?b.isClearing=!1:(e=e.map(function(f){return f.replace(/^(\^?)\*/,"$1.*")}),b.up("panel").fireEvent("query",b,e),b.getClearOnQuery()&&(b.isClearing=!0,b.removeValue(b.getValueRecords())),b.triggers.count&&(b.triggers.count.show(),b.triggers.count.getEl().setHtml("0"),0<e.length?
b.getCorpus().getCorpusTerms().load({params:{query:e.map(function(f){return"("+f+")"}).join("|"),tokenType:b.getTokenType(),stopList:b.getStopList(),inDocumentsCountOnly:!0},callback:function(f,g,h){h&&f&&1==f.length&&b.triggers.count.getEl().setHtml(f[0].getInDocumentsCount())}}):b.triggers.count.hide()))});var c=b.findParentBy(function(d){return d.mixins["Voyant.panel.Panel"]});if(null!=c){this.setParentPanel(c);if(c.getCorpus&&c.getCorpus())b.on("afterrender",function(d){this.doSetCorpus(c.getCorpus())});
else c.on("loadedCorpus",function(d,e){b.doSetCorpus(e)},b);b.hasCorpusLoadedListener=!0}b.on("afterrender",function(d){!1!==b.hasCorpusLoadedListener||b.getCorpus()||(c=b.findParentBy(function(e){return e.mixins["Voyant.panel.Panel"]}),null==c&&(c=b.up("window").panel),d=c.getApplication().getCorpus(),void 0!==d?b.doSetCorpus(d):(c.on("loadedCorpus",function(e,f){b.doSetCorpus(f)},b),b.hasCorpusLoadedListener=!0));b.triggers&&b.triggers.help&&Ext.tip.QuickTipManager.register({target:b.triggers.help.getEl(),
text:b.getIsDocsMode()?b.localize("querySearchDocsModeTip"):b.localize("querySearchTip")});b.triggers&&b.triggers.count&&Ext.tip.QuickTipManager.register({target:b.triggers.count.getEl(),text:b.localize("aggregateInDocumentsCount")})});b.on("beforedestroy",function(d){b.triggers&&b.triggers.help&&Ext.tip.QuickTipManager.unregister(b.triggers.help.getEl());b.triggers&&b.triggers.count&&Ext.tip.QuickTipManager.unregister(b.triggers.count.getEl())});b.callParent(arguments)},doSetCorpus:function(a){if(null!=
a){this.setCorpus(a);if(void 0==this.getStopList())if(this.getApiParam)this.setStopList(this.getApiParam("stopList"));else for(var b=this.up("panel");b;){if(b&&b.getApiParam){this.setStopList(b.getApiParam("stopList"));break}b=b.up("panel")}var c=this.getApiParam?this.getApiParam("categories"):void 0;if(!c)for(b=this.up("panel");b;){if(b&&b.getApiParam){c=b.getApiParam("categories");break}b=b.up("panel")}a=a.getCorpusTerms({corpus:a.getAliasOrId(),proxy:{extraParams:{limit:10,tokenType:this.tokenType,
stopList:this.getStopList(),inDocumentsCountOnly:this.getInDocumentsCountOnly(),categories:c}}});this.setStore(a)}}});Ext.define("Voyant.widget.TotalPropertyStatus",{extend:"Ext.Component",mixins:["Voyant.util.Localization"],alias:"widget.totalpropertystatus",statics:{i18n:{}},initComponent:function(){Ext.applyIf(this,{tpl:this.localize("totalPropertyStatus"),itemId:"totalpropertystatus",style:"margin-right:5px",listeners:{afterrender:function(a){var b=a.up("grid");b&&(b=b.getStore(),a.update({count:b.getTotalCount()}),b.on("datachanged",function(c){a.update({count:c.getTotalCount()})}))}}});this.callParent(arguments)}});Ext.define("Voyant.widget.DocumentSelector",{mixins:["Voyant.util.Localization"],alias:"widget.documentselector",glyph:"xf10c@FontAwesome",statics:{i18n:{}},config:{docs:void 0,corpus:void 0,singleSelect:!1},initComponent:function(){this.setSingleSelect(void 0==this.config.singleSelect?this.getSingleSelect():this.config.singleSelect);Ext.apply(this,{text:this.localize("documents"),menu:{width:250,fbar:[{xtype:"checkbox",hidden:this.getSingleSelect(),boxLabel:this.localize("all"),listeners:{change:{fn:function(a,
b){this.getMenu().items.each(function(c){c.setChecked(b)})},scope:this}}},{xtype:"tbfill"},{xtype:"button",text:this.localize("ok"),hidden:this.getSingleSelect(),scale:"small",handler:function(a,b){var c=[];this.getMenu().items.each(function(d){d.checked&&c.push(d.docId)},this);(b=a.findParentBy(function(d){return d.mixins["Voyant.panel.Panel"]}))&&b.fireEvent("documentsSelected",a,c);a.findParentBy(function(d){return d.isXType("button")&&d.hasVisibleMenu()?(d.hideMenu(),!0):!1})},scope:this},{xtype:"button",
text:this.localize("cancel"),scale:"small",handler:function(a,b){this.findParentBy(function(c){return c.isXType("button")&&c.hasVisibleMenu()?(c.hideMenu(),!0):!1},this);this.hideMenu()},scope:this}]},listeners:{afterrender:function(a){a.on("loadedCorpus",function(c,d){this.setCorpus(d);1==d.getDocumentsCount()?this.hide():a.populate(d.getDocumentsStore().getRange())},a);var b=a.findParentBy(function(c){return c.mixins["Voyant.panel.Panel"]});b&&(b.on("loadedCorpus",function(c,d){a.fireEvent("loadedCorpus",
c,d)},a),b.getCorpus&&b.getCorpus()?a.fireEvent("loadedCorpus",a,b.getCorpus()):b.getStore&&b.getStore()&&b.getStore().getCorpus&&b.getStore().getCorpus()&&a.fireEvent("loadedCorpus",a,b.getStore().getCorpus()))}}})},populate:function(a){this.setDocs(a);var b=void 0,c=void 0,d=!1,e=this.findParentBy(function(k){return k.mixins["Voyant.panel.Panel"]});e&&e.getApiParam&&(b=e.getApiParam("docId"),c=e.getApiParam("docIndex"),void 0!==b&&"string"===typeof b&&(b=b.split(","),d=!0),void 0!==c&&"string"===
typeof c&&(c=c.split(",").map(function(k){return parseInt(k)}),d=!0));var f=this.getMenu();f.removeAll();var g=this.getSingleSelect(),h="docGroup"+Ext.id();a.forEach(function(k,l){l=g&&0==l||!g;d&&(l=void 0!==b&&-1!==b.indexOf(k.get("id"))||void 0!==c&&-1!==c.indexOf(k.get("index")));f.add({xtype:"menucheckitem",text:k.getShortTitle(),docId:k.get("id"),checked:l,group:g?h:void 0,checkHandler:function(m,n){this.getSingleSelect()&&n&&(m=this.findParentBy(function(u){return u.mixins["Voyant.panel.Panel"]}))&&
m.fireEvent("documentSelected",this,k)},scope:this})},this)}});Ext.define("Voyant.widget.DocumentSelectorButton",{extend:"Ext.button.Button",alias:"widget.documentselectorbutton",mixins:["Voyant.widget.DocumentSelector"],initComponent:function(){this.mixins["Voyant.widget.DocumentSelector"].initComponent.apply(this,arguments);this.callParent()}});
Ext.define("Voyant.widget.DocumentSelectorMenuItem",{extend:"Ext.menu.Item",alias:"widget.documentselectormenuitem",mixins:["Voyant.widget.DocumentSelector"],initComponent:function(){this.mixins["Voyant.widget.DocumentSelector"].initComponent.apply(this,arguments);this.callParent()}});Ext.define("Voyant.widget.CorpusDocumentSelector",{extend:"Ext.button.Button",mixins:["Voyant.util.Localization"],alias:"widget.corpusdocumentselector",statics:{i18n:{}},config:{corpus:void 0,singleSelect:!1},initComponent:function(){this.setSingleSelect(void 0==this.config.singleSelect?this.getSingleSelect():this.config.singleSelect);Ext.apply(this,{text:this.localize("scale"),glyph:"xf059@FontAwesome",menu:{items:[{text:this.localize("corpus"),glyph:"xf111@FontAwesome",handler:function(a){var b=
this.findParentBy(function(c){return c.mixins["Voyant.panel.Panel"]});b&&(a.nextSibling().menu.items.each(function(c){c.setChecked(!1,!0)}),b.fireEvent("corpusSelected",this,this.getCorpus()))},scope:this},{xtype:"documentselectormenuitem",singleSelect:this.getSingleSelect()}]},listeners:{afterrender:function(a){a.on("loadedCorpus",function(c,d){this.setCorpus(d);1==d.getDocumentsCount()&&this.hide()},a);var b=a.findParentBy(function(c){return c.mixins["Voyant.panel.Panel"]});b&&(b.on("loadedCorpus",
function(c,d){a.fireEvent("loadedCorpus",c,d)},a),b.getCorpus&&b.getCorpus()?a.fireEvent("loadedCorpus",a,b.getCorpus()):b.getStore&&b.getStore()&&b.getStore().getCorpus&&b.getStore().getCorpus()&&a.fireEvent("loadedCorpus",a,b.getStore().getCorpus()))}}});this.callParent(arguments)}});Ext.define("Voyant.widget.DownloadFilenameBuilder",{extend:"Ext.form.FieldContainer",mixins:["Voyant.util.Localization","Ext.form.field.Field"],alias:"widget.downloadfilenamebuilder",statics:{i18n:{}},config:{name:"documentFilename",itemId:"documentFilename",fields:["pubDate","title","author"],value:["pubDate","title"],width:400},initComponent:function(a){a=a||{};this.initField();this.on("afterrender",function(){this.items.eachKey(function(b){new Ext.dd.DropZone(this.items.get(b).getTargetEl(),{ddGroup:"downloadfilename",
getTargetFromEvent:function(c){c=c.getTarget();return c.className&&-1<c.className.indexOf("dragsource")?c.parentNode:c},onNodeDrop:function(c,d,e,f){c.appendChild(d.el.dom);return!0}})},this);this.getFields().map(function(b){b=Ext.isString(b)?{tag:"span",html:this.localize(b+"Label"),value:b}:b;var c=this.queryById(Ext.Array.contains(this.getValue(),b.value)?"enabled":"available");b=Ext.dom.Helper.append(c.getTargetEl(),Ext.apply(b,{cls:"dragsource"}));Ext.create("Ext.dd.DragSource",b,{ddGroup:"downloadfilename"})},
this)},this);this.callParent(arguments)},defaults:{xtype:"container",width:"100%"},items:[{itemId:"enabled",cls:"dropzone dropzone-enabled"},{itemId:"available",cls:"dropzone dropzone-disabled"}],getValue:function(){return this.rendered?this.getTargetEl().query(".dropzone-enabled .dragsource").map(function(a){return a.getAttribute("value")}):this.value},setValue:function(a){this.rendered?this.getTargetEl().query(".dragsource",!1).forEach(function(b){var c=Ext.Array.contains(this.value,b.getAttribute("value"));
c&&b.parent().hasCls("dropzone-disabled")?this.queryById("enabled").getTargetEl().appendChild(b.dom):!c&&b.parent().hasCls("dropzone-enabled")&&this.queryById("available").getTargetEl().appendChild(b.dom)},this):this.value=a}});Ext.define("Voyant.widget.DownloadFileFormat",{extend:"Ext.form.CheckboxGroup",mixins:["Voyant.util.Localization"],alias:"widget.downloadfileformat",statics:{i18n:{}},initComponent:function(a){a=a||{};Ext.apply(this,{labelAlign:a.labelAlign?a.labelAlign:"right"});Ext.applyIf(this,{fieldLabel:this.localize("fieldLabel"),items:[{boxLabel:this.localize("original"),name:"documentFormat",inputValue:"SOURCE"},{boxLabel:this.localize("voyantXml"),name:"documentFormat",inputValue:"VOYANT"},{boxLabel:this.localize("plainText"),
name:"documentFormat",inputValue:"TXT"}],width:450});this.on("afterrender",function(){this.query("checkbox").forEach(function(b){var c=this.localize(b.inputValue+"Tip");-1==c.indexOf(b.inputValue+"Tip")&&Ext.tip.QuickTipManager.register({target:b.getEl(),text:c})},this)},this);this.on("beforedestroy",function(){this.query("checkbox").forEach(function(b){Ext.tip.QuickTipManager.unregister(b.getEl())},this)},this);this.callParent(arguments)}});Ext.define("Voyant.widget.DownloadOptions",{extend:"Ext.form.FieldSet",mixins:["Voyant.util.Localization"],requires:["Voyant.widget.DownloadFileFormat","Voyant.widget.DownloadFilenameBuilder"],alias:"widget.downloadoptions",statics:{i18n:{}},config:{items:[{xtype: 'component',html: "<p><b>Directions: </b>Arrange the order of metadata in your file names by dragging</p>" + "<p>categories from the pink block to the green block.</p>"},{xtype:"downloadfileformat"},{xtype:"downloadfilenamebuilder"}]},initComponent:function(a){a=a||{};Ext.apply(this,{title:a.title?a.title:this.localize("title")});this.callParent(arguments)}});Ext.define("Voyant.widget.FontFamilyOption",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.fontfamilyoption",statics:{i18n:{},fonts:[{name:"Georgia",value:"Georgia, serif"},{name:"Palatino",value:'"Palatino Linotype", "Book Antiqua", Palatino, serif'},{name:"Times New Roman",value:'"Times New Roman", Times, serif'},{name:"Arial",value:"Arial, Helvetica, sans-serif"},{name:"Arial Black",value:'"Arial Black", Gadget, sans-serif'},{name:"Comic Sans MS",value:'"Comic Sans MS", cursive, sans-serif'},
{name:"Impact",value:"Impact, Charcoal, sans-serif"},{name:"Lato",value:"LatoWeb"},{name:"Lucida",value:'"Lucida Sans Unicode", "Lucida Grande", sans-serif'},{name:"Tahoma/Geneva",value:"Tahoma, Geneva, sans-serif"},{name:"Trebuchet MS/Helvetica",value:'"Trebuchet MS", Helvetica, sans-serif'},{name:"Verdana/Geneva",value:"Verdana, Geneva, sans-serif"},{name:"Courrier New",value:'"Courier New", Courier, monospace'},{name:"Lucida/Monaco",value:'"Lucida Console", Monaco, monospace'}]},name:"fontFamily",
initComponent:function(a){a=a||{};var b=this.up("window").panel.getApiParam("fontFamily"),c=Ext.ClassManager.getClass(this).fonts;Ext.Array.contains(c.map(function(d){return d.value}),b)||c.splice(0,0,{name:b,value:b});Ext.apply(this,{items:{xtype:"combo",queryMode:"local",name:"fontFamily",value:b,triggerAction:"all",editable:!0,fieldLabel:this.localize("label"),labelAlign:"right",displayField:"name",valueField:"value",store:{fields:["name","value"],data:c},width:400}});this.callParent(arguments)}});Ext.define("Voyant.widget.ColorPaletteOption",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.colorpaletteoption",layout:"hbox",margin:"0 0 5px 0",statics:{i18n:{}},paletteTpl:new Ext.XTemplate('\x3ctpl for\x3d"."\x3e','\x3cdiv class\x3d"color" style\x3d"background-color: rgb({color});"\x3e\x3c/div\x3e',"\x3c/tpl\x3e"),paletteStore:new Ext.data.ArrayStore({fields:["id","color"],listeners:{update:function(a,b,c,d,e){},scope:this}}),editPaletteWin:null,spectrum:null,
initComponent:function(a){var b=this.up("window").panel.getApplication(),c=[],d;for(d in b.getPalettes())c.push({name:d,value:d});b=b.getApiParam("palette");Ext.apply(this,{items:[{xtype:"combo",queryMode:"local",value:b,triggerAction:"all",editable:!0,fieldLabel:this.localize("palette"),labelAlign:"right",name:"palette",displayField:"name",valueField:"value",store:{fields:["name","value"],data:c}},{width:10},{xtype:"tbspacer"},{xtype:"button",text:this.localize("editList"),ui:"default-toolbar",handler:this.editPalette,
scope:this}]});this.callParent(arguments)},editPalette:function(){var a=this.down("combo").getValue();this.loadPalette(a);this.editPaletteWin=Ext.create("Ext.window.Window",{title:this.localize("paletteEditor"),modal:!0,height:300,width:425,padding:5,layout:{type:"hbox",align:"stretch"},items:[{flex:1,layout:{type:"vbox",align:"stretch"},items:[{height:24,margin:"0 0 5 0",items:[{xtype:"button",text:this.localize("add"),margin:"0 5 0 0",handler:function(b){b=this.spectrum.spectrum("get").toRgb();
var c=this.editPaletteWin.down("dataview");this.paletteStore.add([[Ext.id(),[b.r,b.g,b.b]]]);c.refresh()},scope:this},{xtype:"button",text:this.localize("remove"),margin:"0 5 0 0",handler:function(b){b=this.editPaletteWin.down("dataview");var c=b.getSelectionModel().getSelection()[0];null!=c&&this.paletteStore.remove(c);b.refresh()},scope:this},{xtype:"button",text:this.localize("clear"),handler:function(b){this.paletteStore.removeAll()},scope:this}]},{xtype:"dataview",flex:1,scrollable:"y",store:this.paletteStore,
tpl:this.paletteTpl,itemSelector:"div.color",overItemCls:"over",selectedItemCls:"selected",selectionModel:{mode:"SINGLE"},listeners:{selectionchange:function(b,c,d){null!=c[0]&&(b=c[0].get("color"),b=this.up("window").panel.getApplication().rgbToHex(b),this.spectrum.spectrum("set",b))},scope:this}}]},{itemId:"colorEditor",width:200,margin:"0 0 0 5",html:'\x3cinput type\x3d"text" style\x3d"display: none;" /\x3e'}],buttons:[{text:this.localize("saveNewPalette"),handler:function(b){this.savePalette();
b.up("window").close()},scope:this},{text:this.localize("cancel"),handler:function(b){b.up("window").close()},scope:this}],listeners:{close:function(b){this.spectrum&&(this.spectrum.spectrum("destroy"),this.spectrum=null)},scope:this}}).show();this.initSpectrum()},setColorForSelected:function(a){if(null!==this.spectrum){a=a.toRgb();a=[a.r,a.g,a.b];var b=this.editPaletteWin.down("dataview").getSelectionModel().getSelection()[0];null!=b&&b.set("color",a)}},initSpectrum:function(){if(null===this.spectrum){var a=
this.editPaletteWin.down("#colorEditor").el.down("input");this.spectrum=$(a.dom).spectrum({flat:!0,showInput:!0,showButtons:!1,preferredFormat:"hex",change:this.setColorForSelected.bind(this),move:this.setColorForSelected.bind(this)})}},loadPalette:function(a){var b=this.up("window").panel.getApplication(),c=b.getColorPalette(a);if(void 0==c)b.loadCustomColorPalette(a).then(function(e){this.loadPalette(a)}.bind(this),function(){});else{var d=[];c.forEach(function(e){d.push([Ext.id(),e])},this);this.paletteStore.loadData(d)}},
savePalette:function(){var a=[];this.paletteStore.each(function(b){a.push(b.get("color"))});this.up("window").panel.getApplication().saveCustomColorPalette(a).then(function(b){var c=this.down("combo");c.getStore().add({name:b,value:b});c.setValue(b);c.updateLayout()}.bind(this))}});Ext.define("Voyant.widget.VoyantChart",{extend:"Ext.chart.CartesianChart",mixins:["Voyant.util.Localization","Voyant.util.Api"],alias:"widget.voyantchart",statics:{i18n:{},api:{tableJson:void 0}},constructor:function(a){a=a||{};this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);this.callParent(arguments)},initComponent:function(a){a=a||{};this.on("afterrender",function(){if(a&&"tableJson"in a)Ext.apply(this,this.getConfigFromTableJson(a.tableJson));else if(this.getApiParam("tableJson")){var b=
this.getConfigFromTableJson();this.setAxes(b.axes);this.setSeries(b.series);this.setLegend(b.legend);this.setStore(b.store);this.redraw()}},this);this.callParent(arguments)},getConfigFromTableJson:function(a){a=a||this.getApiParam("tableJson");if(!a)return{};var b=JSON.parse(a);b.headers=b.headers.map(function(g){return g});1==b.headers.length&&(b.headers.push(1),b.rowKey=1,b.rows.forEach(function(g,h){g&&g.push(h)}));var c=[];b.rowKey||(b.rowKey=b.headers[0]);b.rows.forEach(function(g,h){if(g){var k=
{};k[b.rowKey]=h;g=g.forEach(function(l,m){k[b.headers[m]]=l});c.push(k)}});b.config||(b.config={});a={store:{fields:Object.keys(c[0]),data:c},axes:Ext.isArray(b.config.axes)?b.config.axes:[{},{}],series:[],legend:b.config.noLegend||3>Object.keys(c[0]).length?void 0:{docked:"top"}};b.config.axes||(b.config.axes=[{},{}]);a.axes.forEach(function(g,h){Ext.isObject(b.config.axes)?Ext.apply(g,b.config.axes):Ext.isArray(b.config.axes)&&Ext.apply(g,b.config.axes[h]);Ext.applyIf(g,{type:0==h?"numeric":"category",
position:0==h?"left":"bottom",label:0==h?{}:{rotation:{degrees:-30}}})});for(var d=0,e=b.headers.length;d<e;d++)if(b.headers[d]!=b.rowKey){var f={};b.config.series&&(Ext.isObject(b.config.series)?Ext.apply(f,b.config.series):Ext.isArray(b.config.series)&&Ext.apply(f,b.config.series[a.series.length]));Ext.applyIf(f,{type:"line",xField:b.rowKey,yField:b.headers[d],marker:{radius:2},highlightCfg:{scaling:2},tooltip:{trackMouse:!0,renderer:function(g,h,k){g.setHtml(h.get(k.series.getYField())+": "+h.get(k.series.getYField()))}}});
a.series.push(f)}return a}});Ext.define("Voyant.widget.LiveSearchGrid",{extend:"Ext.grid.Panel",searchValue:null,matches:[],currentIndex:null,searchRegExp:null,caseSensitive:!1,regExpMode:!1,matchCls:"keyword",initComponent:function(){this.callParent(arguments)},tagsRe:/<[^>]*>/gm,tagsProtect:"\u000f",onTextFieldChange:function(a,b){var c=this,d=0,e=c.view,f=c.visibleColumnManager.getColumns();e.refresh();c.searchValue=b;c.matches=[];c.currentIndex=null;null!==c.searchValue&&(c.searchRegExp=new RegExp(b,"g"+(c.caseSensitive?
"":"i")),c.store.each(function(g,h){var k=e.getNode(g);k&&Ext.Array.forEach(f,function(l){var m=Ext.fly(k).down(l.getCellInnerSelector(),!0),n;if(m&&0==l.isXType("widgetcolumn")){var u=m.innerHTML.match(c.tagsRe);var w=m.innerHTML.replace(c.tagsRe,c.tagsProtect);w=w.replace(c.searchRegExp,function(p){++d;n||(c.matches.push({record:g,column:l}),n=!0);return'\x3cspan class\x3d"'+c.matchCls+'"\x3e'+p+"\x3c/span\x3e"},c);Ext.each(u,function(p){w=w.replace(c.tagsProtect,p)});m.innerHTML=w}})},c),d&&(c.currentIndex=
0,c.gotoCurrent()));null===c.currentIndex&&c.getSelectionModel().deselectAll();a.focus()},privates:{gotoCurrent:function(){var a=this.matches[this.currentIndex];this.getNavigationModel().setPosition(a.record,a.column);this.getSelectionModel().select(a.record)}}});Ext.define("Voyant.widget.ProgressMonitor",{extend:"Ext.Base",mixins:["Voyant.util.Localization"],msgbox:void 0,statics:{i18n:{}},config:{progress:void 0,scope:void 0,success:void 0,failure:void 0,args:void 0,tool:void 0,delay:1E3,maxMillisSinceStart:void 0},constructor:function(a){a=a||{};this.mixins["Voyant.util.Localization"].constructor.apply(this,arguments);if(!a||!a.progress||!a.progress.id)return Voyant.application.showError(this.localize("noProgress"));this.initConfig(a);this.callParent(arguments);
this.update()},update:function(){var a=this.getProgress(),b=this.getScope();b=b.localize?b.localize(a.code):this.localize(a.code);b=="["+a.code+"]"&&(b=a.message);b+=" ("+parseInt(100*a.completion)+"%)";var c=this.localize(a.status.toLowerCase());this.msgbox&&this.msgbox.msg.html==b&&this.msgbox.progressBar&&this.msgbox.progressBar.getText()==c||(this.msgbox=Ext.Msg.wait(b,this.localize("progress"),{text:c}));if("LAUNCH"==a.status||"RUNNING"==a.status){var d=this;Ext.defer(function(){Ext.Ajax.request({url:Voyant.application.getTromboneUrl(),
params:{tool:"progress.ProgressMonitor",id:a.id,maxMillisSinceStart:d.getMaxMillisSinceStart()}}).then(function(e,f){(e=Ext.decode(e.responseText))&&e.progress.progress?(d.setProgress(e.progress.progress),d.update()):d.finish(!1,d.localize("badProgress"))},function(e,f){d.finish(!1,e)})},this.getDelay(),this)}else this.finish("FINISHED"==a.status,b);5E3>this.getDelay()&&this.setDelay(this.getDelay()+500)},finish:function(a,b){var c=a?this.getSuccess():this.getFailure(),d=this.getArgs(),e=this.getProgress(),
f=this.getScope();this.close();c&&c.apply?c.apply(f,[a?d:b||e]):Voyant.application.showError(b)},close:function(){this.msgbox&&this.msgbox.close();this.destroy()}});Ext.define("Voyant.widget.VoyantTableTransform",{extend:"Ext.panel.Panel",mixins:["Voyant.util.Localization","Voyant.util.Api"],alias:"widget.voyanttabletransform",statics:{i18n:{},api:{tableHtml:void 0,tableJson:void 0,width:void 0,api:void 0}},html:"",config:{hiddenColumns:void 0},constructor:function(a){a=a||{};this.callParent(arguments)},initComponent:function(a){var b=this;a=a||{};b.mixins["Voyant.util.Api"].constructor.apply(this,arguments);this.config.api&&this.config.api.tableJson&&this.setApiParam("tableJson",
this.config.api.tableJson);b.on("afterrender",function(){b.buildFromParams();var c=this.getTargetEl().down("table");if(c){var d=c.parent(),e=new Ext.ux.grid.TransformGrid(c,{width:this.getApiParam("width")||d.getWidth(),height:this.getApiParam("height")||20+24*c.query("tr").length});e.render(d);if(this.getHiddenColumns()){var f={};Ext.Array.from(this.getHiddenColumns()).forEach(function(g){f[g]=!0});e.getColumns().forEach(function(g){g.text in f&&g.hide()});Ext.defer(function(){e.setWidth(e.getEl().dom.parentNode.offsetWidth)},
10)}}},b);b.callParent(arguments)},buildFromParams:function(){var a=this.getApiParam("tableHtml"),b=this.getApiParam("tableJson");if(a)this.setHtml(a);else if(b){var c="\x3ctable\x3e\x3cthead\x3e\x3ctr\x3e";a=JSON.parse(b);a.headers?a.headers.forEach(function(d){c+="\x3cth\x3e"+d+"\x3c/th\x3e"}):a.rows[0].forEach(function(d,e){c+="\x3cth\x3e"+(e+1)+"\x3c/th\x3e"});c+="\x3c/tr\x3e\x3c/thead\x3e\x3ctbody\x3e";a.rows.forEach(function(d){c+="\x3ctr\x3e";d.forEach(function(e){c+="\x3ctd\x3e"+e+"\x3c/td\x3e"});
c+="\x3c/tr\x3e"});c+="\x3c/tbody\x3e\x3c/table\x3e";this.setHtml(c);a.config&&a.config.hidden&&this.setHiddenColumns(a.config.hidden)}}});
Ext.define("Ext.ux.grid.TransformGrid",{extend:"Ext.grid.Panel",constructor:function(a,b){b=Ext.apply({},b);this.table=Ext.get(a);for(var c=b.fields||[],d=b.columns||[],e=[],f=[],g=a.query("thead th"),h=0,k=g.length,l=a.dom,m,n,u,w;h<k;++h)n=g[h],u=n.innerHTML,w="tcol-"+h,e.push(Ext.applyIf(c[h]||{},{name:w,mapping:"td:nth("+(h+1)+")/@innerHTML"})),f.push(Ext.applyIf(d[h]||{},{text:u,dataIndex:w,flex:1,tooltip:n.title,sortable:!0}));a=b.width?b.width:a.getWidth()+1;b.height&&(m=b.height);Ext.applyIf(b,
{store:{data:l,fields:e,proxy:{type:"memory",reader:{record:"tbody tr",type:"xml"}}},columns:f,width:a,height:m});this.callParent([b]);!1!==b.remove&&l.parentNode.removeChild(l)},doDestroy:function(){this.table.remove();this.tabl=null;this.callParent()}});Ext.namespace("Voyant.categories");
Ext.define("Voyant.categories.CategoriesOption",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.categoriesoption",statics:{i18n:{}},initComponent:function(){var a=this.up("window").panel.getApiParam("categories"),b=a?[{name:a,value:a}]:[];"auto"!==a&&b.push({name:"auto",value:"auto"});Ext.apply(this,{layout:"hbox",margin:"0 0 5px 0",items:[{xtype:"combo",queryMode:"local",triggerAction:"all",fieldLabel:this.localize("categories"),labelAlign:"right",displayField:"name",
valueField:"value",store:{fields:["name","value"],data:b},name:"categories",value:a},{width:10},{xtype:"tbspacer"},{xtype:"button",text:this.localize("edit"),ui:"default-toolbar",handler:function(){void 0===Voyant.categories.Builder&&(Voyant.categories.Builder=Ext.create("Voyant.categories.CategoriesBuilder",{panel:this.up("window").panel}));Voyant.categories.Builder.on("close",function(d){d=d.getCategoriesId();if(void 0!==d){var e=this.down("combo");e.getStore().add({name:d,value:d});e.setValue(d);
this.up("window").panel.setApiParam("categories",d)}},this,{single:!0});var c=this.down("combo").getValue();Voyant.categories.Builder.setCategoriesId(c);Voyant.categories.Builder.show()},scope:this}]});this.callParent(arguments)}});
Ext.define("Voyant.categories.CategoriesBuilder",{extend:"Ext.window.Window",requires:["Voyant.widget.FontFamilyOption"],mixins:["Voyant.util.Localization","Voyant.util.Api"],alias:"widget.categoriesbuilder",statics:{i18n:{title:"Categories Builder",terms:"Terms",term:"Term",rawFreq:"Count",relativeFreq:"Relative",categories:"Categories",addCategory:"Add Category",removeCategory:"Remove Category",removeTerms:"Remove Selected Terms",categoryName:"Category Name",add:"Add",cancel:"Cancel",exists:"Category already exists",
confirmRemove:"Are you sure you want to remove the category?",save:"Save",features:"Features",category:"Category",increaseCategory:"Increase Category Priority",decreaseCategory:"Decrease Category Priority",color:"Color",font:"Font",orientation:"Orientation"},api:{stopList:"auto",query:void 0},features:{color:{xtype:"colorfield",format:"#hex6"},font:{xtype:"combobox",queryMode:"local",displayField:"name",valueField:"value",store:{fields:["name","value"],data:Voyant.widget.FontFamilyOption.fonts}},
orientation:{xtype:"combobox",queryMode:"local",displayField:"name",valueField:"value",store:{fields:["name","value"],data:[{name:"Horizontal",value:0},{name:"Vertical",value:90}]}}}},config:{corpus:void 0,builderWin:void 0,addCategoryWin:void 0,categoriesId:void 0},closeAction:"hide",modal:!0,height:250,width:500,constructor:function(a){a=a||{};a.panel?(this.panel=a.panel,this.app=this.panel.getApplication(),this.categoriesManager=this.app.getCategoriesManager()):console.warn("CategoriesBuilder cannot find panel!");
a.height=.75*this.app.getViewport().getHeight();a.width=.75*this.app.getViewport().getWidth();this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);this.callParent(arguments)},initComponent:function(){Ext.apply(this,{header:!1,layout:"fit",onEsc:Ext.emptyFn,items:{xtype:"tabpanel",title:this.localize("title"),tabBarHeaderPosition:1,items:[{layout:"border",title:this.localize("categories"),items:[{title:this.localize("terms"),split:!0,width:250,region:"west",layout:"fit",items:{itemId:"terms",
xtype:"grid",store:Ext.create("Voyant.data.store.CorpusTermsBuffered",{parentPanel:this}),viewConfig:{plugins:{ptype:"gridviewdragdrop",ddGroup:"terms",copy:!0,enableDrop:!1,dragZone:{getDragText:function(){var a="";this.dragData.records.forEach(function(b){a+=b.get("term")+", "});a=a.substr(0,a.length-2);20<a.length&&(a=a.substr(0,20)+"...");return a}}}},selModel:{mode:"MULTI"},columns:[{text:this.localize("term"),dataIndex:"term",flex:1,sortable:!0},{text:this.localize("rawFreq"),dataIndex:"rawFreq",
width:"autoSize",sortable:!0},{text:this.localize("relativeFreq"),dataIndex:"relativeFreq",renderer:function(a){return Ext.util.Format.number(1E6*a,"0,000")},width:"autoSize",hidden:!0,sortable:!0}],dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"}]}],listeners:{query:function(a,b){this.setApiParam("query",b);a=this.queryById("terms").getStore();a.removeAll();a.load()},scope:this}}},{title:this.localize("categories"),itemId:"categories",region:"center",
xtype:"panel",layout:{type:"hbox",align:"stretch"},scrollable:"x",dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"textfield",fieldLabel:"Category Filter",labelAlign:"right",enableKeyEvents:!0,listeners:{keyup:function(a,b){var c=a.getValue().trim();this.queryById("categories").query("grid").forEach(function(d){""===c?d.getStore().clearFilter():d.getStore().filter("term",c)},this)},scope:this}},"-",{text:this.localize("addCategory"),handler:function(){this.getAddCategoryWin().show()},
scope:this},{text:this.localize("removeTerms"),handler:function(){this.queryById("categories").query("grid").forEach(function(a){var b=a.getSelection();b.forEach(function(c){this.categoriesManager.removeTerm(a.category,c.get("term"))},this);a.getStore().remove(b)},this)},scope:this}]}],items:[]}]},{layout:"fit",itemId:"features",title:this.localize("features"),xtype:"grid",scrollable:"y",store:Ext.create("Ext.data.JsonStore",{fields:["category"]}),columns:[{text:this.localize("category"),dataIndex:"category",
sortable:!1,hideable:!1,flex:1}]}]},buttons:[{text:this.localize("cancel"),handler:function(a){this.setCategoriesId(void 0);a.up("window").close()},scope:this},{text:this.localize("save"),handler:function(a){this.processFeatures();this.setColorTermsFromCategoryFeatures();this.app.saveCategoryData().then(function(b){this.setCategoriesId(b);a.up("window").close()}.bind(this),function(){this.setCategoriesId(void 0);a.up("window").close()}.bind(this))},scope:this}],listeners:{show:function(){this.getCategoriesId()&&
this.getCategoriesId()!==this.getApiParam("categories")?this.app.loadCategoryData(this.getCategoriesId()).then(function(a){this.setColorTermsFromCategoryFeatures();this.buildCategories();this.buildFeatures()}.bind(this)):(this.buildCategories(),this.buildFeatures());this.down("tabpanel").setActiveTab(0)},afterrender:function(a){a.on("loadedCorpus",function(b,c){this.setCorpus(c);this.queryById("terms").getStore().load()},a);this.panel.on("loadedCorpus",function(b,c){a.fireEvent("loadedCorpus",b,c)},
a);this.panel.getCorpus&&this.panel.getCorpus()?a.fireEvent("loadedCorpus",a,this.panel.getCorpus()):this.panel.getStore&&this.panel.getStore()&&this.panel.getStore().getCorpus&&this.panel.getStore().getCorpus()&&a.fireEvent("loadedCorpus",a,this.panel.getStore().getCorpus())},scope:this}});this.setAddCategoryWin(Ext.create("Ext.window.Window",{title:this.localize("addCategory"),modal:!0,closeAction:"hide",layout:"fit",items:{xtype:"form",width:300,bodyPadding:"10 5 5",defaults:{labelAlign:"right"},
items:[{xtype:"textfield",fieldLabel:this.localize("categoryName"),name:"categoryName",allowBlank:!1,validator:function(a){return void 0===this.categoriesManager.getCategoryTerms(a)?!0:this.localize("exists")}.bind(this),enableKeyEvents:!0,listeners:{keypress:function(a,b){b.getKey()===Ext.event.Event.ENTER&&a.up("form").queryById("addCategoryButton").click()},scope:this}}],buttons:[{text:this.localize("cancel"),handler:function(a){a.up("window").close()}},{itemId:"addCategoryButton",text:this.localize("add"),
handler:function(a){var b=a.up("form");b.isValid()&&(b=b.getValues().categoryName,this.addCategory(b),a.up("window").close())},scope:this}]},listeners:{show:function(a){a=a.down("form").getForm();a.reset();a.clearInvalid()}}}));this.callParent(arguments)},addCategory:function(a){this.categoriesManager.addCategory(a);this.queryById("features").getStore().add({category:a});var b=[],c=this.categoriesManager.getCategoryTerms(a);if(void 0!==c)for(var d=0;d<c.length;d++)b.push({term:c[d]});var e=this.queryById("categories").add({xtype:"grid",
category:a,title:a,frame:!0,width:150,margin:"10 0 10 10",layout:"fit",tools:[{type:"close",tooltip:this.localize("removeCategory"),callback:function(g){Ext.Msg.confirm(this.localize("removeCategory"),this.localize("confirmRemove"),function(h){"yes"===h&&this.removeCategory(a)},this)},scope:this}],bbar:[{xtype:"button",text:"",tooltip:this.localize("increaseCategory"),glyph:"xf067@FontAwesome",handler:function(g){g=g.findParentByType("grid");var h=this.queryById("categories"),k=h.prevChild(g);null!==
k&&(h.moveBefore(g,k),this.app.getCategoriesManager().setCategoryRanking(g.getTitle(),h.items.indexOf(g)))},scope:this},"-\x3e",{xtype:"button",text:"",tooltip:this.localize("decreaseCategory"),glyph:"xf068@FontAwesome",handler:function(g){g=g.findParentByType("grid");var h=this.queryById("categories"),k=h.nextChild(g);null!==k&&(h.moveAfter(g,k),this.app.getCategoriesManager().setCategoryRanking(g.getTitle(),h.items.indexOf(g)))},scope:this}],store:Ext.create("Ext.data.JsonStore",{data:b,fields:["term"]}),
viewConfig:{plugins:{ptype:"gridviewdragdrop",ddGroup:"terms",dragZone:{getDragText:function(){var g="";this.dragData.records.forEach(function(h){g+=h.get("term")+", "});return g.substr(0,g.length-2)}}}},selModel:{mode:"MULTI"},columns:[{dataIndex:"term",flex:1,sortable:!0}],listeners:{beforedrop:function(g,h){g=this.up("categoriesbuilder").categoriesManager;var k=h.view.up("grid");if(void 0!==k.category)for(var l=h.records.length-1;0<=l;l--){var m=h.records[l].get("term");g.removeTerm(k.category,
m)}},drop:function(g,h){h.view.getSelectionModel().deselectAll();this.getSelectionModel().deselectAll();g=this.up("categoriesbuilder").categoriesManager;for(var k=[],l=0;l<h.records.length;l++){var m=h.records[l].get("term");k.push(m)}g.addTerms(a,k)}}}),f=new Ext.Editor({updateEl:!0,alignment:"l-l",autoSize:{width:"boundEl"},field:{xtype:"textfield",allowBlank:!1,validator:function(g){return void 0===this.categoriesManager.getCategoryTerms(g)||g===e.getTitle()?!0:this.localize("exists")}.bind(this)},
listeners:{complete:function(g,h,k){this.categoriesManager.renameCategory(k,h);this.buildFeatures()},scope:this}});e.header.getTitle().textEl.on("dblclick",function(g,h){f.startEdit(h)})},removeCategory:function(a){var b=this.queryById("categories"),c=b.queryBy(function(d){return d.category&&d.category==a?!0:!1});b.remove(c[0]);b=this.queryById("features").getStore();b.removeAt(b.findExact("category",a));this.categoriesManager.removeCategory(a)},addFeature:function(a){this.categoriesManager.addFeature(a);
this.buildFeatures()},buildFeatures:function(){this.queryById("features").getStore().removeAll();var a=["category"],b=[{sortable:!1,text:this.localize("category"),dataIndex:"category",flex:1}],c=[],d;for(d in this.categoriesManager.getCategories())c.push({category:d});var e=this.categoriesManager.getFeatures(),f=Ext.ClassManager.getClass(this).features;if(0===Object.entries(e).length)for(var g in f)for(d in e[g]={},this.categoriesManager.getCategories())e[g][d]=void 0;for(g in e){a.push(g);e=f[g];
var h=Ext.applyIf({feature:g,listeners:{change:function(k,l){if(k.rendered){var m=k.up("gridview").indexOf(k.el.up("table")),n=k.up("grid").getStore().getAt(m);n?n.set(k.feature,l):window.console&&console.warn("no record for",m,k)}},scope:this}},e);e.listeners&&Ext.applyIf(h.listeners,e.listeners);b.push({sortable:!1,hideable:!1,text:this.localize(g),dataIndex:g,flex:.5,xtype:"widgetcolumn",widget:h});for(d in this.categoriesManager.getCategories())for(e=this.categoriesManager.getCategoryFeature(d,
g),h=0;h<c.length;h++)if(c[h].category==d){c[h][g]=e;break}}a=Ext.create("Ext.data.JsonStore",{fields:a,data:c});this.queryById("features").reconfigure(a,b)},processFeatures:function(){var a=this.queryById("features").getStore(),b=Object.keys(this.categoriesManager.getFeatures());a.each(function(c){var d=c.get("category");b.forEach(function(e){var f=c.get(e);void 0!==f&&this.categoriesManager.setCategoryFeature(d,e,f)},this)},this)},setColorTermsFromCategoryFeatures:function(){for(var a in this.categoriesManager.getCategories()){var b=
this.categoriesManager.getCategoryFeature(a,"color");if(void 0!==b){b=this.app.hexToRgb(b);for(var c=this.categoriesManager.getCategoryTerms(a),d=0;d<c.length;d++)this.app.setColorForTerm(c[d],b)}}},buildCategories:function(){this.queryById("categories").removeAll();var a=this.categoriesManager.getCategories(),b;for(b in a)this.addCategory(b)}});
Ext.define("Voyant.categories.CategoriesMenu",{extend:"Ext.menu.Menu",alias:"widget.categoriesmenu",config:{terms:[]},constructor:function(a){a=a||{};a.panel?(this.panel=a.panel,this.app=this.panel.getApplication(),this.categoriesManager=this.app.getCategoriesManager()):window.console&&console.warn("can't find panel!");this.callParent(arguments)},setColorTermsFromCategoryFeatures:function(){for(var a in this.categoriesManager.getCategories()){var b=this.categoriesManager.getCategoryFeature(a,"color");
if(void 0!==b){b=this.app.hexToRgb(b);for(var c=this.categoriesManager.getCategoryTerms(a),d=0;d<c.length;d++)this.app.setColorForTerm(c[d],b)}}},initComponent:function(){Ext.apply(this,{items:[{text:"Set category for selected terms",menu:{minWidth:250,itemId:"cats",items:[],minButtonWidth:50,fbar:[{xtype:"button",text:"Ok",handler:function(a){var b=this.getTerms(),c=[],d=[];a.up("menu").items.each(function(e){e.checked?c.push(e.text):d.push(e.text)});d.forEach(function(e){this.categoriesManager.removeTerms(e,
b)},this);c.forEach(function(e){this.categoriesManager.addTerms(e,b)},this);a.up("menu").up("menu").hide();this.setColorTermsFromCategoryFeatures();this.fireEvent("categorySet",this,c)},scope:this},{xtype:"button",text:"Cancel",handler:function(a){a.up("menu").up("menu").hide()}},{xtype:"tbfill"},{xtype:"button",glyph:"xf013@FontAwesome",tooltip:"Show Categories Builder",handler:function(a){void 0===Voyant.categories.Builder&&(Voyant.categories.Builder=Ext.create("Voyant.categories.CategoriesBuilder",
{panel:this.panel}));Voyant.categories.Builder.show()},scope:this}]}}],listeners:{beforeshow:function(a){var b=this.categoriesManager.getCategories();a=a.down("#cats");a.removeAll();var c=this.getTerms();c=Array.isArray(c)?c[0]:c;var d=this.categoriesManager.getCategoriesForTerm(c);a.add(Object.keys(b).map(function(e){return{text:e,xtype:"menucheckitem",checked:-1!==d.indexOf(e)}}))},scope:this}});this.callParent(arguments)}});Ext.define("Voyant.widget.VoyantNetworkGraph",{extend:"Ext.panel.Panel",mixins:["Voyant.util.Localization","Voyant.util.Api"],alias:"widget.voyantnetworkgraph",statics:{i18n:{},api:{jsonData:void 0,docId:void 0,docIndex:void 0,json:void 0,api:void 0}},config:{vis:void 0,visLayout:void 0,nodeData:void 0,edgeData:void 0,nodeSelection:void 0,edgeSelection:void 0,currentNode:void 0,currentEdge:void 0,zoom:void 0,zoomExtent:[.25,8],dragging:!1,nodeScaling:{minSize:8,maxSize:36,scalingFunction:void 0},
edgeScaling:{minSize:1,maxSize:10,scalingFunction:void 0},graphStyle:{node:{normal:{fill:"#c6dbef",fillOpacity:1,stroke:"#6baed6",strokeOpacity:1,strokeWidth:1},highlight:{fill:"#9ecae1",fillOpacity:1,stroke:"#3182bd",strokeOpacity:1,strokeWidth:3}},edge:{normal:{stroke:"#000000",strokeOpacity:.25,strokeWidth:1},highlight:{stroke:"#000000",strokeOpacity:.5,strokeWidth:3}}},graphPhysics:{damping:.4,centralGravity:.1,nodeGravity:-50,springLength:100,springStrength:.25,collisionScale:1.25}},constructor:function(a){a=
a||{};this.setNodeData([]);this.setEdgeData([]);this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);this.callParent(arguments);var b={};this.getApiParam("jsonData")?b=Ext.decode(this.getApiParam("jsonData")):this.getApiParam("json")?b=this.getApiParam("json"):a.json?b=a.json:a.edges?(b.edges=a.edges,a.nodes&&(b.nodes=a.nodes)):a&&a.jsonData&&(b=JSON.parse(a.jsonData));this.loadJson(b)},initComponent:function(a){this.on("boxready",function(b,c){this.initGraph();this.refreshGraph()},this);
this.on("resize",function(b,c,d){if(b=this.body.down("svg"))d=this.body,c=d.getHeight(),d=d.getWidth(),b.dom.setAttribute("width",d),b.dom.setAttribute("height",c),this.getVisLayout().force("x",d3.forceX(d/2)).force("y",d3.forceY(c/2)),Ext.Function.defer(this.zoomToFit,100,this)},this);this.callParent(arguments)},loadJson:function(a){this.processJson(a);var b={};this.getNodeData().forEach(function(e){b[e.term]=!0},this);var c=[],d=[];a.nodes.forEach(function(e){void 0===b[e.term]&&(e.id=this.idGet(e.term),
c.push(e))},this);a.edges.forEach(function(e){for(var f=this.idGet(e.source),g=this.idGet(e.target),h=this.getEdgeData(),k=!1,l=0;l<h.length;l++){var m=h[l];if(m.source.id==f&&m.target.id==g||m.target.id==f&&m.source.id==g){k=!0;break}}k||(e.source=f,e.target=g,e.id=f+"-"+g,d.push(e))},this);this.setNodeData(this.getNodeData().concat(c));this.setEdgeData(this.getEdgeData().concat(d));this.refreshGraph()},processJson:function(a){a&&a.edges||(a&&a.links&&(a.edges=a.links,delete a.links),a&&a.edges||
(a=a||{},a.edges=[]));a.nodes||(a.nodes=[]);if(0===a.nodes.length){var b={};a.edges.forEach(function(c){["source","target"].forEach(function(d){d=c[d];0==d in b?(b[d]=1,a.nodes.push({term:d})):b[d]++;c.value=1})},this);a.nodes.forEach(function(c){Ext.applyIf(c,{value:void 0===b[c.term]?1:b[c.term]})})}else a.nodes.forEach(function(c){Ext.applyIf(c,{value:1})});return a},idGet:function(a){return"vng_"+a.replace(/\W/g,"_")},updateDataForNode:function(a,b){for(var c=this.getNodeData(),d=0;d<c.length;d++)if(c[d].id===
a){Ext.apply(c[d],b);break}},updateDataForEdge:function(a,b){for(var c=this.getEdgeData(),d=0;d<c.length;d++)if(c[d].id===a){Ext.apply(c[d],b);break}},addNode:function(a){Ext.isString(a)&&(a={term:a});a.term&&this.loadJson({nodes:[a]})},removeNode:function(a,b){for(var c=this.getNodeData(),d=0;d<c.length;d++)if(c[d].id===a){c.splice(d,1);break}var e={};c=this.getEdgeData();for(d=c.length-1;0<=d;d--){var f=!1;c[d].source.id===a&&(f=!0,e[c[d].target.id]=!0);c[d].target.id===a&&(f=!0,e[c[d].source.id]=
!0);f&&c.splice(d,1)}if(b){for(d=0;d<c.length;d++)e[c[d].source.id]&&delete e[c[d].source.id],e[c[d].target.id]&&delete e[c[d].target.id];for(var g in e)this.removeNode(g,!0)}this.refreshGraph()},addEdge:function(a){Ext.isObject(a)&&a.source&&a.target&&this.loadJson({edges:[a]})},removeEdge:function(a,b){for(var c=this.getEdgeData(),d=c.length-1;0<=d;d--)c[d].id===a&&c.splice(d,1);if(b){a={};c=this.getNodeData();for(d=0;d<c.length;d++)a[c[d].id]=!0;c=this.getEdgeData();for(d=0;d<c.length;d++)a[c[d].source.id]&&
delete a[c[d].source.id],a[c[d].target.id]&&delete a[c[d].target.id];for(var e in a)this.removeNode(e,!0)}this.refreshGraph()},initGraph:function(){var a=this.getLayout().getRenderTarget();a.update("");var b=a.getWidth(),c=a.getHeight(),d=this.getGraphPhysics();this.setVisLayout(d3.forceSimulation().velocityDecay(d.damping).force("x",d3.forceX(b/2).strength(d.centralGravity)).force("y",d3.forceY(c/2).strength(d.centralGravity)).force("link",d3.forceLink().id(function(f){return f.id}).distance(d.springLength).strength(d.springStrength)).force("charge",
d3.forceManyBody().strength(d.nodeGravity)).force("collide",d3.forceCollide().radius(function(f){return Math.sqrt(f.bbox.width*f.bbox.height)*d.collisionScale})).on("tick",function(){this.getEdgeSelection().attr("x1",function(f){return f.source.x}).attr("y1",function(f){return f.source.y}).attr("x2",function(f){return f.target.x}).attr("y2",function(f){return f.target.y});this.getNodeSelection().attr("transform",function(f){return"translate("+(f.x-.5*f.bbox.width)+","+(f.y-.5*f.bbox.height)+")"});
.075>this.getVisLayout().alpha()&&this.getVisLayout().alpha(-1)}.bind(this)).on("end",function(){Ext.Function.defer(this.zoomToFit,100,this)}.bind(this)));a=d3.select(a.dom).append("svg").attr("width",b).attr("height",c);var e=a.append("g");b=d3.zoom().scaleExtent(this.getZoomExtent()).on("zoom",function(){e.attr("transform",d3.event.transform)});this.setZoom(b);a.call(b);this.setEdgeSelection(e.append("g").attr("class","edges").selectAll(".edge"));this.setNodeSelection(e.append("g").attr("class",
"nodes").selectAll(".node"));this.setVis(e)},resetGraph:function(){this.setNodeData([]);this.setEdgeData([]);this.refreshGraph()},refreshGraph:function(){if(void 0!==this.getVisLayout()){var a=this.getEdgeData(),b=this.getNodeData(),c=d3.extent(b,function(g){return g.value}),d=d3.extent(a,function(g){return g.value}),e=this.getEdgeScaling();void 0===e.scalingFunction&&(e.scalingFunction=d3.scaleLinear().domain(d).range([e.minSize,e.maxSize]));var f=this.getNodeScaling();void 0===f.scalingFunction&&
(f.scalingFunction=d3.scaleLog().domain(c).range([f.minSize,f.maxSize]));c=this.getEdgeSelection().data(a,function(g){return g.id});c.exit().remove();d=c.enter().append("line").attr("class","edge").attr("id",function(g){return g.id}).style("cursor","pointer").style("stroke-width",function(g){return e.scalingFunction(g.value)}).on("mouseover",this.edgeMouseOver.bind(this)).on("mouseout",this.edgeMouseOut.bind(this)).on("click",function(g){d3.event.stopImmediatePropagation();d3.event.preventDefault();
this.setCurrentEdge(g);this.fireEvent("edgeclicked",this,g)}.bind(this));this.setEdgeSelection(d.merge(c));c=this.getNodeSelection().data(b,function(g){return g.id});c.exit().remove();d=c.enter().append("g").attr("class","node").attr("id",function(g){return g.id}).style("cursor","pointer").on("mouseover",this.nodeMouseOver.bind(this)).on("mouseout",this.nodeMouseOut.bind(this)).on("click",function(g){d3.event.stopImmediatePropagation();d3.event.preventDefault();this.setCurrentNode(g);this.fireEvent("nodeclicked",
this,g)}.bind(this)).on("dblclick",function(g){d3.event.stopImmediatePropagation();d3.event.preventDefault();this.fireEvent("nodedblclicked",this,g)}.bind(this)).on("contextmenu",function(g){d3.event.stopImmediatePropagation();d3.event.preventDefault();this.fireEvent("nodecontextclicked",this,g)}.bind(this)).call(d3.drag().on("start",function(g){this.setDragging(!0);d3.event.active||this.getVisLayout().alpha(.3).restart();g.fx=g.x;g.fy=g.y;g.fixed=!0;this.fireEvent("nodedragstart",this,g)}.bind(this)).on("drag",
function(g){this.getVisLayout().alpha(.3);g.fx=d3.event.x;g.fy=d3.event.y;this.fireEvent("nodedrag",this,g)}.bind(this)).on("end",function(g){this.setDragging(!1);1!=g.fixed&&(g.fx=null,g.fy=null);this.fireEvent("nodedragend",this,g)}.bind(this)));d.append("rect");d.append("text").text(function(g){return g.term}).attr("font-family",function(g){return Voyant.application.getCategoriesManager().getFeatureForTerm("font",g.term)}).attr("font-size",function(g){return f.scalingFunction(g.value)+"px"}).attr("dominant-baseline",
"middle").style("user-select","none").each(function(g){g.bbox=this.getBBox()});this.setNodeSelection(d.merge(c));this.getNodeSelection().selectAll("rect").attr("width",function(g){return g.bbox.width+16}).attr("height",function(g){return g.bbox.height+8}).attr("rx",function(g){return Math.max(2,.2*g.bbox.height)}).attr("ry",function(g){return Math.max(2,.2*g.bbox.height)});this.getNodeSelection().selectAll("text").attr("dx",8).attr("dy",function(g){return.5*g.bbox.height+4});this.getEdgeSelection().call(this.applyEdgeStyle.bind(this));
this.getNodeSelection().call(this.applyNodeStyle.bind(this));this.getVisLayout().nodes(b);this.getVisLayout().force("link").links(a);this.getVisLayout().alpha(1).restart()}},zoomToFit:function(a,b){var c=this.getVis().node().getBBox(),d=c.width,e=c.height,f=c.x+d/2,g=c.y+e/2;c=this.getVis().node().parentElement;var h=c.getBoundingClientRect(),k=h.width;h=h.height;a=(a||.8)/Math.max(d/k,e/h);f=[k/2-a*f,h/2-a*g];1>d||d3.select(c).transition().duration(b||500).call(this.getZoom().transform,d3.zoomIdentity.translate(f[0],
f[1]).scale(a))},nodeScaling:function(a,b,c,d){return a===b?.5:Math.max(0,1/(b-a)*(d-a))},applyNodeStyle:function(a,b){b=void 0===b?"normal":b;var c=this.getGraphStyle().node[b];a.selectAll("rect").style("fill",function(d){return c.fill}.bind(this)).style("fill-opacity",function(d){return c.fillOpacity}.bind(this)).style("stroke",function(d){return c.stroke}.bind(this)).style("stroke-opacity",function(d){return c.strokeOpacity}.bind(this)).style("stroke-width",function(d){return c.strokeWidth}.bind(this))},
applyEdgeStyle:function(a,b){b=void 0===b?"normal":b;var c=this.getGraphStyle().edge[b];a.style("stroke",function(d){return c.stroke}.bind(this)).style("stroke-opacity",function(d){return c.strokeOpacity}.bind(this))},edgeMouseOver:function(a){this.getEdgeSelection().call(this.applyEdgeStyle.bind(this));this.getVis().select("#"+a.id).call(this.applyEdgeStyle.bind(this),"highlight")},edgeMouseOut:function(a){this.getEdgeSelection().call(this.applyEdgeStyle.bind(this))},nodeMouseOver:function(a){this.setCurrentNode(a);
this.getNodeSelection().call(this.applyNodeStyle.bind(this));this.getEdgeSelection().each(function(b){if(b.source.id==a.id)var c=b.target.id;else b.target.id==a.id&&(c=b.source.id);void 0!==c&&(this.getVis().select("#"+c).call(this.applyNodeStyle.bind(this),"highlight"),this.getVis().select("#"+b.id).call(this.applyEdgeStyle.bind(this),"highlight"))}.bind(this));this.getVis().select("#"+a.id).call(this.applyNodeStyle.bind(this),"highlight")},nodeMouseOut:function(a){this.getNodeSelection().call(this.applyNodeStyle.bind(this));
this.getEdgeSelection().call(this.applyEdgeStyle.bind(this))}});Ext.define("Voyant.widget.ReaderGraph",{extend:"Ext.container.Container",mixins:["Voyant.util.Localization"],alias:"widget.readergraph",statics:{i18n:{}},config:{parentPanel:void 0,corpus:void 0,documentsStore:void 0,locationMarker:void 0,isDetailedGraph:!0,seriesToolTip:void 0},locationMarkerColor:"#157fcc",DETAILED_GRAPH_DOC_LIMIT:25,LOCATION_UPDATE_FREQ:100,SCROLL_UP:-1,SCROLL_EQ:0,SCROLL_DOWN:1,RESERVED_KEYS:["id","docIndex","readerGraphPadding","readerGraphTotal"],constructor:function(a){this.callParent(arguments)},
initComponent:function(){Ext.apply(this,{layout:{type:"hbox"},items:[]});this.callParent(arguments);var a=this.findParentBy(function(b){return b.mixins["Voyant.panel.Panel"]});if(null!=a)if(this.setParentPanel(a),a.getCorpus&&a.getCorpus())this.on("afterrender",function(b){this.setCorpus(a.getCorpus())},this);else a.on("loadedCorpus",function(b,c){this.setCorpus(c)},this),this.hasCorpusLoadedListener=!0;this.setSeriesToolTip(Ext.create("Ext.tip.ToolTip",{style:"background: #fff",dismissDelay:0}));
this.on("boxready",function(){void 0==this.getLocationMarker()&&this.setLocationMarker(Ext.DomHelper.append(this.getEl(),{tag:"div",style:"background-color: "+this.locationMarkerColor+"; height: 100%; width: 2px; z-index: 3; position: absolute; top: 0; left: 0;"}))})},updateCorpus:function(a){a=a.getDocuments();this.setDocumentsStore(a);this.setIsDetailedGraph(a.getTotalCount()<this.DETAILED_GRAPH_DOC_LIMIT);this.generateChart()},loadQueryTerms:function(a){this.getIsDetailedGraph()?this.getCorpus().getDocumentTerms().load({params:{query:a,
limit:-1,withDistributions:!0},callback:function(b,c){this.populateDetailedChart(b)},scope:this}):this.getCorpus().getCorpusTerms().load({params:{query:a,limit:-1,withDistributions:!0},callback:function(b,c){this.populateChart(b)},scope:this})},populateDetailedChart:function(a){var b={},c=0;a.forEach(function(m){var n=[],u=m.get("distributions"),w=m.get("docId"),p=m.get("docIndex");m=m.get("term");for(var q=0;q<u.length;q++){var r=u[q];r>c&&(c=r);n.push([w,p,q,r,m])}void 0===b[p]&&(b[p]={});b[p][m]=
n});a=this.query("cartesian");for(var d=0;d<a.length;d++){var e=a[d],f=b[d];if(void 0!==f){var g=[],h;for(h in f){var k=f[h],l=this.getParentPanel().getApplication().getColorForTerm(h,!0);g.push({type:"line",xField:"bin",yField:"distribution",style:{lineWidth:1,strokeStyle:l},store:Ext.create("Ext.data.ArrayStore",{fields:["docId","docIndex","bin","distribution","term"],data:k})})}e.getAxes()[0].setMaximum(c);e.setSeries(g)}}},populateChart:function(a){var b={};this.getCorpus().getDocuments().each(function(g,
h){b[h]={}});var c=[];a.forEach(function(g){var h=g.get("term");-1===c.indexOf(h)&&c.push(h);g.get("distributions").forEach(function(k,l){b[l][h]=k})});c.push("readerGraphPadding");a=Object.entries(b).map(function(g){return Object.assign({docIndex:parseInt(g[0])},g[1])});var d=-1;a.forEach(function(g){var h=Object.entries(g).filter(function(k){return"docIndex"!==k[0]}).map(function(k){return k[1]}).reduce(function(k,l){return k+l});g.readerGraphTotal=h;h>d&&(d=h)});a.forEach(function(g){g.readerGraphPadding=
d-g.readerGraphTotal});var e={type:"bar",stacked:!0,fullStack:!0,xField:"docIndex",yField:c,style:{minGapWidth:0,minBarWidth:1,lineWidth:0,strokeStyle:"none"},renderer:function(g,h,k,l){g=g.getField();return{fillStyle:"readerGraphPadding"===g?this.getColor(l,.3):this.getParentPanel().getApplication().getColorForTerm(g,!0)}}.bind(this)},f=this.down("cartesian");f.getAxes()[0].setFields(c);f.setSeries(e);f.setStore(Ext.create("Ext.data.JsonStore",{fields:["docIndex"].concat(c),data:a}))},getColor:function(a,
b){return"rgba("+(0===a%2?[200,200,200]:[240,240,240]).join(",")+","+b+")"},generateChart:function(){function a(k){var l=k.fraction,m=k.relativeHeight,n=this.getColor(k.docIndex,.3),u=b.add({xtype:"cartesian",plugins:{ptype:"chartitemevents"},flex:l,height:"100%",insetPadding:0,background:{type:"linear",degrees:90,stops:[{offset:0,color:n},{offset:m,color:n},{offset:m,color:"white"},{offset:1,color:"white"}]},axes:[{type:"numeric",position:"left",fields:"distribution",hidden:!0},{type:"category",
position:"bottom",fields:"bin",hidden:!0}],listeners:{itemmouseover:function(w,p,q){var r=this.getCorpus().getDocument(p.record.get("docIndex")).getTitle();w.getSeries().forEach(function(v){var x=v.getItemByIndex(p.index);v=x.record.get("term");x=x.record.get("distribution");r+="\x3cbr\x3e"+v+": "+x},this);this.getSeriesToolTip().setHtml(r);w=q.getXY();w[0]+=15;w[1]+=18;this.getSeriesToolTip().showAt(w)},scope:this}});u.body.on("mouseenter",function(w,p){0===u.getSeries().length&&(p=this.getCorpus().getDocument(k.docIndex).getTitle(),
this.getSeriesToolTip().setHtml(p),w=w.getXY(),w[0]+=15,w[1]+=18,this.getSeriesToolTip().showAt(w))},this);u.body.on("mouseleave",function(w,p){this.getSeriesToolTip().hide()},this);u.body.on("click",function(w,p){p=Ext.get(p);w=w.getX();var q=p.getBox();w=(w-q.x)/q.width;p=p.parent(".x-panel");q=p.parent();p=Ext.toArray(q.dom.children).indexOf(p.dom);this.fireEvent("documentRelativePositionSelected",this,{docIndex:p,fraction:w})},this)}var b=this;b.removeAll();for(var c=b.getCorpus().getDocuments(),
d=b.getCorpus().getWordTokensCount(),e=[],f=0;f<c.getCount();f++){var g=c.getAt(f),h=g.get("index");g=g.get("tokensCount-lexical")/d;e.push({docIndex:h,count:1,fraction:g})}if(this.getIsDetailedGraph())for(f=0;f<e.length;f++)g=e[f],g.relativeHeight=1,a.call(this,g);else b.add({xtype:"cartesian",plugins:{ptype:"chartitemevents"},flex:1,height:"100%",animation:!1,insetPadding:0,axes:[{type:"numeric",position:"left",fields:"count",hidden:!0},{type:"category",position:"bottom",fields:"docIndex",hidden:!0}],
series:[{type:"bar",xField:"docIndex",yField:"count",style:{minGapWidth:0,minBarWidth:1,lineWidth:0,strokeStyle:"none"},renderer:function(k,l,m,n){return{fillStyle:this.getColor.call(this,n,.3)}}.bind(this)}],store:Ext.create("Ext.data.JsonStore",{fields:[{name:"docIndex",type:"int"},{name:"count",type:"int"}],data:e}),listeners:{itemmouseover:function(k,l,m){var n=this.getCorpus().getDocument(l.record.get("docIndex")).getTitle();k.getSeries()[0].getFullStack()&&Object.keys(l.record.data).filter(function(u){return-1===
b.RESERVED_KEYS.indexOf(u)}).forEach(function(u){n+="\x3cbr\x3e"+u+": "+l.record.data[u]},this);this.getSeriesToolTip().setHtml(n);k=m.getXY();k[0]+=15;k[1]+=18;this.getSeriesToolTip().showAt(k)},itemclick:function(k,l,m){k=Ext.get(m.getTarget());m=m.getX();k=k.getBox();var n=k.width/this.getCorpus().getDocuments().getCount();m=(m-k.x)%n/n;l=l.record.get("docIndex");l=this.getDocumentsStore().getAt(l).getIndex();this.fireEvent("documentRelativePositionSelected",this,{docIndex:l,fraction:m})},scope:this}}).body.on("mouseleave",
function(k,l){this.getSeriesToolTip().hide()},this)},moveLocationMarker:function(a,b,c){var d=Ext.get(this.getLocationMarker()),e=d.getX();if(this.getIsDetailedGraph()){var f=this.query("cartesian")[a];f&&(e=f.getX()+f.getWidth()*b)}else if(f=this.down("cartesian"))e=f.getWidth()/this.getCorpus().getDocuments().getCount(),e=f.getX()+e*a+e*b;null!=c&&(a=d.getX(),c==this.SCROLL_DOWN&&a>e||c==this.SCROLL_UP&&a<e)&&(e=a);d.setX(e)}});Ext.define("Voyant.widget.EntitiesList",{extend:"Ext.grid.Panel",mixins:["Voyant.util.Localization"],alias:"widget.entitieslist",statics:{i18n:{term:"Term",count:"Count",next:"Next Occurrence",prev:"Previous Occurrence",date:"Date",person:"Person",gpe:"Geopolitical Entity",loc:"Location",money:"Money",time:"Time",product:"Product",cardinal:"Cardinal",quantity:"Quantity",event:"Event",fac:"Facility",language:"Language",law:"Law",norp:"National/Religious/Political",percent:"Percent",work_of_art:"Work of Art",
unknown:"Unknown",duration:"Duration",location:"Location",misc:"Misc",organization:"Organization",set:"Set"}},bins:25,initComponent:function(){var a=this;Ext.apply(this,{title:"Entities",forceFit:!0,store:Ext.create("Ext.data.JsonStore",{fields:"term normalized type docIndex rawFreq positions offset".split(" "),groupField:"type",sorters:[{property:"rawFreq",direction:"DESC"}]}),features:[{ftype:"grouping",hideGroupedHeader:!0,enableGroupingMenu:!1,startCollapsed:!0,groupHeaderTpl:["{name:this.localizeName} ({children.length})",
{localizeName:function(b){return a.localize(b)}}]}],plugins:[{ptype:"rowexpander",rowBodyTpl:new Ext.XTemplate(""),expandOnDblClick:!1}],viewConfig:{listeners:{expandbody:function(b,c,d,e){a.getSelectionModel().select(c,!1,!0);if(""===d.textContent||e&&e.force)b=d.querySelector("div.x-grid-rowbody"),Ext.create("Ext.container.Container",{currentEntityPositionIndex:0,handlePositionChange:function(f){0>f?(this.currentEntityPositionIndex--,0>this.currentEntityPositionIndex&&(this.currentEntityPositionIndex=
c.get("positions").length-1)):(this.currentEntityPositionIndex++,this.currentEntityPositionIndex>c.get("positions").length-1&&(this.currentEntityPositionIndex=0));for(var g=c.get("distribution"),h=f=0,k=0;k<g.length;k++)if(h+=g[k],h>this.currentEntityPositionIndex){f=k;break}g=this.down("sparklinebar");h=g.canvas.el.getBox();k=g.getBarWidth()+g.getBarSpacing();f=Ext.create("Ext.event.Event",new MouseEvent("mousemove",{clientX:h.x+k*f,clientY:h.y+.5*h.height}));g.onMouseMove(f);Voyant.application.dispatchEvent("entityLocationClicked",
this,c,this.currentEntityPositionIndex)},layout:{type:"hbox",align:"middle"},renderTo:b,items:[{xtype:"button",glyph:"xf060@FontAwesome",tooltip:a.localize("prev"),handler:function(f,g){f.up("container").handlePositionChange(-1)}},{xtype:"button",glyph:"xf061@FontAwesome",tooltip:a.localize("next"),margin:"0 5",handler:function(f,g){f.up("container").handlePositionChange(1)}},{xtype:"sparklinebar",values:c.get("distribution"),highlightColor:"#f80",height:24,tipTpl:!1,width:b.offsetWidth-80}],listeners:{boxready:function(f){setTimeout(function(){f.currentEntityPositionIndex=
-1;f.handlePositionChange(1)},50)}}})}}},columns:[{text:this.localize("term"),dataIndex:"term",flex:1},{text:this.localize("count"),dataIndex:"rawFreq",width:50}],listeners:{select:function(b,c,d){Voyant.application.dispatchEvent("entityClicked",this,c)},columnresize:function(b,c,d){}}});this.callParent(arguments)},clearEntities:function(){var a=this.getStore();void 0!==a&&a.removeAll()},addEntities:function(a){var b=this.getStore();if(void 0!==b){var c=!1;0<b.count()&&0<a.length&&(c=b.first().get("docIndex")===
a[0].docIndex);a.forEach(function(d){d.positions?d.distribution=this.getDistributionFromPositions(d.docIndex,d.positions,this.bins):(console.warn("no positions for:",d),d.distribution=[])},this);b.loadData(a,c);!1===c&&this.view.findFeature("grouping").collapseAll()}},getDistributionFromPositions:function(a,b,c){a=Voyant.application.getCorpus().getDocument(a).get("tokensCount-lexical");var d=Math.floor(a/c),e=Array(c);for(a=0;a<c;a++)e[a]=0;b.forEach(function(f){f=Array.isArray(f)?Math.floor(f[0]/
d):Math.floor(f/d);e[f]++});return e}});Ext.define("Voyant.panel.Panel",{mixins:["Voyant.util.Localization","Voyant.util.Api","Voyant.util.Toolable","Voyant.util.DetailedError"],requires:["Voyant.widget.QuerySearchField","Voyant.widget.StopListOption","Voyant.categories.CategoriesOption","Voyant.widget.TotalPropertyStatus"],alias:"widget.voyantpanel",statics:{i18n:{},config:{corpusValidated:!1},api:{corpus:void 0,input:void 0,inputFormat:void 0,subtitle:void 0}},config:{corpus:void 0},constructor:function(a){this.mixins["Voyant.util.Api"].constructor.apply(this,
arguments);this.mixins["Voyant.util.Toolable"].constructor.apply(this,arguments);this.glyph||(this.glyph=Ext.ClassManager.getClass(this).glyph);this.on("afterrender",function(){"facet"!=this.getXType()&&this.getApiParam("subtitle")&&this.getTitle()&&this.setTitle(this.getTitle()+" \x3ci style\x3d'font-size: smaller;'\x3e"+this.getApiParam("subtitle")+"\x3c/i\x3e");this.isXType("grid")&&(this.on("boxready",function(){var b=this.getApiParam("columns");if(void 0!==b&&(!1===Array.isArray(b)&&(b=b.split(",")),
0<b.length)){var c=!1;this.getColumns().forEach(function(d){var e=-1!==b.indexOf(d.dataIndex);c=e||c;d.setVisible(e)});c||this.getColumns().forEach(function(d){d.setVisible(void 0!==d.initialConfig.hidden?!d.initialConfig.hidden:!0)})}},this),this.getSelectionModel().on("selectionchange",function(b,c){},this),this.getStore().on("beforeload",function(){this.selectedRecordsToRemember=this.getSelection()},this),this.getStore().on("load",function(b,c){if(0<Ext.Array.from(this.selectedRecordsToRemember).length){var d=
{};c=Ext.Array.merge(this.selectedRecordsToRemember,c).filter(function(e){return e.getId()in d?!1:d[e.getId()]=!0});b.isBufferedStore?1==b.currentPage&&(b.data.addAll(c),b.totalCount=c.length,b.fireEvent("refresh",b)):(b.loadRecords(c),this.getSelectionModel().select(this.selectedRecordsToRemember),b.fireEvent("refresh",b),this.selectedRecordsToRemember=[])}},this))},this);this.on({loadedCorpus:{fn:function(b,c){this.setApiParam("corpus",c.getAliasOrId());this.setCorpus(c)},priority:999,scope:this}})},
getApplication:function(){return Voyant.application},getBaseUrl:function(){return this.getApplication().getBaseUrl()},openUrl:function(a){this.getApplication().openUrl.apply(this,arguments)},getTromboneUrl:function(){return this.getApplication().getTromboneUrl()},dispatchEvent:function(){var a=this.getApplication();a.dispatchEvent.apply(a,arguments)},showError:function(a,b){Ext.isString(a)&&(a={message:a});Ext.applyIf(a,{title:this.localize("error")+" ("+this.localize("title")+")"});this.getApplication().showError(a,
b)},showResponseError:function(a,b){this.getApplication().showResponseError(a,b)},toastError:function(a){Ext.isString(a)&&(a={html:a});Ext.applyIf(a,{glyph:"xf071@FontAwesome",title:this.localize("error")});this.toast(a)},toastInfo:function(a){Ext.isString(a)&&(a={html:a});Ext.applyIf(a,{glyph:"xf05a@FontAwesome",title:this.localize("info")});this.toast(a)},toast:function(a){Ext.isString(a)&&(a={html:a});Ext.applyIf(a,{slideInDuration:500,shadow:!0,align:"b",anchor:this.getTargetEl()});Ext.toast(a)},
hasCorpusAccess:function(a){var b=this.getApplication();if(b){var c=b.getCorpusAccess();if("ADMIN"==c||"ACCESS"==c)return!0}a||(this.getCorpus&&(a=this.getCorpus()),!a&&b.getCorpus&&(a=b.getCorpus()));return a?"NONCONSUMPTIVE"!=a.getNoPasswordAccess()&&"NONE"!=a.getNoPasswordAccess():!1}});Ext.define("Voyant.panel.VoyantTabPanel",{extend:"Ext.tab.Panel",alias:"widget.voyanttabpanel",mixins:["Voyant.panel.Panel"],statics:{i18n:{}},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){this.callParent(arguments)},listeners:{tabchange:function(a,b){this.tools=[];this.getHeader().tools=[];this.query("toolmenu").forEach(function(c){c.destroy()});this.addTool(b.tools);this.getApplication().dispatchEvent("panelChange",
this)},afterrender:function(a){this.fireEvent("tabchange",this,this.getActiveTab())}},showOptionsClick:function(a){var b=a.getActiveTab();b.showOptionsClick&&b.showOptionsClick.apply(b,arguments)}});Ext.define("Voyant.widget.Facet",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.facet",statics:{i18n:{},api:{stopList:"auto",query:void 0}},constructor:function(a){this.callParent(arguments);Ext.applyIf(a||{},{includeTools:[],rowLines:!1,subtitle:void 0});this.mixins["Voyant.panel.Panel"].constructor.apply(this,[a])},rowLines:!1,initComponent:function(){var a=this;this.store||(this.store=new Ext.create("Voyant.data.store.CorpusFacets",{proxy:{extraParams:{facet:this.facet}},
parentPanel:this}),this.store.getProxy().on("exception",function(b,c,d,e){a.showResponseError("Unable to fetch facet: "+a.facet,c)}));Ext.applyIf(this,{emptyText:this.localize("emptyText"),hideHeaders:!0,selType:"checkboxmodel",columns:[{renderer:function(b,c,d){return"("+d.getInDocumentsCount()+") "+d.getLabel()},flex:1}]});this.callParent();this.corpus&&this.setStoreCorpus(this.corpus);this.on("loadedCorpus",function(b,c){this.setStoreCorpus(c)},this);this.on("query",function(b,c){this.setApiParam("query",
c);this.store.load({params:this.getApiParams()})})},setStoreCorpus:function(a){this.getStore()&&(this.getStore().setCorpus(a),this.getStore().load())}});Ext.define("Voyant.panel.Bubbles",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.bubbles",statics:{i18n:{},api:{stopList:"auto",docIndex:0,limit:100,audio:!1,speed:30},glyph:"xf06e@FontAwesome"},config:{options:{xtype:"stoplistoption"},audio:!1},corpusLoaded:!1,processingLoaded:!1,bubblesAppCode:void 0,bubbles:void 0,oscillator:void 0,gainNode:void 0,constructor:function(){this.mixins["Voyant.util.Localization"].constructor.apply(this,arguments);Ext.apply(this,{title:this.localize("title"),
html:'\x3ccanvas style\x3d"width: 100%; height: 100%"\x3e\x3c/canvas\x3e',dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"documentselectorbutton",singleSelect:!0},{xtype:"slider",fieldLabel:this.localize("speed"),labelAlign:"right",labelWidth:40,width:100,increment:1,minValue:1,maxValue:60,value:30,listeners:{render:function(a){a.setValue(parseInt(this.getApiParam("speed")));this.bubbles&&this.bubbles.frameRate(a.getValue());this.setAudio(a.getValue());Ext.tip.QuickTipManager.register({target:a.getEl(),
text:this.localize("speedTip")})},beforedestroy:function(a){Ext.tip.QuickTipManager.unregister(a.getEl())},changecomplete:function(a,b){this.setApiParam("speed",b);this.bubbles&&this.bubbles.frameRate(b)},scope:this}},{xtype:"checkbox",boxLabel:this.localize("sound"),listeners:{render:function(a){a.setValue(!0===this.getApiParam("audio")||"true"==this.getApiParam("audio"));this.setAudio(a.getValue());Ext.tip.QuickTipManager.register({target:a.getEl(),text:this.localize("soundTip")})},beforedestroy:function(a){Ext.tip.QuickTipManager.unregister(a.getEl())},
change:function(a,b){this.setApiParam("audio",b);this.setAudio(b)},scope:this}},{xtype:"tbfill"},{xtype:"tbtext",html:this.localize("adaptation")}]}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("boxready",function(){this.loadBubbles()});this.on("loadedCorpus",function(a,b){this.corpusLoaded=!0;this.bubbles?this.loadDocument():this.loadBubbles()},this);this.on("resize",function(){this.bubbles&&this.bubbles.size(this.body.getWidth(),this.body.getHeight())});
this.on("documentselected",function(a,b){this.setApiParam("docIndex",this.getCorpus().getDocument(b).getIndex());this.loadDocument()})},setAudio:function(a){this.gainNode&&(this.gainNode.gain.value=a?1:0);this.callParent(arguments)},handleCurrentTerm:function(a){this.oscillator&&(this.oscillator.frequency.value=this.terms[a]?parseInt(2E3*(this.terms[a]-this.minFreq)/(this.maxFreq-this.minFreq)):0)},handleDocFinished:function(){this.gainNode&&(this.gainNode.gain.value=0);var a=parseInt(this.getApiParam("docIndex"));
a+1<this.getCorpus().getDocumentsCount()&&(this.setApiParam("docIndex",a+1),this.loadDocument())},loadDocument:function(){var a=this,b=this.getCorpus().getDocument(parseInt(this.getApiParam("docIndex")));this.up("tabpanel")||this.setTitle(this.localize("title")+" \x3cspan class\x3d'subtitle'\x3e"+b.getFullLabel()+"\x3c/span\x3e");b.loadDocumentTerms(Ext.apply(this.getApiParams(["stopList"]),{limit:100})).then(function(c){a.terms={};c.each(function(d){a.terms[d.getTerm()]=d.getRawFreq()});c=Object.keys(a.terms).map(function(d){return a.terms[d]});
a.minFreq=Ext.Array.min(c);a.maxFreq=Ext.Array.max(c);a.getCorpus().loadTokens({whitelist:Object.keys(a.terms),noOthers:!0,limit:0,docIndex:a.getApiParam("docIndex")}).then(function(d){var e=[];d.each(function(f){e.push(f.getTerm().toLowerCase())});a.bubbles.setLines([b.getTitle(),e.join(" ")]);a.bubbles.loop();a.oscillator.frequency.value=150;a.gainNode.gain.value=a.getAudio()?1:0})})},loadBubbles:function(){if(void 0===this.bubbles&&this.processingLoaded&&void 0!==this.bubblesAppCode&&void 0!==
this.getTargetEl()){var a=this.getTargetEl().dom.querySelector("canvas");this.bubbles=new Processing(a,this.bubblesAppCode);this.bubbles.size(this.getTargetEl().getWidth(),this.getTargetEl().getHeight());this.bubbles.frameRate(this.getApiParam("speed"));this.bubbles.bindJavascript(this);this.bubbles.noLoop();this.bubblesAppCode=void 0;this.corpusLoaded&&this.loadDocument()}},initComponent:function(){Ext.Loader.loadScript({url:this.getBaseUrl()+"resources/processingjs/processing.min.js",onLoad:function(){this.processingLoaded=
!0;this.loadBubbles()},scope:this});Ext.Ajax.request({url:this.getBaseUrl()+"resources/bubbles/bubbles.pjs",success:function(b){this.bubblesAppCode=b.responseText;this.loadBubbles()},scope:this});var a=new (window.AudioContext||window.webkitAudioContext);this.oscillator=a.createOscillator();this.gainNode=a.createGain();this.oscillator.connect(this.gainNode);this.gainNode.connect(a.destination);this.oscillator.frequency.value=0;this.oscillator.start();this.gainNode.gain.value=0;this.callParent(arguments)}});Ext.define("Voyant.panel.Bubblelines",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.bubblelines",statics:{i18n:{},api:{bins:50,query:null,stopList:"auto",docId:void 0,docIndex:void 0,maxDocs:50},glyph:"xf06e@FontAwesome"},config:{bubblelines:void 0,termStore:void 0,docTermStore:void 0,selectedDocs:void 0,options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"colorpaletteoption"}]},termTpl:new Ext.XTemplate('\x3ctpl for\x3d"."\x3e','\x3cdiv class\x3d"term" style\x3d"color: rgb({color});float: left;padding: 3px;margin: 2px;"\x3e{term}\x3c/div\x3e',
"\x3c/tpl\x3e"),constructor:function(){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(a,b){this.setDocTermStore(b.getDocumentTerms({proxy:{extraParams:{withDistributions:"raw",withPositions:!0}},listeners:{load:function(c,d,e,f){d.forEach(function(g){var h=this.processTerms(g),k=g.get("docId");g=g.get("term");var l={};l[g]=h;this.getBubblelines().addTermsToDoc(l,k)},this);this.getBubblelines().doBubblelinesLayout()},scope:this}}));
this.isVisible()&&this.getBubblelines()&&this.initLoad()},this);this.on("activate",function(){this.getCorpus()&&Ext.Function.defer(this.initLoad,100,this)},this);this.on("query",function(a,b){void 0!==b&&""!=b&&this.getDocTermsFromQuery(b)},this);this.on("documentsSelected",function(a,b){this.setApiParam("docId",b);this.getBubblelines().cache.each(function(c){c.hidden=-1===b.indexOf(c.id)});this.getBubblelines().drawGraph()},this);this.on("termsClicked",function(a,b){if(a!==this){var c=[];b.forEach(function(d){Ext.isString(d)?
c.push(d):d.term?c.push(d.term):d.getTerm&&c.push(d.getTerm())});this.getDocTermsFromQuery(c)}},this);this.on("documentTermsClicked",function(a,b){var c=[];b.forEach(function(d){d.getTerm()&&c.push(d.getTerm())});this.getDocTermsFromQuery(c)},this);this.down("#granularity").setValue(parseInt(this.getApiParam("bins")))},initComponent:function(){this.setTermStore(Ext.create("Ext.data.ArrayStore",{fields:["term","color"],listeners:{load:function(a,b,c,d){a=this.down("#termsView");for(c=0;c<b.length;c++)a.select(b[c],
!0)},scope:this}}));Ext.apply(this,{title:this.localize("title"),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{text:this.localize("clearTerms"),glyph:"xf014@FontAwesome",handler:function(){this.down("#termsView").getSelectionModel().deselectAll(!0);this.getTermStore().removeAll();this.setApiParams({query:null});this.getBubblelines().removeAllTerms();this.getBubblelines().drawGraph()},scope:this},{xtype:"documentselectorbutton"},{xtype:"slider",
itemId:"granularity",fieldLabel:this.localize("granularity"),labelAlign:"right",labelWidth:70,width:150,increment:10,minValue:10,maxValue:300,listeners:{changecomplete:function(a,b){this.setApiParams({bins:b});this.getBubblelines().bubbleSpacing=b;this.reloadTermsData()},scope:this}},{xtype:"checkbox",boxLabel:this.localize("separateLines"),boxLabelAlign:"before",checked:!1,handler:function(a,b){this.getBubblelines().SEPARATE_LINES_FOR_TERMS=b;this.getBubblelines().lastClickedBubbles={};this.getBubblelines().setCanvasHeight();
this.getBubblelines().drawGraph()},scope:this}]}],border:!1,layout:"fit",items:{layout:{type:"vbox",align:"stretch"},defaults:{border:!1},items:[{height:30,itemId:"termsView",xtype:"dataview",store:this.getTermStore(),tpl:this.termTpl,itemSelector:"div.term",overItemCls:"over",selectedItemCls:"selected",selectionModel:{mode:"SIMPLE"},focusCls:"",listeners:{beforeitemclick:function(a,b,c,d,e,f){e.preventDefault();e.stopPropagation();a.fireEvent("itemcontextmenu",a,b,c,d,e,f);return!1},beforecontainerclick:function(){event.preventDefault();
event.stopPropagation();return!1},selectionchange:function(a,b){var c=this.down("#termsView"),d=[];c.getStore().each(function(g){-1!==b.indexOf(g)?(d.push(g.get("term")),Ext.fly(c.getNodeByRecord(g)).removeCls("unselected").addCls("selected")):Ext.fly(c.getNodeByRecord(g)).removeCls("selected").addCls("unselected")});for(var e in this.getBubblelines().lastClickedBubbles){a=this.getBubblelines().lastClickedBubbles[e];for(var f in a)-1==d.indexOf(f)&&delete this.getBubblelines().lastClickedBubbles[e][f]}this.getBubblelines().termsFilter=
d;this.getBubblelines().setCanvasHeight();this.getBubblelines().drawGraph()},itemcontextmenu:function(a,b,c,d,e){e.preventDefault();e.stopPropagation();var f=a.isSelected(c);(new Ext.menu.Menu({floating:!0,items:[{text:f?this.localize("hideTerm"):this.localize("showTerm"),handler:function(){f?a.deselect(d):a.select(d,!0)},scope:this},{text:this.localize("removeTerm"),handler:function(){a.deselect(d);var g=this.getTermStore().getAt(d).get("term");this.getTermStore().removeAt(d);a.refresh();this.getBubblelines().removeTerm(g);
this.getBubblelines().setCanvasHeight();this.getBubblelines().drawGraph()},scope:this}]})).showAt(e.getXY())},scope:this}},{flex:1,xtype:"container",autoEl:"div",itemId:"canvasParent",layout:"fit",overflowY:"auto",overflowX:"hidden"}],listeners:{render:function(a){a=this.down("#canvasParent");this.setBubblelines(new Bubblelines({container:a,clickHandler:this.bubbleClickHandler.bind(this)}));this.getBubblelines().bubbleSpacing=parseInt(this.getApiParam("bins"))},afterlayout:function(a){!1===this.getBubblelines().initialized&&
this.getBubblelines().initializeCanvas()},resize:function(a,b,c){this.getBubblelines().doBubblelinesLayout()},scope:this}}});this.callParent(arguments)},initLoad:function(){var a=[];this.getCorpus().getDocuments().each(function(b,c,d){c=c<this.getApiParam("maxDocs");this.getBubblelines().addDocToCache({id:b.getId(),index:b.getIndex(),title:b.getShortTitle(),totalTokens:b.get("tokensCount-lexical"),terms:{},hidden:!c});c&&a.push(b.getId())},this);this.setApiParam("docId",a);this.getCorpus().getCorpusTerms({autoload:!1}).load({callback:function(b,
c,d){var e=[];b.forEach(function(f,g){e.push(f.get("term"))},this);this.getDocTermsFromQuery(e)},scope:this,params:{limit:this.getApiParam("query")?void 0:5,stopList:this.getApiParams("stopList"),query:this.getApiParam("query")}})},getDocTermsFromQuery:function(a){a&&this.setApiParam("query",a);this.getCorpus()&&this.isVisible()&&this.getDocTermStore().load({params:this.getApiParams()})},reloadTermsData:function(){var a=[],b;for(b in this.getBubblelines().currentTerms)a.push(b);this.getDocTermsFromQuery(a)},
filterDocuments:function(){var a=this.getApiParam("docId");""==a&&(a=[],this.getCorpus().getDocuments().each(function(d,e){a.push(d.getId())}),this.setApiParams({docId:a}));"string"==typeof a&&(a=[a]);if(null==a){this.setSelectedDocs(this.getCorpus().getDocuments().clone());var b=this.getSelectedDocs().getCount();if(10<b)for(var c=10;c<b;c++)this.getSelectedDocs().removeAt(10);a=[];this.getSelectedDocs().eachKey(function(d,e){a.push(d)},this);this.setApiParams({docId:a})}else this.setSelectedDocs(this.getCorpus().getDocuments().filterBy(function(d,
e){return-1!=a.indexOf(e)},this))},processTerms:function(a){var b=a.get("term");var c=a.get("rawFreq");var d=a.get("positions");if(0<c){var e=this.getApplication().getColorForTerm(b);-1===this.getTermStore().find("term",b)&&(this.getTermStore().loadData([[b,e]],!0),b=this.getTermStore().find("term",b),this.down("#termsView").select(b,!0));a=a.get("distributions");c={positions:d,distributions:a,rawFreq:c,color:e}}else c=!1;return c},bubbleClickHandler:function(a){this.getApplication().dispatchEvent("termsClicked",
this,a)}});Ext.define("Voyant.panel.Catalogue",{extend:"Ext.panel.Panel",requires:["Voyant.widget.Facet"],mixins:["Voyant.panel.Panel","Voyant.util.Downloadable"],alias:"widget.catalogue",statics:{i18n:{},api:{config:void 0,stopList:"auto",facet:["facet.title","facet.author","facet.language"],title:void 0,splash:void 0,reader:"reader"},glyph:"xf1ea@FontAwesome"},config:{facets:{},matchingDocIds:[],customResultsHtml:void 0},constructor:function(a){a=a||{};this.mixins["Voyant.util.Api"].constructor.apply(this,
arguments);Ext.apply(this,{title:this.localize("title"),layout:{type:"hbox",align:"stretch"},items:[{layout:{type:"vbox",align:"stretch"},itemId:"facets",minWidth:175,width:250,defaults:{width:250,minHeight:150,flex:1,xtype:"facet",animCollapse:!1,collapseFirst:!1,includeTools:{close:{type:"close",tooltip:this.localize("closeFacetTip"),callback:function(b){delete this.facets[b.facet];b.destroy();this.updateResults();this.adjustFacetHeights()},scope:this},add:{type:"plus",tooltip:this.localize("plusFacetTip"),
callback:function(){this.addFacet()},scope:this}}},items:[]},{xtype:"splitter"},{html:a.customResultsHtml||"",itemId:"results",flex:1,minWidth:250,scrollable:!0,margin:5,getCorpus:function(){return this.findParentByType("panel").getCorpus()},listeners:{query:function(b,c){this.findParentByType("panel").updateResults(Ext.isString(c)?[c]:c)}},dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{itemId:"sendToVoyant",text:this.localize("sendToVoyantButton"),disabled:!0,handler:function(){this.mask(this.localize("exportInProgress"));
var b=this;Ext.Ajax.request({url:this.getApplication().getTromboneUrl(),params:{corpus:this.getCorpus().getId(),tool:"corpus.CorpusManager",keepDocuments:!0,docId:this.getMatchingDocIds()},success:function(c,d){b.unmask();c=Ext.JSON.decode(c.responseText);c=b.getBaseUrl()+"?corpus\x3d"+c.corpus.id;b.openUrl(c)},failure:function(c,d){b.unmask();b.showResponseError("Unable to export corpus: "+b.getCorpus().getId(),c)}})},scope:this},{itemId:"export",text:this.localize("downloadButton"),disabled:!0,
handler:function(){this.mask(this.localize("exportInProgress"));var b=this;Ext.Ajax.request({url:this.getApplication().getTromboneUrl(),params:{corpus:this.getCorpus().getId(),tool:"corpus.CorpusManager",keepDocuments:!0,docId:this.getMatchingDocIds()},success:function(c,d){b.unmask();c=Ext.JSON.decode(c.responseText);b.downloadFromCorpusId(c.corpus.id)},failure:function(c,d){b.unmask();b.showResponseError("Unable to export corpus: "+b.getCorpus().getId(),c)}})},scope:this},{xtype:"querysearchfield",
width:200,flex:1},{itemId:"status",xtype:"tbtext"}]}]},{xtype:"splitter"},{xtype:this.getApiParam("reader"),flex:1,minWidth:250,header:!1}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(b,c){this.queryById("status").update((new Ext.XTemplate(this.localize("noMatches"))).apply([c.getDocumentsCount()]));this.getCustomResultsHtml()||(this.getApiParam("splash")?(this.setCustomResultsHtml(this.getApiParam("splash")),this.updateResults()):
(this.setCustomResultsHtml((new Ext.XTemplate(this.localize("noMatches"))).apply([c.getDocumentsCount()])),this.updateResults(),Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",verifyResourceId:"customhtml-"+c.getAliasOrId()},success:function(d,e){(d=Ext.util.JSON.decode(d.responseText))&&d.storedResource&&d.storedResource.id&&Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",retrieveResourceId:"customhtml-"+c.getAliasOrId()},success:function(f,
g){(f=Ext.util.JSON.decode(f.responseText))&&f.storedResource&&f.storedResource.resource&&(this.setCustomResultsHtml(f.storedResource.resource),this.updateResults())},scope:this})},scope:this})))});this.on("afterrender",function(b){var c=this.queryById("facets");this.addFacet({facet:"lexical",includeTools:{add:{type:"plus",tooltip:this.localize("plusFacetTip"),callback:function(){this.addFacet()},scope:this}},store:new Voyant.data.store.CorpusTerms({parentPanel:this,proxy:{extraParams:{stopList:this.getApiParam("stopList")}}})},
c);b=this.getApiParam("facet");Ext.isString(b)&&(b=b.split(","));b.forEach(function(d){this.addFacet({facet:d},c)},this);(b=this.getApiParam("title"))&&this.setTitle(b)})},addFacet:function(a,b){if(!a)return this.selectFacet(function(g){this.addFacet({facet:g})});b=b||this.queryById("facets");var c=a.facet,d='\x3cspan style\x3d"font-size: smaller;"\x3e(\x3cspan class\x3d"info-tip" data-qtip\x3d"'+this.localize("matchingDocuments")+'"\x3e{inDocumentsCount}\x3c/span\x3e)\x3c/span\x3e {term}\x3cspan style\x3d"font-size: smaller;"\x3e (\x3cspan class\x3d"info-tip" data-qtip\x3d"'+
this.localize("rawFreqs")+'"\x3e{rawFreq}\x3c/span\x3e)\x3c/span\x3e',e=this.localize(c+"Title");e=="["+c+"Title]"&&(e=c.replace(/^facet\./,"").replace(/^extra./,""));Ext.applyIf(a,{title:e,collapsible:!0,facet:c,columns:[{renderer:function(g,h,k){return'\x3cspan style\x3d"font-size: smaller;"\x3e(\x3cspan class\x3d"info-tip" data-qtip\x3d"'+this.localize("matchingDocuments")+'"\x3e'+k.getInDocumentsCount()+"\x3c/span\x3e) \x3c/span\x3e"+(k.getLabel?k.getLabel():k.getTerm()+'\x3cspan style\x3d"font-size: smaller;"\x3e (\x3cspan class\x3d"info-tip" data-qtip\x3d"'+
this.localize("rawFreqs")+'"\x3e'+k.getRawFreq()+"\x3c/span\x3e)\x3c/span\x3e")},flex:1}],bbar:[{xtype:"querysearchfield",width:"100%",tokenType:c.replace("facet.",""),itemTpl:d}],corpus:this.getCorpus()});var f=b.add(a);f.getStore().on("load",function(){this.adjustFacetHeights()},this);f.getSelectionModel().on("selectionchange",function(g,h){var k=[];h.forEach(function(l){k.push({facet:f.facet,label:l.getLabel?l.getLabel():l.getTerm()})});this.getFacets()[c]=k;this.updateResults()},this);f.on("query",
function(g,h){this.getFacets()[f.facet]=[];this.updateResults()},this);return f},adjustFacetHeights:function(){var a=this.queryById("facets"),b={},c=-1,d=a.query("facet");d.forEach(function(e){var f=e.getStore().count();f>c&&(c=f);b[e.getId()]=f});d.forEach(function(e){var f=b[e.getId()]/c;e.setFlex(.3+.7*(f-0))},this);a.updateLayout()},updateResults:function(a){var b=this.getFacets();if(!a){a=[];for(facet in b)b[facet].forEach(function(e){a.push(e.facet+":"+e.label)});if(a)return this.updateResults(a)}var c=
this.queryById("results").getTargetEl();c.update(this.getCustomResultsHtml()?this.getCustomResultsHtml():(new Ext.XTemplate(this.localize("noMatches"))).apply([this.getCorpus().getDocumentsCount()]));this.queryById("status").update((new Ext.XTemplate(this.localize("noMatches"))).apply([this.getCorpus().getDocumentsCount()]));this.queryById("sendToVoyant").setDisabled(!0);this.queryById("export").setDisabled(!0);if(a&&0<a.length){this.mask(this.localize("loading"));var d=this.getCorpus().getDocumentQueryMatches();
d.load({params:{query:a,includeDocIds:!0},callback:function(e,f,g){this.unmask();if(e&&0<e.length){this.queryById("status").setHtml(e.length);var h="\x3cul\x3e",k=[];e.forEach(function(m){m.getDocIds().forEach(function(n){k.push(n);var u=d.getCorpus().getDocument(n),w="\x3cli id\x3d'"+c.getId()+"_"+n+"' class\x3d'cataloguedoc'\x3e";w+="\x3ca href\x3d'#' class\x3d'cataloguedoctitle' data\x3d'"+n+"'\x3e"+u.getTitle()+"\x3c/a\x3e";for(facet in b)if(0!=b[facet].length){var p="";if("facet.title"!=facet){var q=
facet.replace(/^.+?\./,"");if(n=u.get(q)){var r=Ext.isArray(n);r?p+="\x3cli\x3e"+q+"\x3cul\x3e":n=[n];n.forEach(function(v){var x=!1;b[facet].forEach(function(z){z.label==v?x=!0:-1==z.facet.indexOf("facet")&&z.label.split(/\W+/).forEach(function(L){0<L.trim().length&&-1<v.toLowerCase().indexOf(L.toLowerCase())&&(x=!0)})});p+="\x3cli\x3e"+(r?"":q.replace("extra.","")+": ")+(x?'\x3cspan class\x3d"keyword"\x3e'+v+"\x3c/span\x3e":v)+"\x3c/li\x3e"});r&&(p+="\x3c/ul\x3e\x3c/li\x3e")}}p&&(w+="\x3cul\x3e"+
p+"\x3c/ul\x3e")}h+=w+"\x3c/li\x3e"})});h+="\x3c/ul\x3e";c.update(h);var l=this;e=c.query(".cataloguedoctitle");e.forEach(function(m){Ext.get(m).on("click",function(n,u){this.dispatchEvent("documentSelected",l,u.getAttribute("data"))},l)});1==e.length&&this.dispatchEvent("documentSelected",l,e[0].getAttribute("data"));this.queryById("status").update((new Ext.XTemplate(this.localize("queryMatches"))).apply([k.length,this.getCorpus().getDocumentsCount()]));this.setMatchingDocIds(Ext.Array.clone(k));
0<k.length&&(this.queryById("export").setDisabled(!1),this.queryById("sendToVoyant").setDisabled(!1));b.lexical&&(e=k.splice(0,5),this.loadSnippets(e,c.first().first()),k&&0<k.length&&this.loadSnippets(k))}},scope:this})}},loadSnippets:function(a,b){var c=this.queryById("results").getTargetEl(),d=this.getFacets();if(d.lexical){d=d.lexical.map(function(f){return f.facet+":"+f.label});var e=this.getCorpus().getContexts({buffered:!1});b&&b.mask(this.localize("loadingSnippets"));e.load({method:"POST",
params:{stripTags:"all",query:d,docId:a,perDocLimit:3,limit:100,accurateTotalNotNeeded:!0},scope:this,callback:function(f,g,h){b&&b.unmask();if(h&&Ext.isArray(f)&&0<f.length){var k={};f.forEach(function(l){k[l.getDocIndex()]||(k[l.getDocIndex()]=[]);k[l.getDocIndex()].push(l)});for(docIndex in k)g=this.getCorpus().getDocument(docIndex).getId(),f='\x3cli style\x3d"list-style-type: none; font-size: smaller;"\x3e'+k[docIndex].map(function(l){return l.getHighlightedContext()}).join(" \u2026 ")+"\x3c/li\x3e",
(g=c.down("#"+c.getId()+"_"+g))?(g.query("ul")&&(f="\x3cul\x3e"+f+"\x3c/ul\x3e"),g.insertHtml("beforeEnd",f)):console.log("Catalogue: no docItem",c)}}})}},selectFacet:function(a){if(!this.facetsSelectionStore){var b={};this.getCorpus().getDocuments().each(function(e){for(var f in e.getData())"corpus"!==f&&0!==f.indexOf("parent")&&-1===f.indexOf("-lexical")&&(b[f]=!0)});b=Object.keys(b);var c="title location publisher pubDate pubPlace language keyword author collection".split(" ");b.sort(function(e,
f){return c.indexOf(f)-c.indexOf(e)});this.facetsSelectionStore=Ext.create("Ext.data.ArrayStore",{fields:["text"],data:b.map(function(e){return[e]})})}var d={};this.queryById("facets").items.each(function(e){d[e.facet]=!0});this.facetsSelectionStore.isFiltered&&this.facetsSelectionStore.clearFilter();this.facetsSelectionStore.filterBy(function(e){return!("facet."+e.get("text")in d)});Ext.create("Ext.window.Window",{title:this.localize("selectFacet"),modal:!0,items:{xtype:"form",width:300,items:{xtype:"combo",
store:this.facetsSelectionStore,forceSelection:!0,width:300},buttons:[{text:this.localize("cancel"),ui:"default-toolbar",glyph:"xf00d@FontAwesome",flex:1,handler:function(e){e.up("window").close()}},{text:this.localize("select"),glyph:"xf00c@FontAwesome",flex:1,handler:function(e){var f=e.up("window").down("combo").getValue();if(f)a.call(this,"facet."+f),e.up("window").close();else return this.showError(this.localize("selectValidFacet"))},scope:this}]},bodyPadding:5}).show()}});Ext.define("Voyant.panel.Cirrus",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.cirrus",statics:{i18n:{},api:{stopList:"auto",categories:void 0,whiteList:void 0,limit:500,visible:50,terms:void 0,docId:void 0,docIndex:void 0,inlineData:void 0,fontFamily:'"Palatino Linotype", "Book Antiqua", Palatino, serif',cirrusForceFlash:!1,background:"0xffffff",fade:!0,smoothness:2,diagonals:"none"},glyph:"xf06e@FontAwesome"},config:{mode:void 0,options:[{xtype:"stoplistoption"},{xtype:"listeditor",
name:"whiteList"},{xtype:"categoriesoption"},{xtype:"fontfamilyoption"},{xtype:"colorpaletteoption"}],records:void 0,terms:void 0,cirrusId:void 0,visLayout:void 0,vis:void 0,tip:void 0,sizeAdjustment:100,minFontSize:12,largestWordSize:0,smallestWordSize:1E6},MODE_CORPUS:"corpus",MODE_DOCUMENT:"mode_document",layout:"fit",constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.getApplication().getCategoriesManager().addFeature("orientation",
function(){return 90*~~(2*Math.random())});this.setCirrusId(Ext.id(null,"cirrus_"))},initComponent:function(a){Ext.apply(this,{title:this.localize("title"),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"corpusdocumentselector",singleSelect:!0},{fieldLabel:this.localize("visibleTerms"),labelWidth:40,width:120,xtype:"slider",increment:25,minValue:25,maxValue:500,listeners:{afterrender:function(b){b.maxValue=this.getApiParam("limit");b.minValue=Math.round(Math.max(5,
parseInt(b.maxValue/20)));b.increment=0===b.maxValue%25&&0===b.minValue%25?25:Math.round((b.maxValue-b.minValue)/10);b.setValue(this.getApiParam("visible"))},changecomplete:function(b,c){this.setApiParams({visible:c});this.loadFromTermsRecords()},scope:this}}]}]});this.callParent(arguments)},listeners:{boxready:function(){this.initVisLayout();var a=this.getApiParam("inlineData");if(void 0!==a){if("["==a.charAt(0))var b=Ext.decode(a,!0);else if(-1<a.indexOf(":"))b=[],a.split(",").forEach(function(d){parts=
d.split(":");b.push({text:parts[0],rawFreq:parseInt(parts[1])})});else{var c={};b=[];a.split(",").forEach(function(d){d in c?c[d]++:c[d]=1});for(term in c)b.push({text:term,rawFreq:c[term]})}null!==b&&0<b.length&&(this.setApiParam("inlineData",b),this.setTerms(b),this.buildFromTerms())}},resize:function(a,b,c){this.getVisLayout()&&this.getCorpus()&&(this.setAdjustedSizes(),a=this.getLayout().getRenderTarget(),b=a.getWidth(),c=a.getHeight(),a.down("svg").set({width:b,height:c}),this.getTerms()&&this.getVisLayout().size([b,
c]).stop().words(this.getTerms()).start())},loadedCorpus:function(a,b){this.getApplication().getCategoriesManager().addFeature("font",this.getApiParam("fontFamily"));this.initVisLayout();this.getApiParam("docIndex")?this.fireEvent("documentSelected",this,b.getDocument(this.getApiParam("docIndex"))):this.getApiParam("docId")?this.fireEvent("documentSelected",this,b.getDocument(this.getApiParam("docId"))):this.loadFromCorpus(b)},corpusSelected:function(a,b){this.loadFromCorpus(b)},documentSelected:function(a,
b){b&&(a=this.getCorpus(),b=a.getDocument(b),this.setApiParam("docId",b.getId()),b=b.getDocumentTerms({autoload:!1,corpus:a,pageSize:this.getApiParam("maxVisible"),parentPanel:this}),this.loadFromDocumentTerms(b))},ensureCorpusView:function(a,b){this.getMode()!=this.MODE_CORPUS&&this.loadFromCorpus(b)}},loadFromCorpus:function(a){void 0===this.getApiParam("inlineData")&&(this.setApiParams({docId:void 0,docIndex:void 0}),this.loadFromCorpusTerms(a.getCorpusTerms({autoload:!1,pageSize:this.getApiParam("maxVisible"),
parentPanel:this})))},loadFromDocumentTerms:function(a){a.load({callback:function(b,c,d){this.setMode(this.MODE_DOCUMENT);this.setRecords(c.getRecords());this.loadFromTermsRecords()},scope:this,params:this.getApiParams()})},loadFromCorpusTerms:function(a){a.load({callback:function(b,c,d){this.setMode(this.MODE_CORPUS);this.setRecords(c.getRecords());this.loadFromTermsRecords()},scope:this,params:this.getApiParams()})},loadFromTermsRecords:function(){var a=this.getRecords(),b=this.getApiParam("visible");
b>a.length&&(b=a.length);for(var c=[],d=0;d<b;d++)0<a[d].get("rawFreq")&&c.push({text:a[d].get("term").replace(/"/g,""),rawFreq:a[d].get("rawFreq")});this.setTerms(c);this.buildFromTerms()},initVisLayout:function(a){if(a||void 0==this.getVisLayout())if(a=this.getApiParam("cirrusForceFlash"),"true"==a||!0===a){this.setApiParam("cirrusForceFlash",!0);a=this.getCirrusId();for(var b={id:a},c=["background","fade","smoothness","diagonals"],d=0;d<c.length;d++)b[c[d]]=this.getApiParam(c[d]);c='\x3cscript type\x3d"text/javascript" src\x3d"'+
this.getApplication().getBaseUrl()+'resources/swfobject/swfobject.js"\x3e\x3c/script\x3e';this.update(c+('\x3cscript type\x3d"text/javascript"\x3ecirrusClickHandler'+a+' \x3d function(word, value) {\n\tif (window.console \x26\x26 console.info) console.info(word, value);\n\tvar cirrusTool \x3d Ext.getCmp("'+this.id+'");\n\tcirrusTool.dispatchEvent("termsClicked", cirrusTool, [word]);\n}\ncirrusLoaded'+a+' \x3d function() {\n\tif (window.console \x26\x26 console.info) console.info("cirrus flash loaded");\n}\ncirrusPNGHandler'+
a+' \x3d function(base64String) {\n\tvar cirrusTool \x3d Ext.getCmp("'+this.id+'");\n\tcirrusTool.cirrusPNGHandler(base64String);\n}\x3c/script\x3e'),!0,function(){function e(f){if("undefined"!==typeof swfobject){var g=f.getLayout().getRenderTarget(),h=g.getWidth();g=g.getHeight();var k=f.getApplication().getBaseUrl()+"resources/cirrus/flash/Cirrus.swf";f.add({xtype:"flash",id:b.id,url:k,width:h,height:g,flashVars:b,flashParams:{menu:"false",scale:"showall",allowScriptAccess:"always",bgcolor:"#222222",
wmode:"opaque"}});f.cirrusFlashApp=Ext.get(b.id).first().dom}else setTimeout(e,50,f)}e(this)},this)}else d=this.getLayout().getRenderTarget(),d.update(""),a=d.getWidth(),c=d.getHeight(),this.setVisLayout(d3.layoutCloud().size([a,c]).overflow(!0).padding(1).rotate(function(e){e=this.getApplication().getCategoriesManager().getFeatureForTerm("orientation",e.text);void 0===e&&(e=90*~~(2*Math.random()));return e}.bind(this)).spiral("archimedean").font(function(e){return this.getApplication().getCategoriesManager().getFeatureForTerm("font",
e.text)}.bind(this)).fontSize(function(e){return e.fontSize}.bind(this)).text(function(e){return e.text}).on("end",this.draw.bind(this))),d=d3.select(d.dom).append("svg").attr("id",this.getCirrusId()).attr("class","cirrusGraph").attr("width",a).attr("height",c),this.setVis(d.append("g").attr("transform","translate("+a/2+","+c/2+")")),void 0===this.getTip()&&this.setTip(Ext.create("Ext.tip.Tip",{}))},buildFromTerms:function(){var a=this.getTerms();if(this.rendered&&a)if(!0===this.getApiParam("cirrusForceFlash"))if(void 0!==
this.cirrusFlashApp&&void 0!==this.cirrusFlashApp.clearAll){for(var b=[],c=0;c<a.length;c++){var d=a[c];!d.text&&d.term&&(d.text=d.term);b.push({word:d.text,size:d.rawFreq,label:d.rawFreq})}this.cirrusFlashApp.clearAll();this.cirrusFlashApp.addWords(b);this.cirrusFlashApp.arrangeWords()}else Ext.defer(this.buildFromTerms,50,this);else{b=1E3;d=-1;for(c=0;c<a.length;c++){var e=a[c].rawFreq;e<b&&(b=e);e>d&&(d=e)}this.setSmallestWordSize(b);this.setLargestWordSize(d);this.setRelativeSizes();this.setAdjustedSizes();
this.getVisLayout().words(a).start()}else Ext.defer(this.buildFromTerms,50,this)},draw:function(a,b){var c=this;this.getLayout().getRenderTarget();var d=this.getVisLayout().size()[0],e=this.getVisLayout().size()[1];b=b?Math.min(d/Math.abs(b[1].x-d/2),d/Math.abs(b[0].x-d/2),e/Math.abs(b[1].y-e/2),e/Math.abs(b[0].y-e/2))/2:1;var f=d3.transition().duration(1E3);a=this.getVis().selectAll("text").data(a,function(h){return h.text});a.exit().transition(f).style("font-size","1px").remove();var g=a.enter().append("text").text(function(h){return h.text}).attr("text-anchor",
"middle").attr("data-freq",function(h){return h.rawFreq}).attr("transform",function(h){return"translate("+[h.x,h.y]+")rotate("+h.rotate+")"}).style("font-family",function(h){return c.getApplication().getCategoriesManager().getFeatureForTerm("font",h.text)}).style("fill",function(h){return c.getApplication().getColorForTerm(h.text,!0)}).style("font-size","1px").on("click",function(h){c.dispatchEvent("termsClicked",c,[h.text])}).on("mouseover",function(h){this.getTip().show()}.bind(this)).on("mousemove",
function(h){var k=this.getTip();k.update(h.text+": "+h.rawFreq);h=Ext.get(this.getCirrusId()).dom;h=d3.mouse(h);h[1]+=30;k.setPosition(h)}.bind(this)).on("mouseout",function(h){this.getTip().hide()}.bind(this));a.merge(g).transition(f).style("font-family",function(h){return c.getApplication().getCategoriesManager().getFeatureForTerm("font",h.text)}).style("fill",function(h){return c.getApplication().getColorForTerm(h.text,!0)}).attr("transform",function(h){return"translate("+[h.x,h.y]+")rotate("+
h.rotate+")"}).style("font-size",function(h){return h.fontSize+"px"});this.getVis().transition(f).attr("transform","translate("+d/2+","+e/2+")scale("+b+")")},map:function(a,b,c,d,e){return d+(a-b)/(c-b)*(e-d)},calculateSizeAdjustment:function(){var a=this.getTerms();if(void 0!==a){var b=this.getLayout().getRenderTarget();b=b.getWidth()*b.getHeight();1E5>b?this.setMinFontSize(8):this.setMinFontSize(12);for(var c=0,d=0;d<a.length;d++){var e=this.calculateWordArea(a[d]);c+=e}this.setSizeAdjustment(b/
c)}},calculateWordArea:function(a){for(var b=Math.log(10*a.relativeSize)*Math.LOG10E,c=(b+a.relativeSize)/2,d=0,e=0;e<a.text.length;e++){var f=a.text.charAt(e);d="f"==f||"i"==f||"j"==f||"l"==f||"r"==f||"t"==f?d+b/3:"m"==f||"w"==f?d+b/(4/3):d+b/1.9}return c*d},setAdjustedSizes:function(){this.calculateSizeAdjustment();var a=this.getTerms();if(void 0!==a)for(var b=0;b<a.length;b++){var c=a[b],d=this.findNewRelativeSize(c);c.fontSize=d>this.getMinFontSize()?d:this.getMinFontSize()}},setRelativeSizes:function(){var a=
this.getTerms();if(void 0!==a)for(var b=0;b<a.length;b++){var c=a[b];c.relativeSize=this.map(c.rawFreq,this.getSmallestWordSize(),this.getLargestWordSize(),.1,1)}},findNewRelativeSize:function(a){var b=this.getSizeAdjustment();b*=this.calculateWordArea(a);return(Math.sqrt(6)*Math.sqrt(6*Math.pow(a.text.length,2)+b*a.text.length)-6*a.text.length)/(2*a.text.length)}});Ext.define("Voyant.panel.CollocatesGraph",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.collocatesgraph",statics:{i18n:{},api:{query:void 0,limit:5,stopList:"auto",context:5,centralize:void 0},glyph:"xf1e0@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}],nodeData:void 0,linkData:void 0,visId:void 0,vis:void 0,visLayout:void 0,nodes:void 0,links:void 0,zoom:void 0,dragging:!1,contextMenu:void 0,currentNode:void 0,networkMode:void 0,graphStyle:{keywordNode:{normal:{fill:"#c6dbef",
stroke:"#6baed6"},highlight:{fill:"#9ecae1",stroke:"#3182bd"}},contextNode:{normal:{fill:"#fdd0a2",stroke:"#fdae6b"},highlight:{fill:"#fd9a53",stroke:"#e6550d"}},link:{normal:{stroke:"#000000",strokeOpacity:.1},highlight:{stroke:"#000000",strokeOpacity:.5}}},graphPhysics:{defaultMode:{damping:.4,centralGravity:.1,nodeGravity:-50,springLength:100,springStrength:.25,collisionScale:1.25},centralizedMode:{damping:.4,centralGravity:.1,nodeGravity:-1,springLength:200,springStrength:1,collisionScale:1}}},
DEFAULT_MODE:0,CENTRALIZED_MODE:1,constructor:function(a){this.setNodeData([]);this.setLinkData([]);this.setVisId(Ext.id(null,"links_"));this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){Ext.apply(this,{title:this.localize("title"),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{text:this.localize("clearTerms"),glyph:"xf014@FontAwesome",handler:this.resetGraph,scope:this},
this.localize("context"),{xtype:"slider",itemId:"contextSlider",minValue:3,value:5,maxValue:30,increment:2,width:50,listeners:{render:function(a){a.setValue(this.getApiParam("context"))},changecomplete:function(a,b){this.setApiParam("context",a.getValue());this.getNetworkMode()===this.DEFAULT_MODE&&(a=this.getNodeData().map(function(c){return c.term}),0<a.length&&(this.setNodeData([]),this.setLinkData([]),this.refresh(),this.loadFromQuery(a)))},scope:this}}]}]});this.setContextMenu(Ext.create("Ext.menu.Menu",
{renderTo:Ext.getBody(),items:[{xtype:"box",itemId:"label",margin:"5px 0px 5px 5px",html:""},{xtype:"menuseparator"},{xtype:"menucheckitem",text:"Fixed",itemId:"fixed",listeners:{checkchange:function(a,b,c){a=this.getCurrentNode();void 0!==a&&(c={fixed:b},b?(c.fx=a.x,c.fy=a.y):(c.fx=null,c.fy=null),this.updateDataForNode(a.id,c))},scope:this}},{xtype:"button",text:"Fetch Collocates",style:"margin: 5px;",handler:function(a,b){a=this.getCurrentNode();void 0!==a&&(this.getNetworkMode()===this.CENTRALIZED_MODE&&
(this.resetGraph(),this.setNetworkMode(this.DEFAULT_MODE),this.setApiParam("centralize",void 0),a.start=0,a.limit=this.getApiParam("limit")),this.fetchCollocatesForNode(a))},scope:this},{xtype:"button",text:"Centralize",style:"margin: 5px;",handler:function(a,b){a=this.getCurrentNode();void 0!==a&&this.doCentralize(a.term);this.getContextMenu().hide()},scope:this},{xtype:"button",text:"Remove",style:"margin: 5px;",handler:function(a,b){b=this.getCurrentNode();void 0!==b&&this.removeNode(b.id);a.up("menu").hide()},
scope:this}]}));this.on("loadedCorpus",function(a,b){this.isVisible()&&this.initLoad()},this);this.on("activate",function(){this.getCorpus()&&0===this.getNodeData().length&&Ext.Function.defer(this.initLoad,100,this)},this);this.on("query",function(a,b){this.loadFromQuery(b)},this);this.on("resize",function(a,b,c){if(a=Ext.get(this.getVisId()))c=this.body,b=c.getHeight(),c=c.getWidth(),a.el.dom.setAttribute("width",c),a.el.dom.setAttribute("height",b),this.getVisLayout().force("x",d3.forceX(c/2)).force("y",
d3.forceY(b/2)),Ext.Function.defer(this.zoomToFit,100,this)},this);this.on("beforedestroy",function(a){this.getVisLayout()&&this.getVisLayout().stop()},this);this.callParent(arguments)},initLoad:function(){this.initGraph();this.setNetworkMode(this.DEFAULT_MODE);if(this.getApiParam("centralize")){this.setNetworkMode(this.CENTRALIZED_MODE);var a=this.getApiParam("centralize");this.doCentralize(a)}else{a=3;var b=this.getApiParam("query");void 0!==b&&(a=0===b.indexOf("^@")?20:Ext.isArray(b)?b.length:
b.split(",").length);this.getCorpus().getCorpusTerms({autoLoad:!1}).load({params:{limit:a,query:b,stopList:this.getApiParam("stopList"),categories:this.getApiParam("categories")},callback:function(c,d,e){e&&this.loadFromCorpusTermRecords(c)},scope:this})}},loadFromQuery:function(a){if(Ext.isArray(a)&&0==a.length)this.setApiParam("query",void 0),this.resetGraph();else{this.setApiParams({query:a});var b=this.getApiParams();b.noCache=!0;(Ext.isString(a)?[a]:a).forEach(function(c){this.getCorpus().getCorpusCollocates({autoLoad:!1}).load({params:Ext.apply(Ext.clone(b),
{query:c}),callback:function(d,e,f){f&&this.loadFromCorpusCollocateRecords(d)},scope:this})},this)}},loadFromCorpusTermRecords:function(a){if(Ext.isArray(a)&&0<a.length){var b=[];a.forEach(function(c){b.push(c.getTerm())});this.loadFromQuery(b)}},loadFromCorpusCollocateRecords:function(a,b){if(Ext.isArray(a)){var c=this.getApiParam("limit"),d=this.getLayout().getRenderTarget(),e=d.getWidth()/2,f=d.getHeight()/2,g={};this.getNodeData().forEach(function(l){g[l.id]=!0},this);var h=[],k=[];a.forEach(function(l,
m){var n=l.getTerm(),u=l.getContextTerm(),w=l.getKeywordRawFreq(),p=l.getContextTermRawFreq(),q=w,r=p;this.getNetworkMode()===this.CENTRALIZED_MODE&&(q=0,r=Math.log(p));0==m&&(void 0===b&&(b=this.idGet(n)),void 0!==g[b]?this.updateDataForNode(b,{title:n+" ("+w+")",type:"keyword",value:q}):(g[b]=!0,m={id:b,term:n,title:n+" ("+w+")",type:"keyword",value:q,start:c,fixed:!1,x:e,y:f},h.push(m)));if(n!=u){n=this.idGet(u);void 0===g[n]&&(g[n]=!0,u={id:n,term:u,title:u+" ("+p+")",type:"context",value:r,start:0,
fixed:!1,x:e,y:f},h.push(u));u=null;p=this.getLinkData();for(r=0;r<p.length;r++)if(m=p[r],m.source.id==b&&m.target.id==n||m.source.id==n&&m.target.id==b){u=m;break}l=l.getContextTermRawFreq();null===u&&k.push({source:b,target:n,value:l,id:b+"-"+n})}},this);this.setNodeData(this.getNodeData().concat(h));this.setLinkData(this.getLinkData().concat(k));this.refresh()}},idGet:function(a){return"links_"+a.replace(/\W/g,"_")},updateDataForNode:function(a,b){for(var c=this.getNodeData(),d=0;d<c.length;d++)if(c[d].id===
a){Ext.apply(c[d],b);break}},removeNode:function(a,b){b=this.getNodeData();for(var c=0;c<b.length;c++)if(b[c].id===a){b.splice(c,1);break}b=this.getLinkData();for(c=b.length-1;0<=c;c--)b[c].source.id!==a&&b[c].target.id!==a||b.splice(c,1);this.setApiParam("query",Ext.Array.remove(Ext.Array.from(this.getApiParam("query")),a));this.refresh()},doCentralize:function(a){this.setApiParam("centralize",a);this.resetGraph();this.setNetworkMode(this.CENTRALIZED_MODE);a={id:this.idGet(a),term:a,title:a+" (1)",
type:"keyword",value:1E3,start:0};this.setNodeData([a]);this.refresh();var b=this.getApiParam("limit");this.setApiParam("limit",150);this.fetchCollocatesForNode(a);this.setApiParam("limit",b)},applyNetworkMode:function(a){if(this.getVisLayout()){if(a===this.DEFAULT_MODE){var b=this.getGraphPhysics().defaultMode;this.getVisLayout().velocityDecay(b.damping).force("link",d3.forceLink().id(function(c){return c.id}).distance(b.springLength).strength(b.springStrength)).force("charge",d3.forceManyBody().strength(b.nodeGravity)).force("collide",
d3.forceCollide(function(c){return Math.sqrt(c.bbox.width*c.bbox.height)*b.collisionScale}))}else b=this.getGraphPhysics().centralizedMode,this.getVisLayout().velocityDecay(b.damping).force("link",d3.forceLink().id(function(c){return c.id}).distance(b.springLength).strength(b.springStrength)).force("charge",d3.forceManyBody().strength(function(c){return"keyword"===c.type?-1E4:0})).force("collide",d3.forceCollide(function(c){return"keyword"===c.type?c.value:Math.sqrt(c.bbox.width*c.bbox.height)*b.collisionScale}));
this.getVisLayout().force("x").strength(b.centralGravity);this.getVisLayout().force("y").strength(b.centralGravity)}return a},initGraph:function(){var a=this.getLayout().getRenderTarget();a.update("");var b=a.getWidth(),c=a.getHeight();this.setVisLayout(d3.forceSimulation().force("x",d3.forceX(b/2)).force("y",d3.forceY(c/2)).on("tick",function(){this.getLinks().attr("x1",function(e){return e.source.x}).attr("y1",function(e){return e.source.y}).attr("x2",function(e){return e.target.x}).attr("y2",function(e){return e.target.y});
this.getNodes().attr("transform",function(e){var f=e.x,g=e.y;if(this.getNetworkMode()===this.DEFAULT_MODE||"keyword"!==e.type)f-=.5*e.bbox.width,g-=.5*e.bbox.height;return"translate("+f+","+g+")"}.bind(this));!this.getDragging()&&.075>this.getVisLayout().alpha()&&this.getVisLayout().alpha(-1)}.bind(this)).on("end",function(){Ext.Function.defer(this.zoomToFit,100,this)}.bind(this)));a=d3.select(a.dom).append("svg").attr("id",this.getVisId()).attr("class","linksGraph").attr("width",b).attr("height",
c);var d=a.append("g");b=d3.zoom().scaleExtent([.25,4]).on("zoom",function(){d.attr("transform",d3.event.transform)});this.setZoom(b);a.call(b);a.on("click",function(){this.getContextMenu().hide()}.bind(this));this.setLinks(d.append("g").attr("class","links").selectAll(".link"));this.setNodes(d.append("g").attr("class","nodes").selectAll(".node"));this.setVis(d)},resetGraph:function(){this.setNodeData([]);this.setLinkData([]);this.setNetworkMode(this.DEFAULT_MODE);this.refresh()},refresh:function(){var a=
this,b=this.getNodeData(),c=this.getLinkData(),d=this.getLinks().data(c,function(f){return f.id});d.exit().remove();var e=d.enter().append("line").attr("class","link").attr("id",function(f){return f.id}).on("mouseover",a.linkMouseOver.bind(a)).on("mouseout",a.linkMouseOut.bind(a)).on("click",function(f){d3.event.stopImmediatePropagation();d3.event.preventDefault();this.dispatchEvent("termsClicked",this,['"'+f.source.term+" "+f.target.term+'"~'+this.getApiParam("context")])}.bind(a)).style("cursor",
"pointer").style("stroke-width",function(f){return a.getNetworkMode()===a.DEFAULT_MODE?Math.max(1,Math.min(15,Math.sqrt(f.value))):1});this.setLinks(e.merge(d));d=this.getNodes().data(b,function(f){return f.id});d.exit().remove();e=d.enter().append("g").attr("class",function(f){return"node "+f.type}).attr("id",function(f){return f.id}).on("mouseover",a.nodeMouseOver.bind(a)).on("mouseout",a.nodeMouseOut.bind(a)).on("click",function(f){d3.event.stopImmediatePropagation();d3.event.preventDefault();
this.dispatchEvent("termsClicked",this,[f.term])}.bind(a)).on("dblclick",function(f){d3.event.stopImmediatePropagation();d3.event.preventDefault();this.fetchCollocatesForNode(f)}.bind(a)).on("contextmenu",function(f,g){d3.event.preventDefault();g=a.getContextMenu();g.queryById("label").setHtml(f.term);g.queryById("fixed").setChecked(f.fixed);g.showAt(d3.event.pageX+10,d3.event.pageY-50)}).call(d3.drag().on("start",function(f){a.setDragging(!0);d3.event.active||a.getVisLayout().alpha(.3).restart();
f.fx=f.x;f.fy=f.y;f.fixed=!0}).on("drag",function(f){a.getVisLayout().alpha(.3);f.fx=d3.event.x;f.fy=d3.event.y;a.isMasked()?a.isOffCanvas(d3.event.x,d3.event.y)||a.unmask():a.isOffCanvas(d3.event.x,d3.event.y)&&a.mask(a.localize("releaseToRemove"))}).on("end",function(f){a.setDragging(!1);1!=f.fixed&&(f.fx=null,f.fy=null);a.isOffCanvas(d3.event.x,d3.event.y)&&(a.unmask(),a.mask(a.localize("cleaning")),a.removeNode(f.id),a.unmask())}));e.append("title");this.getNetworkMode()===this.DEFAULT_MODE?e.append("rect").style("stroke-width",
1).style("stroke-opacity",1):e.filter(function(f){return"keyword"===f.type}).append("circle").style("stroke-width",1).style("stroke-opacity",1);e.append("text").attr("font-family",function(f){return a.getApplication().getCategoriesManager().getFeatureForTerm("font",f.term)}).text(function(f){return f.term}).style("cursor","pointer").style("user-select","none").attr("dominant-baseline","middle");d=e.merge(d);d.selectAll("title").text(function(f){return f.title});d.selectAll("text").attr("font-size",
function(f){return Math.max(10,Math.sqrt(f.value))}).each(function(f){f.bbox=this.getBBox()});this.setNodes(d);this.getNetworkMode()===this.DEFAULT_MODE?(this.getVis().selectAll("rect").attr("width",function(f){return f.bbox.width+16}).attr("height",function(f){return f.bbox.height+8}).attr("rx",function(f){return Math.max(2,.2*f.bbox.height)}).attr("ry",function(f){return Math.max(2,.2*f.bbox.height)}).call(this.applyNodeStyle.bind(this)),this.getVis().selectAll("text").attr("dx",8).attr("dy",function(f){return.5*
f.bbox.height+4})):(this.getVis().selectAll("circle").attr("r",function(f){return Math.min(150,f.bbox.width)}).call(this.applyNodeStyle.bind(this)),this.getVis().selectAll("text").attr("dx",function(f){return"keyword"===f.type?.5*-f.bbox.width:8}).attr("dy",function(f){return"keyword"===f.type?0:.5*f.bbox.height+4}));this.getVis().selectAll("line").call(this.applyLinkStyle.bind(this));this.getVisLayout().nodes(b);this.getVisLayout().force("link").links(c);this.getVisLayout().alpha(1).restart()},isOffCanvas:function(a,
b){var c=Ext.get(this.getVisId());return 0>a||0>b||a>c.getWidth()||b>c.getHeight()},zoomToFit:function(a,b){var c=this.getVis().node().getBBox(),d=c.width,e=c.height,f=c.x+d/2,g=c.y+e/2;c=this.getVis().node().parentElement;var h=c.getBoundingClientRect(),k=h.width;h=h.height;a=(a||.8)/Math.max(d/k,e/h);f=[k/2-a*f,h/2-a*g];1>d||d3.select(c).transition().duration(b||500).call(this.getZoom().transform,d3.zoomIdentity.translate(f[0],f[1]).scale(a))},applyNodeStyle:function(a,b){var c=void 0===b?"normal":
b;a.style("fill",function(d){d=d.type+"Node";return this.getGraphStyle()[d][c].fill}.bind(this));a.style("stroke",function(d){d=d.type+"Node";return this.getGraphStyle()[d][c].stroke}.bind(this))},applyLinkStyle:function(a,b){var c=void 0===b?"normal":b;a.style("stroke",function(d){return this.getGraphStyle().link[c].stroke}.bind(this));a.style("stroke-opacity",function(d){return this.getGraphStyle().link[c].strokeOpacity}.bind(this))},linkMouseOver:function(a){this.getVis().selectAll("line").call(this.applyLinkStyle.bind(this));
this.getVis().select("#"+a.id).call(this.applyLinkStyle.bind(this),"highlight")},linkMouseOut:function(a){this.getVis().selectAll("line").call(this.applyLinkStyle.bind(this))},nodeMouseOver:function(a){this.setCurrentNode(a);this.getVis().selectAll("rect").call(this.applyNodeStyle.bind(this));this.getLinks().each(function(b){if(b.source.id==a.id)var c=b.target.id;else b.target.id==a.id&&(c=b.source.id);void 0!==c&&(this.getVis().select("#"+c+" rect").call(this.applyNodeStyle.bind(this),"highlight"),
this.getVis().select("#"+b.id).call(this.applyLinkStyle.bind(this),"highlight"))}.bind(this));this.getVis().select("#"+a.id+" rect").style("stroke-width",3).call(this.applyNodeStyle.bind(this),"highlight")},nodeMouseOut:function(a){this.getContextMenu().isVisible()||this.setCurrentNode(void 0);this.getVis().selectAll("rect").style("stroke-width",1).call(this.applyNodeStyle.bind(this));this.getVis().selectAll("line").call(this.applyLinkStyle.bind(this))},fetchCollocatesForNode:function(a){var b=this.getApiParam("limit"),
c=this.getApiParam("query");c=Ext.Array.from(this.getApiParam("query"));Ext.Array.include(c,a.term);this.setApiParam("query",c);this.getCorpus().getCorpusCollocates({autoLoad:!1}).load({params:Ext.apply(this.getApiParams(),{query:a.term,start:a.start,limit:b}),callback:function(d,e,f){f&&(this.updateDataForNode(a.id,{start:a.start+b}),this.loadFromCorpusCollocateRecords(d,a.id))},scope:this})}});Ext.define("Voyant.panel.Contexts",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],requires:["Voyant.data.store.Contexts"],alias:"widget.contexts",isConsumptive:!0,statics:{i18n:{},api:{query:void 0,docId:void 0,docIndex:void 0,stopList:"auto",context:5,expand:50,columns:void 0,sort:void 0,dir:void 0,termColors:"categories"},glyph:"xf0ce@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"termcolorsoption"}]},constructor:function(){this.mixins["Voyant.util.Api"].constructor.apply(this,
arguments);this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){var a=this;Ext.apply(a,{title:this.localize("title"),emptyText:this.localize("emptyText"),store:Ext.create("Voyant.data.store.ContextsBuffered",{parentPanel:this,proxy:{extraParams:{stripTags:"all"}}}),selModel:{type:"rowmodel",listeners:{selectionchange:{fn:function(b,c){this.getApplication().dispatchEvent("termLocationClicked",this,c)},scope:this}}},plugins:[{ptype:"rowexpander",
rowBodyTpl:new Ext.XTemplate("")}],dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"},this.localize("context"),{xtype:"slider",minValue:5,value:5,maxValue:50,increment:5,width:50,listeners:{render:function(b){b.setValue(a.getApiParam("context"))},changecomplete:function(b,c){a.setApiParam("context",b.getValue());a.getStore().clearAndLoad({params:a.getApiParams()})}}},this.localize("expand"),{xtype:"slider",minValue:5,
value:5,maxValue:500,increment:10,width:50,listeners:{render:function(b){b.setValue(a.getApiParam("expand"))},changecomplete:function(b,c){a.setApiParam("expand",c);b=a.getView();c=a.plugins[0].recordsExpanded;var d=b.getStore(),e;for(e in c){var f=d.getByInternalId(e),g=b.getRow(f),h=g.parentNode.childNodes[1];c[e]?b.fireEvent("expandbody",g,f,h,{force:!0}):Ext.fly(h).down(".x-grid-rowbody").setHtml("")}}}},{xtype:"corpusdocumentselector"}]}],columns:[{text:this.localize("document"),tooltip:this.localize("documentTip"),
width:"autoSize",dataIndex:"docIndex",sortable:!0,renderer:function(b,c,d,e,f,g){return g.getCorpus().getDocument(b).getTitle()}},{text:this.localize("left"),tooltip:this.localize("leftTip"),align:"right",dataIndex:"left",sortable:!0,flex:1},{text:this.localize("term"),tooltip:this.localize("termTip"),dataIndex:"term",sortable:!0,width:"autoSize",xtype:"coloredtermfield"},{text:this.localize("right"),tooltip:this.localize("rightTip"),dataIndex:"right",sortable:!0,flex:1},{text:this.localize("position"),
tooltip:this.localize("positionTip"),dataIndex:"position",sortable:!0,hidden:!0,flex:1}],listeners:{scope:this,corpusSelected:function(){this.getStore().getCorpus()&&(this.setApiParams({docId:void 0,docIndex:void 0}),this.getStore().clearAndLoad())},documentsSelected:function(b,c){var d=[],e=this.getStore().getCorpus();c.forEach(function(f){d.push(e.getDocument(f).getId())},this);this.setApiParams({docId:d,docIndex:void 0});this.getStore().clearAndLoad()},documentSegmentTermClicked:{fn:function(b,
c){c.term&&(params={query:c.term},c.docId?params.docId=c.docId:params.docIndex=c.docIndex?c.docIndex:0,this.setApiParams(params),this.isVisible()&&this.getStore().clearAndLoad())},scope:this},documentIndexTermsClicked:{fn:function(b,c){var d={},e=[],f={},g=[];c.forEach(function(h){d[h.term]||(e.push(h.term),d[h.term]=!0);f[h.docIndex]||(g.push(h.docIndex),f[h.docIndex]=!0)});this.setApiParams({docId:void 0,docIndex:g,query:e});this.isVisible()&&this.getStore().clearAndLoad({params:this.getApiParams()})},
scope:this},afterrender:function(b){b.getView().on("expandbody",function(c,d,e,f){if(""===e.textContent||f&&f.force){c=Ext.create("Voyant.data.store.Contexts",{stripTags:"all",corpus:b.getStore().getCorpus()});var g=d.getData();d=g.query;null!==d.match(/^[\^@]/)&&(d=g.term);c.load({params:{query:d,docIndex:g.docIndex,position:g.position,limit:1,context:b.getApiParam("expand")},callback:function(h,k,l){l&&1==h.length&&(g=h[0].getData(),Ext.fly(k.expandRow).down(".x-grid-rowbody").setHtml(g.left+" \x3cspan class\x3d'word keyword'\x3e"+
g.middle+"\x3c/span\x3e "+g.right))},expandRow:e})}})}}});a.on("loadedCorpus",function(b,c){0==this.hasCorpusAccess(c)?this.mask(this.localize("limitedAccess"),"mask-no-spinner"):(b=this.getApiParam("query"),void 0!==b&&null!==b.match(/^[\^@]/)?this.getStore().clearAndLoad({params:this.getApiParams()}):c.getCorpusTerms({autoLoad:!1}).load({callback:function(d,e,f){f&&0<d.length&&(this.setApiParam("query",[d[0].getTerm()]),this.getStore().clearAndLoad({params:this.getApiParams()}))},scope:a,params:{limit:1,
query:b,stopList:this.getApiParam("stopList"),forTool:"contexts"}}))});a.on("query",function(b,c){this.setApiParam("query",c);this.getStore().clearAndLoad({params:this.getApiParams()})},a);a.on("documentTermsClicked",function(b,c){var d=[];c.forEach(function(e){d.push({term:e.getTerm(),docIndex:e.getDocIndex()})});this.fireEvent("documentIndexTermsClicked",this,d)});a.on("termsClicked",function(b,c){var d=[];Ext.isString(c)&&(c=[c]);c.forEach(function(e){void 0!==e.docIndex&&d.push({term:e.term,docIndex:e.docIndex})});
0<d.length&&this.fireEvent("documentIndexTermsClicked",this,d)});a.callParent(arguments)}});Ext.define("Voyant.panel.CorpusCollocates",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.corpuscollocates",statics:{i18n:{},api:{stopList:"auto",context:5,query:void 0,docId:void 0,docIndex:void 0,columns:void 0,sort:void 0,dir:void 0,termColors:"categories"},glyph:"xf0ce@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"termcolorsoption"}]},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,
arguments);this.on("loadedCorpus",function(b,c){this.isVisible()&&this.loadFromApis()});a.embedded||a.corpus&&this.fireEvent("loadedCorpus",this,a.corpus);this.on("corpusTermsClicked",function(b,c){if(this.getStore().getCorpus()){var d=[];c.forEach(function(e){d.push(e.get("term"))});this.setApiParams({query:d,docId:void 0,docIndex:void 0});this.isVisible()&&this.loadFromApis()}});this.on("documentsClicked",function(b,c){var d=[];c.forEach(function(e){d.push(e.get("id"))});this.setApiParams({docId:d,
docid:void 0,query:void 0});this.isVisible()&&this.loadFromApis()});this.on("activate",function(){this.getStore().getCorpus()&&this.loadFromApis()},this);this.on("query",function(b,c){0===c.length&&(c=void 0);this.setApiParam("query",c);this.getStore().getProxy().setExtraParam("query",c);this.loadFromApis()},this)},loadFromApis:function(){this.getStore().getCorpus()&&(this.getApiParam("query")?this.getStore().clearAndLoad({params:this.getApiParams()}):this.getStore().getCorpus().getCorpusTerms({leadingBufferZone:0,
autoLoad:!1}).load({callback:function(a,b,c){if(c){var d=[];a.forEach(function(e){d.push(e.getTerm())});this.getStore().getProxy().setExtraParam("query",d);this.setApiParam("query",d);this.loadFromApis()}},scope:this,params:{limit:10,stopList:this.getApiParam("stopList")}}))},initComponent:function(){var a=this,b=Ext.create("Voyant.data.store.CorpusCollocatesBuffered",{parentPanel:this});Ext.apply(a,{title:this.localize("title"),emptyText:this.localize("emptyText"),store:b,selModel:Ext.create("Ext.selection.CheckboxModel",
{listeners:{selectionchange:{fn:function(c,d){if(0<d.length){var e=[],f=this.getApiParam("context");d.forEach(function(g){e.push('"'+g.getKeyword()+" "+g.getContextTerm()+'"~'+f)});this.getApplication().dispatchEvent("termsClicked",this,e)}},scope:this}}}),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"},this.localize("context"),{xtype:"slider",minValue:1,value:5,maxValue:30,increment:2,width:50,listeners:{render:function(c){c.setValue(a.getApiParam("context"))},
changecomplete:function(c,d){a.setApiParam("context",c.getValue());a.loadFromApis()}}},{xtype:"corpusdocumentselector"}]}],columns:[{text:this.localize("term"),dataIndex:"term",tooltip:this.localize("termTip"),sortable:!0,flex:1,xtype:"coloredtermfield",useCategoriesMenu:!0},{text:this.localize("rawFreq"),dataIndex:"rawFreq",tooltip:this.localize("termRawFreqTip"),sortable:!0,width:"autoSize",hidden:!0},{text:this.localize("contextTerm"),dataIndex:"contextTerm",tooltip:this.localize("contextTermTip"),
flex:1,sortable:!0,xtype:"coloredtermfield"},{text:this.localize("contextTermRawFreq"),tooltip:this.localize("contextTermRawFreqTip"),dataIndex:"contextTermRawFreq",width:"autoSize",sortable:!0}],listeners:{scope:this,termsClicked:function(c,d){if(this.getStore().getCorpus()){var e=[];d.forEach(function(f){Ext.isString(f)?e.push(f):f.term?e.push(f.term):f.getTerm&&e.push(f.getTerm())});0<e.length&&(this.setApiParams({docIndex:void 0,docId:void 0,query:e}),this.isVisible()&&this.loadFromApis())}},
corpusSelected:function(){this.getStore().getCorpus()&&(this.setApiParams({docId:void 0,docIndex:void 0}),this.loadFromApis())},documentsSelected:function(c,d){var e=[],f=this.getStore().getCorpus();d.forEach(function(g){e.push(f.getDocument(g).getId())},this);this.setApiParams({docId:e,docIndex:void 0});this.loadFromApis()}}});a.callParent(arguments);a.getStore().getProxy().setExtraParam("withDistributions",!0)}});Ext.define("Voyant.widget.CorpusTermSummary",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.corpustermsummary",statics:{i18n:{},api:{stopList:"auto",query:void 0,limit:5}},config:{corpus:void 0,record:void 0,collocatesStore:void 0,correlationsStore:void 0,phrasesStore:void 0,documentTermsStore:void 0},cls:"corpus-term-summary",constructor:function(a){if(void 0===a.record)return console.warn("CorpusTermSummary: no config.record!"),!1;Ext.apply(this,{items:{itemId:"main",minHeight:200,
scrollable:!0,margin:5},dockedItems:{dock:"bottom",xtype:"toolbar",items:{fieldLabel:this.localize("items"),labelWidth:40,width:120,xtype:"slider",increment:5,minValue:5,maxValue:59,listeners:{boxready:function(c){c.setValue(this.getApiParam("limit"))},changecomplete:function(c,d){this.setApiParam("limit",d);this.loadStuff()},scope:this}}},listeners:{boxready:function(){this.body.on("click",function(c){(c=c.getTarget(null,null,!0))&&"A"==c.dom.tagName&&c.hasCls("corpus-type")&&this.dispatchEvent("termsClicked",
this,[c.getHtml()])},this,{stopPropagation:!0});this.getDockedItems().forEach(function(c){c.getEl().on("click",null,this,{stopPropagation:!0})});this.loadStuff()},scope:this}});Ext.applyIf(a,{title:this.localize("title")+a.record.getTerm()});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);var b=this.getRecord().store.getCorpus();this.setCorpus(b);this.setApiParam("query",this.getRecord().getTerm());this.setCollocatesStore(Ext.create("Voyant.data.store.CorpusCollocates",
{corpus:b}));this.setCorrelationsStore(Ext.create("Voyant.data.store.TermCorrelations",{corpus:b}));this.setPhrasesStore(Ext.create("Voyant.data.store.CorpusNgrams",{corpus:b}));this.setDocumentTermsStore(Ext.create("Voyant.data.store.DocumentTerms",{corpus:b}))},loadStuff:function(){this.getComponent("main").removeAll();for(var a=[],b=0;b<this.getCorpus().getDocumentsCount();b++)a[b]=b;this.getComponent("main").add({xtype:"container",cls:"section",layout:"hbox",align:"bottom",items:[{xtype:"container",
html:'\x3cdiv class\x3d"header"\x3e'+this.localize("distribution")+"\x3c/div\x3e"},{itemId:"distLine",xtype:"sparklineline",values:[],height:20,width:200}],listeners:{afterrender:function(c){c.mask(this.localize("loading"));this.getDocumentTermsStore().load({params:{query:this.getApiParam("query"),docIndex:a,withDistributions:!0,bins:2*parseInt(this.getApiParam("limit"))},callback:function(d,e,f){f&&d&&0<d.length&&(d=d.map(function(g){return g.getDistributions()}).reduce(function(g,h){return g.concat(h)}),
this.down("#distLine").setValues(d),c.unmask())},scope:this})},scope:this}});this.addSection(this.localize("collocates"),this.getCollocatesStore(),this.getApiParams(),'\x3ctpl for\x3d"." between\x3d"; "\x3e\x3ca href\x3d"#" onclick\x3d"return false" class\x3d"corpus-type keyword" voyant:recordId\x3d"{term}"\x3e{term}\x3c/a\x3e\x3cspan style\x3d"font-size: smaller"\x3e ({val})\x3c/span\x3e\x3c/tpl\x3e',function(c){return{term:c.getContextTerm(),val:c.getContextTermRawFreq()}});this.addSection(this.localize("correlations"),
this.getCorrelationsStore(),this.getApiParams(),'\x3ctpl for\x3d"." between\x3d"; "\x3e\x3ca href\x3d"#" onclick\x3d"return false" class\x3d"corpus-type keyword" voyant:recordId\x3d"{term}"\x3e{term}\x3c/a\x3e\x3cspan style\x3d"font-size: smaller"\x3e ({val})\x3c/span\x3e\x3c/tpl\x3e',function(c){return{term:c.get("sourceTerm"),val:c.get("source").rawFreq}});this.addSection(this.localize("phrases"),this.getPhrasesStore(),Ext.apply({minLength:3,sort:"length"},this.getApiParams()),'\x3ctpl for\x3d"."\x3e\x3cdiv\x3e\x26ldquo;{phrase}\x26rdquo;\x3c/div\x3e\x3c/tpl\x3e',
function(c){return{phrase:c.getTerm()}})},addSection:function(a,b,c,d,e){return this.getComponent("main").add({xtype:"container",html:'\x3cdiv class\x3d"header"\x3e'+a+"\x3c/div\x3e",cls:"section",listeners:{afterrender:function(f){f.mask(this.localize("loading"));b.load({params:c,callback:function(g,h,k){f.unmask();k&&g&&0<g.length&&Ext.dom.Helper.append(f.getTargetEl().first().first(),(new Ext.XTemplate('\x3cdiv class\x3d"contents"\x3e'+d+"\x3c/div\x3e")).apply(g.map(e)))}})},scope:this}})}});Ext.define("Voyant.panel.Correlations",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.correlations",statics:{i18n:{},api:{query:void 0,docId:void 0,docIndex:void 0,stopList:"auto",minInDocumentsCountRatio:100,columns:void 0,sort:void 0,dir:void 0,termColors:"categories"},glyph:"xf0ce@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"termcolorsoption"}]},constructor:function(){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,
arguments)},initComponent:function(){var a=this;Ext.apply(a,{title:this.localize("title"),emptyText:this.localize("emptyText"),store:Ext.create("Voyant.data.store.TermCorrelationsBuffered",{parentPanel:this,leadingBufferZone:100}),columns:[{text:this.localize("source"),tooltip:this.localize("sourceTip"),dataIndex:"sourceTerm",sortable:!1,xtype:"coloredtermfield"},{xtype:"widgetcolumn",tooltip:this.localize("trendTip"),width:100,dataIndex:"source-distributions",widget:{xtype:"sparklineline"},text:"\u2190"},
{xtype:"widgetcolumn",tooltip:this.localize("trendTip"),width:100,dataIndex:"target-distributions",widget:{xtype:"sparklineline"},text:"\u2192",align:"right"},{text:this.localize("target"),tooltip:this.localize("targetTip"),dataIndex:"targetTerm",sortable:!1,xtype:"coloredtermfield"},{text:this.localize("correlation"),tooltip:this.localize("correlationTip"),dataIndex:"correlation"},{text:this.localize("significance"),tooltip:this.localize("significanceTip"),dataIndex:"significance"}],listeners:{scope:this,
corpusSelected:function(){this.setApiParams({docIndex:void 0,docId:void 0});this.getStore().getProxy().setExtraParam("tool","corpus.CorpusTermCorrelations");this.getStore().load()},documentsSelected:function(b,c){var d=[],e=this.getStore().getCorpus();c.forEach(function(f){d.push(e.getDocument(f).getId())},this);this.setApiParams({docId:d,docIndex:void 0});this.getStore().getProxy().setExtraParam("tool","corpus.DocumentTermCorrelations");this.getStore().load()}},dockedItems:[{dock:"bottom",xtype:"toolbar",
overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"},{xtype:"tbspacer"},{xtype:"tbtext",itemId:"minInDocumentsCountRatioLabel",text:a.localize("minInDocumentsCountRatioLabel")},{xtype:"slider",increment:5,minValue:0,maxValue:100,width:75,listeners:{afterrender:function(b){b.setValue(this.getApiParam("minInDocumentsCountRatio"));b.up("toolbar").getComponent("minInDocumentsCountRatioLabel").setText((new Ext.XTemplate(a.localize("minInDocumentsCountRatioLabel"))).apply([this.getApiParam("minInDocumentsCountRatio")]))},
changecomplete:function(b,c){this.setApiParams({minInDocumentsCountRatio:c});b.up("toolbar").getComponent("minInDocumentsCountRatioLabel").setText((new Ext.XTemplate(a.localize("minInDocumentsCountRatioLabel"))).apply([c]));this.getStore().load()},scope:this}},{xtype:"corpusdocumentselector"}]}]});a.on("loadedCorpus",function(b,c){1==c.getDocumentsCount()&&this.getStore().getProxy().setExtraParam("tool","corpus.DocumentTermCorrelations");this.isVisible()&&this.getStore().load()});a.on("activate",
function(){this.getStore().getCorpus()&&this.getStore().load()},this);a.on("query",function(b,c){this.setApiParam("query",c);this.getStore().load()},a);a.callParent(arguments)}});Ext.define("Voyant.panel.CorpusCreator",{extend:"Ext.form.Panel",requires:["Ext.form.field.File"],mixins:["Voyant.panel.Panel"],alias:"widget.corpuscreator",isConsumptive:!0,statics:{i18n:{corpusSortInitialOrder:"initial order",dtocIndexDoc:"DToC Index Document"},api:{inputFormat:void 0,language:void 0,xmlDocumentsXpath:void 0,xmlGroupByXpath:void 0,xmlContentXpath:void 0,xmlTitleXpath:void 0,xmlAuthorXpath:void 0,xmlPubDateXpath:void 0,xmlPublisherXpath:void 0,xmlPubPlaceXpath:void 0,xmlKeywordXpath:void 0,
xmlCollectionXpath:void 0,xmlExtraMetadataXpath:void 0,htmlGroupByQuery:void 0,htmlDocumentsQuery:void 0,htmlContentQuery:void 0,htmlTitleQuery:void 0,htmlAuthorQuery:void 0,htmlPubDateQuery:void 0,htmlPublisherQuery:void 0,htmlPubPlaceQuery:void 0,htmlKeywordsQuery:void 0,htmlCollectionQuery:void 0,htmlExtraMetadataQuery:void 0,jsonDocumentsPointer:void 0,jsonContentPointer:void 0,jsonTitlePointer:void 0,jsonAuthorPointer:void 0,jsonPubDatePointer:void 0,jsonPublisherPointer:void 0,jsonPubPlacePointer:void 0,
jsonKeywordsPointer:void 0,jsonCollectionPointer:void 0,jsonExtraMetadataPointer:void 0,tokenization:void 0,adminPassword:void 0,accessPassword:void 0,noPasswordAccess:void 0,tableDocuments:void 0,tableContent:void 0,tableTitle:void 0,tableAuthor:void 0,tablePubDate:void 0,tablePublisher:void 0,tablePubPlace:void 0,tableKeywords:void 0,tableCollection:void 0,tableExtraMetadata:void 0,title:void 0,subTitle:void 0,inputRemoveFrom:void 0,inputRemoveFromAfter:void 0,inputRemoveUntil:void 0,inputRemoveUntilAfter:void 0,
sort:void 0,dtocIndexDoc:-1}},constructor:function(a){this.callParent(arguments);a=a||{};this.mixins["Voyant.panel.Panel"].constructor.call(this,Ext.apply(a,{includeTools:{gear:!0,help:!0,language:this.getLanguageToolMenu()}}))},initComponent:function(){var a=this;Ext.apply(a,{title:this.localize("title"),width:800,frame:!0,padding:10,style:{borderColor:"#aaa",borderStyle:"solid"},frameHeader:!0,layout:{type:"vbox",align:"stretch"},dockedItems:[{xtype:"toolbar",overflowHandler:"scroller",dock:"bottom",
buttonAlign:"right",items:[{text:a.localize("Open"),glyph:"xf115@FontAwesome",tooltip:a.localize("SelectExisting"),hidden:void 0!=this.getCorpus(),handler:function(){Ext.create("Ext.window.Window",{title:a.localize("Open"),layout:"fit",modal:!0,items:{xtype:"form",submitEmptyText:!1,items:{xtype:"corpusselector",margin:10},buttons:[{text:a.localize("Open"),glyph:"xf00c@FontAwesome",handler:function(b){b.up("form").getForm();var c=b.up("form").getForm().getValues().corpus;""!=c?(a.loadCorpus({corpus:c}),
b.up("window").close()):Ext.Msg.show({title:a.localize("SelectExisting"),message:a.localize("PleaseSelectExisting"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR})},flex:1},{text:a.localize("cancel"),glyph:"xf00d@FontAwesome",flex:1,handler:function(b){b.up("window").close()}}]}}).show()}},{xtype:"fileuploadfield",glyph:"xf093@FontAwesome",name:"upload",buttonOnly:!0,hideLabel:!0,ui:"default-toolbar",buttonText:a.localize("Upload"),listeners:{render:function(b){b.fileInputEl.dom.setAttribute("multiple",!0);
Ext.tip.QuickTipManager.register({target:b.getEl(),text:a.localize("UploadLocal")})},beforedestroy:function(b){Ext.tip.QuickTipManager.unregister(b.getEl())},change:function(b,c){if(c){var d=b.up("form").getForm();if(d.isValid()){c=b.fileInputEl.dom.files;for(var e=/\.(png|gif|jpe?g|mp[234a]|mpeg|exe|wmv|avi|ppt|mpg|tif|wav|mov|psd|wma|ai|bmp|pps|aif|pub|dwg|indd|swf|asf|mbd|dmg|flv)$/i,f=/\.(txt|pdf|html?|xml|docx?|rtf|pages|epub|odt|zip|jar|tar|gz|ar|cpio|bzip2|bz2|gzip|csv|tsv|xlsx?)$/i,g=[],h=
[],k=0,l=c.length;k<l;k++){var m=c[k].name;e.test(m)?g.push(m.split("/").pop()):f.test(m)||h.push(m.split("/").pop())}0<g.length||0<h.length?Ext.Msg.show({title:a.localize("fileTypesWarning"),icon:Ext.MessageBox.ERROR,message:a.localize("fileTypesMessage")+"\x3cul\x3e"+(0<g.length?"\x3cli\x3e"+a.localize("badFiles")+g.slice(0,5).join(", ")+(5<g.length?"\u2026":"")+"\x3c/li\x3e":"")+(0<h.length?"\x3cli\x3e"+a.localize("unknownFiles")+h.slice(0,5).join(", ")+(5<h.length?"\u2026":"")+"\x3c/li\x3e":"")+
"\x3c/ul\x3e"+a.localize("sureContinue"),buttons:Ext.Msg.YESNO,fn:function(n){"yes"===n?a.loadForm(d):(b.reset(),b.fileInputEl.dom.setAttribute("multiple",!0))},scope:d}):a.loadForm(d)}}}}},"-\x3e",{xtype:"button",scale:"large",glyph:"xf00d@FontAwesome",text:this.localize("cancel"),hidden:void 0==this.getCorpus(),handler:function(b){(b=this.up("window"))&&b.isFloating()&&b.close()}},{xtype:"button",scale:"large",glyph:"xf00c@FontAwesome",text:this.localize("reveal"),ui:"default",width:200,handler:function(b){var c=
b.up("form").down("#input").getValue();if(""!==c){var d=a.getApiParams();delete d.corpus;delete d.view;delete d.stopList;d.inputFormat&&0!==c.trim().indexOf("\x3c")?Ext.Msg.confirm(a.localize("error"),a.localize("errorNotXmlContinue"),function(e){"yes"==e&&a.loadCorpus(Ext.apply(d,{input:c}))},a):a.loadCorpus(Ext.apply(d,{input:c}))}else Ext.Msg.show({title:a.localize("noTextProvided"),message:a.localize("pleaseProvideText"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR})}}]}],items:[{html:this.getInitialConfig().addTextLabel,
hidden:void 0==this.getInitialConfig().addTextLabel},{height:100,xtype:"textareafield",itemId:"input",emptyText:this.localize("emptyInput")}]});a.on("boxready",function(b){var c=this.getApplication();c.getAllowInput&&"false"==c.getAllowInput()&&(b.getDockedItems().forEach(function(d){b.removeDocked(d)}),b.removeAll(),b.add({xtype:"container",html:"\x3cp\x3e"+b.localize("noAllowInputMessage")+"\x3c/p\x3e"}))});a.callParent(arguments)},loadForm:function(a){var b={tool:this.getCorpus()?"corpus.CorpusMetadata":
"corpus.CorpusCreator"},c=this.getApiParams();this.getCorpus()?Ext.apply(b,{corpus:this.getCorpus().getId(),addDocuments:!0}):delete c.corpus;delete c.view;delete c.stopList;Ext.apply(b,c);var d=this.getApplication().getViewport();d.mask(this.localize("uploadingCorpus"));a.submit({url:this.getTromboneUrl(),params:b,failure:function(e,f){d.unmask();f.result&&(f.result.corpus||f.result.stepEnabledCorpusCreator)?(e={corpus:f.result.corpus?f.result.corpus.metadata.id:f.result.stepEnabledCorpusCreator.storedId},
Ext.applyIf(e,c),this.setCorpus(void 0),this.loadCorpus(e)):this.showResponseError("Unable to load corpus.",f.response)},scope:this})},loadCorpus:function(a){this.getCorpus()&&Ext.apply(a,{corpus:this.getCorpus().getId(),addDocuments:!0});var b=this.up("window");b&&b.isFloating()&&b.close();this.getApplication().loadCorpusFromParams(a)},showOptionsClick:function(a){if(void 0===a.optionsWin){var b=["bo"].concat(Object.keys(Voyant.widget.StopListOption.stoplists).filter(function(c){return"mu"!==c})).sort().map(function(c){return[c,
a._localizeClass(Voyant.widget.StopListOption,c)]});b.unshift(["",a._localizeClass(Voyant.widget.StopListOption,"auto")]);a.optionsWin=Ext.create("Ext.window.Window",{title:a.localize("gearWinTitle"),closeAction:"hide",layout:"fit",bodyPadding:10,anchor:"100% 100%",items:[{xtype:"form",defaultType:"textfield",maxHeight:a.getApplication().getViewport().getHeight()-120,scrollable:!0,fieldDefaults:{labelAlign:"right",labelWidth:110,width:350},items:[{xtype:"combo",fieldLabel:a.localize("inputFormat"),
labelWidth:90,name:"inputFormat",queryMode:"local",store:[["",a.localize("inputFormatAuto")],["dtoc","DToC: Dynamic Table of Contexts"],["TEI","TEI: Text Encoding Initative"],["TEI","TEI Corpus"],["RSS","Really Simple Syndication: RSS"]],value:"",listeners:{afterrender:{fn:function(c){var d=this.getApiParam("inputFormat");d&&c.setValue(d)},scope:a},change:{fn:function(c,d,e){c=c.up("form").down("[name\x3ddtocIndexDoc]");"dtoc"===d?c.show():c.hide()},scope:a}}},{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+
(new Ext.Template(a.localize("advancedOptionsText"))).applyTemplate([a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-xml"])+"\x3c/i\x3e\x3c/p\x3e",width:375},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-titles' target\x3d'voyantdocs'\x3e"+a.localize("corpusOptions")+"\x3c/a\x3e",collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("corpusTitle"),
name:"title"},{fieldLabel:a.localize("corpusSubTitle"),name:"subTitle"},{fieldLabel:a.localize("corpusSort"),name:"sort",xtype:"combo",queryMode:"local",store:[["",a.localize("corpusSortAuto")],["TITLEASC",a.localize("corpusSortTitle")],["AUTHORASC",a.localize("corpusSortAuthor")],["PUBDATEASC",a.localize("corpusSortPubDate")],["NOCHANGE",a.localize("corpusSortInitialOrder")]],value:"",listeners:{afterrender:{fn:function(c){var d=this.getApiParam("sort");d&&c.setValue(d)},scope:a}}},{fieldLabel:a.localize("dtocIndexDoc"),
name:"dtocIndexDoc",xtype:"numberfield",value:-1,minValue:-1,maxValue:99,width:180,hidden:!0}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-text' target\x3d'voyantdocs'\x3e"+a.localize("textOptions")+"\x3c/a\x3e",collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+a.localize("textOptionsText")+"\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("inputRemoveUntil"),name:"inputRemoveUntil"},{fieldLabel:a.localize("inputRemoveUntilAfter"),
name:"inputRemoveUntilAfter"},{fieldLabel:a.localize("inputRemoveFrom"),name:"inputRemoveFrom"},{fieldLabel:a.localize("inputRemoveFromAfter"),name:"inputRemoveFromAfter"}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-xml' target\x3d'voyantdocs'\x3e"+a.localize("xmlOptions")+"\x3c/a\x3e",collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+a.localize("xmlOptionsText")+"\x3c/i\x3e\x3c/p\x3e",width:375},
{fieldLabel:a.localize("xpathContent"),name:"xmlContentXpath"},{fieldLabel:a.localize("xpathTitle"),name:"xmlTitleXpath"},{fieldLabel:a.localize("xpathAuthor"),name:"xmlAuthorXpath"},{fieldLabel:a.localize("xpathDocuments"),name:"xmlDocumentsXpath"},{fieldLabel:a.localize("xpathGroupBy"),name:"xmlGroupByXpath"},{xtype:"fieldset",title:a.localize("xmlAdditionalOptions"),collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{fieldLabel:a.localize("xpathPubDate"),name:"xmlPubDateXpath"},{fieldLabel:a.localize("xpathPublisher"),
name:"xmlPublisherXpath"},{fieldLabel:a.localize("xpathPubPlace"),name:"xmlPubPlaceXpath"},{fieldLabel:a.localize("xpathKeywords"),name:"xmlKeywordXpath"},{fieldLabel:a.localize("xpathCollection"),name:"xmlCollectionXpath"},{xtype:"textareafield",grow:!0,fieldLabel:a.localize("xpathExtra"),name:"xmlExtraMetadataXpath"}]}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-html' target\x3d'voyantdocs'\x3e"+a.localize("htmlOptions")+"\x3c/a\x3e",collapsible:!0,
collapsed:!0,defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+(new Ext.Template(a.localize("htmlOptionsText"))).applyTemplate([a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-html"])+"\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("xpathContent"),name:"htmlContentQuery"},{fieldLabel:a.localize("xpathTitle"),name:"htmlTitleQuery"},{fieldLabel:a.localize("xpathAuthor"),name:"htmlAuthorQuery"},{fieldLabel:a.localize("xpathDocuments"),name:"htmlDocumentsQuery"},
{fieldLabel:a.localize("xpathGroupBy"),name:"htmlGroupByQuery"},{xtype:"fieldset",title:a.localize("xmlAdditionalOptions"),collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{fieldLabel:a.localize("xpathPubDate"),name:"htmlPubDateQuery"},{fieldLabel:a.localize("xpathPublisher"),name:"htmlPublisherQuery"},{fieldLabel:a.localize("xpathPubPlace"),name:"htmlPubPlaceQuery"},{fieldLabel:a.localize("xpathKeywords"),name:"htmlKeywordsQuery"},{fieldLabel:a.localize("xpathCollection"),name:"htmlCollectionQuery"},
{xtype:"textareafield",grow:!0,fieldLabel:a.localize("xpathExtra"),name:"htmlExtraMetadataQuery"}]}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-json' target\x3d'voyantdocs'\x3e"+a.localize("jsonOptions")+"\x3c/a\x3e",collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+(new Ext.Template(a.localize("jsonOptionsText"))).applyTemplate([a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-json"])+"\x3c/i\x3e\x3c/p\x3e",
width:375},{fieldLabel:a.localize("xpathContent"),name:"jsonContentPointer"},{fieldLabel:a.localize("xpathTitle"),name:"jsonTitlePointer"},{fieldLabel:a.localize("xpathAuthor"),name:"jsonAuthorPointer"},{fieldLabel:a.localize("xpathDocuments"),name:"jsonDocumentsPointer"},{xtype:"fieldset",title:a.localize("xmlAdditionalOptions"),collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{fieldLabel:a.localize("xpathPubDate"),name:"jsonPubDatePointer"},{fieldLabel:a.localize("xpathPublisher"),name:"jsonPublisherPointer"},
{fieldLabel:a.localize("xpathPubPlace"),name:"jsonPubPlacePointer"},{fieldLabel:a.localize("xpathKeywords"),name:"jsonKeywordsPointer"},{fieldLabel:a.localize("xpathCollection"),name:"jsonCollectionPointer"},{xtype:"textareafield",grow:!0,fieldLabel:a.localize("xpathExtra"),name:"jsonExtraMetadataPointer"}]}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-tables' target\x3d'voyantdocs'\x3e"+a.localize("tableOptions")+"\x3c/a\x3e",collapsible:!0,collapsed:!0,
defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+(new Ext.Template(a.localize("tableOptionsText"))).applyTemplate([a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-tables"])+"\x3c/i\x3e\x3c/p\x3e",width:375},{xtype:"combo",fieldLabel:a.localize("tableDocuments"),name:"tableDocuments",queryMode:"local",store:[["",a.localize("tableDocumentsTable")],["rows",a.localize("tableDocumentsRows")],["columns",a.localize("tableDocumentsColumns")]],forceSelection:!0,value:""},{xtype:"container",
html:"\x3cp\x3e\x3ci\x3e"+a.localize("tableNoHeadersRowText")+"\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("tableNoHeadersRow"),xtype:"checkboxfield",name:"tableNoHeadersRow",inputValue:"true"},{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+a.localize("tableContentText")+"\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("tableContent"),validator:function(c){return a.validatePositiveNumbersCsv.call(a,c)},name:"tableContent"},{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+a.localize("tableMetadataText")+
"\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("tableAuthor"),validator:function(c){return a.validatePositiveNumbersCsv.call(a,c)},name:"tableAuthor"},{fieldLabel:a.localize("tableTitle"),validator:function(c){return a.validatePositiveNumbersCsv.call(a,c)},name:"tableTitle"},{xtype:"fieldset",title:a.localize("xmlAdditionalOptions"),collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{fieldLabel:a.localize("xpathPubDate"),name:"tablePubDate"},{fieldLabel:a.localize("xpathPublisher"),
name:"tablePublisher"},{fieldLabel:a.localize("xpathPubPlace"),name:"tablePubPlace"},{fieldLabel:a.localize("xpathKeywords"),name:"tableKeywords"},{fieldLabel:a.localize("xpathCollection"),name:"tableCollection"},{xtype:"textareafield",grow:!0,fieldLabel:a.localize("xpathExtra"),name:"tableExtraMetadata"}]}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-processing' target\x3d'voyantdocs'\x3e"+a.localize("processingOptions")+"\x3c/a\x3e",collapsible:!0,
collapsed:!0,items:[{xtype:"combo",fieldLabel:a.localize("language"),name:"language",queryMode:"local",store:b,forceSelection:!0,value:""},{xtype:"combo",fieldLabel:a.localize("tokenization"),name:"tokenization",queryMode:"local",store:[["",a.localize("tokenizationAuto")],["wordBoundaries",a.localize("tokenizationWordBoundaries")],["whitespace",a.localize("tokenizationWhitespace")]],forceSelection:!0,value:""}]},{xtype:"fieldset",title:"\x3ca href\x3d'"+a.getBaseUrl()+"docs/#!/guide/corpuscreator-section-access-management' target\x3d'voyantdocs'\x3e"+
a.localize("accessOptions")+"\x3c/a\x3e",collapsible:!0,collapsed:!0,defaultType:"textfield",items:[{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+a.localize("accessOptionsText")+"\x3c/i\x3e\x3c/p\x3e",width:375},{fieldLabel:a.localize("adminPassword"),name:"adminPassword"},{fieldLabel:a.localize("accessPassword"),name:"accessPassword"},{xtype:"container",html:"\x3cp\x3e\x3ci\x3e"+a.localize("accessModeWithoutPasswordText")+"\x3c/i\x3e\x3c/p\x3e",width:375},{xtype:"combo",fieldLabel:a.localize("accessModeWithoutPassword"),
name:"noPasswordAccess",queryMode:"local",store:[["",a.localize("accessModeNonConsumptive")],["none",a.localize("accessModeNone")]],forceSelection:!0,value:""}]}]}],buttons:[{text:a.localize("ok"),handler:function(c,d){c=c.findParentByType("window");d=c.down("form");d.isValid()?(d=d.getValues(),a.setApiParams(d),c.hide()):a.showError({message:a.localize("invalidForm")})}},{text:a.localize("cancel"),handler:function(c,d){c.findParentByType("window").hide()}}]})}a.optionsWin.showAt(a.getApplication().getViewport().getWidth()/
2-200,10)},validatePositiveNumbersCsv:function(a){a=a.trim();if(0<a.length){if(/[^\d,+ ]/.test(a))return this.localize("numbersCommasOnly");if(/\d\s+\d/.test(a))return this.localize("numbersNeedCommas");a=a.split(/\s*[,+]\s*/);for(var b,c=0,d=a.length;c<d;c++){b=a[c];if(0==b.length)return this.localize("numberEmpty");if(0==parseInt(b))return this.localize("numberZero")}}return!0}});Ext.define("Voyant.panel.DreamScape",{extend:"Ext.Panel",xtype:"dreamscape",mixins:["Voyant.panel.Panel"],statics:{i18n:{},api:{stopList:"auto",hide:[],author:void 0,title:void 0,keyword:void 0,pubDate:void 0,citiesMaxCount:500,minPopulation:1E4,citiesMinFreq:1,connectionsMaxCount:2500,connectionsMinFreq:1,millisPerAnimation:2E3,annotationsId:void 0,source:void 0,overridesId:void 0,filterHasLowerCaseForm:!0,filterIsPersonName:!0,preferredCoordinates:void 0},glyph:"xf124@FontAwesome"},config:{map:void 0,
overlay:void 0,contentEl:void 0,isOpenLayersLoaded:!1,isArcLoaded:!1,animationDelay:25,isProj4Loaded:!1,projection:void 0,filterWidgets:new Ext.util.MixedCollection,drawInteraction:void 0,drawMode:!1,baseLayers:{},annotations:void 0,annotationsLoadedIfAvailable:!1,overrides:{}},html:'\x3cdiv class\x3d"map"\x3e\x3c/div\x3e\x3cdiv class\x3d"ticker"\x3e\x3c/div\x3e',cls:"dreamscape",constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);
Ext.Loader.loadScript({url:this.getBaseUrl()+"resources/openlayers/ol.js",onLoad:function(){void 0===ol.Map.prototype.getLayer&&(ol.Map.prototype.getLayer=function(d){var e=void 0;this.getLayers().forEach(function(f){d===f.get("id")&&(e=f)});return e});this.setIsOpenLayersLoaded(!0)},scope:this});Ext.Loader.loadScript({url:this.getBaseUrl()+"resources/dreamscape/arc.js",onLoad:function(){this.setIsArcLoaded(!0)},scope:this});Ext.Loader.loadScript({url:"https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js",
onLoad:function(){this.setIsProj4Loaded(!0)},scope:this});var b=this.getApiParam("annotationsId");if(b){var c=this;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",retrieveResourceId:b},scope:this}).then(function(d){d=Ext.JSON.decode(d.responseText);d.storedResource.resource&&(d=Ext.JSON.decode(d.storedResource.resource),Ext.isString(d)&&(d=Ext.JSON.decode(d),c.setAnnotations(d)));c.getAnnotations()||c.showError(c.localize("annotationsLoadFailed"));c.setAnnotationsLoadedIfAvailable(!0)},
function(d){c.showResponseError(c.localize("annotationsLoadFailed"),d);c.setAnnotationsLoadedIfAvailable(!0)})}else this.setAnnotationsLoadedIfAvailable(!0)},initComponent:function(){this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);var a=this.getApiParam("hide");Ext.isString(a)&&(a=a.split(","),this.setApiParam("hide"));this.getApplication().getBaseUrl();Ext.apply(this,{title:this.localize("title"),bodyBorder:!0,dockedItems:[{dock:"bottom",xtype:"toolbar",itemId:"bottomToolbar",overflowHandler:"scroller",
items:[{text:this.localize("display"),tooltip:this.localize("displayTip"),glyph:"xf013@FontAwesome",menu:{defaults:{xtype:"menucheckitem",checkHandler:function(b,c){var d=this.getMap(),e=b.getItemId();this.getFilterWidgets().each(function(g){d.getLayer(g.getId()+"-"+e).setVisible(c)});var f=Ext.Array.from(this.getApiParam("hide"));c?f=Ext.Array.remove(f,e):(f.push(e),f=Ext.Array.unique(f));this.setApiParam("hide",f);b.getMenu().setDisabled(0==c)},scope:this,checked:!0},items:[{xtype:"menuitem",text:this.localize("baseLayer"),
tooltip:this.localize("baseLayerTip"),glyph:"xf279@FontAwesome",menu:{items:[{xtype:"radiogroup",columns:1,vertical:!0,defaults:{cls:"map-menu-item",handler:function(b,c){if(c){id=b.getItemId();if(b=this.getBaseLayers()[id])b.setOpacity(1),this.getMap().getLayers().setAt(0,b);"osm"==id||"arcGIS"==id?this.getMap().getLayer("overlayLayer").setVisible(!1):this.getMap().getLayer("overlayLayer").setVisible(!0)}},listeners:{afterrender:function(b){Ext.create("Ext.tip.ToolTip",{target:b,html:'\x3cdiv class\x3d"map-menu-item-tooltip '+
b.getItemId()+'"\x3e\x3c/div\x3e',anchor:"right"})}},scope:this},items:[{boxLabel:this.localize("wms4326"),cls:["map-menu-item","wms4326"],itemId:"wms4326"},{boxLabel:this.localize("osm"),cls:["map-menu-item","osm"],itemId:"osm",checked:!0},{boxLabel:this.localize("arcGIS"),cls:["map-menu-item","arcGIS"],itemId:"arcGIS"}]}]}},{xtype:"menuitem",text:this.localize("projection"),tooltip:this.localize("projectionTip"),glyph:"xf0ac@FontAwesome",menu:{items:[{xtype:"radiogroup",columns:1,vertical:!0,defaults:{handler:function(b,
c){if(c){var d=this;id=b.getItemId();"webMercatorProjection"===id?this.setProjection(ol.proj.get("EPSG:3857")):"mercatorProjection"===id?this.setProjection(ol.proj.get("EPSG:4326")):"gallPetersProjection"===id?(proj4.defs("cea","+proj\x3dcea +lon_0\x3d0 +lat_ts\x3d45 +x_0\x3d0 +y_0\x3d0 +ellps\x3dWGS84 +units\x3dm +no_defs"),b=ol.proj.get("cea"),this.setProjection(b)):"sphereMollweideProjection"===id&&(proj4.defs("ESRI:54009","+proj\x3dmoll +lon_0\x3d0 +x_0\x3d0 +y_0\x3d0 +datum\x3dWGS84 +units\x3dm +no_defs"),
b=ol.proj.get("ESRI:54009"),b.setExtent([-18E6,-9E6,18E6,9E6]),this.setProjection(b));b=this.getProjection().getExtent();c=this.getProjection()==ol.proj.get("EPSG:4326")?360:4.007501668557849E7;b=new ol.View({projection:this.getProjection(),center:ol.extent.getCenter(b||[0,0,0,0]),maxResolution:c/d.body.dom.offsetWidth,zoom:0});var e=this.getMap();e.getLayers().forEach(function(f){f.getSource().getFeatures&&f.getSource().getFeatures().forEach(function(g){var h=g.getGeometry().transform(e.getView().getProjection(),
d.getProjection());g.setGeometry(h)})});e.setView(b)}},listeners:{afterrender:function(b){Ext.create("Ext.tip.ToolTip",{target:b,html:'\x3cdiv class\x3d"map-menu-item-tooltip '+b.getItemId()+'"\x3e\x3c/div\x3e',anchor:"right"})}},scope:this},items:[{boxLabel:this.localize("webMercatorProjection"),itemId:"webMercatorProjection",cls:["map-menu-item","webMercatorProjection"],checked:!0},{boxLabel:this.localize("mercatorProjection"),cls:["map-menu-item","mercatorProjection"],itemId:"mercatorProjection"},
{boxLabel:this.localize("gallPetersProjection"),cls:["map-menu-item","gallPetersProjection"],itemId:"gallPetersProjection"},{boxLabel:this.localize("sphereMollweideProjection"),cls:["map-menu-item","sphereMollweideProjection"],itemId:"sphereMollweideProjection"}]}]}},"-",{text:this.localize("cities"),checked:0==Ext.Array.contains(a,"cities"),itemId:"cities",menu:{defaults:{labelAlign:"right",labelWidth:140},items:[{xtype:"numberfield",fieldLabel:this.localize("citiesMaxCount"),minValue:1,value:parseInt(this.getApiParam("citiesMaxCount")),
listeners:{change:function(b,c,d){this.getFilterWidgets().each(function(e){this.setApiParam("citiesMaxCount",c);var f=e.getGeonames().getCitiesCount();c<d||c<=f?this.filterUpdate(e):e.getGeonames().hasMoreCities()?e.loadGeonames():(b.setValue(f),this.toastInfo((new Ext.XTemplate(this.localize("allNCitiesShown"))).apply([f])))},this)},scope:this}},{xtype:"numberfield",fieldLabel:this.localize("citiesMinPopulation"),minValue:1,value:parseInt(this.getApiParam("minPopulation")),listeners:{change:function(b,
c,d){this.setApiParam("minPopulation",c);this.getFilterWidgets().each(function(e){c>d?this.filterUpdate(e):e.loadGeonames()},this)},scope:this}},{xtype:"numberfield",fieldLabel:this.localize("citiesMinFreq"),minValue:1,value:parseInt(this.getApiParam("citiesMinFreq")),listeners:{change:function(b,c,d){this.getFilterWidgets().each(function(e){this.setApiParam("citiesMinFreq",c);c>d?this.filterUpdate(e):e.loadGeonames()},this)},scope:this}}]}},{text:this.localize("connections"),checked:0==Ext.Array.contains(a,
"connections"),itemId:"connections",menu:{defaults:{labelWidth:140,labelAlign:"right"},items:[{xtype:"numberfield",fieldLabel:this.localize("connectionsMaxCount"),minValue:1,value:parseInt(this.getApiParam("connectionsMaxCount")),listeners:{change:function(b,c,d){this.getFilterWidgets().each(function(e){this.setApiParam("connectionsMaxCount",c);c>d?this.filterUpdate(e):e.loadGeonames()},this)},scope:this}},{xtype:"numberfield",fieldLabel:this.localize("connectionsMinFreq"),minValue:1,value:parseInt(this.getApiParam("connectionsMinFreq")),
listeners:{change:function(b,c,d){this.getFilterWidgets().each(function(e){this.setApiParam("connectionsMinFreq",c);c>d?this.filterUpdate(e):e.loadGeonames()},this)},scope:this}}]}},{xtype:"menucheckitem",checked:0==Ext.Array.contains(a,"animation"),text:this.localize("animations"),itemId:"animation",menu:{defaults:{labelWidth:170,labelAlign:"right",width:280},items:[{xtype:"sliderfield",fieldLabel:this.localize("millisPerAnimation"),value:parseInt(this.getApiParam("millisPerAnimation")),minValue:this.getAnimationDelay(),
maxValue:1E4,listeners:{change:function(b,c,d){this.getFilterWidgets().each(function(e){e.setMillisPerAnimation(c);e.animate()},this)},scope:this}}]}}]}},"-",{text:this.localize("add"),itemId:"addFilter",glyph:"xf067@FontAwesome",handler:function(b){for(var c=this.getApplication().getColorPalette(this.getApiParam("palette"),!0),d=c[0],e=0,f=c.length;e<f;e++){var g=!1;this.getFilterWidgets().each(function(h){if(h.getColor()==c[e])return g=!0,!1});if(0==g){d=c[e];break}}d=b.ownerCt.add({xtype:"geonamesfilter",
corpus:this.getCorpus(),color:d,listeners:{removeFilterWidget:function(h){var k=this.getMap(),l=h.getItemId(),m=this.getFilterWidgets();["connections","cities","animation"].forEach(function(n){k.removeLayer(k.getLayer(l+"-"+n))});m.remove(h);0==m.getCount()&&this.getDockedComponent("bottomToolbar").getComponent("addFilter").click()},filterUpdate:this.filterUpdate,scope:this}});this.getFilterWidgets().add(d.getId(),d);b=this.getMap();f=new ol.layer.Vector({source:new ol.source.Vector({wrapX:!1,useSpatialIndex:!0}),
id:d.getId()+"-connections",visible:!0,opacity:.2,style:this.travelStyleFunction.bind(this),updateWhileAnimating:!0,updateWhileInteracting:!0});b.addLayer(f);f=new ol.layer.Vector({source:new ol.source.Vector({wrapX:!1,useSpatialIndex:!0}),id:d.getId()+"-cities",opacity:.5,style:this.cityStyleFunction.bind(this)});b.addLayer(f);d=new ol.layer.Vector({source:new ol.source.Vector({wrapX:!1,useSpatialIndex:!0}),id:d.getId()+"-animation",style:this.animationStyleFunction.bind(this)});b.addLayer(d)},scope:this}]}]});
this.on("loadedCorpus",function(b,c){this.tryInit()},this);this.callParent()},tryInit:function(){if(this.getIsOpenLayersLoaded()&&this.getIsArcLoaded()&&this.getIsProj4Loaded()&&this.getAnnotationsLoadedIfAvailable()){var a=this.body.down(".map").setId(Ext.id()),b=this,c=this.getBaseLayers();c.osm=new ol.layer.Tile({preload:Infinity,source:new ol.source.OSM({projection:"EPSG:3857"})});c.wms4326=new ol.layer.Tile({preload:Infinity,source:new ol.source.TileWMS({url:"https://ahocevar.com/geoserver/wms",
crossOrigin:"",params:{LAYERS:"ne:NE1_HR_LC_SR_W_DR",TILED:!0},projection:"EPSG:4326"})});c.arcGIS=new ol.layer.Tile({preload:Infinity,source:new ol.source.TileArcGISRest({url:"https://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer",projection:"EPSG:3857"})});var d=new ol.Map({layers:[c.osm],target:a.getId(),loadTilesWhileInteracting:!0,view:new ol.View({center:[0,0],maxResolution:4.007501668557849E7/b.body.dom.offsetWidth,zoom:0})});d.on("singleclick",this.handleSingleClick,
this);d.on("singleclicking",function(g){var h=d.getFeaturesAtPixel(g.pixel);if(h){for(var k=0;k<h.length;k++){var l=h[k];"city"==l.get("type")&&this.handleLocationClick(l)}l=h[0];debugger}if(h){var m=!1;h.forEach(function(n){"city"===n.get("type")&&n.get("selected")?(b.dispatchEvent("termsClicked",b,[n.get("forms").join("|")]),m=!0):"connection"===n.get("type")&&n.get("selected")&&!m&&(b.getFilterWidgets().each(function(u){u=u.getGeonames();if(null!=u){var w="\x3cul\x3e",p=-1;u.getAllConnectionOccurrences(n.get("source"),
n.get("target")).forEach(function(q){q.docIndex!=p&&(p=q.docIndex,w+="\x3ch4\x3e"+b.getCorpus().getDocument(p).getFullLabel()+":\x3c/h4\x3e");w+="\x3cli\x3e"+q.source.left+'\x3ca href\x3d"http://www.geonames.org/'+q.source.id+'" target\x3d"_blank" docIndex\x3d'+q.docIndex+" offset\x3d"+q.source.position+" location\x3d"+q.source.form+" cityId\x3d"+q.source.id+" coordinates\x3d"+JSON.stringify(sourceCoordinates)+' class\x3d"termLocationLink"\x3e'+q.source.form+"\x3c/a\x3e "+q.source.right+" [...] "+
q.target.left+'\x3ca href\x3d"http://www.geonames.org/'+q.target.id+'" target\x3d"_blank" docIndex\x3d'+q.docIndex+" offset\x3d"+q.target.position+" location\x3d"+q.target.form+" cityId\x3d"+q.target.id+" coordinates\x3d"+JSON.stringify(targetCoordinates)+' class\x3d"termLocationLink"\x3e'+q.target.form+"\x3c/a\x3e "+q.target.right+"\x3c/li\x3e"});u=n.get("text");w+="\x3c/ul\x3e";b.getContentEl().setHtml("\x3ch3\x3e"+u+"\x3c/h3\x3e"+w);b.getOverlay().setPosition(g.coordinate);Ext.select(".termLocationLink").elements.forEach(function(q){q.onmouseover=
function(){b.showTermInCorpus(q.getAttribute("docIndex"),q.getAttribute("offset"),q.getAttribute("location"))}})}}),m=!0)},this)}});var e=new ol.layer.Vector({map:d,source:new ol.source.Vector({wrapX:!1,useSpatialIndex:!1}),zIndex:10,selected:!0,style:function(g){if("city"===g.get("type"))return b.cityStyleFunction(g,d.getView().getResolution());if("connection"===g.get("type"))return b.travelStyleFunction(g,d.getView().getResolution())},updateWhileAnimating:!0,updateWhileInteracting:!0});a=new ol.layer.Vector({map:d,
source:new ol.source.Vector({wrapX:!1,useSpatialIndex:!1}),preview:!0,zIndex:15,id:"preview",style:function(g){if("city"===g.get("type"))return b.cityStyleFunction(g,d.getView().getResolution());if("connection"===g.get("type"))return b.travelStyleFunction(g,d.getView().getResolution())},updateWhileAnimating:!0,updateWhileInteracting:!0});d.addLayer(a);d.on("pointermove",function(g){var h=d.getEventPixel(g.originalEvent);h=d.hasFeatureAtPixel(h);d.getViewport().style.cursor=h?"pointer":"";if(!b.getDrawMode()&&
(e.getSource().clear(),h=g.pixel,h=d.getFeaturesAtPixel(h))){for(var k=0;h[k].get("selected")&&(k++,k!==h.length););if(k<h.length){var l=h[k];h={font:"12px Calibri,sans-serif",textAlign:"center",offsetY:-15,fill:new ol.style.Fill({color:[0,0,0,1]}),stroke:new ol.style.Stroke({color:[255,255,255,.5],width:4})};h.text=l.get("text");h=new ol.style.Style({text:new ol.style.Text(h),zIndex:1});"annotation"!==l.get("type")&&(k=new ol.Feature({text:l.get("text"),geometry:l.getGeometry(),forms:l.get("forms"),
selected:!0,coordinates:l.get("coordinates"),width:l.get("width"),visible:l.get("visible"),color:l.get("color"),type:l.get("type"),confidence:l.get("confidence"),source:l.get("source"),target:l.get("target"),cityId:l.get("cityId")}),e.getSource().addFeature(k));l.getGeometry();g=new ol.Feature({geometry:new ol.geom.Point(g.coordinate),selected:!0});g.setStyle(h);e.getSource().addFeature(g);"city"===l.get("type")&&b.getMap().getLayers().forEach(function(m){var n=m.get("id");n&&-1!==n.indexOf("connections")&&
(connections=m.getSource().getFeatures(),connections.forEach(function(u){u.get("target")!==l.get("cityId")&&u.get("source")!==l.get("cityId")||e.getSource().addFeature(new ol.Feature({geometry:u.getGeometry(),selected:!0,coordinates:u.get("coordinates"),width:u.get("width"),visible:u.get("visible"),color:u.get("color"),type:u.get("type")}))}))})}}});a=new ol.source.Vector({wrapX:!1});c=new ol.layer.Vector({source:a,id:"annotations"});var f=this.getAnnotations();f&&(f=(new ol.format.GeoJSON).readFeatures(f),
a.addFeatures(f));d.addLayer(c);this.setDrawInteraction(new ol.interaction.Draw({source:a,type:"Polygon",freehand:!0,alias:"draw"}));this.getDrawInteraction().on("drawend",function(g){g.feature.set("type","annotation");b.editAnnotation(g.feature)});this.setMap(d);this.getTargetEl().down(".ol-zoom");Ext.create("Ext.Button",{glyph:"xf075@FontAwesome",cls:"annotate",renderTo:this.getTargetEl().down(".ticker").parent(),tooltip:this.localize("annotateTip"),enableToggle:!0,toggleHandler:function(g,h){h?
this.getMap().addInteraction(this.getDrawInteraction()):this.getMap().removeInteraction(this.getDrawInteraction())},scope:this});this.getDockedComponent("bottomToolbar").getComponent("addFilter").click()}else Ext.defer(this.tryInit,500,this)},editAnnotation:function(a){var b=a.get("text");Ext.Msg.show({title:this.localize("editAnnotation"),message:this.localize("editAnnotationMessage"),buttons:Ext.Msg.OKCANCEL,multiline:!0,value:b,scope:this,callback:function(c,d){if("ok"==c){""==d?this.getMap().getLayer("annotations").getSource().removeFeature(a):
a.set("text",d);c=new ol.format.GeoJSON;d=this.getMap().getLayer("annotations").getSource().getFeatures();var e=[],f=this.getProjection();d.forEach(function(g){transformedFeature=g.clone();transformedFeature.getGeometry().transform(f?f:"EPSG:3857","EPSG:3857");e.push(transformedFeature)});c=c.writeFeatures(e);this.storeAnnotations(c)}}})},storeAnnotations:function(a){this.mask("storingAnnotations");var b=this;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",storeResource:JSON.stringify(a)},
scope:this}).then(function(c){b.unmask();c=Ext.JSON.decode(c.responseText);b.setApiParam("annotationsId",c.storedResource.id);b.toastInfo(b.localize("annotationsUpdated"))},function(c){b.unmask();b.showResponseError(b.localize("annotationsUpdateFailed"),c)})},travelStyleFunction:function(a,b){var c=new ol.style.Stroke({color:a.get("color"),width:a.get("width")}),d=[new ol.style.Style({stroke:c})],e=a.getGeometry();a=e.getLastCoordinate();e=e.getCoordinateAt(.9);e=Math.atan2(a[1]-e[1],a[0]-e[0]);var f=
new ol.geom.LineString([a,[a[0]-10*b,a[1]+10*b]]);f.rotate(e,a);b=new ol.geom.LineString([a,[a[0]-10*b,a[1]-10*b]]);b.rotate(e,a);d.push(new ol.style.Style({geometry:f,stroke:c}));d.push(new ol.style.Style({geometry:b,stroke:c}));return d},cityStyleFunction:function(a,b){if(a.get("visible")){b=2*Math.PI*a.get("width");var c=a.get("confidence")?b*a.get("confidence"):b;return new ol.style.Style({image:new ol.style.Circle({radius:a.get("width"),fill:new ol.style.Fill({color:a.get("color")}),stroke:new ol.style.Stroke({lineDash:[c,
b-c],color:"rgb(255, 255, 255)",width:2})})})}return!1},animationStyleFunction:function(a){return[new ol.style.Style({stroke:new ol.style.Stroke({color:a.get("color"),width:5})}),new ol.style.Style({geometry:new ol.geom.Circle(a.getGeometry().getFirstCoordinate()),stroke:new ol.style.Stroke({color:"white",width:10})}),new ol.style.Style({geometry:new ol.geom.Circle(a.getGeometry().getLastCoordinate()),stroke:new ol.style.Stroke({color:"white",width:10})})]},showTermInCorpus:function(a,b,c){a=Ext.create("Voyant.data.model.Context",
{docIndex:a,position:b,term:c});this.getApplication().dispatchEvent("termLocationClicked",this,[a])},reloadFilters:function(){this.getFilterWidgets().each(function(a){a.loadGeonames()},this)},filterUpdate:function(a){var b=this;a.clearAnimation();var c=this.getMap(),d=a.getColor(),e=parseInt(this.getApiParam("citiesMaxCount")),f=0;a.getGeonames().eachCity(function(p){p.rawFreq>f&&(f=p.rawFreq)},this,e);var g=c.getLayer(a.getId()+"-cities").getSource(),h=Ext.Array.from(this.getApiParam("hide"));g.clear();
var k=parseInt(this.getApiParam("minPopulation")),l=parseInt(this.getApiParam("citiesMinFreq")),m={};a.getGeonames().eachCity(function(p){if((!k||p.population>=k)&&(!l||p.rawFreq>=l)){m[p.id]=!0;var q=[parseFloat(p.lng),parseFloat(p.lat)];p=new ol.Feature({geometry:(new ol.geom.Point(q)).transform(ol.proj.get("EPSG:4326"),b.getProjection()?b.getProjection():ol.proj.get("EPSG:3857")),text:p.label+" ("+p.rawFreq+")",description:p.label,color:d,selected:!1,width:3+20*Math.sqrt(p.rawFreq/f),visible:!0,
coordinates:q,forms:p.forms,cityId:p.id,type:"city",confidence:p.confidence?100*p.confidence:void 0});g.addFeature(p)}},this,e);0<g.getFeatures().length&&c.getView().fit(g.getExtent());c.getLayer(a.getId()+"-cities").setVisible(0==Ext.Array.contains(h,"cities"));g=c.getLayer(a.getId()+"-connections").getSource();g.clear();0==Object.keys(m).length&&this.toastInfo("No cities available for current criteria.");f=0;a.getGeonames().eachConnection(function(p){p.rawFreq>f&&(f=p.rawFreq)},this);var n=0,u=
parseInt(this.getApiParam("connectionsMaxCount")),w=parseInt(this.getApiParam("connectionsMinFreq"));a.getGeonames().eachConnection(function(p){if((!w||p.rawFreq>=w)&&(!u||n<u)&&p.source.id in m&&p.target.id in m&&(!k||p.source.population>=k&&p.target.population>=k)){var q=(new arc.GreatCircle({x:p.source.lng,y:p.source.lat},{x:p.target.lng,y:p.target.lat})).Arc(100,{offset:100}),r=p.source.label+" -\x3e "+p.target.label+" ("+p.rawFreq+")";q.geometries.forEach(function(v){v=new ol.geom.LineString(v.coords);
v.transform(ol.proj.get("EPSG:4326"),b.getProjection()?b.getProjection():ol.proj.get("EPSG:3857"));v=new ol.Feature({geometry:v,text:r,color:d,width:3+10*Math.sqrt(p.rawFreq/f),source:p.source.id,target:p.target.id,type:"connection"});g.addFeature(v)},this);n++}},this);c.getLayer(a.getId()+"-connections").setVisible(0==Ext.Array.contains(h,"connections"));a.animate()},handleSingleClick:function(a){var b=this.getMap().getFeaturesAtPixel(a.pixel);if(b)for(var c=0;c<b.length;c++){var d=b[c],e=d.get("type");
if("city"==e){this.handleLocationClick(a,d);break}else if("connection"==e){this.handleConnectionClick(d,a.pixel[0],a.pixel[1]);break}else if("annotation"==e){this.editAnnotation(d);break}}},handleConnectionClick:function(a,b,c){Ext.create("Ext.menu.Menu",{items:[{text:this.localize("viewConnections"),tooltip:this.localize("viewConnectionsTip"),glyph:"xf02d@FontAwesome",handler:function(){this.mask("loadingConnections");var d=this;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"corpus.Dreamscape",
corpus:this.getCorpus().getId(),suppressLocations:!0,suppressConnections:!0,sourceId:a.get("source"),targetId:a.get("target"),context:2,limit:25},scope:this}).then(function(e){d.unmask();if((e=Ext.JSON.decode(e.responseText))&&e.dreamscape&&e.dreamscape.connectionOccurrences){var f="\x3ctable style\x3d'font-size:smaller'\x3e";e.dreamscape.connectionOccurrences.connectionOccurrences.forEach(function(g){f+="\x3ctr\x3e\x3ctd style\x3d'text-align: right'\x3e"+g.source.left+"\x3c/td\x3e\x3ctd class\x3d'keyword' style\x3d'text-align: center'\x3e"+
g.source.term+"\x3c/td\x3e\x3ctd\x3e"+g.source.right+"\x3c/td\x3e\x3ctd\x3e\u2026\x3c/td\x3e\x3ctd style\x3d'text-align: right'\x3e"+g.target.left+"\x3c/td\x3e\x3ctd class\x3d'keyword' style\x3d'text-align: center'\x3e"+g.target.term+"\x3c/td\x3e\x3ctd\x3e"+g.target.right+"\x3c/td\x3e\x3c/tr\x3e"});f+="\x3c/table\x3e";Ext.Msg.alert(d.localize("occurrences"),f)}},function(e){d.unmask();return d.showError(d.localize("occurrencesNotLoaded"))})},scope:this}]}).showAt(b,c)},handleLocationClick:function(a,
b){var c=b.get("cityId");Ext.create("Ext.menu.Menu",{items:[{text:this.localize("viewOccurrences"),tooltip:this.localize("viewOccurrencesTip"),glyph:"xf02d@FontAwesome",handler:function(){this.mask("loadingOccurrences");var d=this;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"corpus.Dreamscape",corpus:this.getCorpus().getId(),suppressLocations:!0,suppressConnections:!0,suppressConnectionOccurrences:!0,locationId:c,limit:25},scope:this}).then(function(e){d.unmask();if((e=Ext.JSON.decode(e.responseText))&&
e.dreamscape&&e.dreamscape.occurrences){var f="\x3ctable style\x3d'font-size:smaller'\x3e";e.dreamscape.occurrences.occurrences.forEach(function(g){f+="\x3ctr\x3e\x3ctd style\x3d'text-align: right'\x3e"+g.left+"\x3c/td\x3e\x3ctd class\x3d'keyword' style\x3d'text-align: center'\x3e"+g.term+"\x3c/td\x3e\x3ctd\x3e"+g.right+"\x3c/td\x3e\x3c/tr\x3e"});f+="\x3c/table\x3e";Ext.Msg.alert(d.localize("occurrences"),f)}},function(e){d.unmask();return d.showError(d.localize("occurrencesNotLoaded"))})},scope:this},
{text:this.localize("openInVoyant"),tooltip:this.localize("openInVoyantTip"),glyph:"xf08e@FontAwesome",handler:function(){this.dispatchEvent("termsClicked",this,b.get("forms"))},scope:this},{text:this.localize("editLocation"),tooltip:this.localize("editLocationTip"),glyph:"xf124@FontAwesome",handler:function(){this.mask("loadingAlternatives");var d=this;Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"util.Geonames",query:b.get("forms")},scope:this}).then(function(e){d.unmask();if((e=Ext.JSON.decode(e.responseText))&&
e.geonames&&e.geonames.locations){var f=[];Object.values(e.geonames.locations.locations).forEach(function(g){f.push({boxLabel:g.label+" ("+g.population+")",name:"id",inputValue:g.id,checked:g.id==c})});if(0==f.length)return d.showError(d.localize("editLocationNoLocationsFound"));if(1==f.length&&f[0].inputValue==c)return d.showError(d.localize("editLocationNoAlternativesFound"));Ext.create("Ext.window.Window",{title:d.localize("editLocation"),modal:!0,items:{xtype:"form",items:[{xtype:"radiogroup",
columns:1,vertical:!0,items:f}],listeners:{afterrender:function(g){},scope:this},buttons:[{text:d.localize("cancel"),ui:"default-toolbar",glyph:"xf00d@FontAwesome",flex:1,handler:function(g){g.up("window").destroy()}},{text:d.localize("confirmTitle"),glyph:"xf00c@FontAwesome",flex:1,handler:function(g){var h=g.up("form").getValues().id;if(h&&h!=c){var k={};k[c]=h;d.appendOverrides(k)}g.up("window").destroy()}}]}}).show()}},function(e){d.unmask();d.showResponseError(d.localize("editLocationServerError"),
e)})},scope:this},{text:this.localize("removeLocation"),tooltip:this.localize("removeLocationTip"),glyph:"xf00d@FontAwesome",handler:function(){Ext.Msg.confirm(this.localize("removeLocationConfirmTitle"),this.localize("removeLocationConfirm"),function(d){"yes"==d&&(d={},d[c]="",this.appendOverrides(d))},this)},scope:this}],listeners:{focusleave:function(d){d.destroy()}}}).showAt(a.pixel[0],a.pixel[1])},appendOverrides:function(a,b){if(this.getApiParam("overridesId")&&!b){var c=this;Ext.Ajax.request({url:this.getTromboneUrl(),
params:{tool:"resource.StoredResource",retrieveResourceId:this.getApiParam("overridesId")},scope:this}).then(function(d){var e=Ext.JSON.decode(d.responseText);e&&e.storedResource&&e.storedResource.resource?(d=Ext.decode(e.storedResource.resource),Ext.apply(d,a),c.appendOverrides(d,!0)):c.showResponseError(c.localize("overidesRetrieveError"),d)},function(d){c.showResponseError(c.localize("overidesRetrieveError"),d)})}else c=this,Ext.Ajax.request({url:this.getTromboneUrl(),params:{tool:"resource.StoredResource",
storeResource:Ext.encode(a)},scope:this}).then(function(d){var e=Ext.JSON.decode(d.responseText);e&&e.storedResource&&e.storedResource.id?(c.setApiParam("overridesId",e.storedResource.id),c.reloadFilters()):c.showResponseError(c.localize("overidesRetrieveError"),d)},function(d){c.showResponseError(c.localize("overidesStorageError"),d)})}});
Ext.define("Voyant.widget.GeonamesFilter",{extend:"Ext.Button",xtype:"geonamesfilter",mixins:["Voyant.util.Localization"],statics:{i18n:{filter:"Filter",authorLabel:"authors",titleLabel:"titles",keywordLabel:"full text",pubDateLabel:"dates",loading:"Loading geographical information\u2026",disclaimer:"This is an experimental tool and the accuracy of the data is variable (\x3ca href\x3d'{url}' target\x3d'_blank'\x3esee help\x3c/a\x3e).",noDataForField:"No data seems to be available for this field so it will be disabled.",
close:"Close"}},config:{corpus:void 0,geonames:void 0,color:"#f00",timeout:void 0,currentConnectionOccurrence:void 0,animationLayer:void 0,millisPerAnimation:2E3,stepByStepMode:!1,keepAnimationInFrame:!1},constructor:function(a){a=a||{};var b=new Voyant.data.util.Geonames({corpus:a.corpus});this.setGeonames(b);var c=this;Ext.applyIf(a,{tooltip:this.localize("filterTip"),style:"background-color: white; color: "+a.color,glyph:"xf0b0@FontAwesome",menu:{defaults:{xtype:"querysearchfield",labelWidth:60,
labelAlign:"right",width:250,maxWidth:250,padding:2,listeners:{change:function(d,e){c.loadGeonames()},load:function(d,e,f,g){0==e.length&&""==g.getParams().query&&(Ext.Msg.show({buttonText:{ok:c.localize("close")},icon:Ext.MessageBox.INFO,message:c.localize("noDataForField"),buttons:Ext.Msg.OK}),this.disable())}}},items:[{fieldLabel:this.localize("authorLabel"),tokenType:"author",itemId:"author"},{fieldLabel:this.localize("titleLabel"),itemId:"title",tokenType:"title"},{fieldLabel:this.localize("keywordLabel")},
{xtype:"multislider",fieldLabel:this.localize("pubDateLabel"),itemId:"pubDate",tokenType:"pubDate",values:[0,1],hidden:!0,listeners:{afterrender:function(d){this.getCorpus().getCorpusTerms().load({params:{tokenType:"pubDate",limit:1,sort:"TERMASC"},callback:function(e){if(0==e.length){var f=[];this.getCorpus().each(function(g){var h=parseInt(g.getTitle());0==isNaN(h)&&f.push(parseInt(g.getTitle()))},this);1<f.length&&(d.setMinValue(f[0]),d.setMaxValue(f[f.length-1]),d.tokenType="title",d.suspendEvent("changecomplete"),
d.setValue([f[0],f[f.length-1]]),d.resumeEvent("changecomplete"),d.setVisible(!0))}else d.setMinValue(parseInt(e[0].getTerm())),this.getCorpus().getCorpusTerms().load({params:{tokenType:"pubDate",limit:1,sort:"TERMDESC"},callback:function(g){d.setMaxValue(parseInt(g[0].getTerm()));d.setVisible(!0)},scope:this})},scope:this})},changecomplete:function(d,e){this.loadGeonames()},scope:this}},{xtype:"fieldset",title:"Animation",items:[{xtype:"container",layout:"hbox",defaults:{xtype:"button",text:"",ui:"default-toolbar"},
items:[{glyph:"xf048@FontAwesome",handler:function(){this.getAnimationLayer().getSource().clear();this.clearAnimation();var d=this.getCurrentConnectionOccurrence();d=this.getGeonames().getConnectionOccurrence(d?d.index-1:0);this.setCurrentConnectionOccurrence(d);this.animate()},scope:this},{glyph:"xf04c@FontAwesome",handler:function(d){"xf04b@FontAwesome"==d.getGlyph().glyphConfig?(this.clearAnimation(),d.setGlyph(new Ext.Glyph("xf04c@FontAwesome")),this.setStepByStepMode(!1),this.animate()):(d.setGlyph(new Ext.Glyph("xf04b@FontAwesome")),
this.setStepByStepMode(!0))},scope:this},{glyph:"xf051@FontAwesome",handler:function(){this.getAnimationLayer().getSource().clear();this.clearAnimation();var d=this.getCurrentConnectionOccurrence();d=this.getGeonames().getConnectionOccurrence(d?d.index+1:0);this.setCurrentConnectionOccurrence(d);this.animate()},scope:this},{xtype:"tbtext",text:"\x26nbsp;\x26nbsp;"},{glyph:"xf01e@FontAwesome",handler:function(){this.getAnimationLayer().getSource().clear();this.clearAnimation();this.setCurrentConnectionOccurrence(this.getGeonames().getConnectionOccurrence(0));
this.animate()},scope:this}]},{xtype:"checkbox",checked:!1,handler:function(d,e){c.setKeepAnimationInFrame(e)},boxLabel:"Keep animation in frame"}]},{xtype:"container",text:"\x26nbsp;"},{xtype:"button",text:"remove",scope:this,handler:function(d){this.fireEvent("removeFilterWidget",this);d.ownerCt.ownerCmp.destroy()}}]}});this.callParent([a]);this.on("afterrender",function(d){d.getTargetEl().down(".x-btn-glyph").setStyle("color",this.getColor());var e=d.up("panel");e.mask(d.localize("loading"));d.loadGeonames().then(function(f){e.unmask();
if(1==e.getFilterWidgets().getCount()){var g=f.getCitiesCount(),h=f.getTotalCitiesCount(),k=f.getConnectionsCount();f=f.getTotalConnectionsCount();message=d.localize(g==h&&k==f?"loadedAll":"loadedSome")+"\x3cbr\x3e\x3cbr\x3e"+d.localize("disclaimer");e.toastInfo({autoCloseDelay:5E3,closable:!0,maxWidth:"90%",html:(new Ext.Template(d.localize("disclaimer"))).apply({currentCitiesCount:g,totalCitiesCount:h,currentConnectionsCount:k,totalConnectionsCount:f,url:e.getBaseUrl()+"docs/#!/guide/dreamscape"})})}})},
this)},loadGeonames:function(a){var b=this;a=a||{};var c=[];this.query("querysearchfield").forEach(function(g){var h=g.getItemId();g.getValue().forEach(function(k){c.push(h+":"+k)})});var d=this.down("multislider");if(d&&d.isVisible()){var e=d.getValue();c.push(d.tokenType+":["+e[0]+"-"+e[1]+"]")}0<c.length&&!("query"in a)&&(a.query=c);(d=this.up("panel"))&&d.getApiParams&&Ext.applyIf(a,d.getApiParams("minPopulation connectionsMaxCount connectionsMinFreq source overridesId filterHasLowerCaseForm filterIsPersonName preferredCoordinates".split(" ")));
this.mask("\u2026");var f=this.getGeonames();return f.load(a).then(function(){b.unmask();b.fireEvent("filterUpdate",b,f);return f},function(){b.unmask()})},clearAnimation:function(){this.getTimeout()&&clearTimeout(this.getTimeout())},animate:function(){var a=this.up("panel");if(a){this.clearAnimation();var b=this.getCurrentConnectionOccurrence();if(b){var c=this.getAnimationLayer();c||(c=this.up("panel").getMap().getLayer(this.getId()+"-animation"),this.setAnimationLayer(c));if(c){var d=c.getSource().getFeatures();
if(0==d.length){if(!a)return;var e=a.getMap().getLayer(this.getId()+"-connections").getSource().getFeatures();d=!1;for(var f=0,g=e.length;f<g;f++)if(b.source.id==e[f].get("source")&&b.target.id==e[f].get("target")){d=e[f];break}if(d){this.getKeepAnimationInFrame()&&(g=a.getMap(),e=a.getMap().getView().calculateExtent(g.getSize()),ol.extent.containsExtent(e,d.getGeometry().getExtent())||(newExtent=ol.extent.extend(e,d.getGeometry().getExtent()),g.getView().fit(newExtent)));d=(new arc.GreatCircle({x:b.source.lng,
y:b.source.lat},{x:b.target.lng,y:b.target.lat})).Arc(100,{offset:100});var h=b.source.label+" -\x3e "+b.target.label;d.geometries.forEach(function(k){var l=new ol.geom.LineString([]);l.transform(ol.proj.get("EPSG:4326"),a.getProjection()?a.getProjection():ol.proj.get("EPSG:3857"));k=new ol.Feature({geometry:l,allcoords:k.coords,text:h,color:this.getColor(),width:5,start:(new Date).getTime()});c.getSource().addFeature(k)},this);a.body.down(".ticker");a.body.down(".ticker").setHtml(b.source.left+" \x3cspan class\x3d'keyword'\x3e"+
b.source.term+"\x3c/span\x3e "+b.source.right+" \u2026 "+b.target.left+" \x3cspan class\x3d'keyword'\x3e"+b.target.term+"\x3c/span\x3e "+b.target.right)}else{if(!this.getGeonames())return;b=this.getGeonames().getConnectionOccurrence(b.index+1);this.setCurrentConnectionOccurrence(b);c.getSource().clear()}return this.setTimeout(setTimeout(this.animate.bind(this),1))}if(0<d.length){g=d[0].getGeometry().getCoordinates();e=d[0].get("allcoords");if(g.length<e.length)return g=((new Date).getTime()-d[0].get("start"))*
e.length/this.getMillisPerAnimation(),line=new ol.geom.LineString(e.slice(0,g)),line.transform(ol.proj.get("EPSG:4326"),a.getProjection()?a.getProjection():ol.proj.get("EPSG:3857")),d[0].set("geometry",line),this.setTimeout(setTimeout(this.animate.bind(this),25));b=this.getGeonames().getConnectionOccurrence(b.index+1);if(!this.getStepByStepMode())return this.setCurrentConnectionOccurrence(b),c.getSource().clear(),this.setTimeout(setTimeout(this.animate.bind(this),1))}}}else if(this.getGeonames()&&
(b=this.getGeonames().getConnectionOccurrence(0)))return this.setCurrentConnectionOccurrence(b),this.setTimeout(setTimeout(this.animate.bind(this),1))}}});Ext.define("Voyant.panel.Knots",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.knots",statics:{i18n:{},api:{query:null,stopList:"auto",docId:void 0,audio:!1},glyph:"xf06e@FontAwesome"},config:{knots:void 0,termStore:void 0,docTermStore:void 0,tokensStore:void 0,options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"colorpaletteoption"}],refreshInterval:100,startAngle:315,angleIncrement:15,currentTerm:void 0},termTpl:new Ext.XTemplate('\x3ctpl for\x3d"."\x3e','\x3cdiv class\x3d"term" style\x3d"color: rgb({color});float: left;padding: 3px;margin: 2px;"\x3e{term}\x3c/div\x3e',
"\x3c/tpl\x3e"),constructor:function(){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(a,b){a=b.getDocument(0);var c=this.processDocument(a);this.getKnots().setCurrentDoc(c);this.setApiParams({docId:a.getId()});this.getDocTermStore().getProxy().setExtraParam("corpus",b.getId());this.getTokensStore().setCorpus(b);this.getDocTermStore().load({params:{limit:5,stopList:this.getApiParams("stopList")}})},this);this.on("activate",
function(){this.getCorpus()&&Ext.Function.defer(function(){this.getDocTermStore().load({params:{limit:5,stopList:this.getApiParams("stopList")}})},100,this)},this);this.on("query",function(a,b){void 0!==b&&""!=b&&this.getDocTermsFromQuery(b)},this);this.on("documentSelected",function(a,b){a=this.getCorpus().getDocument(b);this.setApiParam("docId",a.getId());var c=this.getKnots().currentDoc.terms;b=[];for(var d in c)b.push(d);this.setApiParams({query:b});d=b.length;0===d&&(d=5);this.getKnots().setCurrentDoc(this.processDocument(a));
this.getDocTermStore().load({params:{query:b,limit:d,stopList:this.getApiParams("stopList")}})},this);this.on("termsClicked",function(a,b){var c=[];b.forEach(function(d){Ext.isString(d)?c.push(d):d.term?c.push(d.term):d.getTerm&&c.push(d.getTerm())});0<c.length&&this.getDocTermsFromQuery(c)},this);this.on("corpusTermsClicked",function(a,b){var c=[];b.forEach(function(d){d.getTerm()&&c.push(d.getTerm())});this.getDocTermsFromQuery(c)},this);this.on("documentTermsClicked",function(a,b){var c=[];b.forEach(function(d){d.getTerm()&&
c.push(d.getTerm())});this.getDocTermsFromQuery(c)},this)},initComponent:function(){this.setTermStore(Ext.create("Ext.data.ArrayStore",{fields:["term","color"]}));this.setDocTermStore(Ext.create("Ext.data.Store",{model:"Voyant.data.model.DocumentTerm",autoLoad:!1,remoteSort:!1,proxy:{type:"ajax",url:Voyant.application.getTromboneUrl(),extraParams:{tool:"corpus.DocumentTerms",withDistributions:"raw",withPositions:!0},reader:{type:"json",rootProperty:"documentTerms.terms",totalProperty:"documentTerms.total"},
simpleSortMode:!0},listeners:{beforeload:function(a){a.getProxy().setExtraParam("docId",this.getApiParam("docId"))},load:function(a,b,c,d){var e={};b&&0<b.length?(b.forEach(function(f){var g=this.processTerms(f);f.get("docId");f=f.get("term");e[f]=g},this),this.getKnots().addTerms(e),this.getKnots().buildGraph()):this.toastInfo({html:this.localize("noTermsFound"),align:"bl"})},scope:this}}));this.setTokensStore(Ext.create("Voyant.data.store.Tokens",{stripTags:"all",listeners:{beforeload:function(a){a.getProxy().setExtraParam("docId",
this.getApiParam("docId"))},load:function(a,b,c,d){var e="",f=this.getCurrentTerm();b.forEach(function(g){e=g.getPosition()==f.tokenId?e+("\x3cstrong\x3e"+g.getTerm()+"\x3c/strong\x3e"):e+g.getTerm()});Ext.Msg.show({title:this.localize("context"),message:e,buttons:Ext.Msg.OK,icon:Ext.Msg.INFO})},scope:this}}));Ext.apply(this,{title:this.localize("title"),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{text:this.localize("clearTerms"),glyph:"xf00d@FontAwesome",
handler:function(){this.down("#termsView").getSelectionModel().deselectAll(!0);this.getTermStore().removeAll();this.setApiParams({query:null});this.getKnots().removeAllTerms();this.getKnots().drawGraph()},scope:this},{xtype:"documentselectorbutton",singleSelect:!0},{xtype:"slider",itemId:"speed",fieldLabel:this.localize("speed"),labelAlign:"right",labelWidth:50,width:100,increment:50,minValue:0,maxValue:500,value:500-this.getRefreshInterval(),listeners:{changecomplete:function(a,b){this.setRefreshInterval(500-
b);this.getKnots()&&this.getKnots().buildGraph()},scope:this}},{xtype:"slider",itemId:"startAngle",fieldLabel:this.localize("startAngle"),labelAlign:"right",labelWidth:35,width:85,increment:15,minValue:0,maxValue:360,value:this.getStartAngle(),listeners:{changecomplete:function(a,b){this.setStartAngle(b);this.getKnots()&&this.getKnots().buildGraph()},scope:this}},{xtype:"slider",itemId:"tangles",fieldLabel:this.localize("tangles"),labelAlign:"right",labelWidth:30,width:80,increment:5,minValue:5,maxValue:90,
value:this.getAngleIncrement(),listeners:{changecomplete:function(a,b){this.setAngleIncrement(b);this.getKnots()&&this.getKnots().buildGraph()},scope:this}},{xtype:"checkbox",boxLabel:this.localize("sound"),listeners:{render:function(a){a.setValue(!0===this.getApiParam("audio")||"true"==this.getApiParam("audio"));Ext.tip.QuickTipManager.register({target:a.getEl(),text:this.localize("soundTip")})},beforedestroy:function(a){Ext.tip.QuickTipManager.unregister(a.getEl())},change:function(a,b){this.getKnots()&&
this.getKnots().setAudio(b)},scope:this}}]}],border:!1,layout:"fit",items:{layout:{type:"vbox",align:"stretch"},defaults:{border:!1},items:[{height:30,itemId:"termsView",xtype:"dataview",store:this.getTermStore(),tpl:this.termTpl,itemSelector:"div.term",overItemCls:"over",selectedItemCls:"selected",selectionModel:{mode:"SIMPLE"},focusCls:"",listeners:{beforeitemclick:function(a,b,c,d,e,f){e.preventDefault();e.stopPropagation();a.fireEvent("itemcontextmenu",a,b,c,d,e,f);return!1},beforecontainerclick:function(){event.preventDefault();
event.stopPropagation();return!1},selectionchange:function(a,b){var c=this.down("#termsView"),d=[];c.getStore().each(function(e){-1!==b.indexOf(e)?(d.push(e.get("term")),Ext.fly(c.getNodeByRecord(e)).removeCls("unselected").addCls("selected")):Ext.fly(c.getNodeByRecord(e)).removeCls("selected").addCls("unselected")});this.getKnots().termsFilter=d;this.getKnots().drawGraph()},itemcontextmenu:function(a,b,c,d,e){e.preventDefault();e.stopPropagation();var f=a.isSelected(c);(new Ext.menu.Menu({floating:!0,
items:[{text:f?this.localize("hideTerm"):this.localize("showTerm"),handler:function(){f?a.deselect(d):a.select(d,!0)},scope:this},{text:this.localize("removeTerm"),handler:function(){a.deselect(d);var g=this.getTermStore().getAt(d).get("term");this.getTermStore().removeAt(d);a.refresh();this.getKnots().removeTerm(g);this.getKnots().drawGraph()},scope:this}]})).showAt(e.getXY())},scope:this}},{flex:1,xtype:"container",autoEl:"div",itemId:"canvasParent",layout:"fit",overflowY:"auto",overflowX:"hidden"}],
listeners:{render:function(a){a=this.down("#canvasParent");this.setKnots(new Knots({container:a,clickHandler:this.knotClickHandler.bind(this),audio:!0===this.getApiParam("audio")||"true"==this.getApiParam("audio")}))},afterlayout:function(a){!1===this.getKnots().initialized&&this.getKnots().initializeCanvas()},resize:function(a,b,c){this.getKnots().doLayout()},scope:this}}});this.callParent(arguments)},updateRefreshInterval:function(a){this.getKnots()&&(50>a?(a=50,this.getKnots().progressiveDraw=
!1):this.getKnots().progressiveDraw=!0,this.getKnots().refreshInterval=a,this.getKnots().buildGraph(this.getKnots().drawStep))},updateStartAngle:function(a){this.getKnots()&&(this.getKnots().startAngle=a,this.getKnots().recache(),this.getKnots().buildGraph())},updateAngleIncrement:function(a){this.getKnots()&&(this.getKnots().angleIncrement=a,this.getKnots().recache(),this.getKnots().buildGraph())},loadFromCorpusTerms:function(a){this.getKnots()&&(this.getKnots().removeAllTerms(),this.getTermStore().removeAll(!0));
a.load({callback:function(b,c,d){var e=[];"string"==typeof e&&(e=[e]);b.forEach(function(f,g){e.push(f.get("term"))},this);this.getDocTermsFromQuery(e)},scope:this,params:{limit:5,stopList:this.getApiParams("stopList")}})},getDocTermsFromQuery:function(a){a&&this.setApiParam("query",a);this.getCorpus()&&this.isVisible()&&(this.setApiParams({query:a}),this.getDocTermStore().load({params:this.getApiParams()}))},reloadTermsData:function(){var a=[],b;for(b in this.bubblelines.currentTerms)a.push(b);this.getDocTermsFromQuery(a)},
filterDocuments:function(){var a=this.getApiParam("docId");""==a&&(a=[],this.getCorpus().getDocuments().each(function(d,e){a.push(d.getId())}),this.setApiParams({docId:a}));"string"==typeof a&&(a=[a]);if(null==a){this.selectedDocs=this.getCorpus().getDocuments().clone();var b=this.selectedDocs.getCount();if(10<b)for(var c=10;c<b;c++)this.selectedDocs.removeAt(10);a=[];this.selectedDocs.eachKey(function(d,e){a.push(d)},this);this.setApiParams({docId:a})}else this.selectedDocs=this.getCorpus().getDocuments().filterBy(function(d,
e){return-1!=a.indexOf(e)},this)},processDocument:function(a){var b=a.getShortTitle();b=b.replace("\x26hellip;","...");return{id:a.getId(),index:a.get("index"),title:b,totalTokens:a.get("tokensCount-lexical"),terms:{},lineLength:void 0}},processTerms:function(a){var b=a.get("term");var c=a.get("rawFreq"),d=a.get("positions");if(0<c){var e=this.getApplication().getColorForTerm(b);if(-1===this.getTermStore().find("term",b)){this.getTermStore().loadData([[b,e]],!0);var f=this.getTermStore().find("term",
b);this.down("#termsView").select(f,!0)}a=a.get("distributions");b={term:b,positions:d,distributions:a,rawFreq:c,color:e}}else b=!1;return b},knotClickHandler:function(a){this.setCurrentTerm(a);var b=a.tokenId-10;0>b&&(b=0);this.getTokensStore().load({start:b,limit:21});a=[a].map(function(c){return c.term});this.getApplication().dispatchEvent("termsClicked",this,a)}});Ext.define("Voyant.panel.Phrases",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.phrases",isConsumptive:!0,statics:{i18n:{},api:{stopList:"auto",query:void 0,docId:void 0,docIndex:void 0,minLength:2,maxLength:50,overlapFilter:"length",columns:void 0,sort:"length",dir:"desc"},glyph:"xf0ce@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}]},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,
arguments);this.on("loadedCorpus",function(b,c){this.isVisible()&&(0==this.hasCorpusAccess(c)?this.mask(this.localize("limitedAccess"),"mask-no-spinner"):this.loadFromApis())});a.embedded||a.corpus&&this.fireEvent("loadedCorpus",this,a.corpus);this.on("corpusTermsClicked",function(b,c){if(this.getStore().getCorpus()){var d=[];c.forEach(function(e){d.push(e.get("term"))});this.setApiParams({query:d,docId:void 0,docIndex:void 0});this.isVisible()&&this.getStore().load({params:this.getApiParams()})}});
this.on("activate",function(){this.getStore().getCorpus()&&this.loadFromApis()},this);this.on("query",function(b,c){this.setApiParam("query",c);this.getStore().getProxy().setExtraParam("query",c);this.loadFromApis()},this)},loadFromApis:function(){this.getStore().getCorpus()&&this.getStore().load({params:this.getApiParams()})},initComponent:function(){var a=this,b=Ext.create("Voyant.data.store.CorpusNgramsBuffered",{parentPanel:a,leadingBufferZone:100});b.on("beforeload",function(c){return a.hasCorpusAccess(c.getCorpus())});
a.on("sortchange",function(c,d,e,f){this.setApiParam("sort",d.dataIndex);this.setApiParam("dir",e);c=this.getApiParams("stopList query docId docIndex sort dir minLength maxLength overlapFilter".split(" "));d=this.getStore().getProxy();for(var g in c)d.setExtraParam(g,c[g])},a);Ext.apply(a,{title:this.localize("title"),emptyText:this.localize("emptyText"),store:b,selModel:Ext.create("Ext.selection.CheckboxModel",{listeners:{selectionchange:{fn:function(c,d){if(0<d.length){var e=[];d.forEach(function(f){e.push('"'+
f.getTerm()+'"')});this.getApplication().dispatchEvent("termsClicked",this,e)}},scope:this}}}),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"},"-",{text:a.localize("length"),tooltip:"test",xtype:"label"},{xtype:"slider",minValue:2,values:[2,30],maxValue:30,increment:1,width:75,tooltip:this.localize("lengthTip"),listeners:{render:{fn:function(c){var d=c.getValues();c.setValue(0,parseInt(this.getApiParam("minLength",
d[0])));c.setValue(1,parseInt(this.getApiParam("maxLength",d[1])))},scope:a},changecomplete:{fn:function(c,d){c=c.getValues();this.setApiParam("minLength",parseInt(c[0]));this.setApiParam("maxLength",parseInt(c[1]));this.getStore().load({params:this.getApiParams()})},scope:a}}},{xtype:"corpusdocumentselector"},"-",{xtype:"button",text:this.localize("overlap"),tooltip:this.localize("overlapTip"),menu:{items:[{xtype:"menucheckitem",text:this.localize("overlapNone"),group:"overlap",inputValue:"none",
checkHandler:function(){this.setApiParam("overlapFilter","none");this.getStore().load({params:this.getApiParams()})},scope:this},{xtype:"menucheckitem",text:this.localize("overlapLength"),group:"overlap",inputValue:"length",checkHandler:function(){this.setApiParam("overlapFilter","length");this.getStore().load({params:this.getApiParams()})},scope:this},{xtype:"menucheckitem",text:this.localize("overlapFreq"),group:"overlap",inputValue:"rawFreq",checkHandler:function(){this.setApiParam("overlapFilter",
"rawFreq");this.getStore().load({params:this.getApiParams()})},scope:this}],listeners:{afterrender:{fn:function(c){var d=this.getApiParam("overlapFilter");c.items.each(function(e){e.group&&e.setChecked(e.inputValue==d)},this)},scope:this}}}}]}],columns:[{text:this.localize("term"),dataIndex:"term",tooltip:this.localize("termTip"),sortable:!0,flex:1},{text:this.localize("rawFreq"),dataIndex:"rawFreq",tooltip:this.localize("termRawFreqTip"),sortable:!0,width:"autoSize"},{text:this.localize("length"),
dataIndex:"length",tooltip:this.localize("lengthTip"),sortable:!0,width:"autoSize"},{xtype:"widgetcolumn",text:this.localize("trend"),tooltip:this.localize("trendTip"),width:120,dataIndex:"distributions",widget:{xtype:"sparklineline"}}],listeners:{corpusSelected:function(){this.setApiParams({docIndex:void 0,docId:void 0});this.loadFromApis()},documentsSelected:function(c,d){var e=[],f=this.getStore().getCorpus();d.forEach(function(g){e.push(f.getDocument(g).getId())},this);this.setApiParams({docId:e,
docIndex:void 0});this.loadFromApis()},termsClicked:{fn:function(c,d){if(this.getStore().getCorpus()){var e=[];d.forEach(function(f){Ext.isString(f)?e.push(f):f.term?e.push(f.term):f.getTerm&&e.push(f.getTerm())});0<e.length&&(this.setApiParams({docIndex:void 0,docId:void 0,query:e}),this.isVisible()&&this.isVisible()&&this.getStore().clearAndLoad({params:this.getApiParams()}))}},scope:this}}});a.callParent(arguments);a.getStore().getProxy().setExtraParam("withDistributions",!0)}});Ext.define("Voyant.panel.CorpusTerms",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.corpusterms",statics:{i18n:{},api:{stopList:"auto",query:void 0,maxBins:100,termColors:"categories",comparisonCorpus:void 0,columns:void 0,sort:void 0,dir:void 0},glyph:"xf0ce@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"termcolorsoption"},{xtype:"corpusselector",name:"comparisonCorpus",fieldLabel:"comparison corpus"}]},constructor:function(a){this.mixins["Voyant.util.Api"].constructor.apply(this,
arguments);this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){var a=this,b=Ext.create("Voyant.data.store.CorpusTermsBuffered",{parentPanel:this,proxy:{extraParams:{withDistributions:"relative",forTool:"corpusterms"}}});Ext.apply(a,{title:this.localize("title"),emptyText:this.localize("emptyText"),store:b,selModel:Ext.create("Ext.selection.CheckboxModel",{pruneRemoved:!1,listeners:{selectionchange:{fn:function(c,d){d&&0<d.length&&
this.getApplication().dispatchEvent("corpusTermsClicked",this,d)},scope:this}},mode:"SIMPLE"}),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"}]}],plugins:[{ptype:"rowexpander",rowBodyTpl:new Ext.XTemplate("")}],viewConfig:{listeners:{expandbody:function(c,d,e,f){(""===e.textContent||f&&f.force)&&Ext.create("Voyant.widget.CorpusTermSummary",{record:d,header:!1,renderTo:e.querySelector("div")})},scope:this}},columns:[{xtype:"rownumberer",
width:"autoSize",sortable:!1},{text:this.localize("term"),tooltip:this.localize("termTip"),dataIndex:"term",flex:1,sortable:!0,xtype:"coloredtermfield",useCategoriesMenu:!0},{text:this.localize("rawFreq"),tooltip:this.localize("rawFreqTip"),dataIndex:"rawFreq",width:"autoSize",sortable:!0},{text:this.localize("relativeFreq"),tooltip:this.localize("relativeFreqTip"),dataIndex:"relativeFreq",renderer:function(c){return Ext.util.Format.number(1E6*c,"0,000")},width:"autoSize",hidden:!0,sortable:!0},{text:this.localize("relativePeakedness"),
tooltip:this.localize("relativePeakednessTip"),dataIndex:"relativePeakedness",renderer:Ext.util.Format.numberRenderer("0,000.0"),width:"autoSize",hidden:!0,sortable:!0},{text:this.localize("relativeSkewness"),tooltip:this.localize("relativeSkewnessTip"),dataIndex:"relativeSkewness",renderer:Ext.util.Format.numberRenderer("0,000.0"),width:"autoSize",hidden:!0,sortable:!0},{text:this.localize("corpusComparisonDifference"),tooltip:this.localize("corpusComparisonDifferenceTip"),dataIndex:"comparisonRelativeFreqDifference",
renderer:Ext.util.Format.numberRenderer("0,000.00000"),width:"autoSize",hidden:!this.getApiParam("comparisonCorpus"),sortable:!0,listeners:{show:function(c,d,e){a.getApiParam("comparisonCorpus")||a.showError(a.localize("noCorpusComparison"))}}},{xtype:"widgetcolumn",text:this.localize("trend"),tooltip:this.localize("trendTip"),flex:1,dataIndex:"distributions",widget:{xtype:"sparklineline",tipTpl:new Ext.XTemplate("{[this.getDocumentTitle(values.x,values.y)]}",{getDocumentTitle:function(c,d){return this.panel.store.getCorpus().getDocument(c).getTitle()+
"\x3cbr\x3e"+this.panel.localize("relativeFreqLabel")+" "+Ext.util.Format.number(1E6*d,"0,000")},panel:a})}}]});a.on("loadedCorpus",function(c,d){100<d.getDocumentsCount()&&this.getStore().getProxy().setExtraParam("bins",this.getApiParam("maxBins"));this.isVisible()&&this.getStore().load()},a);a.on("activate",function(){a.getStore().getCorpus()&&a.getStore().load({params:this.getApiParams()})},a);a.on("query",function(c,d){this.setApiParam("query",d);this.getStore().removeAll();this.getStore().load()},
a);a.callParent(arguments)}});Ext.define("Voyant.panel.DocumentTerms",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel"],requires:["Voyant.data.store.DocumentTerms"],alias:"widget.documentterms",config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"},{xtype:"termcolorsoption"}]},statics:{i18n:{},api:{stopList:"auto",query:void 0,docId:void 0,docIndex:void 0,bins:10,columns:void 0,sort:void 0,dir:void 0,termColors:"categories"},glyph:"xf0ce@FontAwesome"},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,
arguments);this.on("loadedCorpus",function(c,d){c=this.getStore();c.setCorpus(d);this.isVisible()&&c.load()});if(a.embedded){window.console&&console.warn(a.embedded.then);var b=Ext.getClass(a.embedded).getName();"Voyant.data.store.DocumentTerms"!=b&&"Voyant.data.model.Document"!=b||this.fireEvent("loadedCorpus",this,a.embedded.getCorpus())}else a.corpus&&this.fireEvent("loadedCorpus",this,a.corpus);this.on("query",function(c,d){this.fireEvent("corpusTermsClicked",c,d)},this);this.on("corpusTermsClicked",
function(c,d){if(this.getStore().getCorpus()){var e=[];d.forEach(function(f){e.push(Ext.isString(f)?f:f.get("term"))});this.setApiParams({query:e,docId:void 0,docIndex:void 0});this.isVisible()&&this.getStore().load({params:this.getApiParams()})}});this.on("documentsClicked",function(c,d){var e=[];d.forEach(function(f){e.push(f.get("id"))});this.setApiParams({docId:e,query:void 0});this.isVisible()&&this.getStore().load({params:this.getApiParams()})});this.on("documentsSelected",function(c,d){this.setApiParams({docId:d,
query:void 0});this.isVisible()&&this.getStore().load({params:this.getApiParams()})});this.on("corpusSelected",function(c,d){this.setApiParams({docId:void 0,docIndex:void 0});this.isVisible()&&this.getStore().load({params:this.getApiParams()})});this.on("activate",function(){this.getStore().getCorpus()&&this.getStore().load({params:this.getApiParams()})},this)},initComponent:function(){var a=Ext.create("Voyant.data.store.DocumentTermsBuffered",{parentPanel:this});Ext.apply(this,{title:this.localize("title"),
emptyText:this.localize("emptyText"),store:a,selModel:Ext.create("Ext.selection.CheckboxModel",{listeners:{selectionchange:{fn:function(b,c){this.getApplication().dispatchEvent("documentTermsClicked",this,c)},scope:this}},pruneRemoved:!1,mode:"SIMPLE"}),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"},{xtype:"corpusdocumentselector"}]}],columns:[{text:"#",width:30,dataIndex:"docIndex",sortable:!0,renderer:function(b){return b+
1}},{text:this.localize("term"),dataIndex:"term",tooltip:this.localize("termTip"),sortable:!0,flex:1,xtype:"coloredtermfield",useCategoriesMenu:!0},{text:this.localize("rawFreq"),dataIndex:"rawFreq",tooltip:this.localize("rawFreqTip"),width:"autoSize",sortable:!0},{text:this.localize("relativeFreq"),tooltip:this.localize("relativeFreqTip"),dataIndex:"relativeFreq",width:"autoSize",sortable:!0,renderer:Ext.util.Format.numberRenderer("0,000")},{text:this.localize("tfidf"),tooltip:this.localize("tfidfTip"),
dataIndex:"tfidf",width:"autoSize",sortable:!0,hidden:!0,renderer:Ext.util.Format.numberRenderer("0,000.000")},{text:this.localize("zscore"),tooltip:this.localize("zscoreTip"),dataIndex:"zscore",width:"autoSize",sortable:!0,hidden:!0,renderer:Ext.util.Format.numberRenderer("0,000.000")},{xtype:"widgetcolumn",text:this.localize("trend"),tooltip:this.localize("trendTip"),flex:1,dataIndex:"distributions",widget:{xtype:"sparklineline"}}],listeners:{termsClicked:{fn:function(b,c){if(this.getStore().getCorpus()){var d=
[];c.forEach(function(e){Ext.isString(e)?d.push(e):e.term?d.push(e.term):e.getTerm&&d.push(e.getTerm())});0<d.length&&(this.setApiParams({docIndex:void 0,docId:void 0,query:d}),this.isVisible()&&this.isVisible()&&this.getStore().load({params:this.getApiParams()}))}},scope:this}}});this.callParent(arguments);this.getStore().getProxy().setExtraParam("withDistributions",!0)}});Ext.define("Voyant.panel.Documents",{extend:"Ext.grid.Panel",mixins:["Voyant.panel.Panel","Voyant.util.Downloadable"],alias:"widget.documents",isConsumptive:!0,statics:{i18n:{newCorpusError:"There was an error creating the new the corpus. You may not have permission to do this."},api:{query:void 0,docIndex:void 0,docId:void 0,columns:void 0,sort:void 0,dir:void 0},glyph:"xf0ce@FontAwesome"},MODE_EDITING:"editing",MODE_NORMAL:"normal",config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}],
mode:this.MODE_NORMAL},constructor:function(a){var b=Ext.create("Voyant.data.store.Documents",{selModel:{pruneRemoved:!1},proxy:{extraParams:{forTool:"documents"}}}),c=[{xtype:"querysearchfield"},{xtype:"totalpropertystatus"}],d=this;a&&a.mode==this.MODE_EDITING||c.push({text:this.localize("modify"),tooltip:this.localize("modifyTip"),glyph:"xf044@FontAwesome",scope:this,itemId:"modifyButton",handler:function(e){Ext.create("Ext.window.Window",{title:this.localize("title"),modal:!0,width:"80%",minWidth:300,
minHeight:200,height:"80%",layout:"fit",frame:!0,border:!0,items:{xtype:"documents",mode:this.MODE_EDITING,corpus:this.getStore().getCorpus(),header:!1,viewConfig:{plugins:{ptype:"gridviewdragdrop"},listeners:{beforedrop:function(f,g,h,k,l){return this.getStore().getCount()<this.getStore().getCorpus().getDocumentsCount()?(f=this.up("panel"),Ext.Msg.show({title:f.localize("error"),message:f.localize("reorderFilteredError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR}),!1):!0}}}},buttons:[{text:this.localize("add"),
tooltip:this.localize("addTip"),glyph:"xf067@FontAwesome",handler:function(f){f.up("window").close();Ext.create("Ext.window.Window",{header:!1,modal:!0,layout:"fit",items:{xtype:"corpuscreator",corpus:this.getStore().getCorpus()}}).show()},scope:this},{text:this.localize("remove"),tooltip:this.localize("removeTip"),glyph:"xf05e@FontAwesome",hidden:1==this.getStore().getCorpus().getDocumentsCount(),handler:this.keepRemoveReorderHandler,itemId:"remove",scope:this},{text:this.localize("keep"),tooltip:this.localize("keepTip"),
glyph:"xf00c@FontAwesome",hidden:1==this.getStore().getCorpus().getDocumentsCount(),handler:this.keepRemoveReorderHandler,itemId:"keep",scope:this},{text:this.localize("reorder"),tooltip:this.localize("reorderTip"),glyph:"xf0dc@FontAwesome",hidden:1==this.getStore().getCorpus().getDocumentsCount(),handler:this.keepRemoveReorderHandler,itemId:"reorder",scope:this},{text:"Cancel",glyph:"xf00d@FontAwesome",handler:function(f){f.up("window").close()}}]}).show()}},{text:this.localize("downloadButton"),
glyph:"xf019@FontAwesome",itemId:"downloadButton",handler:function(){d.downloadFromCorpusId(d.getStore().getCorpus().getId())}});Ext.apply(this,{title:this.localize("title"),emptyText:this.localize("emptyText"),columns:[{xtype:"rownumberer",renderer:function(e,f,g){return g.getIndex()+1},sortable:!1},{text:this.localize("documentTitle"),dataIndex:"title",sortable:!0,renderer:function(e,f,g){return g.getTitle()},flex:3},{text:this.localize("documentAuthor"),dataIndex:"author",sortable:!0,hidden:!0,
renderer:function(e,f,g){return g.getAuthor()},flex:2},{text:this.localize("documentPubDate"),dataIndex:"pubDate",sortable:!0,hidden:!0,renderer:function(e,f,g){return g.getPubDate()},flex:2},{text:this.localize("documentPublisher"),dataIndex:"publisher",sortable:!1,hidden:!0,renderer:function(e,f,g){return g.getPublisher()},flex:2},{text:this.localize("documentPubPlace"),dataIndex:"pubPlace",sortable:!1,hidden:!0,renderer:function(e,f,g){return g.getPubPlace()},flex:2},{text:this.localize("documentKeyword"),
dataIndex:"keyword",sortable:!1,hidden:!0,renderer:function(e,f,g){return g.getKeyword()},flex:2},{text:this.localize("documentCollection"),dataIndex:"collection",sortable:!1,hidden:!0,renderer:function(e,f,g){return g.getCollection()},flex:2},{text:this.localize("tokensCountLexical"),dataIndex:"tokensCount-lexical",renderer:Ext.util.Format.numberRenderer("0,000"),sortable:!0,width:"autoSize"},{text:this.localize("typesCountLexical"),dataIndex:"typesCount-lexical",renderer:Ext.util.Format.numberRenderer("0,000"),
width:"autoSize"},{text:this.localize("typeTokenRatioLexical"),dataIndex:"typeTokenRatio-lexical",renderer:function(e){return Ext.util.Format.percent(e)},width:"autoSize"},{text:this.localize("averageWordsPerSentence"),dataIndex:"averageWordsPerSentence",renderer:Ext.util.Format.numberRenderer("0,000.0"),tooltip:this.localize("averageWordsPerSentenceTip"),width:"autoSize"},{text:this.localize("language"),dataIndex:"language",hidden:!0,renderer:function(e,f,g,h,k,l,m){return m.ownerCt.getLanguage(e)},
width:"autoSize"}],store:b,selModel:{type:"rowmodel",mode:"MULTI",listeners:{selectionchange:{fn:function(e,f){this.getApplication().dispatchEvent("documentsClicked",this,f,this.getStore().getCorpus())},scope:this}}},dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:c}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(e,f){this.store.setCorpus(f);if(this.isVisible())this.store.load({params:this.getApiParams()});
else this.on("afterrender",function(){this.store.load({params:this.getApiParams()})},this);e=this.getApplication();if(!1===this.hasCorpusAccess(f)||e.getAllowDownload&&"false"===e.getAllowDownload())this.queryById("modifyButton").hide(),this.queryById("downloadButton").hide()});this.on("activate",function(){this.getStore().getCorpus()&&this.getStore().load({params:this.getApiParams()})},this);this.on("query",function(e,f){this.setApiParam("query",f);this.store.load({params:this.getApiParams()})});
a.embedded&&("Voyant.data.model.Corpus"==Ext.getClass(a.embedded).getName()?a.corpus=a.embedded:"Voyant.data.store.Documents"==Ext.getClass(a.embedded).getName()&&(this.store.setRecords(a.embedded.getData()),a.corpus=a.embedded.getCorpus()));a.corpus&&this.fireEvent("loadedCorpus",this,a.corpus)},keepRemoveReorderHandler:function(a){var b=a.up("window").down("documents"),c=b.getSelection(),d=b.getStore().getCorpus().getDocumentsCount(),e=a.getItemId();if("reorder"==e){if(b.getStore().getCount()<d)return Ext.Msg.show({title:this.localize("error"),
message:this.localize("reorderFilteredError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR});docIndex=[];b.getStore().each(function(f){docIndex.push(f.getIndex())},this);for(a=1;a<docIndex.length;a++)if(docIndex[a-1]>docIndex[a])return Ext.Msg.confirm(b.localize("newCorpus"),(new Ext.Template(b.localize(e+"Documents"))).applyTemplate([c.length]),function(f){"yes"===f&&(docIndex=[],this.getStore().each(function(g){docIndex.push(g.getIndex())},this),f={docIndex:docIndex},f[e+"Documents"]=!0,this.editCorpus(f))},
b);return Ext.Msg.show({title:this.localize("error"),message:this.localize("reorderOriginalError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR})}return 0<c.length?c.length==d?1==d?Ext.Msg.show({title:this.localize("error"),message:this.localize("onlyOneError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR}):Ext.Msg.show({title:this.localize("error"),message:this.localize("allSelectedError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR}):Ext.Msg.confirm(this.localize("newCorpus"),(new Ext.Template(this.localize(e+"SelectedDocuments"))).applyTemplate([c.length]),
function(f){"yes"===f&&(docIndex=[],c.forEach(function(g){docIndex.push(g.getIndex())}),f={docIndex:docIndex},f[e+"Documents"]=!0,this.editCorpus(f))},b):b.getApiParam("query")&&b.getStore().getCount()<d?Ext.Msg.confirm(this.localize("newCorpus"),(new Ext.Template(this.localize(e+"FilteredDocuments"))).applyTemplate([c.length]),function(f){"yes"===f&&(docIndex=[],this.getStore().each(function(g){docIndex.push(g.getIndex())},this),f={docIndex:docIndex},f[e+"Documents"]=!0,this.editCorpus(f))},b):Ext.Msg.show({title:this.localize("error"),
message:this.localize("selectOrFilterError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR})},editCorpus:function(a){Ext.apply(a,{tool:"corpus.CorpusManager",corpus:this.getStore().getCorpus().getId()});var b=this.getApplication(),c=b.getViewport();c.mask(this.localize("Creating new corpus\u2026"));Ext.Ajax.request({url:this.getApplication().getTromboneUrl(),method:"POST",params:a,success:function(d){c.unmask();d=Ext.decode(d.responseText);b.openUrl(b.getBaseUrl()+"?corpus\x3d"+d.corpus.id)},failure:function(d){c.unmask();
Ext.Msg.show({title:this.localize("error"),message:this.localize("newCorpusError"),buttons:Ext.Msg.OK,icon:Ext.Msg.ERROR})},scope:this});(a=this.up("window"))&&a.isFloating()&&a.close()}});Ext.define("Voyant.panel.DocumentsFinder",{extend:"Ext.grid.Panel",require:["Voyant.data.store.DocumentQueryMatches","Ext.grid.plugin.CellEditing"],mixins:["Voyant.panel.Panel"],alias:"widget.documentsfinder",statics:{i18n:{}},config:{exportGridAll:!1},constructor:function(a){this.cellEditing=Ext.create("Ext.grid.plugin.CellEditing",{clicksToEdit:1});this.cellEditing.on("edit",this.onEditComplete,this);var b=this;Ext.apply(this,{title:this.localize("title"),emptyText:this.localize("emptyText"),plugins:[this.cellEditing],
bbar:[{text:this.localize("addRow"),glyph:"xf055@FontAwesome",handler:this.addRow,scope:this},{text:this.localize("exportNewCorpus"),disabled:!0,glyph:"xf08e@FontAwesome",tooltip:this.localize("exportNewCorpusTip"),handler:function(){var c=this.getQueryFromStore();c?(this.setLoading(!0),this.getCorpus().getDocumentQueryMatches().load({params:{query:c,createNewCorpus:!0},callback:function(d,e,f){this.setLoading(!1);f?(d=e.getProxy().getReader().rawData.documentsFinder.corpus,d=this.getBaseUrl()+"?corpus\x3d"+
d,Ext.Msg.alert({title:this.localize("title"),message:"\x3ca href\x3d'"+d+"' target\x3d'_blank'\x3eNew Corpus\x3c/a\x3e"})):Ext.create("Voyant.util.ResponseError",{msg:this.localize("unsuccessfulQuery"),response:e.getError().response}).show()},scope:this})):Ext.Msg.alert({title:this.localize("title"),message:this.localize("noMatches")})},scope:this,cls:"exportBtn"},{xtype:"tbtext",name:"status",cls:"status"}],columns:[{text:this.localize("query"),dataIndex:"query",renderer:function(c){return Ext.isEmpty(c)?
'\x3cspan class\x3d"placeholder"\x3e'+b.localize("emptyQuery")+"\x3c/span\x3e":c},editor:!0,minWidth:150,maxWidth:300},{text:this.localize("field"),dataIndex:"field",editor:{xtype:"combo",typeAhead:!0,triggerAction:"all",forceSelection:!0,value:"",valueField:"value",listeners:{change:function(){Ext.isEmpty(this.getValue())&&this.reset()}},store:new Ext.data.Store({fields:["text","value"],data:[[this.localize("textField"),"text"],[this.localize("advancedField"),"advanced"]]})},width:150,renderer:function(c){return Ext.isEmpty(c)?
"":b.localize(c+"Field")}},{text:this.localize("operator"),dataIndex:"operator",editor:{xtype:"combo",forceSelection:!0,store:new Ext.data.Store({autoDestroy:!0,fields:["text","value"],displayField:"text",valueField:"value",data:[{text:"AND",value:"+"},{text:"OR",value:""}]})},minWidth:75,maxWidth:75},{text:this.localize("count"),dataIndex:"count",renderer:function(c,d,e){return Ext.isEmpty(e.get("query"))?"":Ext.util.Format.number(c,"0,000")},minWidth:100,maxWidth:100},{xtype:"actioncolumn",width:25,
getGlyph:"xf014@FontAwesome",tooltip:this.localize("deleteQueryTip"),menuDisabled:!0,sortable:!1,handler:this.removeRow,scope:this}],store:new Ext.data.Store({autoDestroy:!0,fields:["id","operator","field","query","count"],data:[["","","","",0]]})});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(c,d){if((c=d.getDocuments())&&0<c.getCount()){var e=c.getDocument(0),f=[];["title","author","pubDate","publisher","pubPlace"].forEach(function(g){Ext.isEmpty(e.get(g))||
f.push([this.localize(g+"Field"),g])},this);f&&(c=this.getColumnManager().getHeaderByDataIndex("field").getEditor(),c.getStore().each(function(g){f.push([g.get("text"),g.get("value")])},this),c.setStore(Ext.create("Ext.data.Store",{fields:["text","value"],data:f})));this.updateStatus(0);this.setLoading(!1)}})},removeRow:function(a,b){this.getStore().removeAt(b);0==this.getStore().getCount()&&this.addRow();this.updateAggregate()},addRow:function(){this.store.loadData([["","","","",0]],!0)},onEditComplete:function(a,
b){a=this.getQueryFromRecord(b.record);if(Ext.isEmpty(a))b.record.set("count",""),this.updateAggregate();else{var c=b.view.getCell(b.record,this.getColumnManager().getHeaderByDataIndex("count"));c.mask("loading");this.getCorpus().getDocumentQueryMatches().load({params:{query:a},callback:function(d,e,f){c.unmask();f?b.record.set("count",0==d.length?0:d[0].get("count")):(Ext.create("Voyant.util.ResponseError",{msg:this.localize("unsuccessfulQuery"),response:e.getError().response}).show(),b.record.set("count",
0));this.updateAggregate()},scope:this})}},getQueryFromRecord:function(a){if(Ext.isEmpty(a)||Ext.isEmpty(a.get("query")))return"";var b=a.get("query").trim();if(Ext.isEmpty(b))return"";a=a.get("field");return Ext.isEmpty(a?a.trim():a)?b:a+":"+b},getQueryFromStore:function(){var a="";this.getStore().each(function(b){var c=this.getQueryFromRecord(b);Ext.isEmpty(c)||(Ext.isEmpty(a)||(b=b.get("operator"),a+="AND"==b?" + ":" | "),a+=c)},this);console.warn(a);return a},updateAggregate:function(){var a=
this.getStore().sum("count");a&&"string"!=typeof a?1==a?(a=this.getStore().getAt(0).get("count"),this.updateStatus(this.getStore().getAt(0).get("count"))):(a=this.getQueryFromStore(),Ext.isEmpty(a)||(this.status||(this.status=this.down("[cls~\x3dstatus]")),this.status.mask(this.localize("loading")),this.getCorpus().getDocumentQueryMatches().load({params:{query:a},callback:function(b,c,d){this.status.unmask();d?this.updateStatus(b[0].get("count")):(Ext.create("Voyant.util.ResponseError",{msg:this.localize("unsuccessfulQuery"),
response:c.getError().response}).show(),this.updateStatus(0))},scope:this}))):this.updateStatus(0)},updateStatus:function(a){this.status||(this.status=this.down("[cls~\x3dstatus]"));this.exportBtn||(this.exportBtn=this.down("[cls~\x3dexportBtn]"));0==a?this.status.update((new Ext.XTemplate(this.localize("noMatches"))).apply([this.getCorpus().getDocumentsCount()])):this.status.update((new Ext.XTemplate(this.localize("queryMatches"))).apply([a,this.getCorpus().getDocumentsCount()]));this.exportBtn.setDisabled(0==
a)}});Ext.define("Voyant.panel.Embedder",{extend:"Ext.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.embedder",statics:{i18n:{title:"Embedder",url:"URL",go:"Go",help:"Embedder provides a way to embed a web page into your Voyant Tools experience.",helpTip:"Embedder provides a way to embed a web page into your Voyant Tools experience."},api:{url:void 0},glyph:"xf0c1@FontAwesome"},constructor:function(a){this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);this.setApiParam("url",a.url);this.callParent(arguments);
this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){Ext.apply(this,{title:this.localize("title"),layout:{type:"fit"},items:{xtype:"uxiframe",src:this.getApiParam("url")},tbar:[{xtype:"textfield",value:this.getApiParam("url"),emptyText:this.localize("url"),listeners:{specialkey:function(a,b){b.getKey()==b.ENTER&&a.up("panel").down("uxiframe").load(a.getValue())}}},{xtype:"button",text:this.localize("go"),handler:function(a){var b=a.prev("textfield").getValue();
a.up("panel").down("uxiframe").load(b)}}]});this.callParent()},loadUrl:function(a){this.down("uxiframe").load(a)}});Ext.define("Voyant.panel.Fountain",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.fountain",statics:{i18n:{title:"FountainMeter"},api:{stopList:"auto",docIndex:0,speed:30,groups:void 0},glyph:"xf06e@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}],audio:!1,words:[],groups:{},moveWordsTimeout:void 0},constructor:function(){this.mixins["Voyant.util.Localization"].constructor.apply(this,arguments);Ext.apply(this,{title:this.localize("title"),
layout:{type:"hbox",align:"stretch"},items:[{html:"\x3csvg\x3e\x3c/svg\x3e",itemId:"fountain",flex:2},{flex:1,layout:"vbox",items:[{xtype:"polar",itemId:"gauge",width:300,flex:1,store:{fields:["mph","fuel","temp","rpm"],data:[{val:10}]},series:{type:"gauge",colors:this.getApplication().getColorPalette(this.getApplication().getApiParam("palette"),!0),angleField:"val",donut:20}},{width:300,height:16,items:{xtype:"sparklineline",itemId:"gaugsparkline",values:[0,1,2,34],height:16,width:300},listeners:{afterrender:function(a){a.getTargetEl().setStyle("cursor",
"pointer");a.getTargetEl().on("click",function(b,c,d){clearTimeout(this.getMoveWordsTimeout());this.getWords().forEach(function(e){e.svg&&(e.svg.remove(),delete e.svg);e.direction=-1});b=Math.floor(b.event.offsetX*this.getWords().length/c.offsetWidth);this.moveWords(b)},this)},scope:this}}]}],dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"documentselectorbutton",singleSelect:!0},{xtype:"slider",fieldLabel:this.localize("speed"),labelAlign:"right",labelWidth:40,
width:100,increment:1,minValue:1,maxValue:60,value:30,listeners:{render:function(a){a.setValue(parseInt(this.getApiParam("speed")));this.bubbles&&this.bubbles.frameRate(a.getValue());this.setAudio(a.getValue());Ext.tip.QuickTipManager.register({target:a.getEl(),text:this.localize("speedTip")})},beforedestroy:function(a){Ext.tip.QuickTipManager.unregister(a.getEl())},changecomplete:function(a,b){this.setApiParam("speed",b);this.bubbles&&this.bubbles.frameRate(b)},scope:this}}]}]});this.callParent(arguments);
this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(a,b){this.loadDocument()},this)},loadDocument:function(){var a=this,b=parseInt(this.getApiParam("docIndex"))||0;this.getCorpus().getWordsArray({docIndex:b,stopList:"auto"}).then(function(c){var d=c.map(function(m){return m.toLowerCase()});if(void 0==a.getApiParam("groups")){var e={};d.forEach(function(m){5<m.length&&!(m in e)&&(e[m]=m.length)});d=Math.max.apply(this,Object.values(e));d=d3.scaleLinear().domain([4,
d]).range([.5,1]);for(var f in e)e[f]=d(e[f]);a.setGroups({length:{color:a.getApplication().getColorForTerm("length"),terms:e}})}f=a.getComponent("fountain").getTargetEl();d=f.down("svg");d.set({width:f.getWidth(),height:f.getHeight()});var g=d.dom;d3.select(g).selectAll("*").remove();var h={},k=a.getGroups();a.setWords(c.slice(0,1E3).map(function(m){m=new a.FountainWord(m.toLowerCase());m.word in h?h[m.word]++:h[m.word]=1;m.min=parseInt(Math.random()*g.clientHeight*.05);var n=Math.sqrt(10*Math.random());
m.yshift=1>2*Math.random()?-n:n;m.jump=g.clientHeight/10;m.groupVals={};for(var u in k)m.word in k[u].terms&&(m.groupVals[u]=k[u].terms[m.word]);return m}));Math.max.apply(this,Object.values(h));var l=d3.scaleLog().domain([1,Math.max.apply(this,Object.values(h))]).range([4,12]);a.getWords().forEach(function(m){m.fontSize=l(h[m.word])});a.moveWords()})},FountainWord:function(a){this.word=a;this.direction=-1},moveWords:function(a){var b=this.getWords(),c=this.getComponent("fountain").getTargetEl().down("svg").dom,
d=c.clientHeight,e=c.clientWidth;this.getGroups();for(var f=d3.scaleLinear().domain([0,d]).range([1,0]),g=[],h=0,k=0;k<b.length;k++)if(h++,0==Object.keys(b[k].groupVals).length?g.push(0):Object.values(b[k].groupVals).forEach(function(m){g.push(m)}),0>b[k].direction)if(b[k].svg){var l=parseInt(b[k].svg.attr("y"));b[k].svg.attr("y",l-(l-b[k].min)/5);b[k].svg.attr("x",parseInt(b[k].svg.attr("x"))+b[k].yshift);l=parseInt(b[k].svg.attr("y"));b[k].ys.push(l);l<=b[k].min&&(b[k].direction=1)}else{if(l=d3.select(c).append("text").text(b[k].word).attr("font-size",
b[k].fontSize).attr("text-anchor","middle").attr("x",e/2).attr("y",d-Math.random()*d/5).attr("fill",0==Object.keys(b[k].groupVals).length?"black":this.getApplication().getColorForTerm(Object.keys(b[k].groupVals).shift(),!0)),b[k].ys=[d],b[k].svg=l,!a||k>a)break}else 0<b[k].direction?b[k].svg&&0<b[k].ys.length?(b[k].svg.attr("y",b[k].ys.pop()),b[k].svg.attr("x",parseInt(b[k].svg.attr("x"))+b[k].yshift),b[k].svg.attr("opacity",f(parseInt(b[k].svg.attr("y"))))):b[k].direction=0:"svg"in b[k]&&(b[k].svg.remove(),
delete b[k].svg);a=0==g.length?0:100*Ext.mean(g);c=this.down("polar");c.getStore().getAt(0).set("val",a);c.setSprites({type:"text",text:Ext.util.Format.number(a,"%0.0"),x:145,y:240});a=this.down("sparklineline");a.setValues(100<g.length?this.chunkify(g,100,!0).map(function(m){return Ext.mean(m)}):g);a.setWidth(h*a.ownerCt.getWidth()/b.length);this.setMoveWordsTimeout(Ext.defer(this.moveWords,100,this))},chunkify:function(a,b,c){if(2>b)return[a];var d=a.length,e=[],f=0;if(0===d%b)for(c=Math.floor(d/
b);f<d;)e.push(a.slice(f,f+=c));else if(c)for(;f<d;)c=Math.ceil((d-f)/b--),e.push(a.slice(f,f+=c));else{b--;c=Math.floor(d/b);for(0===d%c&&c--;f<c*b;)e.push(a.slice(f,f+=c));e.push(a.slice(c*b))}return e},initComponent:function(){this.callParent(arguments)}});Ext.define("Voyant.panel.RezoViz",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.rezoviz",statics:{i18n:{timedOut:"The entities call took too long and has timed out. Retry?",maxLinks:"Max. Links",nerService:"Entity Identification Service"},api:{query:void 0,limit:50,type:["organization","location","person"],minEdgeCount:2,stopList:"auto",docId:void 0,nerService:"spacy"},glyph:"xf1e0@FontAwesome"},config:{graphStyle:{link:{normal:{stroke:"#000000",strokeOpacity:.1},highlight:{stroke:"#000000",
strokeOpacity:.5}}},options:[{xtype:"stoplistoption"}]},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){var a=this,b={};["person","location","organization"].forEach(function(c){var d=a.getApplication().getColorForEntityType(c,!0),e=d3.hsl(d);e.s*=.85;e.l*=1.15;var f=d3.hsl(d);f.s*=.85;var g=d3.hsl(d);d=d3.hsl(d);d.l*=.75;b[c+"Node"]={normal:{fill:e.toString(),stroke:f.toString()},highlight:{fill:g.toString(),
stroke:d.toString()}}});this.setGraphStyle(Ext.apply(this.getGraphStyle(),b));Ext.apply(a,{title:this.localize("title"),layout:"fit",items:{xtype:"voyantnetworkgraph",applyNodeStyle:function(c,d){var e=void 0===d?"normal":d;this.getGraphStyle();c.selectAll("rect").style("fill",function(f){f=f.type+"Node";return a.getGraphStyle()[f][e].fill}).style("stroke",function(f){f=f.type+"Node";return a.getGraphStyle()[f][e].stroke})},listeners:{nodeclicked:function(c,d){a.dispatchEvent("termsClicked",a,[d.term])},
edgeclicked:function(c,d){a.dispatchEvent("termsClicked",a,['"'+d.source.term+" "+d.target.term+'"~'+a.getApiParam("context")])}}},dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"corpusdocumentselector"},{xtype:"button",text:this.localize("categories"),menu:{items:[{xtype:"menucheckitem",text:this.localize("people"),itemId:"person",checked:!0},{xtype:"menucheckitem",text:this.localize("locations"),itemId:"location",checked:!0},{xtype:"menucheckitem",text:this.localize("organizations"),
itemId:"organization",checked:!0},{xtype:"button",text:this.localize("reload"),style:"margin: 5px;",handler:this.categoriesHandler,scope:this}]}},{xtype:"button",text:this.localize("nerService"),menu:{items:[{xtype:"menucheckitem",group:"nerService",text:"SpaCy",itemId:"spacy",checked:!0,handler:this.serviceHandler,scope:this},{xtype:"menucheckitem",group:"nerService",text:"NSSI",itemId:"nssi",checked:!0,handler:this.serviceHandler,scope:this},{xtype:"menucheckitem",group:"nerService",text:"Voyant",
itemId:"voyant",checked:!1,handler:this.serviceHandler,scope:this}]}},{xtype:"numberfield",itemId:"minEdgeCount",fieldLabel:this.localize("minEdgeCount"),labelAlign:"right",labelWidth:120,width:170,maxValue:10,minValue:1,allowDecimals:!1,allowExponential:!1,allowOnlyWhitespace:!1,listeners:{render:function(c){c.setRawValue(this.getApiParam("minEdgeCount"))},change:function(c,d){c.isValid()&&(this.setApiParam("minEdgeCount",d),this.preloadEntities())},scope:this}},{xtype:"slider",fieldLabel:this.localize("maxLinks"),
labelAlign:"right",labelWidth:100,width:170,minValue:10,maxValue:1E3,increment:10,listeners:{render:function(c){c.setValue(this.getApiParam("limit"))},changecomplete:function(c,d){this.setApiParam("limit",d);this.preloadEntities()},scope:this}}]}]});this.on("loadedCorpus",function(c,d){this.isVisible()&&this.preloadEntities()},this);this.on("corpusSelected",function(c,d){this.setApiParam("docId",void 0);this.preloadEntities()},this);this.on("documentsSelected",function(c,d){this.setApiParam("docId",
d);this.preloadEntities()},this);this.on("activate",function(){this.getCorpus()&&0===this.down("voyantnetworkgraph").getNodeData().length&&Ext.Function.defer(this.preloadEntities,100,this)},this);this.on("query",function(c,d){this.loadFromQuery(d)},this);a.callParent(arguments)},categoriesHandler:function(a){var b=[];a.up("menu").items.each(function(c){c.checked&&b.push(c.itemId)});this.setApiParam("type",b);this.preloadEntities()},serviceHandler:function(a){this.setApiParam("nerService",a.itemId);
this.preloadEntities()},preloadEntities:function(){var a=this;new Voyant.data.util.DocumentEntities({annotator:this.getApiParam("nerService")},function(){a.getEntities()})},getEntities:function(){this.down("voyantnetworkgraph").resetGraph();this.getCorpus().getId();var a=this.getLayout().getRenderTarget();a.mask(this.localize("loadingEntities"));Ext.Ajax.request({url:this.getApplication().getTromboneUrl(),method:"POST",params:{tool:"corpus.EntityCollocationsGraph",annotator:this.getApiParam("nerService"),
type:this.getApiParam("type"),limit:this.getApiParam("limit"),minEdgeCount:this.getApiParam("minEdgeCount"),corpus:this.getCorpus().getId(),docId:this.getApiParam("docId"),stopList:this.getApiParam("stopList"),noCache:!0},timeout:12E4,success:function(b){a.unmask();b=Ext.decode(b.responseText);if(0==b.entityCollocationsGraph.edges.length){this.showError({msg:this.localize("noEntities")});var c=this.getApiParam("minEdgeCount");1<c&&Ext.Msg.confirm(this.localize("error"),this.localize("noEntitiesForEdgeCount"),
function(d){"yes"===d&&(d=Math.max(1,c-1),this.queryById("minEdgeCount").setRawValue(d),this.setApiParam("minEdgeCount",d),this.preloadEntities())},this)}else this.processEntities(b.entityCollocationsGraph)},failure:function(b){a.unmask();Ext.Msg.confirm(this.localize("error"),this.localize("timedOut"),function(c){"yes"===c&&this.preloadEntities()},this)},scope:this})},processEntities:function(a){var b=a.nodes;a=a.edges;var c=this.getLayout().getRenderTarget(),d=c.getWidth()/2,e=c.getHeight()/2;c=
[];for(var f=0;f<b.length;f++){var g=b[f];c.push({term:g.term,title:g.term+" ("+g.rawFreq+")",type:g.type,value:g.rawFreq,fixed:!1,x:d,y:e})}d=[];for(f=0;f<a.length;f++)e=a[f].nodes,d.push({source:b[e[0]].term,target:b[e[1]].term,rawFreq:b[e[1]].rawFreq});this.down("voyantnetworkgraph").loadJson({nodes:c,edges:d})}});Ext.define("Voyant.panel.Loom",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.loom",statics:{i18n:{title:"Loom",controls:"Controls",frequenciesGroup:"Frequencies",coverageGroup:"Coverage",distributionsGroup:"Distribution",termsGroup:"Terms",inDocumentsLabel:"in documents",inDocumentsLabelTip:"each term must be present in the number of documents defined by this range",spanSomeLabel:"some documents",spanSomeLabelTip:"each term must be present in at least one document defined by this range",
spanAllLabel:"all documents",spanAllLabelTip:"each term must be present in all documents defined by this range",spanOnlyLabel:"only documents",spanOnlyLabelTip:"each term must be present in only the documents defined by this range",rawFreqLabel:"raw frequency",rawFreqLabelTip:"raw term frequencies for the term must be between these values (inclusively)",rawFreqPercentileLabel:"raw frequency percentile",rawFreqPercentileLabelTip:"raw term frequencies for the term must be between these percentile values (inclusively), this is useful for saying something like terms in the top 90th percentile which will provide 10% of words regardless of the variation in values.",
distributionsStdDevLabel:"standard deviation of distributions",distributionsStdDevLabelTip:"the standard deviation of term distribution scores must be between the defined range of values (lower will be for values that are more consistent, higher will be for values that have greater variability)",distributionsStdDevPercentileLabel:"percentile of standard deviations of distributions",distributionsStdDevPercentileLabelTip:"the percentile of standard deviations of distributions must be between the defined range of values (lower will be for values that are more consistent, higher will be for values that have greater variability)",
termsLengthLabel:"term length",termsLengthLabelTip:"the length (number of characters) of the term (word)",termsLengthPercentileLabel:"term length percentile",termsLengthPercentileLabelTip:"the percentile of the length (number of characters) of the term (word)",distributionIncreasesLabel:"increases in distribution values",distributionIncreasesLabelTip:"the number of increases of the distribution values must be between the defined range (inclusively)",distributionConsecutiveIncreasesLabel:"consecutive decreases in distribution values",
distributionConsecutiveIncreasesLabelTip:"the number of consecutive decreases of the distribution values must be between the defined range (inclusively)",distributionDecreasesLabel:"decreases in distribution values",distributionDecreasesLabelTip:"the number of decreases of the distribution values must be between the defined range (inclusively)",distributionConsecutiveDecreasesLabel:"consecutive decreases in distribution values",distributionConsecutiveDecreasesLabelTip:"the number of consecutive decreases of the distribution values must be between the defined range (inclusively)",
distributionMaxLabel:"distribution maximum",distributionMaxLabelTip:"the maximum of the distribution values must be between the defined range (inclusively)",distributionMinLabel:"distribution minimum",distributionMinLabelTip:"the minimum of the distribution values must be between the defined range (inclusively)",presetsGroup:"pre-sets",presetHighFreq:"terms that are high frequency",presetHighFreqLonger:"terms that are longer and high frequency",presetSingleDoc:"higher frequency terms that only occur once",
presetIncreaseDistributions:"terms that generally increase in frequency",presetDecreaseDistributions:"terms that generally decrease in frequency ",presetNearStartDistributions:"terms that peak in distribution toward the beginning ",presetNearEndDistributions:"terms that peak in distribution toward the end ",presetSporadicDistributions:"terms whose distributions vary the most",visibleTerms:"max terms",scaling:"scaling",scaleLinear:"linear",scaleLog:"logarithmic",scaleSqrt:"square root"},api:{limit:500,
stopList:"auto",inDocuments:void 0,spanSome:void 0,spanAll:void 0,spanOnly:void 0,termLength:void 0,termsLengthPercentile:void 0,rawFreq:void 0,rawFreqPercentile:void 0,distributionsStdDev:void 0,distributionsStdDevPercentile:void 0,distributionIncreases:void 0,distributionDecreases:void 0,distributionConsecutiveIncreases:void 0,distributionConsecutiveDecreases:void 0,distributionMax:void 0,distributionMin:void 0,scaling:"linear"},glyph:"xf1e0@FontAwesome"},config:{store:void 0,terms:void 0,options:[{xtype:"stoplistoption"},
{xtype:"categoriesoption"}],controls:void 0},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);var a=new Ext.util.MixedCollection({allowFunctions:!0});a.addAll({inDocuments:new Voyant.util.LoomControl({group:"coverage",name:"inDocuments",initControl:function(e){this.setMin(1);this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){e=
e.getDistributions().filter(function(f){return 0<f}).length;return e>=this.getLow()&&e<=this.getHigh()}}),spanSome:new Voyant.util.LoomControl({group:"coverage",name:"spanSome",offsetTipText:!0,initControl:function(e){this.setMax(e.getAt(0).getDistributions().length-1)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();for(e=e.getDistributions();f<g+1;f++)if(0<e[f])return!0;return!1}}),spanAll:new Voyant.util.LoomControl({group:"coverage",name:"spanAll",offsetTipText:!0,initControl:function(e){this.setMax(e.getAt(0).getDistributions().length-
1)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();for(e=e.getDistributions();f<g+1;f++)if(0==e[f])return!1;return!0}}),spanOnly:new Voyant.util.LoomControl({group:"coverage",name:"spanOnly",offsetTipText:!0,initControl:function(e){this.setMax(e.getAt(0).getDistributions().length-1)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=0;h<e.length;h++)if(h<f||h>g){if(0<e[h])return!1}else if(0==e[h])return!1;return!0}}),rawFreq:new Voyant.util.LoomControl({group:"frequencies",
name:"rawFreq",offsetTipText:!0,initControl:function(e){e=e.getRange().map(function(f){return f.get("rawFreq")});this.setMin(Ext.Array.min(e));this.setMax(Ext.Array.max(e))},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.get("rawFreq");return e>=f&&e<=g}}),rawFreqPercentile:new Voyant.util.LoomControl({group:"frequencies",name:"rawFreqPercentile",min:0,max:100,initControl:function(e){this.vals=e.getRange().map(function(f){return f.get("rawFreq")});this.vals.sort(function(f,g){return f-
g})},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=Ext.Array.indexOf(this.vals,e.get("rawFreq"));e=Math.round(100*e/this.vals.length);return e>=f&&e<=g}}),distributionsStdDev:new Voyant.util.LoomControl({group:"frequencies",name:"distributionsStdDev",initControl:function(e){var f=Ext.Array.flatten(e.getRange().map(function(h){return h.getDistributions()})),g=d3.scaleLinear().domain([d3.min(f),d3.max(f)]).range([0,100]);e.each(function(h){if(void 0===h.get("distributionsStdDev")){var k=
h.getDistributions(),l=k.map(function(n){return g(n)}),m=Ext.Array.mean(l);k=k.map(function(n){n-=m;return n*n});k=Ext.Array.mean(k);h.set("distributionsStdDev",Math.sqrt(k))}});e=e.getRange().map(function(h){return h.get("distributionsStdDev")});this.setMin(Ext.Array.min(e));this.setMax(Ext.Array.max(e))},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.get("distributionsStdDev");return e>=f&&e<=g}}),distributionsStdDevPercentile:new Voyant.util.LoomControl({group:"frequencies",
name:"distributionsStdDevPercentile",min:0,max:100,initControl:function(e){this.vals=e.getRange().map(function(f){return f.get("distributionsStdDev")});this.vals.sort(function(f,g){return f-g})},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=Ext.Array.indexOf(this.vals,e.get("distributionsStdDev"));e=Math.round(100*e/this.vals.length);return e>=f&&e<=g}}),termsLength:new Voyant.util.LoomControl({group:"terms",name:"termsLength",offsetTipText:!0,initControl:function(e){e=e.getRange().map(function(f){return f.get("term").length});
this.setMin(Ext.Array.min(e));this.setMax(Ext.Array.max(e))},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.get("term").length;return e>=f&&e<=g}}),termsLengthPercentile:new Voyant.util.LoomControl({group:"terms",name:"termsLengthPercentile",min:0,max:100,initControl:function(e){this.vals=e.getRange().map(function(f){return f.get("term").length});this.vals.sort(function(f,g){return f-g})},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=Ext.Array.indexOf(this.vals,
e.get("term").length);e=Math.round(100*e/this.vals.length);return e>=f&&e<=g}}),distributionIncreases:new Voyant.util.LoomControl({group:"distributions",name:"distributionIncreases",initControl:function(e){this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=0,k=1;k<e.length;k++)if(e[k]>e[k-1]&&(h++,h>g))return!1;return h>=f}}),distributionConsecutiveIncreases:new Voyant.util.LoomControl({group:"distributions",
name:"distributionConsecutiveIncreases",initControl:function(e){this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=0,k=1;k<e.length;k++)if(e[k]>e[k-1]){if(h++,h>g)return!1}else h=0;return h>=f}}),distributionDecreases:new Voyant.util.LoomControl({group:"distributions",name:"distributionDecreases",initControl:function(e){this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){var f=
this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=0,k=1;k<e.length;k++)if(e[k]<e[k-1]&&(h++,h>g))return!1;return h>=f}}),distributionConsecutiveDecreases:new Voyant.util.LoomControl({group:"distributions",name:"distributionConsecutiveDecreases",initControl:function(e){this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=0,k=1;k<e.length;k++)if(e[k]<e[k-1]){if(h++,h>g)return!1}else h=0;return h>=
f}}),distributionMax:new Voyant.util.LoomControl({group:"distributions",name:"distributionMax",initControl:function(e){this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){var f=this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=Ext.Array.max(e);f<g;f++)if(e[f]==h)return!0;return!1}}),distributionMin:new Voyant.util.LoomControl({group:"distributions",name:"distributionMin",initControl:function(e){this.setMax(e.getAt(0).getDistributions().length)},validateRecord:function(e){var f=
this.getLow(),g=this.getHigh();e=e.getDistributions();for(var h=Ext.Array.min(e);f<g;f++)if(e[f]==h)return!0;return!1}})});a.each(function(e){var f=this.getApiParam(e.getName()),g=(f||"").split(",");e.setEnabled(void 0!==f);2==g.length&&(e.setLow(parseInt(g[0])),e.setHigh(parseInt(g[1])));e.on("change",function(h){h.getEnabled()?this.setApiParam(h.getName(),h.getLow()+","+h.getHigh()):this.setApiParam(h.getName(),void 0);this.filterRecords()},this)},this);this.setControls(a);var b=this,c=function(){var e=
b.getApiParams();b.controls.each(function(f){f.setEnabled(!1,!0);f=f.getName();f in e&&b.setApiParam(f,void 0)})},d=[{text:this.localize("presetsGroup"),menu:{items:[{text:this.localize("presetHighFreq"),handler:function(){c();this.filterRecords()},scope:this},{text:this.localize("presetHighFreqLonger"),handler:function(){c();this.controls.getByKey("termsLengthPercentile").setEnabled(!0,!0).setValues(50,100,!0);this.controls.getByKey("rawFreqPercentile").setEnabled(!0,!0).setValues(50,100)},scope:this},
{text:this.localize("presetSingleDoc"),handler:function(){c();this.controls.getByKey("inDocuments").setEnabled(!0,!0).setValues(1,1)},scope:this},{text:this.localize("presetIncreaseDistributions"),handler:function(){c();var e=this.controls.getByKey("distributionIncreases"),f=e.getMax();e.setEnabled(!0,!0).setValues(Math.round(.75*f),f)},scope:this},{text:this.localize("presetDecreaseDistributions"),handler:function(){c();var e=this.controls.getByKey("distributionDecreases"),f=e.getMax();e.setEnabled(!0,
!0).setValues(Math.round(.75*f),f)},scope:this},{text:this.localize("presetNearStartDistributions"),handler:function(){c();var e=this.controls.getByKey("distributionMax"),f=e.getMax();e.setEnabled(!0,!0).setValues(0,Math.round(.2*f))},scope:this},{text:this.localize("presetNearEndDistributions"),handler:function(){c();var e=this.controls.getByKey("distributionMax"),f=e.getMax();e.setEnabled(!0,!0).setValues(Math.round(.8*f),f)},scope:this},{text:this.localize("presetSporadicDistributions"),handler:function(){c();
this.controls.getByKey("distributionsStdDevPercentile").setEnabled(!0,!0).setValues(80,100)},scope:this}]}},{xtype:"tbspacer"}];["frequencies","coverage","distributions","terms"].map(function(e){d.push({text:this.localize(e+"Group"),menu:{items:a.filterBy(function(f){return f.getGroup()==e}).getRange().map(function(f){return{xtype:"menucheckitem",checked:f.getEnabled(),text:this.localize(f.getName()+"Label"),tooltip:this.localize(f.getName()+"LabelTip"),listeners:{beforerender:function(g){g.setChecked(f.getEnabled());
f.on("change",function(){g.setChecked(f.getEnabled())})},click:function(g){f.setEnabled(g.checked);g.getMenu().setDisabled(!g.checked);g.checked?g.getMenu().show():g.getMenu().hide()}},menu:{disabled:!f.getEnabled(),items:{xtype:"multislider",width:100,minValue:f.getMin()||0,maxValue:f.getMax()||0,values:[f.getLow()||0,f.getHigh()||0],tipText:function(g){return f.getOffsetTipText()?g.value+1:g.value},listeners:{beforerender:function(g){g.updateFromControl(f);f.on("change",function(){g.updateFromControl(f)})},
changecomplete:function(g){f.setValues(g.getValues())}},updateFromControl:function(g){this.setMinValue(g.getMin()||0);this.setMaxValue(g.getMax());this.setValue(0,g.getLow()||0);this.setValue(1,void 0===g.getHigh()?g.getMax()||0:g.getHigh())}}}}},this)}})},this);Ext.apply(this,{title:this.localize("title"),layout:{type:"hbox",align:"stretch"},listeners:{afterrender:function(){var e=this.getComponent("terms"),f=this.getComponent("threads");e.on("termHovered",function(g,h){if(g=f.getTargetEl().dom.querySelector("path[term\x3d"+
h+"]")){var k=function(l,m){opacity=l.getAttribute("opacity");0<opacity&&(opacity-=.01,l.setAttribute("opacity",opacity),m/=2,Ext.defer(k,m,this,[l,m]))};g.setAttribute("opacity",1);k(g,1E3)}})}},items:[{itemId:"terms",width:100,layout:"fit",listeners:{filterchange:function(e){var f=this.getTargetEl(),g=f.getWidth(),h=f.getHeight(),k=e.getCount();f.setHtml(" ");terms=e.getRange().map(function(w,p){return{term:w.getTerm(),col:Voyant.application.getColorForTerm(w.getTerm(),!0),x:g/2,y:p*h/k}});terms.sort(function(w,
p){return w.term.localeCompare(p.term)});e=d3.select(f.dom).append("svg").attr("width",g).attr("height",h).append("g").attr("transform","translate(-.5,-.5)");var l=Math.ceil(h/terms.length),m=e.selectAll("ytext").data(terms).enter().append("text").text(function(w,p){return w.term}).attr("class","ytext").attr("text-anchor","middle").attr("x",g/2).attr("y",function(w,p){return l*p}).attr("fill",function(w){return Voyant.application.getColorForTerm(w.term,!0)});l=Math.ceil(h/terms.length);var n=d3.fisheye.circular().radius(50).distortion(2);
yFisheye=d3.fisheye.scale(d3.scaleIdentity).domain([0,h]);var u=this;e.on("mousemove",function(){var w=d3.mouse(this);currentItem=Math.round(w[1]*terms.length/h);currentItem=Math.min(currentItem,terms.length-1);n.focus(w[1]);yFisheye.focus(w[1]);var p=m.nodes();p[currentItem]&&u.fireEvent("termHovered",u,p[currentItem].textContent);var q=14,r=Math.max(w[1],q),v=1;d3.select(p[currentItem]).attr("y",function(L){return r}).attr("font-size",q).attr("fill-opacity",v);for(var x=void 0,z=currentItem-1;-1<
z;z--)8<=q?(r-=q,q-=.5):(void 0==x&&(x=r/z),r-=x),.1<v&&(v-=.05),d3.select(p[z]).attr("y",function(L){return r}).attr("font-size",q).attr("fill-opacity",v);q=14;r=Math.max(w[1],q);v=1;x=void 0;z=currentItem+1;for(w=terms.length;z<w;z++)8<=q?(r+=q,q-=.5):(void 0==x&&(x=(h-r)/(w-z)),r+=x),.1<v&&(v-=.05),d3.select(p[z]).attr("y",function(L){return r}).attr("font-size",q).attr("fill-opacity",v)})}}},{itemId:"threads",layout:"fit",flex:1,listeners:{filterchange:function(e){var f=this.getTargetEl(),g=f.getWidth(),
h=f.getHeight();f.setHtml(" ");terms=e.getRange().map(function(q){return{term:q.getTerm(),vals:q.getDistributions()}});var k=d3.select(f.dom).append("svg").attr("width",f.getWidth()).attr("height",f.getHeight());if(0==terms.length)return this.up("panel").toastInfo("No hits");var l=g/terms[0].vals.length;e=this.up("loom").getApiParam("scaling");var m=("sqrt"==e?d3.scaleSqrt():"log"==e?d3.scaleLog():d3.scaleLinear()).domain([Math.max(1E-6,Ext.Array.min(terms.map(function(q){return Ext.Array.min(q.vals)}))),
Math.max(1E-6,Ext.Array.max(terms.map(function(q){return Ext.Array.max(q.vals)})))]).range([1E-6,h-2]),n=d3.line().curve(d3.curveCardinal).x(function(q,r){return l/2+l*r}).y(function(q){return h-1-m(q)}),u=k.append("g").attr("opacity",0),w=u.append("rect").attr("fill","white").attr("text-anchor","middle").attr("alignment-baseline","middle").attr("stroke","rgba(0,0,0,.05)").attr("class","rect").attr("x",100).attr("y",100).attr("width",70).attr("height",16).attr("opacity",1),p=u.append("text").attr("text-anchor",
"middle").attr("alignment-baseline","middle").attr("x",100).attr("y",100).text("testing");terms.forEach(function(q){var r=Voyant.application.getColorForTerm(q.term,!0);k.append("path").datum(q.vals).attr("fill","none").attr("stroke",r).attr("opacity",.5).attr("stroke-linejoin","round").attr("stroke-linecap","round").attr("stroke-width",1).attr("class","line").attr("d",n);k.append("path").datum(q.vals).attr("fill","none").attr("stroke",r).attr("opacity",0).attr("stroke-width",3).attr("class","line").attr("term",
q.term).attr("d",n).on("mouseover",function(){d3.select(this).attr("opacity",1);var v=d3.mouse(this);u.attr("opacity",1);w.attr("x",v[0]-35).attr("y",v[1]-8+(v[1]>h/2?-18:18));p.text(q.term).attr("fill",r).attr("x",v[0]).attr("y",v[1]+(v[1]>h/2?-18:18))}).on("mouseout",function(){d3.select(this).attr("opacity",0);u.attr("opacity",0)});u.raise()},this)}}}],dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[d[0],d[2],d[3],d[4],d[5],{fieldLabel:this.localize("visibleTerms"),
labelWidth:70,width:120,xtype:"slider",increment:25,minValue:25,maxValue:5E3,listeners:{afterrender:function(e){e.setValue(parseInt(this.getApiParam("limit")))},changecomplete:function(e,f){this.setApiParams({limit:f});this.fireEvent("loadedCorpus",this,this.getCorpus())},scope:this}},{text:this.localize("scaling"),menu:{defaults:{xtype:"menucheckitem",handler:function(e){this.setApiParam("scaling",e.getItemId());this.getComponent("threads").fireEventArgs("filterchange",[this.getStore()])},scope:this,
listeners:{afterrender:function(e){e.setChecked(e.getItemId()==this.getApiParam("scaling"))},scope:this},group:"scaling"},items:[{text:this.localize("scaleLinear"),itemId:"linear"},{text:this.localize("scaleLog"),itemId:"log"},{text:this.localize("scaleSqrt"),itemId:"sqrt"}]}}]}]});this.on("loadedCorpus",function(e,f){e=1==f.getDocumentsCount()?f.getDocumentTerms():f.getCorpusTerms();e.on("load",function(){this.updateControlsFromStore();this.filterRecords()},this);e.on("filterchange",function(){this.getComponent("terms").fireEventArgs("filterchange",
arguments);this.getComponent("threads").fireEventArgs("filterchange",arguments)},this);this.setStore(e);params=this.getApiParams();Ext.apply(params,{withDistributions:!0});e.load({callback:function(g,h,k){this.filterRecords()},scope:this,params:params})},this);this.callParent(arguments)},filterRecords:function(){var a=this.getStore();a.clearFilter();var b=parseInt(this.getApiParam("limit")),c=0;a.filterBy(function(d){return Ext.Array.every(this.getControls().getRange(),function(e){return 0==e.getEnabled()||
e.getValidateRecord().call(e,d)},this)&&c++<b},this)},updateControlsFromStore:function(){var a=this.getStore();this.getControls().each(function(b){b.suspendEvent("change");b.initControl.call(this,a);void 0===b.getMin()&&b.setMin(0);void 0==b.getLow()&&b.setLow(b.getMin());void 0===b.getMax()&&b.setMax(1);void 0==b.getHigh()&&b.setHigh(b.getMax());b.resumeEvent("change")})},revalidate:function(){var a=this.body.down("canvas").dom,b=a.getContext("2d");b.clearRect(0,0,a.width,a.height);var c=this.query("loomcontrol"),
d=new Voyant.panel.LoomTermRecords;this.getStore().each(function(e){var f=e.getDistributions().map(function(g){return!0});Ext.Array.each(c,function(g){if(g.getChecked()&&g.validateRecord){g=g.validateRecord.call(this,g.getField(),e,e.getDistributions());if(Ext.isBoolean(g)&&!g)return f=!1;if(Ext.isArray(g)){for(var h=0;h<f.length;h++)f[h]=f[h]&&g[h];return Ext.Array.some(f,function(k){return k})}}});Ext.isArray(f)&&Ext.Array.some(f,function(g){return g})&&d.add(e)});d.update(a,b)}});
Ext.define("Voyant.panel.LoomTermRecords",{config:{termRecords:[]},constructor:function(a){this.setTermRecords([]);this.callParent(arguments)},add:function(a){this.getTermRecords().push(new Voyant.panel.LoomTermRecord(a))},update:function(a,b){var c=Ext.Array.min(this.getTermRecords().map(function(e){return Ext.Array.min(e.getValues())})),d=Ext.Array.max(this.getTermRecords().map(function(e){return Ext.Array.max(e.getValues())}));this.getTermRecords().forEach(function(e){e.update(a,b,c,d)})}});
Ext.define("Voyant.panel.LoomTermRecord",{config:{record:void 0,values:void 0,term:void 0,texts:void 0},constructor:function(a){this.setRecord(a);this.setValues(a.getDistributions());var b=a.getTerm();this.setTerm(b);this.setTexts(a.getDistributions().map(function(c){return new Ext.draw.sprite.Text({type:"text",text:b})}));this.callParent(arguments)},update:function(a,b,c,d){var e=this.getValues(),f=a.offsetWidth/e.length,g=a.offsetHeight,h=this.getTerm();this.getTexts().forEach(function(k,l){b.fillText(h,
f/2+l*f,g-e[l]*g/d)})}});
Ext.define("Voyant.util.LoomControl",{extend:"Ext.Base",mixins:["Ext.mixin.Observable"],constructor:function(a){this.mixins.observable.constructor.call(this,a);this.callParent(arguments)},config:{group:void 0,name:void 0,enabled:!1,min:void 0,max:void 0,low:void 0,high:void 0,initControls:Ext.emptyFn,validateRecord:Ext.emptyFn,offsetTipText:!1},setMin:function(){this.callParent(arguments);this.fireEvent("change",this);return this},setMax:function(){this.callParent(arguments);this.fireEvent("change",
this);return this},setLow:function(){this.callParent(arguments);this.fireEvent("change",this);return this},setHigh:function(){this.callParent(arguments);this.fireEvent("change",this);return this},setValues:function(a,b){this.suspendEvent("change");Ext.isArray(a)?(this.setLow(a[0]),this.setHigh(a[1])):(this.setLow(a),this.setHigh(b));this.resumeEvent("change");(3>arguments.length||!arguments[2])&&this.fireEvent("change",this);return this},setEnabled:function(){this.callParent(arguments);(2>arguments.length||
!arguments[1])&&this.fireEvent("change",this);return this}});Ext.define("Voyant.panel.MicroSearch",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.microsearch",statics:{i18n:{},api:{stopList:"auto",query:void 0},glyph:"xf1ea@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}],maxTokens:0,tokensPerSegment:0,maxVerticalLines:0,maxSegments:0},constructor:function(a){Ext.apply(this,{title:this.localize("title"),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield"}]}]});
this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(b,c){if(this.rendered)this.initialize();else this.on("afterrender",function(){this.initialize()},this)});this.on("query",function(b,c){this.setApiParam("query",c);this.updateSearchResults()})},initialize:function(){var a=this.getTargetEl(),b=this.getCorpus();this.setMaxVerticalLines(Math.floor((a.getHeight()-10)/5));var c=b.getDocumentsCount(),d=10*c,e=Math.floor((a.getWidth()-
d-10)/c);200<e&&(e=200);d=Math.floor(e/3);1>d&&(d=1);this.setMaxSegments(d*this.getMaxVerticalLines());b=b.getDocuments();this.setMaxTokens(b.max("tokensCount-lexical"));this.setTokensPerSegment(this.getMaxTokens()<this.getMaxSegments()?1:Math.ceil(this.getMaxTokens()/this.getMaxSegments()));var f="\x3ctable cellpadding\x3d'0' cellspacing\x3d'0' style\x3d'height: 100%'\x3e\x3ctr\x3e";this.segments=[];b.each(function(h){docIndex=h.getIndex();f+='\x3ctd style\x3d"overflow: hidden; vertical-align: top; width: '+
e+'px;"\x3e\x3cdiv class\x3d"docLabel" style\x3d"white-space: nowrap; width: '+e+'px;" data-qtip\x3d"'+h.getFullLabel()+'"\x3e'+h.getFullLabel()+'\x3c/div\x3e\x3ccanvas style\x3d"display: block;" width\x3d"'+e+'" height\x3d"'+a.getHeight()+'" id\x3d"'+this.body.id+"-"+docIndex+'"\x3e\x3c/td\x3e';docIndex+1<c&&(f+='\x3ctd style\x3d"width: 10px;"\x3e\x26nbsp;\x3c/td\x3e')},this);f+="\x3c/tr\x3e\x3c/table\x3e";a.update(f);this.updateSearchResults();if(!this.getApiParam("query")){var g=this;return this.getCorpus().loadCorpusTerms({limit:1,
stopList:this.getApiParam("stopList"),categories:this.getApiParam("categories")}).then(function(h){h=h.getAt(0).getTerm();g.down("querysearchfield").addValue(new Voyant.data.model.CorpusTerm({term:h}));g.fireEvent("query",g,[h])})}},updateSearchResults:function(){query=this.getApiParam("query");this.getCorpus().getDocuments().each(function(a){var b=this.redistributeDistributions(a,Array(this.getMaxSegments()));this.drawDocumentDistributions(a,null,b)},this);0<Ext.Array.from(query).length&&(this.mask(this.localize("loading")),
this.getCorpus().getDocumentTerms().load({params:{query:Ext.Array.from(query),withDistributions:"relative",bins:this.getMaxSegments(),categories:this.getApiParam("categories")},callback:function(a,b,c){this.unmask();var d=0,e=Number.MAX_VALUE,f=[];a.forEach(function(g){var h=this.getCorpus().getDocument(g.getDocIndex()),k=this.redistributeDistributions(h,g.getDistributions()),l=Ext.Array.max(k);l>d&&(d=l);k.forEach(function(m){m&&m<e&&(e=m)});void 0===f[g.getDocIndex()]&&(f[g.getDocIndex()]={});f[g.getDocIndex()][g.getTerm()]=
this.redistributeDistributions(h,g.getDistributions())},this);f.forEach(function(g,h){for(var k in g){var l=g[k];this.drawDocumentDistributions(this.getCorpus().getDocument(h),k,l,e||Ext.Array.min(l),d||Ext.Array.max(l))}},this)},scope:this}))},redistributeDistributions:function(a,b){a=Math.ceil(a.getLexicalTokensCount()/this.getTokensPerSegment());if(b.length>a){for(var c=[],d=0;d<b.length;d++){var e=parseInt(d*a/b.length);c[e]?c[e].push(b[d]):c[e]=[b[d]]}b=c;for(d=0;d<b.length;d++)b[d]=Ext.Array.mean(b[d])}return b},
drawDocumentDistributions:function(a,b,c,d,e){var f=this.getTargetEl().dom.querySelector("#"+this.body.id+"-"+a.getIndex());a=f.getContext("2d");var g=0;f=f.clientWidth;var h=0,k=null===b,l=[230,230,230];k||(l=this.getApplication().getColorForTerm(b));for(b=0;b<c.length;b++)k?(a.fillStyle="rgb(230,230,230)",a.fillRect(g,h,3,3)):c[b]&&(a.fillStyle="rgba("+l[0]+","+l[1]+","+l[2]+","+(.7*(c[b]-d)/(e-d)+.3)+")",a.fillRect(g,h,3,3)),g+=3,g>=f&&(g=0,h+=5)}});Ext.define("Voyant.panel.Mandala",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.mandala",statics:{i18n:{},api:{stopList:"auto",query:void 0,labels:!0},glyph:"xf1db@FontAwesome"},gutter:5,textFont:"12px sans-serif",config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}]},constructor:function(){this.mixins["Voyant.util.Localization"].constructor.apply(this,arguments);Ext.apply(this,{title:this.localize("title"),html:'\x3cdiv style\x3d"text-align: center"\x3e\x3ccanvas width\x3d"800" height\x3d"600"\x3e\x3c/canvas\x3e\x3c/div\x3e',
dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{text:this.localize("add"),glyph:"xf067@FontAwesome",handler:function(){this.editMagnet()},scope:this},{text:this.localize("clear"),glyph:"xf014@FontAwesome",handler:function(){this.setApiParam("query",void 0);this.updateFromQueries(!0);this.editMagnet()},scope:this},{xtype:"checkbox",boxLabel:this.localize("labels"),listeners:{render:function(a){a.setValue(!0===this.getApiParam("labels"));Ext.tip.QuickTipManager.register({target:a.getEl(),
text:this.localize("labelsTip")})},beforedestroy:function(a){Ext.tip.QuickTipManager.unregister(a.getEl())},change:function(a,b){this.setApiParam("labels",b);this.draw()},scope:this}}]}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("boxready",function(a){var b=this.getTargetEl().dom.querySelector("canvas"),c=this;b.addEventListener("mousemove",function(d){var e=b.getBoundingClientRect(),f=d.clientX-e.left,g=d.clientY-e.top,h=!1,k=parseInt(c.textFont)/
2;c.documents&&c.documents.forEach(function(l){var m=f>l.x-k&&f<l.x+k&&g>l.y-k&&g<l.y+k;m!=l.isHovering&&(h=!0);l.isHovering=m});radius=parseInt(c.textFont)/2;for(term in c.magnets)d=f>c.magnets[term].x-radius&&f<c.magnets[term].x+radius&&g>c.magnets[term].y-radius&&g<c.magnets[term].y+radius,d!=c.magnets[term].isHovering&&(h=!0),c.magnets[term].isHovering=d;h&&c.draw()},!1);b.addEventListener("click",function(d){var e=b.getBoundingClientRect(),f=d.clientX-e.left;d=d.clientY-e.top;parseInt(c.textFont);
for(term in c.magnets)f>c.magnets[term].x-radius&&f<c.magnets[term].x+radius&&d>c.magnets[term].y-radius&&d<c.magnets[term].y+radius&&c.editMagnet(term)},!1)});this.on("loadedCorpus",function(a,b){this.documents=[];a=this.getTargetEl().dom.querySelector("canvas");var c=a.getContext("2d"),d=a.width/2;c.font=this.textFont;b.getDocuments().each(function(e){var f=e.getTinyTitle();this.documents.push({doc:e,label:f,width:c.measureText(f).width,x:d,y:d,matches:[],isHovering:!1})},this);this.updateDocs(a);
this.draw();this.updateFromQueries()},this);this.on("resize",function(){var a=this.getTargetEl().dom.querySelector("canvas"),b=Math.min(this.getTargetEl().getWidth(),this.getTargetEl().getHeight());a.width=b;a.height=b;this.updateMagnets();this.updateDocs();this.draw(a)})},editMagnet:function(a){var b=this,c=Ext.Array.from(b.getApiParam("query"));Ext.create("Ext.window.Window",{title:this.localize("EditMagnet"),modal:!0,items:{xtype:"form",width:300,items:[{xtype:"querysearchfield",corpus:this.getCorpus(),
store:this.getCorpus().getCorpusTerms({proxy:{extraParams:{stopList:this.getApiParam("stopList")}}}),stopList:this.getApiParam("stopList"),listeners:{afterrender:function(d){if(a){var e=new Ext.create("Voyant.data.model.CorpusTerm",{term:a});d.getStore().loadData(e,!0);d.setValue(e)}}}},{xtype:"numberfield",fieldLabel:b.localize("rotateClockwise"),minValue:0,maxValue:c.length-1,value:0,stepValue:1,width:200,name:"rotate"}],buttons:[{text:this.localize("remove"),glyph:"xf0e2@FontAwesome",flex:1,ui:"default-toolbar",
handler:function(d){var e=Ext.Array.filter(Ext.Array.from(b.getApiParam("query")),function(f){return f!=a});b.setApiParam("query",e);b.updateFromQueries(0==e.length);d.up("window").close()},scope:this},{xtype:"tbfill"},{text:this.localize("cancel"),ui:"default-toolbar",glyph:"xf00d@FontAwesome",flex:1,handler:function(d){d.up("window").close()}},{text:this.localize("update"),glyph:"xf00c@FontAwesome",flex:1,handler:function(d){var e=d.up("window").down("querysearchfield").getValue().join("|");if(e){for(var f=
-1,g=0;g<c.length;g++)if(a==c[g]){f=g;c[g]=e;var h=d.up("window").down("numberfield").getValue();h&&(c.splice(g,1),g+=h,g>c.length&&(g-=c.length+1),c.splice(g,0,e));break}-1==f&&c.push(e)}b.setApiParam("query",c);b.updateFromQueries(0==c.length);d.up("window").close()},scope:this}]},bodyPadding:5}).show()},updateFromQueries:function(a){this.magnets=void 0;this.documents.forEach(function(d){d.matches=[]});this.updateDocs();this.draw();if(this.documents){var b=this.getApiParams();b.query||(b.limit=
10);var c=Ext.Array.from(this.getApiParam("query"));(!a||0<c.length)&&this.getCorpus().getCorpusTerms().load({params:Ext.apply(b,{withDistributions:!0}),callback:function(d){var e=this.getTargetEl().dom.querySelector("canvas"),f=e.getContext("2d");diam=e.width;rad=diam/2;f.font=this.textFont;var g={};e=0;for(var h=d.length;e<h;e++){var k=d[e].getTerm();d[e].getDistributions().forEach(function(l,m){0<l&&this.documents[m].matches.push(k)},this);g[k]={record:d[e],colour:this.getApplication().getColor(e),
width:f.measureText(k).width,isHovering:!1}}this.magnets={};c.forEach(function(l){g[l]&&(this.magnets[l]=g[l],delete g[l])},this);for(k in g)this.magnets[k]=g[k];this.setApiParam("query",Object.keys(this.magnets));this.updateMagnets();this.updateDocs();this.draw()},scope:this})}},updateMagnets:function(a){a=this.getTargetEl().dom.querySelector("canvas");a=a.width/2;var b=Object.keys(this.magnets||{}).length,c=0,d;for(d in this.magnets)Ext.apply(this.magnets[d],{x:a+(a-this.gutter-50)*Math.cos(2*Math.PI*
c/b),y:a+(a-this.gutter-50)*Math.sin(2*Math.PI*c/b)}),c++},updateDocs:function(a){a=a||this.getTargetEl().dom.querySelector("canvas");diam=a.width;rad=diam/2;var b=[];if(this.documents){this.documents.forEach(function(d,e){if(0==Ext.Array.from(d.matches).length)b.push(e);else if(1==Ext.Array.from(d.matches).length){var f=15*Math.random()+15,g=15*Math.random()+15;d.targetX=this.magnets[d.matches[0]].x+(0==Math.round(Math.random())?f:-f);d.targetY=this.magnets[d.matches[0]].y+(0==Math.round(Math.random())?
g:-g)}else{g=f=0;var h=d.matches.map(function(n){return this.magnets[n].record.getDistributions()[e]},this),k=Ext.Array.min(h),l=Ext.Array.max(h),m=0;d.matches.forEach(function(n,u){weight=l==k?1:(h[u]-k+k)/(l-k+k);m+=weight;f+=this.magnets[n].x*weight;g+=this.magnets[n].y*weight},this);d.targetX=f/m;d.targetY=g/m}},this);a=0;for(var c=b.length;a<c;a++)Ext.apply(this.documents[a],{targetX:rad+(rad-this.gutter)*Math.cos(2*Math.PI*a/c),targetY:rad+(rad-this.gutter)*Math.sin(2*Math.PI*a/c)})}},draw:function(a,
b){a=a||this.getTargetEl().dom.querySelector("canvas");b=b||a.getContext("2d");b.font=this.textFont;var c=a.width/2;b.clearRect(0,0,a.width,a.height);var d=this.getApiParam("labels");b.beginPath();b.strokeStyle="rgba(0,0,0,.1)";b.fillStyle="rgba(0,0,0,.02)";b.arc(c,c,c-this.gutter,0,2*Math.PI,!1);b.fill();b.lineWidth=2;b.stroke();var e=!1;if(this.documents&&0<this.documents.length){var f=Ext.Array.each(this.documents,function(p){return!p.isHovering},this);!0===f&&(f=Ext.Array.each(Object.keys(this.magnets||
{}),function(p){return!this.magnets[p].isHovering},this));var g={};hoveringDocs=[];this.documents.forEach(function(p,q){p.matches.forEach(function(r,v){b.beginPath();b.moveTo(p.x,p.y);b.lineTo(this.magnets[r].x,this.magnets[r].y);!0===f?b.strokeStyle="rgba("+this.magnets[r].colour.join(",")+",.1)":p.isHovering||this.magnets[r].isHovering?(hoveringDocs[q]=!0,g[r]=!0,b.strokeStyle="rgba("+this.magnets[r].colour.join(",")+",.5)"):b.strokeStyle="rgba(0,0,0,.02)";b.stroke()},this)},this);var h=parseInt(this.textFont)/
2,k=parseInt(this.textFont)+4;this.documents.forEach(function(p,q){if(d||p.isHovering||1==hoveringDocs[q]){var r=p.width+4;b.fillStyle=p.isHovering||1==hoveringDocs[q]||!0===f?"white":"rgba(255,255,255,.05)";b.fillRect(p.x-r/2,p.y-k/2,r,k);b.strokeStyle=p.isHovering||1==hoveringDocs[q]||!0===f?"rgba(0,0,0,.2)":"rgba(0,0,0,.05)";b.strokeRect(p.x-r/2,p.y-k/2,r,k);b.textAlign="center";b.fillStyle=p.isHovering||1==hoveringDocs[q]||!0===f?"rgba(0,0,0,.8)":"rgba(0,0,0,.05)";b.fillText(p.label,p.x,p.y)}else b.beginPath(),
b.fillStyle="rgba(0,0,0,.8)",b.arc(p.x,p.y,h,0,2*Math.PI),b.fill(),b.stroke();q=Math.abs(p.x-p.targetX);r=Math.abs(p.y-p.targetY);if(0!=q||0!=r)1>q?p.x=p.targetX:(q/=2,p.x=p.x>p.targetX?p.x-q:p.x+q),1>r?p.y=p.targetY:(r/=2,p.y=p.y>p.targetY?p.y-r:p.y+r),e=!0},this);a=0;k=parseInt(this.textFont)+4;b.textAlign="center";b.textBaseline="middle";for(var l in this.magnets)d||l in g||this.magnets[l].isHovering?(a=this.magnets[l].width+4,b.fillStyle=l in g||this.magnets[l].isHovering||!0===f?"white":"rgba(255,255,255,.05)",
b.fillRect(this.magnets[l].x-a/2,this.magnets[l].y-k/2,a,k),b.strokeStyle=l in g||this.magnets[l].isHovering||!0===f?"rgb("+this.magnets[l].colour.join(",")+")":"rgba(0,0,0,.05)",b.strokeRect(this.magnets[l].x-a/2,this.magnets[l].y-k/2,a,k),b.textAlign="center",b.fillStyle=l in g||this.magnets[l].isHovering||!0===f?"rgba(0,0,0,.8)":"rgba(0,0,0,.05)",b.fillText(l,this.magnets[l].x,this.magnets[l].y)):(b.beginPath(),b.fillStyle="rgb("+this.magnets[l].colour.join(",")+")",b.strokeStyle="rgb("+this.magnets[l].colour.join(",")+
")",b.arc(this.magnets[l].x,this.magnets[l].y,12,0,2*Math.PI),b.fill(),b.stroke())}if(e){var m=this;setTimeout(function(){m.draw()},100)}else if(this.documents){c=Math.max(c/this.documents.length,50);a=0;for(l=this.documents.length;a<l;a++)for(var n=0;n<l;n++)if(a<n){var u=this.documents[a].x-this.documents[n].x,w=this.documents[a].y-this.documents[n].y;Math.sqrt(u*u+w*w)<c&&(u*=.1,w*=.1,this.documents[a].targetX+=u,this.documents[n].targetX-=u,this.documents[a].targetY+=w,this.documents[n].targetY-=
w,e=!0)}e&&(m=this,setTimeout(function(){m.draw()},100))}}});Ext.define("Voyant.panel.MicroOcp",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.microocp",statics:{i18n:{title:"MicroOCP"},api:{config:void 0,stopList:"auto",uri:void 0},glyph:"xf1ea@FontAwesome"},config:{editor:void 0},constructor:function(a){a=a||{};this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);var b=Ext.create("Ext.data.Store",{fields:[{name:"cocoa",type:"string"}]});Ext.apply(this,{title:this.localize("title"),layout:"border",dockedItems:[{dock:"bottom",
xtype:"toolbar",overflowHandler:"scroller",groupId:"tbar",items:[{text:"Create New Voyant Corpus",handler:function(){var c=this.down("grid").getSelectionModel().getSelection().map(function(p){return p.get("cocoa")});if(0==c.length)return this.showError({title:"Error",msg:"No items are selected in the grid (on the right)."});itemsMap={};c.forEach(function(p){itemsMap[p]=!0});var d=this.getEditor().getValue();c=/<(\/)?(\w+)(\s(\w+))?>/g;for(var e,f={};null!=(e=c.exec(d));){var g="/"==e[1],h=e[2],k=
e[4],l=e[4]?e[2]+" "+e[4]:e[2];g||l in itemsMap?(h in f&&(f[h][f[h].length-1].end=e.index),g||(h in f||(f[h]=[]),f[h].push({start:e.index+e[0].length,tag:h,attr:k}))):l in itemsMap&&h in f&&(f[h][f[h].length-1].end=e.index)}isGroupItems=this.getDockedComponent(1).down("checkbox").checked;var m=[];if(isGroupItems){var n={};for(h in f)f[h].forEach(function(p,q){if(q=d.substring(p.start,p.end).replace(/<\/?\w+(\s+\w)*>/g,"").trim())p=p.tag+(p.attr?" "+p.attr:""),n[p]=p in n?n[p]+q:q});for(l in n)m.push({title:l,
text:n[l]})}else for(h in f)f[h].forEach(function(p,q){var r=d.substring(p.start,p.end).replace(/<\/?\w+(\s+\w)*>/g,"").trim();r&&m.push({title:p.tag+(p.attr?" "+p.attr:"")+" "+(q+1),text:r})});if(0==m.length)return this.showError({title:"Error",msg:"No documents found."});this.mask();var u=Ext.Msg.progress("Creating","Creating new corpus."),w=this;(new Corpus({inputFormat:"json",input:Ext.JSON.encode({documents:m}),jsonDocumentsPointer:"/documents",jsonTitlePointer:"/title",jsonContentPointer:"/text"})).then(function(p){u.close();
w.unmask();var q=w.getApplication();w.openUrl(q.getBaseUrl()+"?corpus\x3d"+p.getAliasOrId())})},scope:this},{xtype:"checkbox",boxLabel:"Combine documents with the same tag attribute.",checked:!0}]}],items:[{xtype:"panel",autoScroll:!0,flex:1,height:"100%",align:"stretch",header:!1,region:"center",listeners:{boxready:function(){}}},{xtype:"grid",region:"east",height:"100%",align:"stretch",scrollable:!0,header:!1,width:200,selModel:Ext.create("Ext.selection.CheckboxModel",{mode:"SIMPLE"}),store:b,columns:[{text:"COCOA",
flex:1,dataIndex:"cocoa"}]}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("loadedCorpus",function(c,d){this.getApiParam("uri")||d.getPlainText().then(function(e){e.replace(/(\r\n|\r|\n)(\r\n|\r|\n)(\r\n|\r|\n)+/g,"\n\n")})},this);this.on("afterrender",function(c){Ext.Msg.alert("MicroOCP","MicroOCP is an experimental prototype that is intended to give a taste of working with the COCOA markup format (COunt and COncordance on the Atlas). Cocoa tags are like switches, you can place one and that tag remains in effect until the next instance of the tag, which can have an optional attribute (single word). As an enhancement to COCOA, you can also close a tag.\x3cpre\x3e\x26lt;speaker jack\x26gt;I'm falling \x26lt;speaker jill\x26gt;down the hill.\x26lt;/speaker\x26gt;\x3c/pre\x3e")})}});Ext.define("Voyant.panel.Reader",{extend:"Ext.panel.Panel",requires:["Voyant.data.store.Tokens"],mixins:["Voyant.panel.Panel"],alias:"widget.reader",isConsumptive:!0,statics:{i18n:{highlightEntities:"Highlight Entities",entityType:"entity type",nerVoyant:"Entity Identification with Voyant",nerNssi:"Entity Identification with NSSI",nerSpacy:"Entity Identification with SpaCy"},api:{start:0,limit:1E3,skipToDocId:void 0,query:void 0},glyph:"xf0f6@FontAwesome"},config:{innerContainer:void 0,tokensStore:void 0,
documentsStore:void 0,documentTermsStore:void 0,documentEntitiesStore:void 0,exportVisualization:!1,lastScrollTop:0,scrollIntoView:!1,insertWhere:"beforeEnd",lastLocationUpdate:new Date,options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}]},SCROLL_UP:-1,SCROLL_EQ:0,SCROLL_DOWN:1,LOCATION_UPDATE_FREQ:100,INITIAL_LIMIT:1E3,MAX_TOKENS_FOR_NER:1E5,constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(a){var b=
Ext.create("Voyant.data.store.Tokens",{parentTool:this,proxy:{extraParams:{forTool:"reader"}}}),c=this;b.on("beforeload",function(d){return c.hasCorpusAccess(d.getCorpus())});b.on("load",function(d,e,f){if(f){var g="",h=this.localize("documentFrequency"),k=!1,l=-1,m=!1;e.forEach(function(n){0==n.getPosition()&&(g+="\x3ch3\x3e"+this.getDocumentsStore().getById(n.getDocId()).getFullLabel()+"\x3c/h3\x3e");n.getDocIndex()!=l&&(k=this.getDocumentsStore().getById(n.getDocId()).isPlainText(),l=n.getDocIndex());
if(n.isWord())m=!1,g+="\x3cspan class\x3d'word' id\x3d'"+n.getId()+"' data-qtip\x3d'\x3cdiv class\x3d\"freq\"\x3e"+h+" "+n.getDocumentRawFreq()+"\x3c/div\x3e'\x3e"+n.getTerm()+"\x3c/span\x3e";else{n=n.getTermWithLineSpacing(k);var u=0==n.indexOf("\x3cbr /\x3e");if(!m||!u&&0!=n.trim().length)g+=n,m=u}},this);this.updateText(g);this.highlightKeywords();void 0!==this.getDocumentEntitiesStore()&&this.highlightEntities()}},this);this.setTokensStore(b);this.on("query",function(d,e){this.loadQueryTerms(e)},
this);this.setDocumentTermsStore(Ext.create("Ext.data.Store",{model:"Voyant.data.model.DocumentTerm",autoLoad:!1,remoteSort:!1,proxy:{type:"ajax",url:Voyant.application.getTromboneUrl(),extraParams:{tool:"corpus.DocumentTerms",withPositions:!0,bins:25,forTool:"reader"},reader:{type:"json",rootProperty:"documentTerms.terms",totalProperty:"documentTerms.total"},simpleSortMode:!0},listeners:{load:function(d,e,f,g){this.highlightKeywords(e)},scope:this}}));this.on("afterrender",function(){var d=this.down('panel[region\x3d"center"]');
this.setInnerContainer(d.getLayout().getRenderTarget());d.body.on("scroll",function(e,f){e=this.getLastScrollTop()<f.scrollTop?this.SCROLL_DOWN:this.getLastScrollTop()>f.scrollTop?this.SCROLL_UP:this.SCROLL_EQ;if(e==this.SCROLL_UP&&1>f.scrollTop)this.fetchPrevious(!0);else if(e==this.SCROLL_DOWN&&f.scrollHeight-f.scrollTop<1.5*f.offsetHeight)this.fetchNext(!1);else{var g=0==f.scrollTop?0:f.scrollHeight-f.scrollTop==f.clientHeight?1:(f.scrollTop+.5*f.clientHeight)/f.scrollHeight;(new Date-this.getLastLocationUpdate()>
this.LOCATION_UPDATE_FREQ||0==g||1==g)&&this.updateLocationMarker(g,e)}this.setLastScrollTop(f.scrollTop)},this);d.body.on("click",function(e,f){f=Ext.get(f);f.hasCls("word")&&(e=Voyant.data.model.Token.getInfoFromElement(f),f=f.getHtml(),e=[{term:f,docIndex:e.docIndex}],this.loadQueryTerms([f]),this.getApplication().dispatchEvent("termsClicked",this,e))},this);this.getCorpus()&&(void 0===this.getApiParam("skipToDocId")&&this.setApiParam("skipToDocId",this.getCorpus().getDocument(0).getId()),this.load(),
(d=this.getApiParam("query"))&&this.loadQueryTerms(Ext.isString(d)?[d]:d));this.on("loadedCorpus",function(){void 0===this.getApiParam("skipToDocId")&&this.setApiParam("skipToDocId",this.getCorpus().getDocument(0).getId());this.load(!0);var e=this.getApiParam("query");e&&this.loadQueryTerms(Ext.isString(e)?[e]:e)},this)},this);Ext.apply(this,{title:this.localize("title"),cls:"voyant-reader",layout:"fit",items:{layout:"border",items:[{bodyPadding:10,region:"center",border:!1,autoScroll:!0,html:'\x3cdiv class\x3d"readerContainer"\x3e\x3c/div\x3e'},
{xtype:"readergraph",region:"south",weight:0,height:30,split:{size:2},splitterResize:!0,border:!1,listeners:{documentRelativePositionSelected:function(d,e){d=this.getDocumentsStore().getAt(e.docIndex);var f=d.get("tokensCount-lexical");e=Math.floor(f*e.fraction)-this.getApiParam("limit")/2;this.setApiParams({skipToDocId:d.getId(),start:0>e?0:e});this.load(!0)},scope:this}},{xtype:"entitieslist",region:"east",weight:10,width:"40%",split:{size:2},splitterResize:!0,border:!1,hidden:!0,collapsible:!0,
animCollapse:!1}]},dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{glyph:"xf060@FontAwesome",handler:function(){this.fetchPrevious(!0)},scope:this},{glyph:"xf061@FontAwesome",handler:function(){this.fetchNext(!0)},scope:this},{xtype:"tbseparator"},{xtype:"querysearchfield"},"-\x3e",{glyph:"xf0eb@FontAwesome",tooltip:this.localize("highlightEntities"),itemId:"nerServiceParent",hidden:!0,menu:{items:[{xtype:"menucheckitem",group:"nerService",text:this.localize("nerSpacy"),
itemId:"spacy",checked:!0,handler:this.nerServiceHandler,scope:this},{xtype:"menucheckitem",group:"nerService",text:this.localize("nerNssi"),itemId:"nssi",checked:!1,handler:this.nerServiceHandler,scope:this},{xtype:"menucheckitem",group:"nerService",text:this.localize("nerVoyant"),itemId:"stanford",checked:!1,handler:this.nerServiceHandler,scope:this}]}}]}],listeners:{loadedCorpus:function(d,e){this.getTokensStore().setCorpus(e);this.getDocumentTermsStore().getProxy().setExtraParam("corpus",e.getId());
d=e.getDocuments();this.setDocumentsStore(d);this.rendered&&(this.load(),0==this.hasCorpusAccess(e)&&this.mask(this.localize("limitedAccess"),"mask-no-spinner"),(e=this.getApiParam("query"))&&this.loadQueryTerms(Ext.isString(e)?[e]:e))},termsClicked:function(d,e){var f=[];e.forEach(function(g){Ext.isString(g)?f.push(g):g.term?f.push(g.term):g.getTerm&&f.push(g.getTerm())});0<f.length&&this.loadQueryTerms(f)},corpusTermsClicked:function(d,e){var f=[];e.forEach(function(g){g.getTerm()&&f.push(g.getTerm())});
this.loadQueryTerms(f)},documentTermsClicked:function(d,e){var f=[];e.forEach(function(g){g.getTerm()&&f.push(g.getTerm())});this.loadQueryTerms(f)},documentSelected:function(d,e){d=this.getTokensStore().getCorpus().getDocument(e);this.setApiParams({skipToDocId:d.getId(),start:0});this.load(!0)},documentsClicked:function(d,e,f){0<e.length&&(this.setApiParams({skipToDocId:e[0].getId(),start:0}),this.load(!0))},termLocationClicked:function(d,e){if(void 0!==e[0]){d=e[0];e=d.get("docIndex");var f=d.get("position");
this.showTermLocation(e,f,d)}},documentIndexTermsClicked:function(d,e){void 0!==e[0]&&(d=Ext.create("Voyant.data.model.Token",e[0]),this.fireEvent("termLocationClicked",this,[d]))},entityClicked:function(d,e){d=e.get("docIndex");var f=e.get("positions")[0];Array.isArray(f)&&(f=f[0]);this.showTermLocation(d,f,e)},entityLocationClicked:function(d,e,f){d=e.get("docIndex");f=e.get("positions")[f];Array.isArray(f)&&(f=f[0]);this.showTermLocation(d,f,e)},scope:this}});this.callParent(arguments)},loadQueryTerms:function(a){if(a&&
0<a.length){var b=this.getApiParam("skipToDocId");if(void 0===b){b=0;var c=this.getLocationInfo();c&&(b=c[0].docIndex);b=this.getCorpus().getDocument(b).getId()}this.getDocumentTermsStore().load({params:{query:a,docId:b,categories:this.getApiParam("categories"),limit:-1}});this.down("readergraph").loadQueryTerms(a)}},showTermLocation:function(a,b,c){var d=b-this.getApiParam("limit")/2,e=this.getCorpus().getDocument(a);this.setApiParams({skipToDocId:e.getId(),start:0>d?0:d});this.load(!0,{callback:function(){var f=
this.body.dom.querySelector("#_"+a+"_"+b);f&&(f.scrollIntoView({block:"center"}),Ext.fly(f).frame("#f80"));c.get("type")?this.highlightEntities():this.highlightKeywords(c,!1)},scope:this})},highlightKeywords:function(a,b){var c=this.getInnerContainer().first();c.select("span[class*\x3dkeyword]").removeCls("keyword").applyStyles({backgroundColor:"transparent",color:"black"});void 0===a&&0<this.getDocumentTermsStore().getCount()&&(a=this.getDocumentTermsStore().getData().items);void 0!==a&&(Ext.isArray(a)||
(a=[a]),a.forEach(function(d){var e=d.get("term"),f=this.getApplication().getColorForTerm(e),g=this.getApplication().getTextColorForBackground(f);f="rgb("+f.join(",")+") !important";g="rgb("+g.join(",")+") !important";var h="background-color:"+f+";color:"+g+";";if(d.get("positions")){e=d.get("positions");var k=d.get("docIndex");e.forEach(function(m){(m=c.dom.querySelector("#_"+k+"_"+m))&&Ext.fly(m).addCls("keyword").dom.setAttribute("style",h)})}else{var l=new RegExp("^"+e+"$","i");c.select("span.word").each(function(m,
n,u){m.dom.firstChild&&m.dom.firstChild.nodeValue.match(l)&&m.addCls("keyword").dom.setAttribute("style",h)})}},this))},nerServiceHandler:function(a){a=a.itemId;var b=[],c=this.getLocationInfo();if(c)for(var d=c[0].docIndex;d<=c[1].docIndex;d++)b.push(d);else b.push(0);var e=this.down("entitieslist");e.clearEntities();this.clearEntityHighlights();var f=this;new Voyant.data.util.DocumentEntities({annotator:a,includeEntities:!0,docIndex:b},function(g){g&&(f.clearEntityHighlights(),f.setDocumentEntitiesStore(g),
f.highlightEntities(),e.expand().show().addEntities(g))})},clearEntityHighlights:function(){this.getInnerContainer().first().select(".entity").each(function(a){a.removeCls("entity start middle end location person organization misc money time percent date duration set unknown");a.dom.setAttribute("data-qtip",a.dom.getAttribute("data-qtip").replace(/<div class="entity">.*?<\/div>/g,""))})},highlightEntities:function(){var a=this.getInnerContainer().first(),b=this.getDocumentEntitiesStore(),c=this.localize("entityType");
b.forEach(function(d){var e=d.positions;e?e.forEach(function(f){var g=1<f.length;if(g&&2===f.length&&1<f[1]-f[0])for(var h=f[1],k=f[0]+1,l=1;k<h;)f.splice(l,0,k),k++,l++;h=0;for(k=f.length;h<k;h++)if(l=f[h],-1===l)console.warn("missing position for: "+d.term);else if(l=a.selectNode("#_"+d.docIndex+"_"+l,!1)){var m="";g&&(m=0===h?"start ":h===k-1?"end ":"middle ");l.addCls("entity "+m+d.type);m=l.dom.getAttribute("data-qtip");-1===m.indexOf('class\x3d"entity"')&&l.dom.setAttribute("data-qtip",m+'\x3cdiv class\x3d"entity"\x3e'+
c+": "+d.type+"\x3c/div\x3e")}}):console.warn("no positions for: "+d.term)})},fetchPrevious:function(a){var b=this.getInnerContainer().first(),c=b.first(".word");if(null!=c&&!1===c.hasCls("loading"))for(;c;){if(c.hasCls("word")){b=Voyant.data.model.Token.getInfoFromElement(c);var d=b.docIndex;b=b.position;var e=this.getDocumentsStore().getAt(d),f=this.getApiParam("limit"),g=!1;if(0===d&&0===b){a=this.down('panel[region\x3d"center"]').body;0!=c.getScrollIntoViewXY(a,a.dom.scrollTop,a.dom.scrollLeft).y&&
c.dom.scrollIntoView();c.frame("red");break}0<d&&0===b?(g=!0,d--,e=this.getDocumentsStore().getAt(d),d=e.get("tokensCount-lexical"),b=d-f,0>b&&(b=0,this.setApiParam("limit",d))):(f--,b-=f);0>b&&(b=0);c.insertSibling("\x3cdiv class\x3d'loading'\x3e"+this.localize("loading")+"\x3c/div\x3e","before",!1).mask();g||c.destroy();c=e.getId();this.setApiParams({skipToDocId:c,start:b});this.setInsertWhere("afterBegin");this.setScrollIntoView(a);this.load();this.setApiParam("limit",this.INITIAL_LIMIT);break}c.destroy();
c=b.first()}},fetchNext:function(a){var b=this.getInnerContainer().first(),c=b.last();if(!1===c.hasCls("loading"))for(;c;){if(c.hasCls("word")){b=Voyant.data.model.Token.getInfoFromElement(c);var d=b.docIndex,e=b.position,f=this.getDocumentsStore().getAt(b.docIndex),g=f.getId();f=f.get("tokensCount-lexical");if(e+this.getApiParam("limit")>=f&&d==this.getCorpus().getDocumentsCount()-1)if(d=f-e,1>=d){c.dom.scrollIntoView();c.frame("red");break}else this.setApiParam("limit",d);for(d=c.dom.nextSibling;d;)e=
d,d=d.nextSibling,e.parentNode.removeChild(e);c.insertSibling("\x3cdiv class\x3d'loading'\x3e"+this.localize("loading")+"\x3c/div\x3e","after",!1).mask();c.destroy();this.setApiParams({skipToDocId:g,start:b.position});this.setInsertWhere("beforeEnd");this.setScrollIntoView(a);this.load();this.setApiParam("limit",this.INITIAL_LIMIT);break}c.destroy();c=b.last()}},load:function(a,b){a&&(this.getInnerContainer().first().destroy(),this.getInnerContainer().setHtml('\x3cdiv class\x3d"readerContainer"\x3e\x3cdiv class\x3d"loading"\x3e'+
this.localize("loading")+"\x3c/div\x3e\x3c/div\x3e"),this.getInnerContainer().first().first().mask());a=this.getTokensStore();a.lastOptions&&a.lastOptions.params.skipToDocId&&a.lastOptions.params.skipToDocId!==this.getApiParam("skipToDocId")&&(a=this.getDocumentTermsStore(),a.lastOptions&&this.loadQueryTerms(a.lastOptions.params.query));this.getTokensStore().load(Ext.apply(b||{},{params:Ext.apply(this.getApiParams(),{stripTags:"blocksOnly",stopList:""})}))},updateText:function(a){var b=this.getInnerContainer().down(".loading");
b&&b.destroy();var c=this.getInnerContainer().first().insertHtml(this.getInsertWhere(),a,!0);c&&this.getScrollIntoView()&&(c.dom.scrollIntoView(),Ext.Function.defer(function(){var d=Ext.get(c.id);d&&d.frame("red")},100));a=this.down('panel[region\x3d"center"]').body.dom;this.updateLocationMarker(0==a.scrollTop?0:a.scrollHeight-a.scrollTop==a.clientHeight?1:(a.scrollTop+.5*a.clientHeight)/a.scrollHeight)},updateLocationMarker:function(a,b){var c=this.getLocationInfo();if(c){var d=c[0],e=c[1];c=this.getCorpus();
var f=!1;0!==d.position&&(f=!0);for(var g={},h=0,k=this.getApplication().getEntitiesEnabled?this.getApplication().getEntitiesEnabled():!1,l=d.docIndex;l<=e.docIndex;){var m=c.getDocument(l).get("tokensCount-lexical");m>this.MAX_TOKENS_FOR_NER&&(k=!1);l===e.docIndex&&(m=e.position);l===d.docIndex&&(m-=d.position);h+=m;g[l]=m;l++}l=this.down("#nerServiceParent");k?l.show():l.hide();h=Math.round(h*a);k=a=0;for(l=d.docIndex;l<=e.docIndex&&!(a=l,k+=g[l],k>=h);l++);e=g[a]-(k-h);f&&a===d.docIndex&&(e+=d.position);
d=e/c.getDocument(a).get("tokensCount-lexical");this.down("readergraph").moveLocationMarker(a,d,b)}},getLocationInfo:function(){var a=Ext.DomQuery.select(".word",this.getInnerContainer().down(".readerContainer",!0)),b=a[0];a=a[a.length-1];return void 0!==b&&void 0!==a?(b=Voyant.data.model.Token.getInfoFromElement(b),a=Voyant.data.model.Token.getInfoFromElement(a),[b,a]):null}});Ext.define("Voyant.panel.SimpleDocReader",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.simpledocreader",isConsumptive:!0,statics:{i18n:{},api:{docIndex:void 0,docId:void 0},glyph:"xf0f6@FontAwesome"},config:{},constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(a){Ext.apply(this,{html:'\x3ciframe style\x3d"width: 100%; height: 100%; border: none;"\x3e\x3c/iframe\x3e',dockedItems:[{dock:"bottom",
xtype:"toolbar",overflowHandler:"scroller",items:[{glyph:"xf060@FontAwesome",handler:this.fetchPrevious,scope:this},{glyph:"xf061@FontAwesome",handler:this.fetchNext,scope:this}]}],listeners:{loadedCorpus:function(b,c){"true"!==this.getApiParam("autoLoadOnLoadedCorpus","false")&&this.fireEvent("documentSelected",this,0)},documentSelected:function(b,c){this.setApiParams({docIndex:this.getCorpus().getDocument(c).getIndex(),docId:void 0});this.fetch()},scope:this}});this.callParent(arguments)},fetchPrevious:function(){var a=
void 0!==this.getApiParam("docIndex")?this.getCorpus().getDocument(this.getApiParam("docIndex")):void 0!==this.getApiParam("docId")?this.getCorpus().getDocument(this.getApiParam("docId")):this.getCorpus().getDocument(1);0<a.getIndex()?(this.setApiParams({docIndex:a.getIndex()-1,docId:void 0}),this.fetch()):this.toastInfo(this.localize("noPrevious"))},fetchNext:function(){if(void 0!==this.getApiParam("docIndex"))var a=this.getCorpus().getDocument(this.getApiParam("docIndex"));else if(void 0!==this.getApiParam("docId"))a=
this.getCorpus().getDocument(this.getApiParam("docId"));else return this.setApiParams({docIndex:0,docId:void 0}),this.fetch();a.getIndex()<this.getCorpus().getDocumentsCount()-1?(this.setApiParams({docIndex:a.getIndex()+1,docId:void 0}),this.fetch()):this.toastInfo(this.localize("noNext"))},fetch:function(){var a=void 0!==this.getApiParam("docIndex")?this.getCorpus().getDocument(this.getApiParam("docIndex")):void 0!==this.getApiParam("docId")?this.getCorpus().getDocument(this.getApiParam("docId")):
this.getCorpus().getDocument(0);var b=this.getTargetEl().down("iframe",!0);b.setAttribute("src","about:blank");if(this.getApiParam("originalUrlMetadataKey")){var c=a.get(this.getApiParam("originalUrlMetadataKey"));if(c){b.setAttribute("src",c);return}}a={corpus:this.getCorpus().getId(),docIndex:a.getIndex(),tool:"corpus.DocumentTokens",template:"docTokensPlusStructure2html",outputFormat:"html",limit:0};c=this.getTromboneUrl()+"?"+Ext.Object.toQueryString(a);b.setAttribute("src",c)}});Ext.define("Voyant.panel.ScatterPlot",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],requires:["Ext.chart.CartesianChart"],alias:"widget.scatterplot",statics:{i18n:{},api:{docId:void 0,analysis:"ca",limit:50,dimensions:3,bins:10,clusters:3,perplexity:15,iterations:1500,comparisonType:"relative",stopList:"auto",target:void 0,term:void 0,query:void 0,whitelist:void 0,label:["summary","docs","terms"],storeJson:void 0},glyph:"xf06e@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}],
caStore:null,pcaStore:null,tsneStore:null,docSimStore:null,termStore:null,chartMenu:null,newTerm:null,termsTimeout:null,highlightData:{x:0,y:0,r:0},highlightTask:null},tokenFreqTipTemplate:null,docFreqTipTemplate:null,constructor:function(a){this.mixins["Voyant.util.Api"].constructor.apply(this,arguments);if("storeJson"in a){var b=JSON.parse(a.storeJson);Ext.apply(a,b)}this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},initComponent:function(){this.setCaStore(Ext.create("Voyant.data.store.CAAnalysis",
{listeners:{load:this.maskAndBuildChart,scope:this}}));this.setPcaStore(Ext.create("Voyant.data.store.PCAAnalysis",{listeners:{load:this.maskAndBuildChart,scope:this}}));this.setTsneStore(Ext.create("Voyant.data.store.TSNEAnalysis",{listeners:{load:this.maskAndBuildChart,scope:this}}));this.setDocSimStore(Ext.create("Voyant.data.store.DocSimAnalysis",{listeners:{load:this.maskAndBuildChart,scope:this}}));this.setTermStore(Ext.create("Ext.data.JsonStore",{fields:[{name:"term"},{name:"rawFreq",type:"int"},
{name:"relativeFreq",type:"number"},{name:"coordinates",mapping:"vector"},{name:"category"}],sorters:[{property:"rawFreq",direction:"DESC"}],groupField:"category"}));this.setChartMenu(Ext.create("Ext.menu.Menu",{items:[{text:this.localize("remove"),itemId:"remove",glyph:"xf068@FontAwesome"},{text:this.localize("nearby"),itemId:"nearby",glyph:"xf0b2@FontAwesome"}],listeners:{hide:function(){var a=this.down("#chart").getSeries();a[0].enableToolTips();a[1].enableToolTips()},scope:this}}));this.tokenFreqTipTemplate=
new Ext.Template(this.localize("tokenFreqTip"));this.docFreqTipTemplate=new Ext.Template(this.localize("docFreqTip"));Ext.apply(this,{title:this.localize("title"),layout:"border",autoDestroy:!0,items:[{itemId:"chartParent",region:"center",layout:"fit",tbar:{overflowHandler:"scroller",items:[{xtype:"querysearchfield",itemId:"filterTerms",width:150},{text:this.localize("labels"),itemId:"labels",glyph:"xf02b@FontAwesome",menu:{items:[{text:this.localize("summaryLabel"),itemId:"summary",xtype:"menucheckitem"},
{text:this.localize("docsLabel"),itemId:"docs",xtype:"menucheckitem"},{text:this.localize("termsLabel"),itemId:"terms",xtype:"menucheckitem"}],listeners:{afterrender:function(a){var b=this.getApiParam("label");a.items.each(function(c){c.setChecked(-1<b.indexOf(c.getItemId()))})},click:function(a,b){a=this.getApiParam("label");var c=b.getItemId();Ext.isString(a)&&(a=[a]);b.checked&&-1==a.indexOf(c)?a.push(c):!b.checked&&-1<a.indexOf(c)&&(a=a.filter(function(d){return d!=c}));this.setApiParam("label",
a);this.doLabels();this.queryById("chart").redraw()},scope:this}}}]},listeners:{query:function(a,b){this.getTermStore().filter([{property:"term",value:b,anyMatch:!0}]);this.filterChart(b)},scope:this}},{itemId:"optionsPanel",title:this.localize("options"),region:"west",split:!0,collapsible:!0,collapseMode:"header",width:135,scrollable:"y",layout:{type:"vbox",align:"stretch"},defaults:{xtype:"button",margin:"5",labelAlign:"top"},items:[{xtype:"label",text:this.localize("input")},{xtype:"documentselectorbutton"},
{text:this.localize("freqsMode"),itemId:"comparisonType",glyph:"xf201@FontAwesome",tooltip:this.localize("freqsModeTip"),menu:{items:[{text:this.localize("rawFrequencies"),itemId:"comparisonType_raw",group:"freqsMode",xtype:"menucheckitem"},{text:this.localize("relativeFrequencies"),itemId:"comparisonType_relative",group:"freqsMode",xtype:"menucheckitem"},{text:this.localize("tfidf"),itemId:"comparisonType_tfidf",group:"freqsMode",xtype:"menucheckitem"}],listeners:{click:function(a,b){void 0!==b&&
(a=b.getItemId().split("_")[1],a!==this.getApiParam("comparisonType")&&(this.setApiParam("comparisonType",a),this.loadFromApis(!0)))},scope:this}}},{fieldLabel:this.localize("numTerms"),itemId:"limit",xtype:"numberfield",minValue:5,listeners:{change:function(a,b,c){function d(){this.setApiParam("limit",b);this.loadFromApis()}null!==c&&(null!==this.getTermsTimeout()&&clearTimeout(this.getTermsTimeout()),a.isValid()&&this.setTermsTimeout(setTimeout(d.bind(this),500)))},scope:this}},{xtype:"container",
html:'\x3chr style\x3d"border: none; border-top: 1px solid #cfcfcf;"/\x3e'},{xtype:"label",text:this.localize("output")},{text:this.localize("analysis"),itemId:"analysis",glyph:"xf1ec@FontAwesome",overflowHandler:"scroller",menu:{items:[{text:this.localize("pca"),itemId:"analysis_pca",group:"analysis",xtype:"menucheckitem"},{text:this.localize("ca"),itemId:"analysis_ca",group:"analysis",xtype:"menucheckitem"},{text:this.localize("tsne"),itemId:"analysis_tsne",group:"analysis",xtype:"menucheckitem"},
{text:this.localize("docSim"),itemId:"analysis_docSim",group:"analysis",xtype:"menucheckitem"}],listeners:{click:function(a,b){void 0!==b&&(a=b.getItemId().split("_")[1],a!==this.getApiParam("analysis")&&(this.doAnalysisChange(a),this.loadFromApis(!0)))},scope:this}}},{fieldLabel:this.localize("perplexity"),itemId:"perplexity",xtype:"slider",minValue:5,maxValue:100,increment:1,listeners:{changecomplete:function(a,b){this.setApiParam("perplexity",b);this.loadFromApis(!0)},scope:this}},{fieldLabel:this.localize("iterations"),
itemId:"iterations",xtype:"slider",minValue:100,maxValue:5E3,increment:100,listeners:{changecomplete:function(a,b){this.setApiParam("iterations",b);this.loadFromApis(!0)},scope:this}},{text:this.localize("clusters"),itemId:"clusters",glyph:"xf192@FontAwesome",menu:{items:[{text:"1",itemId:"clusters_1",group:"clusters",xtype:"menucheckitem"},{text:"2",itemId:"clusters_2",group:"clusters",xtype:"menucheckitem"},{text:"3",itemId:"clusters_3",group:"clusters",xtype:"menucheckitem"},{text:"4",itemId:"clusters_4",
group:"clusters",xtype:"menucheckitem"},{text:"5",itemId:"clusters_5",group:"clusters",xtype:"menucheckitem"}],listeners:{click:function(a,b){void 0!==b&&(a=parseInt(b.getItemId().split("_")[1]),a!==this.getApiParam("clusters")&&(this.setApiParam("clusters",a),this.loadFromApis(!0)))},scope:this}}},{text:this.localize("dimensions"),itemId:"dimensions",glyph:"xf1b2@FontAwesome",menu:{items:[{text:"2",itemId:"dimensions_2",group:"dimensions",xtype:"menucheckitem"},{text:"3",itemId:"dimensions_3",group:"dimensions",
xtype:"menucheckitem"}],listeners:{click:function(a,b){if(void 0!==b&&(a=parseInt(b.getItemId().split("_")[1]),a!==this.getApiParam("dimensions"))){if(3==a&&"ca"==this.getApiParam("analysis")&&3==this.getCorpus().getDocumentsCount())return!1;this.setApiParam("dimensions",a);this.loadFromApis(!0)}},scope:this}}},{itemId:"reloadButton",text:this.localize("reload"),glyph:"xf021@FontAwesome",handler:function(){this.loadFromApis()},scope:this}]},{itemId:"termsGrid",xtype:"grid",title:this.localize("terms"),
region:"east",width:250,split:!0,collapsible:!0,collapseMode:"header",forceFit:!0,features:[{ftype:"grouping",hideGroupedHeader:!0,enableGroupingMenu:!1}],bbar:{overflowHandler:"scroller",items:[{itemId:"nearbyButton",xtype:"button",text:this.localize("nearby"),glyph:"xf0b2@FontAwesome",flex:1,handler:function(a){var b=a.up("panel").getSelection()[0];void 0===b?this.toastError({html:this.localize("noTermSelected"),anchor:a.up("panel").getTargetEl()}):(a=b.get("term"),this.getNearbyForTerm(a))},scope:this},
{itemId:"removeButton",xtype:"button",text:this.localize("remove"),glyph:"xf068@FontAwesome",flex:1,handler:function(a){var b=a.up("panel").getSelection()[0];void 0===b?this.toastError({html:this.localize("noTermSelected"),anchor:a.up("panel").getTargetEl()}):(a=b.get("term"),this.removeTerm(a))},scope:this}]},tbar:{overflowHandler:"scroller",items:[{xtype:"querysearchfield",itemId:"addTerms",flex:1}]},columns:[{text:this.localize("term"),dataIndex:"term",flex:1,sortable:!0},{text:this.localize("rawFreq"),
dataIndex:"rawFreq",flex:.75,minWidth:70,sortable:!0},{text:this.localize("relFreq"),dataIndex:"relativeFreq",flex:.75,minWidth:70,sortable:!0,hidden:!0}],selModel:{type:"rowmodel",mode:"SINGLE",allowDeselect:!0,toggleOnClick:!0,listeners:{selectionchange:{fn:function(a,b){b=b[0];void 0!==b?(a=b.get("term"),b="document"===b.get("category"),this.selectTerm(a,b),b?(this.queryById("nearbyButton").disable(),this.queryById("removeButton").disable()):(this.queryById("nearbyButton").enable(),this.queryById("removeButton").enable())):
this.selectTerm()},scope:this}}},store:this.getTermStore(),listeners:{expand:function(a){a.getView().refresh()},query:function(a,b){0<b.length&&-1===this.getTermStore().findExact("term",b[0])?(this.setNewTerm(b),this.loadFromApis()):this.setNewTerm(null)},scope:this}}]});this.on("boxready",function(a,b,c){400>b&&(this.queryById("optionsPanel").collapse(),this.queryById("termsGrid").collapse());this.config.storeClass&&this.config.storeData&&this.loadStoreFromJson(this.config.storeClass,this.config.storeData)},
this);this.on("beforedestroy",function(a){a=this.queryById("chart");null!==a&&this.queryById("chartParent").remove(a)},this);this.on("loadedCorpus",function(a,b){a=function(c){var d=this.getApiParam(c);this.queryById(c).down("#"+c+"_"+d).setChecked(!0)}.bind(this);a("analysis");this.doAnalysisChange(this.getApiParam("analysis"));a("comparisonType");a("clusters");this.queryById("perplexity").setValue(this.getApiParam("perplexity"));this.queryById("iterations").setValue(this.getApiParam("iterations"));
3==b.getDocumentsCount()&&this.setApiParam("dimensions",2);a("dimensions");this.getCaStore().setCorpus(b);this.getPcaStore().setCorpus(b);this.getDocSimStore().setCorpus(b);this.loadFromApis()},this);this.on("documentsSelected",function(a,b){this.setApiParam("docId",b);this.loadFromApis()},this);this.callParent(arguments)},doAnalysisChange:function(a){this.setApiParam("analysis",a);this.queryById("nearbyButton").setDisabled("tsne"===a);this.queryById("reloadButton").setVisible("tsne"===a);this.queryById("perplexity").setVisible("tsne"===
a);this.queryById("iterations").setVisible("tsne"===a);"ca"===a&&3==this.getCorpus().getDocumentsCount()&&(this.setApiParam("dimensions",2),this.queryById("dimensions").menu.items.get(0).setChecked(!0))},loadStoreFromJson:function(a,b){"Voyant.data.store.CAAnalysis"==a?(this.getCaStore().loadRawData(b),this.doAnalysisChange("ca"),this.maskAndBuildChart.call(this,this.getCaStore())):"Voyant.data.store.PCAAnalysis"==a?(this.getPcaStore().loadRawData(b),this.doAnalysisChange("pca"),this.maskAndBuildChart.call(this,
this.getPcaStore())):"Voyant.data.store.TSNEAnalysis"==a?(this.getTsneStore().loadRawData(b),this.doAnalysisChange("tsne"),this.maskAndBuildChart.call(this,this.getTsneStore())):"Voyant.data.store.DocSimAnalysis"==a&&(this.getDocSimStore().loadRawData(b),this.doAnalysisChange("docSim"),this.maskAndBuildChart.call(this,this.getDocSimStore()))},maskAndBuildChart:function(a){this.queryById("chartParent").mask(this.localize("plotting"));Ext.defer(this.buildChart,50,this,[a])},buildChart:function(a){var b=
this,c=this.queryById("chart");null!==c&&this.queryById("chartParent").remove(c);this.queryById("termsGrid").getSelectionModel().deselectAll();c=a.getAt(0);var d=this.getApiParam("dimensions");a="";if("pca"===this.getApiParam("analysis")){for(var e=c.getPrincipalComponents(),f=0,g=0;g<e.length;g++)f+=parseFloat(e[g].get("eigenValue"));if(0!=f){a=this.localize("pcTitle")+"\n";var h=["xAxis","yAxis","fill"];for(g=0;g<e.length&&!(g>=d);g++){var k=e[g].get("eigenValue")/f*100;a+=this.localize("pc")+" "+
(g+1)+" ("+this.localize(h[g])+"): "+Math.round(100*k)/100+"%\n"}}}else if("tsne"!==this.getApiParam("analysis"))for(a=this.localize("caTitle")+"\n",h=["xAxis","yAxis","fill"],e=c.getDimensions(),g=0;g<e.length&&!(g>=d);g++)k=e[g].get("percentage"),a+=this.localize("dimension")+" "+(g+1)+" ("+this.localize(h[g])+"): "+Math.round(100*k)/100+"%\n";var l=0,m=Number.MAX_VALUE,n=0,u=Number.MAX_VALUE;"docSim"!==this.getApiParam("analysis")&&this.getTermStore().removeAll();var w=[],p=[];c.getTokens().forEach(function(q){var r=
q.get("rawFreq"),v=q.get("category");void 0===v&&(v="term",q.set("category","term"));var x="term"===v;x&&(r>l&&(l=r),r<m&&(m=r));this.getTermStore().findExact("term",-1===q.get("term"))&&this.getTermStore().addSorted(q);if(3===d){var z=q.get("vector")[2];void 0!==z&&(z<u&&(u=z),z>n&&(n=z))}r={x:q.get("vector")[0],y:q.get("vector")[1]||0,z:q.get("vector")[2]||0,term:q.get("term"),rawFreq:r,relativeFreq:q.get("relativeFreq"),cluster:q.get("cluster"),category:v,disabled:!1};x?w.push(r):("bin"===q.get("category")?
r.term=r.title="Bin "+q.get("docIndex"):(r.docIndex=q.get("docIndex"),q=this.getCorpus().getDocument(r.docIndex),null!==q&&(r.term=q.getShortTitle(),r.title=q.getTitle())),p.push(r))},this);c=this.getTermStore().getCount();this.queryById("limit").setRawValue(c);this.setApiParam("limit",c);c=Ext.create("Ext.data.JsonStore",{fields:"term x y z rawFreq relativeFreq cluster category docIndex disabled".split(" "),data:w});g=Ext.create("Ext.data.JsonStore",{fields:"term x y z rawFreq relativeFreq cluster category docIndex disabled".split(" "),
data:p});a={itemId:"chart",xtype:"cartesian",interactions:["crosszoom","panzoom","itemhighlight"],plugins:{ptype:"chartitemevents"},axes:[{type:"numeric",position:"bottom",fields:["x"],label:{rotate:{degrees:-30}}},{type:"numeric",position:"left",fields:["y"]}],sprites:[{type:"text",text:a,x:70,y:70}],innerPadding:{top:25,right:25,bottom:25,left:25},series:[{type:"customScatter",xField:"x",yField:"y",store:c,label:{font:"14px Helvetica",field:"term",display:"over"},tooltip:{trackMouse:!0,style:"background: #fff",
renderer:function(q,r,v){q.setHtml(b.tokenFreqTipTemplate.apply([r.get("term"),r.get("rawFreq"),r.get("relativeFreq")]))}},marker:{type:"circle"},highlight:{fillStyle:"yellow",strokeStyle:"black"},renderer:function(q,r,v,x){q=v.store.getAt(x);if(null!==q){var z=q.get("cluster");-1===z&&(z=0);v=.65;x=1;!0===q.get("disabled")?x=v=.1:3===d&&q.get("z")&&(v=b.interpolate(q.get("z"),u,n,0,1));z=b.getApplication().getColor(z);r.fillStyle="rgba("+z.join(",")+","+v+")";r.strokeStyle="rgba("+z.join(",")+","+
x+")";q=q.get("rawFreq");q=b.interpolate(q,m,l,2,20);r.radius=q}},scope:this},{type:"customScatter",xField:"x",yField:"y",store:g,label:{font:"14px Helvetica",field:"term",display:"over",color:this.getDefaultDocColor(!0)},tooltip:{trackMouse:!0,style:"background: #fff",renderer:function(q,r,v){q.setHtml(b.docFreqTipTemplate.apply([r.get("title"),r.get("rawFreq")]))}},marker:{type:"diamond"},highlight:{fillStyle:"yellow",strokeStyle:"black"},renderer:function(q,r,v,x){q=v.store.getAt(x);null!==q&&
(v=q.get("cluster"),v=-1===v||"docSim"!==b.getApiParam("analysis")?b.getDefaultDocColor():b.getApplication().getColor(v),x=.65,3===d&&q.get("z")&&(x=b.interpolate(q.get("z"),u,n,0,1)),r.fillStyle="rgba("+v.join(",")+","+x+")",r.strokeStyle="rgba("+v.join(",")+",1)",r.radius=5)},scope:this}],listeners:{itemclick:function(q,r,v){q=r.record.data;"doc"===q.category?(q=this.getCorpus().getDocument(q.docIndex),this.getApplication().dispatchEvent("documentsClicked",this,[q])):"term"===q.category&&(q=Ext.create("Voyant.data.model.CorpusTerm",
q),this.getApplication().dispatchEvent("corpusTermsClicked",this,[q]))},render:function(q){q.body.on("contextmenu",function(r,v){r.preventDefault();r=r.getXY();var x=Ext.fly(v).getXY();v=r[0]-x[0];x=r[1]-x[1];var z=this.down("#chart").getItemForPoint(v,x);null!=z&&"term"===z.record.get("category")&&(v=this.down("#chart").getSeries(),v[0].disableToolTips(),v[1].disableToolTips(),x=z.record.get("term"),v=(new Ext.Template(this.localize("removeTerm"))).apply([x]),this.getChartMenu().queryById("remove").setText(v),
v=(new Ext.Template(this.localize("nearbyTerm"))).apply([x]),x=this.getChartMenu().queryById("nearby"),x.setText(v),x.setDisabled("tsne"===this.getApiParam("analysis")),this.getChartMenu().on("click",function(L,H){void 0!==H&&(L=z.record.get("term"),"nearby"===H.getItemId()?this.getNearbyForTerm(L):this.removeTerm(L))},this,{single:!0}),this.getChartMenu().showAt(r))},this)},scope:this}};a=Ext.create("Ext.chart.CartesianChart",a);this.queryById("chartParent").insert(0,a);this.queryById("chartParent").unmask();
this.doLabels();null!==this.getNewTerm()&&(this.selectTerm(this.getNewTerm()[0]),this.setNewTerm(null))},getDefaultDocColor:function(a){return this.getApplication().getColor(6,a)},doLabels:function(){var a=this.queryById("chart"),b=a.getSeries();a=a.getSurface("chart").getItems()[0];var c=this.getApiParam("label");-1<c.indexOf("summary")?a.show():a.hide();-1<c.indexOf("terms")?b[0].getLabel().show():b[0].getLabel().hide();-1<c.indexOf("docs")?b[1].getLabel().show():b[1].getLabel().hide()},selectTerm:function(a,
b){var c=this.down("#chart");if(null!==c)if(void 0===a)c.getSeries()[0].setHighlightItem(null),c.getSeries()[1].setHighlightItem(null);else{if(!0===b){var d=c.getSeries()[1];a=d.getStore().findExact("title",a)}else d=c.getSeries()[0],a=d.getStore().findExact("term",a);if(-1!==a){var e=d.getStore().getAt(a),f=d.getSprites()[0];e={series:d,category:d.getItemInstancing()?"items":"markers",index:a,record:e,field:d.getYField(),sprite:f};d.setHighlightItem(e);b?c.getSeries()[0].setHighlightItem(null):c.getSeries()[1].setHighlightItem(null);
b=this.getPointFromIndex(d,a);this.setHighlightData({x:b[0],y:b[1],r:50});null==this.getHighlightTask()&&this.setHighlightTask(Ext.TaskManager.newTask({run:this.doHighlight,scope:this,interval:25,repeat:this.getHighlightData().r}));this.getHighlightTask().restart()}}},getPointFromIndex:function(a,b){a=a.getSprites()[0];return null!==a.surfaceMatrix?a.attr.matrix.clone().prependMatrix(a.surfaceMatrix).transformPoint([a.attr.dataX[b],a.attr.dataY[b]]):[0,0]},doHighlight:function(){var a=this.down("#chart");
if(0<this.getHighlightData().r){for(var b=a.getSurface(),c=null,d=b.getItems(),e=0;e<d.length;e++){var f=d[e];if("customHighlight"==f.id){c=f;break}}null==c?b.add({id:"customHighlight",type:"circle",strokeStyle:"red",fillStyle:"none",radius:this.getHighlightData().r,x:this.getHighlightData().x,y:this.getHighlightData().y}):(c.setAttributes({x:this.getHighlightData().x,y:this.getHighlightData().y,radius:this.getHighlightData().r}),this.getHighlightData().r-=1.5,0>=this.getHighlightData().r&&(this.getHighlightData().r=
0,b.remove(c,!0)));a.redraw()}},filterChart:function(a){Ext.isString(a)&&(a=[a]);for(var b=[],c=0;c<a.length;c++)b.push(new RegExp(a[c]));a=this.queryById("chart");c=a.getSeries()[0];var d=c.getLabel();c.getStore().each(function(e){var f=!1;if(0==b.length)f=!0;else for(var g=0;g<b.length&&!(f=f||b[g].test(e.get("term")));g++);e.set("disabled",!f);e=e.store.indexOf(e);d.setAttributesFor(e,{hidden:!f})},this);a.redraw()},getCurrentTerms:function(){var a=[];this.getTermStore().each(function(b){"term"===
b.get("category")&&a.push(b.get("term"))});return a},getNearbyForTerm:function(a){var b=Math.max(2E3,Math.round(this.getCorpus().getWordTokensCount()/100));this.setApiParams({limit:b,target:a});this.loadFromApis();this.setApiParam("target",void 0)},removeTerm:function(a){var b=this.down("#chart").getSeries()[0],c=b.getStore().findExact("term",a);b.getStore().removeAt(c);c=this.getTermStore().findExact("term",a);this.getTermStore().removeAt(c);a=this.getTermStore().getCount();this.queryById("limit").setRawValue(a)},
loadFromApis:function(a){this.queryById("chartParent").mask(this.localize("analyzing"));var b={},c=this.getCurrentTerms();null!==this.getNewTerm()&&(c=c.concat(this.getNewTerm()),this.setApiParam("limit",c.length));0<c.length&&(null!==this.getNewTerm()||a)&&(b.query=c.join(","));Ext.apply(b,this.getApiParams());null!=b.target&&(b.term=c);"pca"===b.analysis?this.getPcaStore().load({params:b}):"tsne"===b.analysis?this.getTsneStore().load({params:b}):"docSim"===b.analysis?this.getDocSimStore().load({params:b}):
this.getCaStore().load({params:b})},interpolate:function(a,b,c,d,e){return d+(e-d)*Math.max(0,Math.min(1,(a-b)/(c-b)))}});Ext.define("Ext.chart.series.CustomScatter",{extend:"Ext.chart.series.Scatter",alias:"series.customScatter",type:"customScatter",seriesType:"scatterSeries",tipsDisabled:!1,enableToolTips:function(){this.tipsDisabled=!1},disableToolTips:function(){this.tipsDisabled=!0},showTip:function(a,b){this.tipsDisabled||this.callParent(arguments)}});Ext.define("Voyant.panel.StreamGraph",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.streamgraph",statics:{i18n:{},api:{limit:5,stopList:"auto",query:void 0,withDistributions:"relative",bins:50,docIndex:void 0,docId:void 0},glyph:"xf1fe@FontAwesome"},config:{visLayout:void 0,vis:void 0,mode:"corpus",layerData:void 0,graphId:void 0,options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}]},graphMargin:{top:20,right:60,bottom:110,left:80},MODE_CORPUS:"corpus",MODE_DOCUMENT:"document",
constructor:function(a){this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.setGraphId(Ext.id(null,"streamgraph_"))},initComponent:function(){Ext.apply(this,{title:this.localize("title"),tbar:new Ext.Toolbar({overflowHandler:"scroller",items:["-\x3e",{xtype:"legend",store:new Ext.data.JsonStore({fields:["name","mark","active"]}),listeners:{itemclick:function(a,b,c,d){a=Ext.fly(c.firstElementChild).hasCls("x-legend-inactive");b.set("active",a);b=this.getCurrentTerms();
this.setApiParams({query:b,limit:b.length,stopList:void 0,categories:this.getApiParam("categories")});this.loadFromCorpus()},scope:this}},"-\x3e"]}),bbar:{overflowHandler:"scroller",items:[{xtype:"querysearchfield"},{xtype:"button",text:this.localize("clearTerms"),handler:function(){this.setApiParams({query:void 0});this.loadFromRecords([])},scope:this},{xtype:"corpusdocumentselector",singleSelect:!0},{text:this.localize("freqsMode"),glyph:"xf201@FontAwesome",tooltip:this.localize("freqsModeTip"),
menu:{items:[{text:this.localize("relativeFrequencies"),checked:!0,itemId:"relative",group:"freqsMode",checkHandler:function(a,b){b&&(this.setApiParam("withDistributions","relative"),this.loadFromCorpus())},scope:this},{text:this.localize("rawFrequencies"),checked:!1,itemId:"raw",group:"freqsMode",checkHandler:function(a,b){b&&(this.setApiParam("withDistributions","raw"),this.loadFromCorpus())},scope:this}]}},{xtype:"slider",itemId:"segmentsSlider",fieldLabel:this.localize("segments"),labelAlign:"right",
labelWidth:70,width:150,increment:10,minValue:10,maxValue:300,listeners:{afterrender:function(a){a.setValue(this.getApiParam("bins"))},changecomplete:function(a,b){this.setApiParams({bins:b});this.loadFromCorpus()},scope:this}}]}});this.on("loadedCorpus",function(a,b){1==this.getCorpus().getDocumentsCount()&&this.getMode()!=this.MODE_DOCUMENT&&this.setMode(this.MODE_DOCUMENT);"bins"in this.getModifiedApiParams()||this.getMode()!=this.MODE_CORPUS||(a=b.getDocumentsCount(),this.setApiParam("bins",100<
a?100:a));this.isVisible()&&this.loadFromCorpus()},this);this.on("corpusSelected",function(a,b){a.isXType("corpusdocumentselector")&&(this.setMode(this.MODE_CORPUS),this.setApiParams({docId:void 0,docIndex:void 0}),this.setCorpus(b),this.loadFromCorpus())});this.on("documentSelected",function(a,b){a=b.getId();this.setApiParam("docId",a);this.loadFromDocumentTerms()},this);this.on("query",function(a,b){a=this.getCurrentTerms();a.push(b);this.setApiParams({query:a,limit:a.length,stopList:void 0});this.getMode()===
this.MODE_DOCUMENT?this.loadFromDocumentTerms():this.loadFromCorpusTerms(this.getCorpus().getCorpusTerms())},this);this.on("resize",this.resizeGraph,this);this.on("boxready",this.initGraph,this);this.callParent(arguments)},loadFromCorpus:function(){var a=this.getCorpus();this.getApiParam("docId")||this.getApiParam("docIndex")?this.loadFromDocumentTerms():1==a.getDocumentsCount()?this.loadFromDocument(a.getDocument(0)):this.loadFromCorpusTerms(a.getCorpusTerms())},loadFromCorpusTerms:function(a){var b=
this.getApiParams("limit stopList query withDistributions bins categories".split(" "));b.bins&&b.bins>this.getCorpus().getDocumentsCount()&&(b.bins=this.getCorpus().getDocumentsCount());a.load({callback:function(c,d,e){e?(this.setMode(this.MODE_CORPUS),this.loadFromRecords(c)):Voyant.application.showResponseError(this.localize("failedGetCorpusTerms"),d)},scope:this,params:b})},loadFromDocument:function(a){if(a.then){var b=this;a.then(function(c){b.loadFromDocument(c)})}else"Voyant.data.model.Document"==
Ext.getClassName(a)&&(this.setApiParams({docIndex:void 0,query:void 0,docId:a.getId()}),this.isVisible()&&this.loadFromDocumentTerms())},loadFromDocumentTerms:function(a){this.getCorpus()&&(a=a||this.getCorpus().getDocumentTerms({autoLoad:!1}),a.load({callback:function(b,c,d){d?(this.setMode(this.MODE_DOCUMENT),this.loadFromRecords(b)):Voyant.application.showResponseError(this.localize("failedGetDocumentTerms"),c)},scope:this,params:this.getApiParams("docId docIndex limit stopList query withDistributions bins categories".split(" "))}))},
loadFromRecords:function(a){var b=[],c=[];a.forEach(function(d,e){e=d.getTerm();d=d.get("distributions");for(var f=0;f<d.length;f++)void 0===c[f]&&(c[f]={}),c[f][e]=d[f];b.push({id:e,name:e,mark:this.getApplication().getColorForTerm(e,!0),active:!0})},this);this.setLayerData(c);this.down("[xtype\x3dlegend]").getStore().loadData(b);this.doLayout()},doLayout:function(a){a=this.getLayerData();if(void 0!==a){var b=this,c=[];this.down("[xtype\x3dlegend]").getStore().each(function(n){c.push(n.getId())});
if(this.getMode()===this.MODE_DOCUMENT)var d=this.getApiParam("bins");else{d=this.getApiParam("bins");var e=this.getCorpus().getDocumentsCount();d=d<e?d:e}this.getVisLayout().keys(c);e=this.getVisLayout()(a);a=this.body.down("svg").getWidth()-this.graphMargin.left-this.graphMargin.right;var f=d3.scaleLinear().domain([0,d-1]).range([0,a]),g=d3.min(e,function(n){return d3.min(n,function(u){return u[0]})}),h=d3.max(e,function(n){return d3.max(n,function(u){return u[1]})});d=this.body.down("svg").getHeight()-
this.graphMargin.top-this.graphMargin.bottom;var k=d3.scaleLinear().domain([g,h]).range([d,0]),l=d3.area().x(function(n,u){return f(u)}).y0(function(n){return k(n[0])}).y1(function(n){return k(n[1])}).curve(d3.curveCatmullRom);if(this.getMode()===this.MODE_CORPUS){var m=[];this.getCorpus().getDocuments().each(function(n){m.push(n.getTinyLabel())});g=d3.scalePoint().domain(m).range([0,a]);h=d3.axisBottom(g)}else h=d3.axisBottom(f);g=d3.axisLeft(k);e=this.getVis().selectAll("path").data(e,function(n){return n});
e.attr("d",function(n){return l(n)}).style("fill",function(n){return b.getApplication().getColorForTerm(n.key,!0)}).select("title").text(function(n){return n.key});e.enter().append("path").attr("d",function(n){return l(n)}).style("fill",function(n){return b.getApplication().getColorForTerm(n.key,!0)}).append("title").text(function(n){return n.key});e.exit().remove();this.getVis().selectAll("g.axis").remove();this.getVis().append("g").attr("class","axis x").attr("transform","translate(0,"+d+")").call(h);
this.getMode()===this.MODE_CORPUS?(this.getVis().select("g.axis.x").selectAll("text").each(function(){d3.select(this).attr("text-anchor","end").attr("transform","rotate(-45)")}),e=this.localize("documents")):e=this.localize("documentSegments");this.getVis().select("g.axis.x").append("text").attr("text-anchor","middle").attr("transform","translate("+a/2+", "+(this.graphMargin.bottom-30)+")").attr("fill","#000").text(e);this.getVis().append("g").attr("class","axis y").attr("transform","translate(0,0)").call(g);
a="raw"===this.getApiParam("withDistributions")?this.localize("rawFrequencies"):this.localize("relativeFrequencies");this.getVis().select("g.axis.y").append("text").attr("text-anchor","middle").attr("transform","translate(-"+(this.graphMargin.left-20)+", "+d/2+") rotate(-90)").attr("fill","#000").text(a)}},getCurrentTerms:function(){var a=[];this.down("[xtype\x3dlegend]").getStore().each(function(b){b.get("active")&&a.push(b.get("name"))},this);return a},initGraph:function(){if(void 0===this.getVisLayout()){var a=
this.getLayout().getRenderTarget();this.setVisLayout(d3.stack().offset(d3.stackOffsetWiggle).order(d3.stackOrderInsideOut));this.setVis(d3.select(a.dom).append("svg").attr("id",this.getGraphId()).append("g").attr("transform","translate("+this.graphMargin.left+","+this.graphMargin.top+")"));this.resizeGraph()}},resizeGraph:function(){var a=this.body,b=a.getWidth(),c=a.getHeight();d3.select(a.dom).select("svg").attr("width",b).attr("height",c);this.doLayout()}});Ext.define("Voyant.panel.Summary",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.summary",statics:{i18n:{readabilityIndex:"Readability Index:",docsDensityTip:"ratio of unique words in this document",avgWordsPerSentenceTip:"average words per sentence in this document",readabilityTip:"the Coleman-Liau readability index for this document"},api:{stopList:"auto",start:0,limit:5,numberOfDocumentsForDistinctiveWords:10},glyph:"xf1ea@FontAwesome"},config:{options:[{xtype:"stoplistoption"},
{xtype:"categoriesoption"}]},autoScroll:!0,cls:"corpus-summary",constructor:function(a){Ext.apply(this,{title:this.localize("title"),items:{itemId:"main",cls:"main",margin:10},dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{fieldLabel:this.localize("items"),labelWidth:40,width:120,xtype:"slider",increment:5,minValue:5,maxValue:59,listeners:{afterrender:function(b){b.setValue(this.getApiParam("limit"))},changecomplete:function(b,c){this.setApiParams({limit:c});this.loadSummary()},
scope:this}}]}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("afterrender",function(){this.body.addListener("click",function(b){(b=b.getTarget(null,null,!0))&&"A"==b.dom.tagName&&(b.hasCls("document-id")?(b=b.getAttribute("val","voyant"),b=this.getCorpus().getDocuments().getById(b),this.dispatchEvent("documentsClicked",this,[b])):b.hasCls("corpus-type")?this.dispatchEvent("termsClicked",this,[b.getHtml()]):b.hasCls("document-type")&&this.dispatchEvent("documentIndexTermsClicked",
this,[{term:b.getHtml(),docIndex:b.getAttribute("docIndex","voyant")}]))},this)});this.on("loadedCorpus",function(b,c){if(this.rendered)this.loadSummary();else this.on("afterrender",function(){this.loadSummary()},this)});a&&a.corpus&&this.fireEvent("loadedCorpus",this,a.corpus);this.on("resize",function(){var b=this.getWidth()-200;this.query("sparklineline").forEach(function(c){c.getWidth()>b&&c.setWidth(b)})},this)},loadSummary:function(){var a=this,b=this.queryById("main");b.removeAll();b.add({cls:"section",
html:this.getCorpus().getString()});var c=this.getCorpus().getDocuments().getRange(),d=this.getApiParam("limit");if(1<c.length){var e=new Ext.XTemplate('\x3ctpl for\x3d"." between\x3d"; "\x3e\x3ca href\x3d"#" onclick\x3d"return false" class\x3d"document-id" voyant:val\x3d"{id}" data-qtip\x3d"{title}"\x3e{shortTitle}\x3c/a\x3e\x3cspan style\x3d"font-size: smaller"\x3e (\x3cspan class\x3d"info-tip" data-qtip\x3d"{valTip}"\x3e{val}\x3c/span\x3e)\x3c/span\x3e\x3c/a\x3e\x3c/tpl\x3e');if(25>c.length)var f=
4*c.length;else if(50>c.length)f=2*c.length;else if(100<c.length){var g=b.getWidth()-200;f=g<c.length?c.length:g}this.localize("numberOfTerms");c.sort(function(h,k){return k.getLexicalTokensCount()-h.getLexicalTokensCount()});b.add(this.showSparklineSection(function(h){return h.getLexicalTokensCount()},this.localize("docsLength"),this.localize("longest"),this.localize("shortest"),c,d,e,f,this.localize("numberOfTerms")));c.sort(function(h,k){return k.getLexicalTypeTokenRatio()-h.getLexicalTypeTokenRatio()});
b.add(this.showSparklineSection(function(h){return Ext.util.Format.number(h.getLexicalTypeTokenRatio(),"0.000")},this.localize("docsDensity"),this.localize("highest"),this.localize("lowest"),c,d,e,f,this.localize("docsDensityTip")));c.sort(function(h,k){return k.getAverageWordsPerSentence()-h.getAverageWordsPerSentence()});b.add(this.showSparklineSection(function(h){return Ext.util.Format.number(h.getAverageWordsPerSentence(),"0.0")},this.localize("averageWordsPerSentence"),this.localize("highest"),
this.localize("lowest"),c,d,e,f,this.localize("avgWordsPerSentenceTip")))}else if(g=c[0])b.add({cls:"section",html:"\x3cb\x3e"+this.localize("docsDensity")+"\x3c/b\x3e "+Ext.util.Format.number(g.getLexicalTypeTokenRatio(),"0.000")}),b.add({cls:"section",html:"\x3cb\x3e"+this.localize("averageWordsPerSentence")+"\x3c/b\x3e "+Ext.util.Format.number(g.getAverageWordsPerSentence(),"0.0")});this.getCorpus().getReadability().then(function(h){c.forEach(function(l){var m=h.find(function(n){return n.docId===
l.getId()});m&&l.set("readability",m.readability)});var k=b.items.length-2;1<c.length?(c.sort(function(l,m){return m.get("readability")-l.get("readability")}),b.insert(k,a.showSparklineSection(function(l){return Ext.util.Format.number(l.get("readability"),"0.000")},a.localize("readabilityIndex"),a.localize("highest"),a.localize("lowest"),c,d,e,f,a.localize("readabilityTip")))):b.insert(k,{cls:"section",html:"\x3cb\x3e"+a.localize("readabilityIndex")+"\x3c/b\x3e "+Ext.util.Format.number(c[0].get("readability"),
"0.000")})});b.add({cls:"section",items:[{html:this.localize("mostFrequentWords"),cls:"header"},{cls:"contents",html:"\x3cul\x3e\x3cli\x3e\x3c/li\x3e\x3c/ul\x3e"}],listeners:{afterrender:function(h){h.mask(a.localize("loading"));a.getCorpus().getCorpusTerms().load({params:{limit:a.getApiParam("limit"),stopList:a.getApiParam("stopList"),forTool:"summary"},callback:function(k,l,m){m&&k&&0<k.length&&(h.unmask(),l=h.down("panel[cls~\x3dcontents]").getTargetEl().selectNode("li"),Ext.dom.Helper.append(l,
(new Ext.XTemplate('\x3ctpl for\x3d"." between\x3d"; "\x3e\x3ca href\x3d"#" onclick\x3d"return false" class\x3d"corpus-type keyword" voyant:recordId\x3d"{id}"\x3e{term}\x3c/a\x3e\x3cspan style\x3d"font-size: smaller"\x3e ({val})\x3c/span\x3e\x3c/tpl\x3e')).apply(k.map(function(n){return{id:n.getId(),term:n.getTerm(),val:n.getRawFreq()}}))))}})}}});1<c.length&&b.add({cls:"section",items:[{html:this.localize("distinctiveWords"),cls:"header"},{cls:"contents",html:"\x3col\x3e\x3c/ol\x3e"}],itemId:"distinctiveWords",
listeners:{afterrender:function(h){a.showMoreDistinctiveWords()}},scope:this})},showSparklineSection:function(a,b,c,d,e,f,g,h,k){var l=this;return{cls:"section",items:[{layout:"hbox",align:"bottom",items:[{html:b,cls:"header"},{xtype:"sparklineline",values:this.getCorpus().getDocuments().getRange().map(function(m){return a.call(l,m)}),tipTpl:new Ext.XTemplate("{[this.getDocumentTitle(values.x,values.y)]}",{getDocumentTitle:function(m,n){return"("+n+") "+this.panel.getCorpus().getDocument(m).getTitle()},
panel:l}),height:16,width:h}]},{cls:"contents",html:"\x3cul\x3e\x3cli\x3e"+c+" "+g.apply(e.slice(0,e.length>f?f:parseInt(e.length/2)).map(function(m){return{id:m.getId(),shortTitle:m.getShortTitle(),title:m.getTitle(),val:a.call(l,m),valTip:k}}))+"\x3c/li\x3e\x3cli\x3e"+d+" "+g.apply(e.slice(-(e.length>f?f:parseInt(e.length/2))).reverse().map(function(m){return{id:m.getId(),shortTitle:m.getShortTitle(),title:m.getTitle(),val:a.call(l,m),valTip:k}}))+"\x3c/li\x3e"}]}},showMoreDistinctiveWords:function(){var a=
this.queryById("distinctiveWords"),b=a.getTargetEl().selectNode("ol"),c=Ext.dom.Query.select("li:not(.more)",b).length,d=parseInt(this.getApiParam("numberOfDocumentsForDistinctiveWords")),e=this.getCorpus().getDocuments().getRange(c,c+d-1);if(e&&Ext.isArray(e)){var f=[];e.forEach(function(g){f.push(g.getIndex())});0<f.length&&this.getCorpus().getDocumentTerms().load({addRecords:!0,params:{docIndex:f,perDocLimit:parseInt(this.getApiParam("limit")),limit:d*parseInt(this.getApiParam("limit")),stopList:this.getApiParam("stopList"),
sort:"TFIDF",dir:"DESC",forTool:"summary"},scope:this,callback:function(g,h,k){var l={};if(k&&g&&Ext.isArray(g)){g.forEach(function(u,w,p){w=u.getDocIndex();w in l||(l[w]=[]);l[w].push({id:u.getId(),docIndex:u.getDocIndex(),type:u.getTerm(),val:Ext.util.Format.number(u.get("rawFreq"),"0,000"),docId:u.get("docId")})});f.forEach(function(u){if(l[u]){var w=this.getCorpus().getDocument(u);m=l[u].length;Ext.dom.Helper.append(b,{tag:"li","voyant:index":String(u),html:'\x3ca href\x3d"#" onclick\x3d"return false" class\x3d"document-id document-id-distinctive" voyant:val\x3d"'+
w.get("id")+'"\x3e'+w.getShortTitle()+"\x3c/a\x3e"+this.localize("colon")+" "+(new Ext.XTemplate(this.localize("documentType"))).apply({types:l[u]})+"."})}},this);a.updateLayout();var m=d;remaining=this.getCorpus().getDocuments().getTotalCount()-c-f.length;if(0<remaining){g=new Ext.Template(this.localize("moreDistinctiveWords"));var n=Ext.dom.Helper.append(b,{tag:"li",cls:"more",html:g.apply([m>remaining?remaining:m,remaining])},!0);n.on("click",function(){n.remove();this.showMoreDistinctiveWords()},
this)}}}})}},getExportVisualization:function(){return!1},getExtraDataExportItems:function(){return[{name:"export",inputValue:"dataAsTsv",boxLabel:this.localize("exportGridCurrentTsv")}]},exportDataAsTsv:function(a,b){var c="";a.query("panel[cls~\x3dsection]").forEach(function(d){var e="",f=d.down("panel[cls~\x3dheader]"),g=d.down("panel[cls~\x3dcontents]");f?(e+=f.getEl().dom.textContent+"\n",g&&g.getEl().select("li").elements.forEach(function(h){e+=h.textContent.replace(/:/,":\t").replace(/\)[,;]/g,
")\t")+"\n"})):e=d.getEl().dom.textContent+"\n";c+=e+"\n"});Ext.Msg.show({title:a.localize("exportDataTitle"),message:a.localize("exportDataTsvMessage"),buttons:Ext.Msg.OK,icon:Ext.Msg.INFO,prompt:!0,multiline:!0,value:c})}});Ext.define("Voyant.panel.TextualArc",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.textualarc",statics:{i18n:{},api:{stopList:"auto",docIndex:0,speed:50,minRawFreq:2},glyph:"xf06e@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"container",items:{xtype:"numberfield",name:"minRawFreq",minValue:1,maxValue:10,value:2,labelWidth:150,labelAlign:"right",initComponent:function(){var a=this.up("window").panel;this.fieldLabel=a.localize(this.fieldLabel);this.on("afterrender",
function(b){Ext.tip.QuickTipManager.register({target:b.getEl(),text:a.localize("minRawFreqTip")})});this.on("beforedestroy",function(b){Ext.tip.QuickTipManager.unregister(b.getEl())});this.callParent(arguments)},fieldLabel:"minRawFreq"}}],perim:[],diam:void 0},tokensFetch:500,constructor:function(){this.mixins["Voyant.util.Localization"].constructor.apply(this,arguments);this.config.options[1].fieldLabel=this.localize(this.config.options[1].fieldLabel);Ext.apply(this,{title:this.localize("title"),
html:'\x3ccanvas width\x3d"800" height\x3d"600"\x3e\x3c/canvas\x3e',dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"combo",itemId:"search",queryMode:"local",displayField:"term",valueField:"term",width:90,emptyText:this.localize("search"),forceSelection:!0,disabled:!0},{xtype:"documentselectorbutton",singleSelect:!0},{xtype:"slider",fieldLabel:this.localize("speed"),labelAlign:"right",labelWidth:40,width:100,increment:1,minValue:0,maxValue:100,value:30,listeners:{render:function(a){a.setValue(parseInt(this.getApiParam("speed")));
Ext.tip.QuickTipManager.register({target:a.getEl(),text:this.localize("speedTip")})},beforedestroy:function(a){Ext.tip.QuickTipManager.unregister(a.getEl())},changecomplete:function(a,b){this.setApiParam("speed",b);this.isReading=0!==b;this.draw()},scope:this}},{xtype:"tbfill"},{xtype:"tbtext",html:this.localize("adaptation")}]}]});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.on("boxready",function(a){var b=this.getTargetEl().dom.querySelector("canvas");
this.draw(b);b.addEventListener("mousemove",function(c){if(a.documentTerms){var d=b.getBoundingClientRect(),e=c.clientX-d.left,f=c.clientY-d.top,g={};a.documentTerms.each(function(h){var k=h.get("x"),l=h.get("y");if(k>e-15&&k<e+15&&l>f-15&&l<f+15)return g[h.getTerm()]=!0,!1});if(0!=Object.keys(a.currentTerms||{}).length||0!=Object.keys(g).length)a.currentTerms=g,a.draw(b)}},!1)});this.on("loadedCorpus",function(a,b){this.loadDocument()},this);this.on("documentselected",function(a,b){this.setApiParam("docIndex",
this.getCorpus().getDocument(b).getIndex());this.loadDocument()});this.on("resize",function(){var a=this.getTargetEl().getWidth()-20-20,b=this.getTargetEl().getHeight()-20-20,c=Math.max(a,b),d=c/2,e=Math.min(a,b)/c,f=this.getTargetEl().dom.querySelector("canvas");f.width=this.getTargetEl().getWidth();f.height=this.getTargetEl().getHeight();this.setDiam(c);this.setPerim([]);for(f=parseInt(.75*c);this.getPerim().length<c;)this.getPerim().push({x:20+a/2+d*(a>b?1:e)*Math.cos(2*Math.PI*f/c),y:20+b/2+d*
(b>a?1:e)*Math.sin(2*Math.PI*f/c)}),f++==c&&(f=0)})},draw:function(a,b){a=a||this.getTargetEl().dom.querySelector("canvas");b=b||a.getContext("2d");b.clearRect(0,0,a.width,a.height);b.fillStyle="rgba(0,0,0,.1)";this.getPerim().forEach(function(d,e){0==e%3&&b.fillRect(d.x-5,d.y,10,1)});if(this.documentTerms&&(this.drawTerms(a,b),this.drawReading(a,b),this.isReading)){var c=this;setTimeout(function(){c.draw()},10)}},drawReading:function(a,b){b=b||this.getTargetEl().dom.querySelector("canvas").getContext("2d");
var c=2E3-1999*parseInt(this.getApiParam("speed"))/100;if(this.isReading&&this.documentTerms){var d=parseInt(this.readingIndex*this.getPerim().length/this.lastToken);b.fillStyle="purple";b.fillRect(this.getPerim()[d].x,this.getPerim()[d].y,5,5);var e=void 0==this.readingStartTime;this.readingStartTime=this.readingStartTime||(new Date).getTime();d=this.readingStartTime+c-(new Date).getTime();if(this.sourceTerm&&this.targetTerm){if(e||0>=d){this.previousBeziers=this.previousBeziers||[];e=this.sourceTerm.get("x");
var f=this.sourceTerm.get("y"),g=this.targetTerm.get("x"),h=this.targetTerm.get("y");this.previousTerm&&this.previousTerm.get("x");this.previousTerm&&this.previousTerm.get("y");var k=Math.max(100,.5*Math.abs(e-g)),l=Math.max(100,.5*Math.abs(f-h));this.previousBeziers.unshift([e,f,e>g?e-k:e+k,h>f?f+l:f-l,g,h]);10<this.previousBeziers.length&&this.previousBeziers.pop()}for(e=0;e<this.previousBeziers.length;e++)b.strokeStyle="rgba(0,0,255,"+(1-.1*e)+")",this.drawBezierSplit.apply(this,Ext.Array.merge([b],
this.previousBeziers[e],[e+1==this.previousBeziers.length?1-d/c:0],[0==e?1-d/c:1]));0>=d&&(this.readingStartTime=void 0,this.read())}e=this.readingIndex+1;for(f=this.tokens.getCount();e<f&&this.tokens.getAt(e).getTerm().toLowerCase()!=this.targetTerm.getTerm();e++);c=e-parseInt(d*(e-this.readingIndex)/c);for(d=this.tokens.getCount();c<e&&!(c<d&&this.tokens.getAt(c).isWord());c++);c=this.tokens.getRange(c,f=Math.min(this.readingIndex+50,this.tokens.getCount())).map(function(m){return m.getTerm()});
b.font="14px sans-serif";b.fillStyle="rgba(0,0,0,.5)";b.textAlign="left";b.fillText(c.join(""),a.width/4,a.height-5);b.clearRect(.75*a.width,a.height-20,a.width,30)}else this.documentTerms&&this.documentTerms.getCount()<this.documentTerms.getTotalCount()&&(c=a.width/4,b.strokeStyle="rgba(0,0,0,.5)",b.fillStyle="rgba(0,0,0,.2)",b.strokeRect(c,a.height-12,2*c,10),b.fillRect(c,a.height-12,this.documentTerms.getCount()*c*2/this.documentTerms.getTotalCount(),10))},drawTerms:function(a,b){a=a||this.getTargetEl().dom.querySelector("canvas");
b=b||a.getContext("2d");b.textAlign="center";this.documentTerms&&0<this.getPerim().length&&this.documentTerms.each(function(c){var d=c.getRawFreq(),e=c.getTerm(),f=c.get("x"),g=c.get("y");isCurrentTerm=this.currentTerms&&e in this.currentTerms;isReadingTerm=this.sourceTerm&&this.sourceTerm.getTerm()==e;b.font=10*a.width/800*Math.log(d)/Math.log(this.maxRawFreq)+(isCurrentTerm||isReadingTerm?10:5)+"px sans-serif";b.fillStyle=isCurrentTerm?"red":isReadingTerm?"blue":"rgba(0,0,0,"+(.9*d/this.maxRawFreq+
.1)+")";if(isCurrentTerm||isReadingTerm)b.strokeStyle=isCurrentTerm?"rgba(255,0,0,.2)":"rgba(0,255,0,.4)",c.getDistributions().forEach(function(h,k){0<h&&this.getPerim()[k]&&(b.beginPath(),b.moveTo(f,g),b.lineTo(this.getPerim()[k].x,this.getPerim()[k].y),b.stroke())},this);b.fillText(e,f,g)},this)},read:function(a){Ext.isNumber(a)?this.readingIndex=a:this.readingIndex++;this.sourceTerm&&(this.previousTerm=this.sourceTerm);a=this.readingIndex;for(var b=this.tokens.getCount();a<b;a++){var c=this.tokens.getAt(a);
c=c.getTerm().toLowerCase();if(c in this.termsMap&&(this.sourceTerm=this.termsMap[c],1<=this.sourceTerm.getRawFreq())){this.readingIndex=a;break}}a=this.readingIndex+1;for(b=this.tokens.getCount();a<b&&!(c=this.tokens.getAt(a),c=c.getTerm().toLowerCase(),c in this.termsMap&&(this.targetTerm=this.termsMap[c],1<=this.targetTerm.getRawFreq()));a++);!this.tokensLoading&&this.tokens.getCount()-this.readingIndex<this.tokensFetch&&this.fetchMoreTokens();this.draw()},loadDocument:function(){this.documentTerms&&
(this.documentTerms.destroy(),this.documentTerms=void 0);this.termsMap={};this.draw();var a=this.getCorpus().getDocument(parseInt(this.getApiParam("docIndex")));this.up("tabpanel")||this.setTitle(this.localize("title")+" \x3cspan class\x3d'subtitle'\x3e"+a.getFullLabel()+"\x3c/span\x3e");this.lastToken=parseInt(a.get("lastTokenStartOffset-lexical"));this.documentTerms=a.getDocumentTerms({proxy:{extraParams:{stopList:this.getApiParam("stopList"),bins:this.getDiam(),withDistributions:"raw",minRawFreq:parseInt(this.getApiParam("minRawFreq"))}}});
a=this.queryById("search");a.setDisabled(!0);a.setStore(this.documentTerms);this.fetchMoreDocumentTerms()},fetchMoreDocumentTerms:function(){this.documentTerms?this.documentTerms.load({params:{start:this.documentTerms.getCount(),limit:0==this.documentTerms.getCount()?10:250},callback:function(a){0<a.length?(this.maxRawFreq=this.documentTerms.max("rawFreq"),a.forEach(function(b){var c=y=0;b.get("distributions").forEach(function(d,e){c+=this.getPerim()[e].x*d;y+=this.getPerim()[e].y*d},this);b.set("x",
c/b.getRawFreq());b.set("y",y/b.getRawFreq())},this),Ext.Function.defer(this.fetchMoreDocumentTerms,0,this),this.draw()):(this.queryById("search").setDisabled(!1),this.termsMap={},this.documentTerms.each(function(b){this.termsMap[b.getTerm()]=b},this),this.tokens&&this.tokens.removeAll(!0),this.fetchMoreTokens())},addRecords:!0,scope:this}):this.loadDocument()},fetchMoreTokens:function(){if(!this.tokens)this.tokens=this.getCorpus().getDocument(parseInt(this.getApiParam("docIndex"))).getTokens({proxy:{extraParams:{stripTags:"all"}}}),
this.noMoreTokens=!1;else if(this.noMoreTokens)return;var a=0==this.tokens.getCount();this.tokensLoading=!0;var b=parseInt(this.getApiParam("speed"));this.tokens.load({params:{start:this.tokens.getCount(),limit:50==b&&a?200:Math.pow(110-b,2)},callback:function(c){this.tokensLoading=!1;0<c.length?(c.forEach(function(d){"other"==d.getTokenType()&&d.set("term",d.getTerm().replace(/\s+/g," "))}),a&&(this.previousBeziers=[],this.isReading=!0,this.read(0))):this.noMoreTokens=!0},addRecords:!0,scope:this})},
animatePathDrawing:function(a,b,c,d,e,f,g,h){var k=null,l=function(m){null===k&&(k=m);m=Math.min((m-k)/h,1);a.clearRect(0,0,a.canvas.width,a.canvas.height);drawBezierSplit(a,b,c,d,e,f,g,0,m);1>m&&window.requestAnimationFrame(l)};window.requestAnimationFrame(l)},drawBezierSplit:function(a,b,c,d,e,f,g,h,k){a.beginPath();if(0==h&&1==k)a.moveTo(b,c),a.quadraticCurveTo(d,e,f,g);else if(h!=k){var l=h*h,m=1-h,n=m*m,u=2*h*m,w=n*b+u*d+l*f,p=n*c+u*e+l*g;l=k*k;m=1-k;n=m*m;u=2*k*m;m=n*b+u*d+l*f;l=n*c+u*e+l*g;
b=this.lerp(this.lerp(b,d,h),this.lerp(d,f,h),k);c=this.lerp(this.lerp(c,e,h),this.lerp(e,g,h),k);a.moveTo(w,p);a.quadraticCurveTo(b,c,m,l)}a.stroke();a.closePath()},lerp:function(a,b,c){return(1-c)*a+c*b}});Ext.define("Voyant.panel.TopicContexts",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.topiccontexts",statics:{i18n:{},api:{},glyph:"xf06e@FontAwesome"},constructor:function(a){Ext.apply(this,{title:this.localize("title"),cls:"twic_body"});this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments)},listeners:{loadedCorpus:function(a,b){this.loadFromCorpus(b)}},loadFromCorpus:function(a){a=Ext.Loader.getPath("resources")+"/twic/current/data/input/json";
var b=TWiC.Level.prototype.Instance();b.LoadJSON(a+"/twic_corpusinfo.json",a+"/twic_corpusmap.json");var c=this;b.m_queue.await(function(){var d=[],e=[],f=new TWiC.TopicBar({x:0,y:635},{width:1280,height:165},"dickinson",b,[]);e.push(f);var g=new TWiC.DocumentBar({x:1055,y:0},{width:225,height:635},"dickinson",b,[]);e.push(g);g=new TWiC.CorpusClusterView({x:0,y:0},{width:1055,height:635},"dickinson",b,[f,g]);d.push(g);f.m_linkedViews.push(g);f=c.getLayout().getRenderTarget();b.Initialize([0,0],{width:f.getWidth(),
height:f.getHeight()},"dickinson",d,e,"#"+f.getId());b.Start()}.bind(b))}});Ext.define("Voyant.panel.TermsBerry",{extend:"Ext.panel.Panel",mixins:["Voyant.panel.Panel"],alias:"widget.termsberry",statics:{i18n:{},api:{stopList:"auto",context:2,numInitialTerms:75,query:void 0,docIndex:void 0,docId:void 0,categories:void 0},glyph:"xf1db@FontAwesome"},config:{options:[{xtype:"stoplistoption"},{xtype:"categoriesoption"}],mode:void 0,scalingFactor:3,minRawFreq:void 0,maxRawFreq:void 0,maxCollocateValue:void 0,minFillValue:void 0,maxFillValue:void 0,currentData:{},blacklist:{},
visLayout:void 0,vis:void 0,visInfo:void 0,visId:void 0,currentNode:void 0,tip:void 0,contextMenu:void 0},MODE_TOP:"top",MODE_DISTINCT:"distinct",MIN_TERMS:5,MAX_TERMS:500,COLLOCATES_LIMIT:1E6,MIN_SCALING:1,MAX_SCALING:5,MIN_STROKE_OPACITY:.1,MAX_STROKE_OPACITY:.3,layout:"fit",constructor:function(a){this.setMode(this.MODE_TOP);this.callParent(arguments);this.mixins["Voyant.panel.Panel"].constructor.apply(this,arguments);this.setVisId(Ext.id(null,"termspack_"))},initComponent:function(){Ext.apply(this,
{title:this.localize("title"),dockedItems:[{dock:"bottom",xtype:"toolbar",overflowHandler:"scroller",items:[{xtype:"querysearchfield",clearOnQuery:!0},{xtype:"button",text:this.localize("strategy"),menu:{items:[{xtype:"menucheckitem",group:"strategy",checked:this.getMode()===this.MODE_TOP,text:this.localize("topTerms"),checkHandler:function(a,b){b&&(this.setMode(this.MODE_TOP),this.doLoad())},scope:this},{xtype:"menucheckitem",group:"strategy",checked:this.getMode()===this.MODE_DISTINCT,text:this.localize("distinctTerms"),
checkHandler:function(a,b){b&&(this.setMode(this.MODE_DISTINCT),this.doLoad())},scope:this}]}},{fieldLabel:this.localize("numTerms"),labelWidth:50,labelAlign:"right",width:120,xtype:"slider",increment:1,minValue:this.MIN_TERMS,maxValue:this.MAX_TERMS,listeners:{afterrender:function(a){a.setValue(parseInt(this.getApiParam("numInitialTerms")))},changecomplete:function(a,b){this.setApiParam("numInitialTerms",b);this.doLoad()},scope:this}},{fieldLabel:this.localize("context"),labelWidth:50,labelAlign:"right",
width:120,xtype:"slider",increment:1,minValue:1,maxValue:30,listeners:{afterrender:function(a){a.setValue(this.getApiParam("context"))},changecomplete:function(a,b){this.setApiParams({context:b});this.doLoad()},scope:this}},{fieldLabel:this.localize("scaling"),labelWidth:50,labelAlign:"right",width:120,xtype:"slider",increment:1,minValue:this.MIN_SCALING,maxValue:this.MAX_SCALING,listeners:{afterrender:function(a){a.setValue(this.getScalingFactor())},changecomplete:function(a,b){this.setScalingFactor(Math.abs(b-
(this.MAX_SCALING+1)));this.reload()},scope:this}}]}]});this.setContextMenu(Ext.create("Ext.menu.Menu",{renderTo:Ext.getBody(),items:[{xtype:"box",itemId:"label",margin:"5px 0px 5px 5px",html:""},{xtype:"menuseparator"},{xtype:"button",text:"Remove",style:"margin: 5px;",handler:function(a,b){a=this.getCurrentNode();void 0!==a&&(delete this.getCurrentData()[a.data.term],this.getBlacklist()[a.data.term]=!0,this.setCurrentNode(void 0));this.getContextMenu().hide();this.reload()},scope:this}]}));this.on("query",
function(a,b){0<b.length&&this.doLoad(b)},this);this.callParent(arguments)},listeners:{boxready:function(){this.initVisLayout()},resize:function(a,b,c){this.getVisLayout()&&this.getCorpus()&&(a=this.getLayout().getRenderTarget(),b=a.getWidth(),c=a.getHeight(),a.down("svg").set({width:b,height:c}),this.getVisLayout().size([b,c]),this.reload())},loadedCorpus:function(a,b){this.isVisible()&&this.doLoad()},activate:function(){this.getCorpus()&&this.doLoad()}},doLoad:function(a){this.resetVis();void 0===
a&&(this.resetMinMax(),this.setCurrentData({}));this.getMode()===this.MODE_DISTINCT?this.getDistinctTerms(a):this.getTopTerms(a)},reload:function(){var a=this.processCollocates([]);0<a.length&&(this.resetVis(),this.buildVisFromData(a))},resetMinMax:function(){this.setMinRawFreq(void 0);this.setMaxRawFreq(void 0);this.setMaxCollocateValue(void 0);this.setMinFillValue(void 0);this.setMaxFillValue(void 0)},resetVis:function(){var a=this.getVis();a&&a.selectAll(".node").remove()},getTopTerms:function(a){var b=
parseInt(this.getApiParam("numInitialTerms")),c=this.getApiParam("stopList"),d=this.getApiParam("categories");void 0!==a&&(c=b=void 0);this.getCorpus().getCorpusTerms().load({params:{query:a,categories:d,limit:b,stopList:c},callback:function(e,f,g){g&&this.loadFromRecords(e)},scope:this})},getDistinctTerms:function(a){var b=parseInt(this.getApiParam("numInitialTerms")),c=this.getApiParam("stopList"),d=this.getApiParam("categories");void 0!==a&&(c=b=void 0);var e=Math.ceil(parseInt(this.getApiParam("numInitialTerms"))/
this.getCorpus().getDocumentsCount());this.getCorpus().getDocumentTerms().load({params:{query:a,categories:d,limit:b,perDocLimit:e,stopList:c,sort:"TFIDF",dir:"DESC"},callback:function(f,g,h){h&&this.loadFromRecords(f)},scope:this})},loadFromQuery:function(a){this.getCorpus().getCorpusTerms().load({params:{query:a},callback:function(b,c,d){d&&this.loadFromRecords(b)},scope:this})},loadFromRecords:function(a){if(Ext.isArray(a)&&0<a.length){var b=this.getMaxRawFreq(),c=this.getMinRawFreq(),d=this.getMinFillValue(),
e=this.getMaxFillValue(),f=[];a.forEach(function(g){var h=g.getTerm();if(!this.getBlacklist()[h]){var k=g.getRawFreq(),l=this.getMode()===this.MODE_DISTINCT?g.get("tfidf"):g.getInDocumentsCount();if(void 0===b||k>b)b=k;if(void 0===c||k<c)c=k;if(void 0===e||l>e)e=l;if(void 0===d||l<d)d=l;this.getCurrentData()[h]={term:h,rawFreq:k,relativeFreq:g.get("relativeFreq"),fillValue:l,collocates:[]};f.push(h)}},this);this.setMaxRawFreq(b);this.setMinRawFreq(c);this.setMinFillValue(d);this.setMaxFillValue(e);
this.getCollocatesForQuery(f)}},getCollocatesForQuery:function(a){var b=[];for(c in this.getCurrentData())b.push(c);this.setApiParams({mode:"corpus"});var c=this.getApiParams();this.getCorpus().getCorpusCollocates().load({params:Ext.apply(Ext.clone(c),{query:a,collocatesWhitelist:b,limit:this.COLLOCATES_LIMIT}),callback:function(d,e,f){f&&this.buildVisFromData(this.processCollocates(d))},scope:this})},processCollocates:function(a){for(var b=this.getCurrentData(),c=this.getMaxCollocateValue(),d=0;d<
a.length;d++){var e=a[d],f=e.getTerm(),g=e.getContextTerm();e=e.getContextTermRawFreq();if(void 0===c||e>c)c=e;void 0!==b[f]&&f!=g&&b[f].collocates.push({term:g,value:e})}this.setMaxCollocateValue(c);a=[];for(f in b)a.push(b[f]);return a},buildVisFromData:function(a){var b=this;if(this.getVis()){a.push({term:"$$$root$$$",collocates:[],rawFreq:1});var c=d3.stratify().id(function(h){return h.term}).parentId(function(h){return"$$$root$$$"!==h.term?"$$$root$$$":""})(a).sort(function(h,k){return h.rawFreq<
k.rawFreq?1:h.rawFreq>k.rawFreq?-1:0}).sum(function(h){return Math.pow(h.rawFreq,1/b.getScalingFactor())});this.getVisLayout()(c);c=this.getVis().selectAll(".node").data(c.descendants());c.attr("transform",function(h){return"translate("+h.x+","+h.y+")"});c.selectAll("circle").attr("r",function(h){return h.r});var d=d3.scalePow().exponent(1/3).domain([0,this.getMaxCollocateValue()]).range(["#fff","#bd3163"]);var e=this.getMode()===this.MODE_DISTINCT?d3.scalePow().exponent(.2).domain([this.getMinFillValue(),
this.getMaxFillValue()]).range(["#dedede","#fff"]):d3.scaleLinear().domain([this.getMaxFillValue(),this.getMinFillValue()]).range(["#dedede","#fff"]);var f=this.getVisLayout().size();f=Math.min(f[0],f[1])/2;a=Math.sqrt(Math.PI*f*f/a.length/Math.PI)/3;f=Math.abs(this.getScalingFactor()-(this.MAX_SCALING+1));f=Math.max(1,f-1);f*=a;var g=d3.scaleLinear().domain([this.getMinRawFreq(),this.getMaxRawFreq()]).range([a,f]);a=c.enter().append("g").attr("class","node").style("visibility",function(h){return 0<