This repository has been archived by the owner on Mar 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
1182 lines (1039 loc) · 38.8 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var $app = (function () {
// The languages and vocabularies available.
var _options = {
sq: {
name: 'Shqip',
webapp: 'https://l10n.org.al',
vocabularies: {
ICT_sq: 'Fjalori ICT',
huazime_sq: 'Fjalë të Huaja',
},
disqus: 'l10n-sq', // disqus shortname
translate_in_context_url: 'https://l10n.org.al/btr/project/dashohoxha/v.btranslator.org/',
keyboard: {
layout: 'custom',
customLayout: {
'normal' : [
"q w e r t y u i o p",
"a s d f g h j k l :",
"z x c v b n m ' \" !",
"\u00eb \u00e7 {bksp} {enter} {accept} {cancel}",
"{shift} {alt} . {space}",
],
'shift' : [
"Q W E R T Y U I O P",
"A S D F G H J K L ;",
"Z X C V B N M ` \u00a6 ?",
"\u00cb \u00c7 {tab} {enter} {accept} {cancel}",
"{shift} {alt} , {space}",
],
'alt' : [
"0 1 2 3 4 5 6 7 8 9",
"\u00a7 \u20ac $ # % _ - + = *",
"( ) [ ] { } < > / \\",
"& | ~ ^ {enter} {accept} {cancel}",
"{shift} {alt} @ {space}",
],
/*
'alt-shift' : [
"0 1 2 3 4 5 6 7 8 9",
"\u00a7 \u20ac $ # % _ - + = *",
"( ) [ ] { } < > / \\",
"& | ~ ^ {enter} {accept} {cancel}",
"{shift} {alt} @ {space}",
],
*/
},
},
/*
//keyboard: { layout: 'albanian-qwerty' },
keyboard: {
layout: 'custom',
customLayout: {
'normal' : [
"` 1 2 3 4 5 6 7 8 9 0 - = {bksp}",
"{tab} q w e r t y u i o p \u00eb '",
"a s d f g h j k l ; \u00e7 # {enter}",
"{shift} \\ z x c v b n m , . / {shift}",
"{accept} {alt} {space} {alt} {cancel}"],
'shift' : [
'\u00ac ! " \u00a7 $ % ^ & * ( ) _ + {bksp}',
"{tab} Q W E R T Y U I O P \u00cb @",
"A S D F G H J K L : \u00c7 ~ {enter}",
"{shift} \u00a6 Z X C V B N M < > ? {shift}",
"{accept} {alt} {space} {alt} {cancel}"
],
'alt' : [
"| 1 2 3 4 5 6 { } [ ] - = {bksp}",
"{tab} q w \u20ac r t y u i o p \u00f7 \u00d7",
"a s d f g h j k l ; \u00e7 # {enter}",
"{shift} \\ z x c v b n m , . / {shift}",
"{accept} {alt} {space} {alt} {cancel}"
],
'alt-shift' : [
'| ! " \u00a7 $ % ^ & * ( ) _ + {bksp}',
"{tab} Q W \u20AC R T Y U I O P \u00cb @",
"A S D F G H J K L : \u00c7 ~ {enter}",
"{shift} \u00a6 Z X C V B N M < > ? {shift}",
"{accept} {alt} {space} {alt} {cancel}"
] },
},
*/
},
};
var _settings = {
save: function () {
localStorage.setItem('vocabulary.lng', $config.lng);
localStorage.setItem('vocabulary.vocabulary', $config.vocabulary);
localStorage.setItem('vocabulary.custom_keyboard', $config.custom_keyboard ? 'true' : 'false');
_settings.set_title();
_settings.update_panel();
_menu.update();
var term = $('#search-term')[0].value;
term ? _term.display(term) : _term.get_random();
},
/** Load language and vocabulary from the local storage */
load: function () {
// Load lng.
var lng = localStorage.getItem('vocabulary.lng');
if (lng && lng != 'undefined') {
$config.lng = lng;
if ($config.update_app_language) {
_l10n.set_language($config.lng);
}
}
// Load vocabulary.
var vocabulary = localStorage.getItem('vocabulary.vocabulary');
if (vocabulary && vocabulary != 'undefined') {
$config.vocabulary = vocabulary;
}
// Load custom_keyboard
var kbd = localStorage.getItem('vocabulary.custom_keyboard');
if (kbd && kbd != 'undefined') {
$config.custom_keyboard = (kbd == 'true' ? true : false);
}
// Update.
this.set_title();
this.update_panel();
},
set_title: function () {
if (!_options[$config.lng]) return;
var title = _options[$config.lng].vocabularies[$config.vocabulary];
document.title = title;
$('h1').html(title);
},
update_panel: function () {
// Fill the list of languages.
var data = { languages: [] };
$.each(_options, function (lng, obj) {
data.languages.push({
lng: lng,
language: obj.name,
selected: (lng==$config.lng ? 'checked="checked"' : ''),
});
});
var tmpl = $('#tmpl-languages').html();
$('#languages').html(Mustache.render(tmpl, data)).trigger('create');
// Fill the list of vocabularies.
var data = { vocabularies: [] };
if (_options[$config.lng]) {
$.each(_options[$config.lng].vocabularies, function (id, name) {
data.vocabularies.push({
id: id,
name: name,
selected: (id==$config.vocabulary ? 'checked="checked"' : ''),
});
});
}
var tmpl = $('#tmpl-vocabularies').html();
$('#vocabularies').html(Mustache.render(tmpl, data)).trigger('create');
// Set the value of the keyboard checkbox.
$('#custom-keyboard').attr('checked', $config.custom_keyboard);
// Update layout of the panel.
$('#settings').trigger('updatelayout');
// Update config and settings when a vocabulary is selected.
$('.vocabulary').on('click', function () {
$config.vocabulary = this.value;
_settings.save();
});
// Update config and settings when a language is selected.
$('.lng').on('click', function () {
$config.lng = this.value;
for (var v in _options[$config.lng].vocabularies) break;
$config.vocabulary = v;
_settings.save();
if ($config.update_app_language) {
_l10n.set_language($config.lng);
}
});
// Update custom_keyboard when the switch is flipped.
$('#custom-keyboard').change(function () {
$config.custom_keyboard = $(this).is(':checked');
localStorage.setItem('vocabulary.custom_keyboard', $config.custom_keyboard ? 'true' : 'false');
var term = $('#search-term')[0].value;
_term.display(term);
});
},
};
/**
* Implement "translation in context".
*
* It works like this: when the user makes a Ctrl+Click on a
* string/translation anywhere on the UI, a browser tab/window is
* opened automatically with the correct url in the translation server
* (web application), where he can give a translation or a new
* suggestion for the selected string. (Of course, for a normal Click
* the UI works as normally it should.)
*
* Hopefully this can help to improve the quality of translations,
* since the user knows the context where the string is being used. It
* can also facilitate giving feedback and suggestions to the
* translator(s) of a program.
*/
var _translate_in_context = {
/**
* Override the gettext function "_()", so that instead of the
* translation it returns a "decorated" translation (which can
* handle Ctrl+Click properly). The function "_t()" will always
* return the original undecorated translation.
*/
init: function () {
// The function "_t()" will always return the original
// undecorated translation.
window._t = window._;
// Override the gettext function "_()", so that instead of the
// translation it returns a "decorated" translation (which can
// handle Ctrl+Click properly).
if ($config.translate_in_context) {
window._t = window._;
window._ = _translate_in_context.get_decorated_translation;
for (var property in window._t)
window._[property] = window._t[property];
// Assign event handler to elements of class 'gettext'.
$(document).ready(_translate_in_context.apply);
}
},
/**
* Return a "decorated" translation (which can handle Ctrl+Click
* properly). The ID of the string is included as an attribute.
*/
get_decorated_translation: function (text) {
var sguid = Sha1.hash(text);
var decorated_translation =
'<span class="gettext" sguid="' + sguid + '">'
+ _t(text)
+ '</span>';
return decorated_translation;
},
/**
* Return the URL of the selected string on the translation
* server.
*/
get_url: function (el) {
var url = 'https://btranslator.org/translations/';
if ( _options[$config.lng]
&& _options[$config.lng].translate_in_context_url )
{
url = _options[$config.lng].translate_in_context_url;
}
var sguid = $(el).attr('sguid');
return url + $config.lng + '/' + sguid;
},
/**
* Assign the event handler function to the elements with class
* 'gettext'.
*/
apply: function () {
if ($config.translate_in_context) {
$('.gettext').off('click', _translate_in_context.handle_ctrl_click);
$('.gettext').on('click', _translate_in_context.handle_ctrl_click);
}
},
/**
* Handle the Ctrl+Click event by opening a browser tab with the
* correct URL. Return 'false' so that the click event fails.
*/
handle_ctrl_click: function(event) {
if (event.ctrlKey) {
var url = _translate_in_context.get_url(this);
try {
var w = window.open(url, 'translate');
w.href= url;
} catch (e) {}
finally {
return false;
}
}
},
};
// Initialize translation in context.
_translate_in_context.init();
// Google Analytics
if ($config.ga_id) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
}
else {
window.ga = function(){};
}
ga('create', $config.ga_id, 'auto');
ga('send', 'pageview');
$(document).ready(function () {
$('.ui-btn').on('click', function() {
var label = $(this)[0].textContent;
ga('send', 'event', 'button', 'click', label);
});
});
var _menu = {
init: function () {
_menu.update();
$('#menuButton').on('click', function() {
if ($user.isLoged()) {
$('#login').hide();
$('#register').hide();
$('#logout').show();
$('#profile').show();
$user.is_admin ? $('#del-term').show() : $('#del-term').hide();
if ($user.is_subscribed) {
$('#subscribe').hide();
$('#unsubscribe').show();
}
else {
$('#subscribe').show();
$('#unsubscribe').hide();
}
}
else {
$('#login').show();
$('#register').show();
$('#logout').hide();
$('#profile').hide();
$('#del-term').hide();
$('#subscribe').hide();
$('#unsubscribe').hide();
}
});
},
update: function () {
// Render the menu template.
var menu_tmpl = $('#tmpl-menu').html();
var data = {
base_url: $config.base_url,
lng: $config.lng,
vocabulary: $config.vocabulary,
webapp_url: $config.webapp_url,
external_links: $config.external_links,
'User': _('User'),
'Sign in': _('Sign in'),
'Sign out': _('Sign out'),
'Sign up': _('Sign up'),
'Subscribe': _('Subscribe'),
'Unsubscribe': _('Unsubscribe'),
'Profile': _('Profile'),
'Settings': _('Settings'),
'Contact': _('Contact'),
'Links': _('Links'),
'Project': _('Project'),
'Delete': _('Delete'),
'Details': _('Details'),
'Dashboard': _('Dashboard'),
'List': _('List'),
'Download': _('Download'),
};
$("#popupMenu")
.html(Mustache.render(menu_tmpl, data))
.enhanceWithin().popup();
_translate_in_context.apply();
$('#login').on('click', function () {
$user.login();
});
$('#logout').on('click', function () {
$user.logout();
});
$('#subscribe').on('click', function () {
$user.subscribe();
});
$('#unsubscribe').on('click', function () {
$user.subscribe('unsubscribe');
});
// Close the menu when an item is clicked.
$('#popupMenu li').on('click', function() {
$('#popupMenu').popup('close');
});
// When the button del-term is clicked.
$('#del-term').on('click', function () {
var term = $('#search-term')[0].value;
var message = 'You are deleting the term "' + term + '", its translations and the votes.'
$user.confirm(message, function () {
var sguid = Sha1.hash(term + $config.vocabulary);
_term.del(sguid);
});
});
},
};
var _l10n = {
/** Translate the application interface. */
translate: function () {
// Translate seetings.
$('#lang').html(_('Language'));
$('#vocab').html(_('Vocabulary'));
$('label[for="custom-keyboard"]').html(_('Use Custom Keyboard:'));
$('#done').html(_('Done'));
// Translate search.
$('#search-term').attr('placeholder', _t('Search for a word...'));
$('#add-new-term').html( _('Add New Term'));
// Translate menu.
_menu.update();
},
/** Load the translations for the given language. */
set_language: function (lng) {
$.getScript('l10n/po/' + lng + '.js')
.done(_l10n.translate)
.fail(function () {
if (lng=='en') return;
_l10n.set_language('en');
});
},
}
/**
* When the page with id 'vocabulary' is created,
* do the things that are listed in the function.
*/
$(document).on('pagecreate', '#vocabulary', function() {
// Load language and vocabulary from the local storage.
_settings.load();
// Translate the app interface.
_l10n.translate();
// Setup menu items.
_menu.init();
// Attach the function '_suggestions.list' to the event
// 'filterablebeforefilter' from the list of suggestions.
$('#suggestions').on('filterablebeforefilter', _suggestions.list);
// When the button 'Random' is clicked, get and display a random term.
$('#random').on('click', function (event) {
_term.get_random();
});
// When the search button is clicked, go and fetch the translations
// of the term that is entered on the search textbox.
$('#search-button').on('click', function (event) {
var term = $('#search-term')[0].value;
_term.display(term);
});
// Add a new term when the button is clicked.
$('#add-new-term').on('click', _term.add);
// Remove a dynamic-popup after it has been closed.
$(document).on('popupafterclose', '.dynamic-popup', function() {
$(this).remove();
});
// Display the term that is given after #, or any random term.
var term = window.location.hash.slice(1);
term ? _term.display(term) : _term.get_random(true);
// Initialize Disqus.
(_options[$config.lng] && _options[$config.lng].disqus) ?
_disqus.init(_options[$config.lng].disqus) :
$('#disqus').hide();
});
var _social_share = {
/** Update the social share buttons. */
update: function(term, translations) {
var title = $('h1').html() + ': ' + term;
var summary = term + ' <==> ' + translations.join(' / ');
var mobile_url = $config.app_url
+ '/?lng=' + $config.lng + '&proj=' + $config.vocabulary
+ '#' + term;
var url = $config.api_url
+ '/vocabulary/' + $config.vocabulary + '/' + term
+ '/?url=' + encodeURIComponent(mobile_url);
$('#share-facebook').off().on('click', function() {
window.open('https://www.facebook.com/sharer/sharer.php'
+ '?u=' + encodeURIComponent(url));
});
$('#share-googleplus').off().on('click', function() {
window.open('https://plus.google.com/share'
+ '?url=' + encodeURIComponent(url)
+ '&hl=' + $config.lng);
});
$('#share-twitter').off().on('click', function() {
window.open("https://twitter.com/intent/tweet"
+ '?text=' + encodeURIComponent(summary)
+ '&url=' + encodeURIComponent(mobile_url)
+ '&hashtags=' + $config.vocabulary);
});
$('#share-linkedin').off().on('click', function() {
window.open("https://www.linkedin.com/shareArticle?mini=true"
+ '&url=' + encodeURIComponent(mobile_url)
+ '&title=' + encodeURIComponent(title)
+ '&summary=' + encodeURIComponent(summary)
+ '&source=' + encodeURIComponent($('h1').html()));
});
},
};
var _disqus = {
// Initialize Disqus.
init: function (shortname) {
if (typeof(DISQUS) == 'undefined'){
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
},
// Reload disqus data.
reload: function (sguid, term) {
if ($('.disqus-wrap').length == 1) {
$('.disqus-inactive').addClass('disqus-active').removeClass('disqus-inactive').attr('id','disqus_thread');
}
if (typeof(DISQUS) !== 'undefined'){
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = 'translations/' + $config.lng + '/' + sguid;
this.page.title = term;
if ($config.webapp_url) {
this.page.url = $config.webapp_url + '/vocabulary/' + $config.vocabulary + '/' + term;
}
else {
this.page.url = 'https://l10n.org.al/vocabulary/' + $config.vocabulary + '/' + term;
}
}
});
}
},
};
var _term = {
/** Display the given term. */
display: function (term) {
// If there is an suggestion autoselect timeout, clear it.
if (_suggestions.autoselect) {
clearTimeout(_suggestions.autoselect);
_suggestions.autoselect = null;
}
// Update the search input box.
$('#search-term')[0].value = term;
// Get and display the list of translations.
var sguid = Sha1.hash(term + $config.vocabulary);
_translations.display(sguid);
// Track with Google Analytics.
ga('set', 'page', term);
ga('send', 'pageview');
},
/**
* Get and display a random term from the vocabulary.
*
* @param check {boolean}
* Default is 'false'. If 'true', display the term
* only if the search box is empty.
*/
get_random: function (check) {
var check = check || false;
http_request('/api/translations/get_random_sguid', {
type: 'POST',
data: {
target: 'random',
scope: 'vocabulary/' + $config.vocabulary,
},
})
.then(function (result) {
// Check that the search box is empty.
if (check && $('#search-term')[0].value != '') { return; }
// Get and display the translations of the string.
_translations.display(result.sguid);
});
},
/** Add a new term. */
add: function () {
var term = $('#search-term')[0].value;
if (!term) return false;
// Get the access_token.
var access_token = $user.token.access_token();
if (!access_token) {
$user.token.get().done(_term.add);
return false;
}
// Add the new term.
var arr = $config.vocabulary.split('_');
var name = arr[0], lng = arr[1];
http_request('/api/vocabulary/add_string', {
type: 'POST',
data: {
name: name,
lng: lng,
string: term,
notify: true,
},
headers: {
'Authorization': 'Bearer ' + access_token,
}
})
.done(function (result) {
if (result.messages.length) {
display_service_messages(result.messages);
}
else {
_translations.display(result.sguid);
message('New term added.');
}
});
},
/** Delete the term with the given id. */
del: function (sguid) {
var access_token = $user.token.access_token();
if (!access_token) {
$user.token.get().done(function () {
_term.del(sguid);
});
return;
}
var arr = $config.vocabulary.split('_');
var name = arr[0], lng = arr[1];
http_request('/api/vocabulary/del_string', {
type: 'POST',
data: {
name: name,
lng: lng,
sguid: sguid,
},
headers: { 'Authorization': 'Bearer ' + access_token }
})
.done(function (result) {
if (result.messages.length) {
display_service_messages(result.messages);
}
else {
message('Term deleted.');
_translations.hide();
$('#add-new-term').show();
}
});
},
};
var _suggestions = {
/**
* This function is called when the user starts to type a term on the
* search-term input. It retrieves from the server a list of
* autocomplete suggestions and displays them under the search box.
*/
list: function (event, data) {
// Hide the rest of the page, except search.
_translations.hide();
$('#add-new-term').hide();
$('#social-share-buttons').hide();
$('#disqus').hide();
// Get the search term typed so far.
var search_term = $(data.input).val();
if (!search_term) { return; }
if (search_term.length < 2) { return; }
// Retrieve a suggestions list from the server and display them.
var url = '/auto/string/vocabulary'
+ '/' + $config.vocabulary + '/' + search_term;
http_request(url).then(_suggestions.display);
},
/**
* Build and display a list of the terms suggested from the server.
* When a term is clicked it should be selected.
*/
display: function(term_list) {
// If there is an autoselect timeout, clear it.
if (_suggestions.autoselect) {
clearTimeout(_suggestions.autoselect);
_suggestions.autoselect = null;
}
// Get the numbers of terms
var count = Object.keys(term_list).length;
// If the list is empty, add the current term as a new term.
if (count == 0) {
_suggestions.hide();
$('#add-new-term').show();
return;
}
// If there is only one term in the list,
// autoselect it (after 2 seconds of inactivity).
if (count == 1) {
for (var term in term_list) break;
_suggestions.autoselect = setTimeout(function () {
_term.display(term);
}, 2*1000);
}
// Get the data for the list of suggestions.
var data = { terms: [] };
$.each(term_list, function (id, term) {
data.terms.push(term);
});
// Render and display the template of suggestions.
var tmpl = $('#tmpl-suggestions').html();
$('#suggestions').html(Mustache.render(tmpl, data))
.listview('refresh').trigger('updatelayout');
// When a term from the list is clicked, select that term.
$('.term').on('click', function () {
// Display the selected term.
var term = $(this).html();
_term.display(term);
});
},
/** Hide the list of suggestions. */
hide: function () {
$('#suggestions')
.html('')
.listview('refresh')
.trigger('updatelayout');
},
};
var _translations = {
/** Hide the list of translations. */
hide: function () {
$('#translations')
.html('')
.listview('refresh')
.trigger('updatelayout');
},
/** Get the translations of the given sguid and display them. */
display: function (sguid) {
// Hide the list of suggestions and the button that adds a new term.
_suggestions.hide();
$('#add-new-term').hide();
var url = '/api/translations/' + sguid + '?lng=' + $config.lng;
http_request(url).then(function (result) {
//console.log(result.string); return; //debug
// If result.string is null, there is no such string.
if (result.string === null) {
_translations.hide();
$('#add-new-term').show();
return;
}
// Set the selected term on the search box.
var term = result.string.string;
$('#search-term')[0].value = term;
// Set the link for the details.
$('#details').attr('href', $config.webapp_url +
'/vocabulary/' + $config.vocabulary + '/' + term);
// Get the data for the list of translations.
var data = {
translations: [],
'New translation': _t('New translation'),
};
$.each(result.string.translations, function (i, trans) {
data.translations.push({
id: trans.tguid,
translation: trans.translation,
author: trans.author,
time: $.timeago(trans.time),
vote_nr: trans.count,
voted: trans.votes.hasOwnProperty($user.name) ? ' voted' : '',
});
});
// Render and display the template of translations.
var tmpl = $('#tmpl-translations').html();
$('#translations').html(Mustache.render(tmpl, data))
.listview('refresh').trigger('create').trigger('updatelayout');
// Attach a custom keyboard to the field of new translations.
_translations.attach_keyboard();
// Store the string id (we need it when submitting
//a new translation).
$('#new-translation').data('sguid', result.string.sguid);
// Store the votes for each translation.
$.each(result.string.translations, function (i, trans) {
var $li = $('li#' + trans.tguid);
$li.data('tguid', trans.tguid);
$li.data('translation', trans.translation);
$li.data('votes', trans.votes);
});
// When a translation from the list is clicked,
// display a popup with its details.
$('.translation').on('click', _translation.display_popup);
// Sending a new translation to the server.
$('#new-translation-form').on('submit', _translation.submit);
$('#send-new-translation').on('click', _translation.submit);
// Update the social share buttons.
var term = result.string.string;
var translations = [];
$.each(result.string.translations, function (i, trans) {
translations.push(trans.translation);
});
_social_share.update(term, translations);
$('#social-share-buttons').show();
// Get the disqus comments for this term.
if (_options[$config.lng] && _options[$config.lng].disqus) {
_disqus.reload(sguid, term);
$('#disqus').show();
}
});
},
/** Attach a custom keyboard to the field of new translations. */
attach_keyboard: function() {
if (!$config.custom_keyboard) return;
if (!_options[$config.lng]) return;
if (!_options[$config.lng].keyboard) return;
var kbd = _options[$config.lng].keyboard;
var options = {
keyBinding : 'mousedown touchstart',
stayOpen : true,
position : {
of : null,
my : 'left top',
at : 'left top',
at2: 'left bottom',
collision: 'fit',
}
};
if (kbd.customLayout) {
options.layout = 'custom';
options.customLayout = kbd.customLayout;
}
else if (kbd.layout) {
options.layout = kbd.layout;
};
var theme = {
// keyboard wrapper theme
container : { theme:'a' },
// theme added to all regular buttons
buttonMarkup : { theme:'b', shadow:'false', corners:'true' },
// theme added to all buttons when they are being hovered
buttonHover : { theme:'b' },
// theme added to action buttons (e.g. tab, shift, accept, cancel);
// parameters here will override the settings in the buttonMarkup
buttonAction : { theme:'b' },
// theme added to button when it is active (e.g. shift is down)
// All extra parameters will be ignored
buttonActive : { theme:'a' }
};
$('#new-translation').keyboard(options).addMobile(theme);
},
};
var _translation = {
/**
* When a translation from the list is clicked, display
* a popup with the details of this translation.
*/
display_popup: function (event) {
// Get the data for the list of voters.
var data = {
translation: $(this).data('translation'),
delete: ($user.is_moderator || $user.is_admin),
nr : 0,
voters: [],
'Vote': _('Vote'),
'Delete': _('Delete'),
'Voters': _('Voters'),
};
var votes = $(this).data('votes');
$.each(votes, function (user, vote) {
if (!vote.name) return;
data.nr += 1;
var voter_name = vote.name;
if (voter_name == $user.name) {
voter_name = '<span class="user">' + voter_name + '</span>';
}
data.voters.push({
name: voter_name,
time: $.timeago(vote.time),
});
});
// Render and display the template of translation details.
var tmpl = $('#tmpl-translation-details').html();
var popup_html = Mustache.render(tmpl, data);
$(popup_html)
.appendTo($.mobile.activePage)
.toolbar();
$("#translation-details")
.popup() // init popup
.popup('open'); // open popup
_translate_in_context.apply();
// Get the id of the translation.
var tguid = $(this).data('tguid');
// When the 'Vote' button is clicked,
// send a vote for this translation.
$('#vote').on('click', function () {
$("#translation-details").popup('close');
_translation.vote(tguid);
});
// When the 'Delete' button is clicked,
// delete this translation.
$('#delete').on('click', function (event) {
$("#translation-details").popup('close');
_translation.del(tguid);
});
},
/**
* Send a vote for the translation with the given id.
*/
vote: function (tguid) {
var access_token = $user.token.access_token();
if (!access_token) {
$user.token.get().done(function () {
_translation.vote(tguid);
});
return;
}
http_request('/api/translations/vote', {
type: 'POST',
data: { tguid: tguid },
headers: { 'Authorization': 'Bearer ' + access_token }
})
.done(function (result) {
if (result.messages.length) {
display_service_messages(result.messages);
}
else {
message('Vote saved.');